Skip to content

Instantly share code, notes, and snippets.

@juanca
Created February 16, 2022 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanca/9024cfcaa20df93747ebe43aeadb5934 to your computer and use it in GitHub Desktop.
Save juanca/9024cfcaa20df93747ebe43aeadb5934 to your computer and use it in GitHub Desktop.
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