Skip to content

Instantly share code, notes, and snippets.

@cedricbahirwe
Last active May 3, 2023 14:15
Show Gist options
  • Save cedricbahirwe/8932dd0c540724f1ab35f55b4d541ad6 to your computer and use it in GitHub Desktop.
Save cedricbahirwe/8932dd0c540724f1ab35f55b4d541ad6 to your computer and use it in GitHub Desktop.
My Attempted Algorithmic Solution to Andela Interview Question
import Foundation
var prereqsCourses = [
("Software Design", "Algorithms"),
("Foundations of Computer Science", "Operating Systems"),
("Computer Networks", "Computer Architecture"),
("Computer Architecture", "Software Design"),
("Algorithms", "Foundations of Computer Science"),
("Data Structures", "Computer Networks")
]
func getOrderedCourses(_ courses: [(preq: String, next: String)]) -> [String] {
let firstCourse = getFirstCourse(prereqsCourses)!
var result: [String] = [firstCourse]
var nextCourse: String? = firstCourse
while nextCourse != nil {
if let course = getNextCourse(nextCourse!,
courses: courses) {
result.append(course)
nextCourse = course
} else {
return result
}
}
return result
func getNextCourse(_ currentCourse: String, courses: [(String, String)]) -> String? {
for course in courses {
if course.0 == currentCourse {
return course.1
}
}
return nil
}
}
func getFirstCourse(_ courses: [(String, String)]) -> String? {
var firstCourse: String?
let preReqs = courses.map { $0.0 }
let coursesToBeTaken = courses.map { $0.1 }
firstCourse = preReqs.first(where: { coursesToBeTaken.contains($0) == false })
return firstCourse
}
let firstCourse = getFirstCourse(prereqsCourses)!
let orderedCourses = getOrderedCourses(prereqsCourses)
print("First Course:", firstCourse)
print("Ordered Courses:", orderedCourses)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment