Last active
December 20, 2017 15:27
-
-
Save timbrandin/6d0ee4851d9cae579e0c3f2e3c564920 to your computer and use it in GitHub Desktop.
Generate a linked list of people with support for couples, used to create the christmas chain (one person gives only to one other person).
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
// Unique list of people, list in list is a couple that for some reason only can give to a specific person. | |
const list = [ | |
['person1', 'person2'], // couple | |
'person3', | |
'person4', | |
['person5', 'person6'], // couple | |
'person7', | |
]; | |
// randomize the list of who gives to who. | |
const shuffle = arr => { | |
const array = [...arr]; | |
const copy = []; | |
let n = arr.length; | |
let i; | |
// While there remain elements to shuffle. | |
while (n) { | |
// Pick a remaining element. | |
n -= 1; | |
i = Math.floor(Math.random() * n); | |
// And move it to the new array. | |
copy.push(array.splice(i, 1)[0]); | |
} | |
return copy; | |
}; | |
// flattens the array into a one dimensional list. | |
const flatten = arr => [].concat(...arr.map( v => v instanceof Array ? flatten(val) : [val])) | |
// print the list of who gives to who. | |
const print = arr => { | |
const flat = flatten(arr); | |
for (let i = 0; i < flat.length; i += 1) { | |
console.log(flat[i], '=>', flat[(i + 1) % flat.length]); | |
} | |
}; | |
print(shuffle(list)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice work! Added it now.
Do you mean that it would be faster with the random number generator or just that you tested it with that?