Skip to content

Commit

Permalink
Merge e162756 into 9dc3351
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Nov 23, 2018
2 parents 9dc3351 + e162756 commit 0f1cad8
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,4 @@ problems from
* [Day 89](https://github.com/vaskoz/dailycodingproblem-go/issues/187)
* [Day 90](https://github.com/vaskoz/dailycodingproblem-go/issues/189)
* [Day 91](https://github.com/vaskoz/dailycodingproblem-go/issues/192)
* [Day 92](https://github.com/vaskoz/dailycodingproblem-go/issues/194)
45 changes: 45 additions & 0 deletions day92/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package day92

// CourseOrder returns how to take all the courses.
// If it's not possible to take all the courses, returns nil.
// Runs in O(N) time.
func CourseOrder(prereq map[string][]string) []string {
var result []string
marked := make(map[string]int)
for n := range prereq {
if _, found := marked[n]; !found {
newest := visit(n, prereq, marked, result)
if len(newest) > len(result) {
result = newest
}
}
}
if len(marked) != len(prereq) {
return nil
}
reverse(result)
return result
}

func reverse(n []string) {
for i := 0; i < len(n)/2; i++ {
n[i], n[len(n)-1-i] = n[len(n)-1-i], n[i]
}
}

func visit(node string, graph map[string][]string,
marked map[string]int, result []string) []string {
if mark := marked[node]; mark != 0 {
return nil
}
marked[node] = 1
for _, m := range graph[node] {
newest := visit(m, graph, marked, result)
if len(newest) > len(result) {
result = newest
}
}
marked[node] = 2
result = append([]string{node}, result...)
return result
}
45 changes: 45 additions & 0 deletions day92/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package day92

import (
"reflect"
"testing"
)

var testcases = []struct {
prereqs map[string][]string
expected []string
}{
{map[string][]string{
"CSC300": {"CSC100", "CSC200"},
"CSC200": {"CSC100"},
"CSC100": {},
},
[]string{"CSC100", "CSC200", "CSC300"}},
{map[string][]string{
"CSC300": {"CSC100"},
"CSC100": {"CSC300"},
},
[]string{"CSC100", "CSC300"}},
{map[string][]string{
"CSC300": {"CSC100"},
"CSC400": {"CSC200"},
},
nil},
}

func TestCourseOrder(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := CourseOrder(tc.prereqs); !reflect.DeepEqual(result, tc.expected) {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func BenchmarkCourseOrder(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
CourseOrder(tc.prereqs)
}
}
}

0 comments on commit 0f1cad8

Please sign in to comment.