Created
February 16, 2022 23:03
-
-
Save juanca/9024cfcaa20df93747ebe43aeadb5934 to your computer and use it in GitHub Desktop.
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 _ = require('underscore'); | |
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'], | |
]; | |
function findPairs(pairs) { | |
const studentMap = pairs.reduce((acc, [id, course]) => { | |
acc[id] = (acc[id] ?? []).concat(course); | |
return acc; | |
}, {}); | |
// 2D map of students | |
const studentPairs = pairs | |
// Get IDs | |
.map(pair => pair[0]) | |
// Get unique IDs | |
.reduce((acc, id) => (acc.includes(id) ? acc : acc.concat(id)), []) | |
// New struct with pairs and shared classes (empty for now) | |
.reduce((acc, id, i, ids) => { | |
acc[id] = ids.filter(_id => _id !== id).reduce((_acc, _id) => { | |
// eslint-disable-next-line no-param-reassign,no-underscore-dangle | |
_acc[_id] = _.intersection(studentMap[id], studentMap[_id]); | |
return _acc; | |
}, {}); | |
return acc; | |
}, {}); | |
function genKey(id1, id2) { | |
return [id1, id2].sort().join(','); | |
} | |
return Object.entries(studentPairs).reduce((acc, [id1, subMap]) => { | |
return Object.entries(subMap).reduce((acc2, [id2, courses]) => { | |
if (acc[genKey(id1, id2)]) return acc; | |
acc[genKey(id1, id2)] = courses; | |
return acc; | |
}, {}); | |
}, {}); | |
} | |
console.log(findPairs(studentCoursePairs1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment