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)); |
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?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A version that does not need the condition in the loop.
The inner arrays (the person who need to give to a specific person) are unpacked to a single linear list.
becomes:
With this structure the print method will be a lot simpler.
Tested with the following seedable js random, to check the same result is achieved as in previous version.