-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeepMind1.java
More file actions
80 lines (67 loc) · 2.57 KB
/
DeepMind1.java
File metadata and controls
80 lines (67 loc) · 2.57 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
72
73
74
75
76
77
78
79
// You start at index 0 in an array with length 'h'. At each step, you can move to the left, move to the right, or
// stay in the same place(Note! Stay in the same place also takes one step).
// How many possible ways are you still at index 0 after you have walked 'n' step?
//
// Example: n = 3
// 1. right->left->stay
// 2. right->stay->left
// 3. stay->right->left
// 4. stay->stay->stay
//
// Can anyone solve it in n^2
import java.util.*;
/*
* Given list of tasks and its dependants, figure out the correct order we should execute those tasks.
*/
public class DeepMind1 {
private static final Map<String, List<String>> TASKS = new TreeMap<String, List<String>>() {
{
put("task1", new ArrayList<>(Arrays.asList("task2", "task3")));
put("task2", new ArrayList<>(Arrays.asList("task3")));
put("task3", new ArrayList<>());
put("task4", new ArrayList<>(Arrays.asList("task1")));
put("task5", new ArrayList<>(Arrays.asList("task4", "task1")));
put("task6", new ArrayList<>(Arrays.asList("task5")));
}
};
private List<String> getCorrectOrder(Map<String, List<String>> tasks) {
List<String> retList = new ArrayList<>();
if (tasks.isEmpty()) {
return retList;
}
Iterator<Map.Entry<String, List<String>>> iterator = tasks.entrySet().iterator();
Stack<String> stack = new Stack<>();
while (iterator.hasNext()) {
String currentTask = iterator.next().getKey();
stack.push(currentTask);
System.out.format("Adding %s\n", currentTask);
}
while (!stack.empty()) {
String task = stack.peek();
System.out.format("Looking at %s\n", task);
List<String> depTasks = tasks.get(task);
boolean allValid = false;
if (depTasks != null) {
allValid = true;
for (String depTask : depTasks) {
if (!retList.contains(depTask)) {
allValid = false;
stack.push(depTask);
}
}
}
if (depTasks == null || allValid) {
if (!retList.contains(task)) {
retList.add(task);
}
stack.pop();
}
}
return retList;
}
public void run() {
System.out.println(TASKS);
List<String> orderedTasks = getCorrectOrder(TASKS);
System.out.println(orderedTasks);
}
}