-
-
Save nonZero/9c27e609dcb8ad921e2ad1fd67a4193a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<script src="random_groups2.js"></script> |
This file contains hidden or 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
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