Created
November 16, 2022 21:54
-
-
Save Krinkle/13f141c34f624ca96c17504f11e44459 to your computer and use it in GitHub Desktop.
This file contains 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 sets in JavaScript | |
* | |
* Inspired by https://fosstodon.org/@[email protected]/109354031141521705 | |
* | |
* Author: Timo Tijhof (2022). | |
* License: Public domain. | |
*/ | |
const NAMES = [ | |
'Apricot', | |
'Banana', | |
'Cherimoya', | |
'Gac', | |
'Irvingia', | |
'Rambutan' | |
]; | |
// Given 6 values in a circle, we can make 6 connections (or "pairs") | |
// | |
// A pair must be more than 0 but less than SIZE distance from each | |
// other to not be with itself. That means 1—5 distance in our case. | |
// | |
// This allows for SIZE-1 (5) sets of 6 pairs, or 30 unique pairs. | |
const POSSIBLE_SETS = NAMES.length - 1; | |
const all = new Set(); | |
for (let distance = 1; distance <= POSSIBLE_SETS; distance++) { | |
const current = new Set(); | |
for (let i = 0; i < NAMES.length; i++) { | |
const a = NAMES[i]; | |
// mod is the same as deducting until you're under | |
const b = NAMES[(i + distance) % NAMES.length]; | |
const pair = a + ' ' + b; | |
current.add(pair); | |
all.add(pair); | |
} | |
console.log( | |
`d=${distance} Set(${current.size}) =`, | |
Array.from(current).join(',\n') + '.\n' | |
); | |
} | |
console.log('Unique pairs', all.size); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment