Skip to content

Instantly share code, notes, and snippets.

@nonZero
Forked from anonymous/random_group2.html
Created November 27, 2017 21:20
Show Gist options
  • Save nonZero/9c27e609dcb8ad921e2ad1fd67a4193a to your computer and use it in GitHub Desktop.
Save nonZero/9c27e609dcb8ad921e2ad1fd67a4193a to your computer and use it in GitHub Desktop.
<script src="random_groups2.js"></script>
let split_to_groups = function (source, n) {
const items = source.slice();
const arr = [];
for (let i = 0; i < n; i++) {
arr.push([]);
}
// my solution!!!
let next = 0;
while (items.length) {
const i = Math.floor(Math.random() * items.length);
arr[next].push(items[i]);
items.splice(i, 1);
next = (next + 1) % arr.length;
}
return arr;
};
function testProgram() {
"use strict";
const TEST_DATA = "a b c d e f g h i j";
const groups = split_to_groups(TEST_DATA.split(' '), 3);
console.log(groups);
for (let group of groups) {
console.log(group);
}
console.assert(groups[0].length === 4);
console.assert(groups[1].length === 3);
console.assert(groups[2].length === 3);
const groups_str = groups.reduce((a, x) => a.concat(x), []).sort().join(" ");
console.log(groups_str);
console.assert(groups_str === TEST_DATA);
console.log("OK");
}
testProgram();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment