forked from jmcilhargey/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchpt4-build-order.js
More file actions
71 lines (49 loc) · 1.62 KB
/
chpt4-build-order.js
File metadata and controls
71 lines (49 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
function canProjectsBeCompleted(projectsToComplete, listOfDependencies) {
var graphOfProjects = buildTheGraph(projectsToComplete, listOfDependencies);
return makeBuildOrder(graphOfProjects);
}
function buildTheGraph(projectsToComplete, listOfDependencies) {
var graphOfProjects = {};
projectsToComplete.forEach(function(project) {
graphOfProjects[project] = [];
});
listOfDependencies.forEach(function(dependency) {
graphOfProjects[dependency[0]].push(dependency[1]);
});
return graphOfProjects;
}
function makeBuildOrder(graphOfProjects) {
var projectList = [];
for (var project in graphOfProjects) {
if (!graphOfProjects[project].length) {
projectList.push(project);
delete graphOfProjects[project];
}
}
while (projectList.length) {
var builtProject = projectList.pop();
for (var project in graphOfProjects) {
var findDependency = graphOfProjects[project].indexOf(builtProject);
if (findDependency > -1) {
graphOfProjects[project].splice(findDependency, 1);
if (!graphOfProjects[project].length) {
projectList.push(project);
delete graphOfProjects[project];
}
}
}
}
return getSizeOf(graphOfProjects) === 0;
}
function getSizeOf(object) {
var size = 0;
for (var key in object) {
if (object.hasOwnProperty(key)) {
size++;
}
}
return size;
}
var projects = ["a", "b", "c", "d", "e", "f"];
var dependencies = [["d", "a"], ["b", "f"], ["d", "b"], ["a", "f"], ["c", "d"]];
console.log(canProjectsBeCompleted(projects, dependencies));