Skip to content

Commit 304a1ab

Browse files
committedJun 7, 2020
order_courses: Order college courses, given prereqs for each course.
1 parent e0585f0 commit 304a1ab

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
 

‎order_courses_spec.rb

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Given college courses, each with array of prereqs, return possible order of
2+
# courses to take, so you always take prereqs before each related course
3+
4+
# Depth-first search algorithm with stack
5+
6+
def order(hash)
7+
ans, stack = [], []
8+
9+
hash.each do |id, pre|
10+
if pre == []
11+
ans << id.to_s if !ans.include?(id.to_s)
12+
next
13+
end
14+
15+
stack << id.to_s
16+
17+
while !stack.empty?
18+
top = stack.last
19+
if !ans.include?(top) && hash[top.to_sym] == []
20+
ans << stack.pop
21+
end
22+
23+
hash[top.to_sym].each do |prereq|
24+
if !ans.include?(prereq) && !stack.include?(prereq) # not visited
25+
stack << prereq
26+
if !ans.include?(top) && prereq == []
27+
ans << top
28+
end
29+
end
30+
end
31+
32+
hash[top.to_sym] = [] # marks value of top as visited
33+
end
34+
end
35+
36+
ans
37+
end
38+
39+
describe '#order' do
40+
it 'returns articles in proper order, first showing prereqs' do
41+
expect(order({'A': [], 'B': [], 'C': []})).to eq ['A', 'B', 'C']
42+
expect(order({'A': ['B'], 'B': [], 'C': []})).to eq ['B', 'A', 'C']
43+
expect(order({'A': ['B', 'C'], 'B': [], 'C': []})).to eq ['C', 'B', 'A']
44+
expect(order({'A': [], 'B': ['C', 'D'], 'C': ['D'], 'D': []})).to eq ['A', 'D', 'C', 'B']
45+
expect(order({'A': ['E'], 'B': ['C', 'D', 'E'], 'C': ['D', 'E'], 'D': [], 'E': []})).to eq ['E', 'A', 'D', 'C', 'B']
46+
end
47+
end

0 commit comments

Comments
 (0)
Please sign in to comment.