From d8ddcbdd216875c1e1b742592a4e28411b4663a1 Mon Sep 17 00:00:00 2001 From: erius Date: Mon, 3 Jun 2024 02:06:06 +0300 Subject: [PATCH] Implemented hogwarts --- hogwarts/courselist.go | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/hogwarts/courselist.go b/hogwarts/courselist.go index 34ea140..e2c947a 100644 --- a/hogwarts/courselist.go +++ b/hogwarts/courselist.go @@ -2,6 +2,39 @@ package hogwarts -func GetCourseList(prereqs map[string][]string) []string { - return []string{} +import ( + "log" + "slices" +) + +func singleCourseList( + course string, prereqs map[string][]string, list []string, traversed []string, +) []string { + if slices.Contains(traversed, course) { + log.Panic("Recursive prereqs, aborting...") + } + traversed = append(traversed, course) + for _, prereqCourse := range prereqs[course] { + if !slices.Contains(list, prereqCourse) { + i := slices.Index(list, course) + if i == -1 { + list = append(list, prereqCourse) + } else { + list = slices.Insert(list, i, prereqCourse) + } + } + list = singleCourseList(prereqCourse, prereqs, list, traversed) + } + return list +} + +func GetCourseList(prereqs map[string][]string) []string { + list := make([]string, 0) + for course := range prereqs { + if !slices.Contains(list, course) { + list = append(list, course) + } + list = singleCourseList(course, prereqs, list, []string{}) + } + return list }