Created
March 17, 2020 06:09
-
-
Save jfbrennan/da814cbeb9b5c9023c8f94b3b8ad2c7a to your computer and use it in GitHub Desktop.
Student-Course Pairs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const studentCoursePairs1 = [ | |
["58", "Linear Algebra"], | |
["94", "Art History"], | |
["94", "Operating Systems"], | |
["17", "Software Design"], | |
["58", "Mechanics"], | |
["58", "Economics"], | |
["17", "Linear Algebra"], | |
["17", "Political Science"], | |
["94", "Economics"], | |
["25", "Economics"], | |
["58", "Software Design"] | |
]; | |
const studentCoursePairs2 = [ | |
["42", "Software Design"], | |
["0", "Advanced Mechanics"], | |
["9", "Art History"], | |
]; | |
function findPairs(studentCoursePairs) { | |
const result = new Map(); // {[student id pair], [courses]} | |
let studentIds = new Set(); | |
function findSharedCourses(studentPair, studentCoursePairs) { | |
const counts = {}; | |
const sharedCourses = []; | |
// Updates course counts for the given student pair | |
for (const [studentId, course] of studentCoursePairs) { | |
if (studentId === studentPair[0] || studentId === studentPair[1]) { | |
counts[course] = counts[course] ? counts[course] + 1 : 1; | |
} | |
} | |
// Add courses that both students have | |
for (const course in counts) { | |
if (counts[course] === 2) { | |
sharedCourses.push(course); | |
} | |
} | |
return sharedCourses; | |
} | |
// 1. Get unique student ids | |
for (const pair of studentCoursePairs) { | |
studentIds.add(pair[0]); | |
} | |
studentIds = [...studentIds]; | |
// 2. For each student pair find shared courses and add to the result | |
while (studentIds.length) { | |
for (let j = 1; j < studentIds.length; j++) { | |
const studentPair = [studentIds[0], studentIds[j]]; | |
const sharedCourses = findSharedCourses(studentPair, studentCoursePairs); | |
result.set(studentPair, sharedCourses); | |
} | |
// All pairs have been created for the current student, remove them | |
studentIds.splice(0, 1); | |
} | |
return result; | |
} | |
console.log(findPairs(studentCoursePairs1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment