Skip to content

Instantly share code, notes, and snippets.

@io-developer
Last active April 16, 2020 22:38
Show Gist options
  • Save io-developer/d5809677a5950eca1a192467ac6d2b65 to your computer and use it in GitHub Desktop.
Save io-developer/d5809677a5950eca1a192467ac6d2b65 to your computer and use it in GitHub Desktop.
function secretSanta(values, mutuality = 0.5) {
let offset = 0;
return values
.map((val, index) => ({index: index, order: Math.random()}))
.sort((a, b) => a.order - b.order)
.map((item, next, items) => {
[next, offset] = (++next - offset > 1 && items.length - next > 1 && Math.random() < mutuality)
? [offset, next]
: [next < items.length ? next : offset, offset];
return [values[item.index], values[items[next].index]];
});
}
// Example output
for (let mutuality=0.0; mutuality <= 1.0; mutuality += 0.5) {
console.log(`Mutuality ${mutuality}: `, secretSanta(['Alice', 'Bob', 'Craig', 'Dave', 'Eve', 'Fiona', 'Gloria'], mutuality));
}
/* [ [from who, to who], ... ]
Mutuality 0: [
[ 'Craig', 'Alice' ],
[ 'Alice', 'Fiona' ],
[ 'Fiona', 'Dave' ],
[ 'Dave', 'Gloria' ],
[ 'Gloria', 'Bob' ],
[ 'Bob', 'Eve' ],
[ 'Eve', 'Craig' ]
]
Mutuality 0.5: [
[ 'Gloria', 'Dave' ],
[ 'Dave', 'Craig' ],
[ 'Craig', 'Bob' ],
[ 'Bob', 'Eve' ],
[ 'Eve', 'Gloria' ],
[ 'Alice', 'Fiona' ],
[ 'Fiona', 'Alice' ]
]
Mutuality 1: [
[ 'Alice', 'Bob' ],
[ 'Bob', 'Alice' ],
[ 'Dave', 'Gloria' ],
[ 'Gloria', 'Dave' ],
[ 'Eve', 'Fiona' ],
[ 'Fiona', 'Craig' ],
[ 'Craig', 'Eve' ]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment