Skip to content

Instantly share code, notes, and snippets.

@lauslim12
Created December 29, 2020 08:08
Show Gist options
  • Save lauslim12/8de78c6cbdf70972af15d49a6390f80d to your computer and use it in GitHub Desktop.
Save lauslim12/8de78c6cbdf70972af15d49a6390f80d to your computer and use it in GitHub Desktop.
An algorithm to equally distribute students to the number of available teachers.
/**
* Group.js
* An algorithm to equally distribute students to the number of available teachers.
* Complexity is O(n).
*
* @input Arrays of teachers and students.
* @output Array of objects of grouped students and teachers.
*
* Run in Node (CommonJS)
* How to run: Clone or copy the gist, then do node ./group.js
*/
/**
* Prepare our data.
*/
const teachers = require('./teachers');
const students = require('./students');
/**
* Shuffles a list with Fischer Yates Algorithm.
* Complexity: O(n).
*
* @param {...number} list
*/
function fischerYates(...list) {
for (let i = 0; i < list.length; i += 1) {
// 1. Get a random number between zero and the max array length, inclusive.
const randomNumber = Math.floor(Math.random() * list.length);
// 2. Shuffle.
const placeholder = list[i];
list[i] = list[randomNumber];
list[randomNumber] = placeholder;
}
}
/**
* Driver code.
*/
function main() {
// 0. Prepare a variable to store the results of the operation.
const results = [];
// 1. Shuffle first.
fischerYates(students);
fischerYates(teachers);
// 2. Assign each teachers to a new array.
teachers.forEach((teacher) => {
results.push({
teacher,
students: [],
});
});
// 3. Assign each students to the 'results' array, pop them.
// Pop an array with a random index.
// Complexity: O(n).
let counter = 0;
while (students.length > 0) {
const randomIndex = Math.floor(Math.random() * students.length);
results[counter].students.push(students[randomIndex]);
students.splice(randomIndex, 1);
if (counter === teachers.length - 1) {
counter = 0;
} else {
counter += 1;
}
}
// Print the results.
for (let i = 0; i < results.length; i += 1) {
console.log(results[i]);
}
}
if (require.main === module) {
main();
}
module.exports = [
{
id: 'S1',
name: 'Thomas Andreas',
},
{
id: 'S2',
name: 'Bernardus Gery Santoso',
},
{
id: 'S3',
name: 'Kharansyah Tawaddhu Shalam',
},
{
id: 'S4',
name: 'Sinzie Winata',
},
{
id: 'S5',
name: 'Attar Kusuma Pratiwa',
},
{
id: 'S6',
name: 'Farrel Irsyad Fanny',
},
{
id: 'S7',
name: 'Mochamad Rizky Zaldi',
},
{
id: 'S8',
name: 'Lucky Benedict',
},
{
id: 'S9',
name: 'Muhammad Faisal Farhan',
},
{
id: 'S10',
name: 'Deka Primatio Deandra',
},
{
id: 'S11',
name: 'Gregorius Haryanto Setiadi',
},
{
id: 'S12',
name: 'Muhammad Faiz Ramdhani',
},
{
id: 'S13',
name: 'Fadla Ichsan',
},
{
id: 'S14',
name: 'Raul Andrian',
},
];
module.exports = [
{
id: 'T1',
name: 'Mr. Krabs',
},
{
id: 'T2',
name: 'Spongebob Squarepants',
},
{
id: 'T3',
name: 'Squidward Tentacles',
},
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment