Created
March 17, 2022 16:00
-
-
Save dherault/d9e373b88cfddc2792310625f2bbb460 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
function simon(n = 4, start = 0) { | |
if (n < 0) { | |
throw new Error('1st input number is too low') | |
} | |
if (start < 0) { | |
throw new Error('2nd input number is too low') | |
} | |
const colors = [ | |
'red', | |
'orange', | |
'yellow', | |
'green', | |
'blue', | |
'violet', | |
].sort(() => Math.random() - 0.5); | |
if (n > colors.length) { | |
throw new Error('1st input number is too high') | |
} | |
const seed = [ | |
0, 1, 2, 3, 4, 5, 6, | |
1, 2, 3, 4, 5, 6, 0, | |
2, 3, 4, 5, 6, 0, 1, | |
3, 4, 5, 6, 0, 1, 2, | |
5, 6, 0, 1, 2, 3, 4, | |
4, 5, 6, 0, 1, 2, 3, | |
6, 0, 1, 2, 3, 4, 5, | |
0, 2, 1, 4, 3, 6, 5, | |
1, 3, 2, 5, 4, 6, 0, | |
2, 4, 3, 6, 5, 0, 1, | |
3, 5, 4, 6, 1, 0, 2, | |
4, 6, 5, 0, 2, 1, 3, | |
5, 6, 1, 0, 3, 2, 4, | |
6, 0, 2, 1, 4, 3, 5, | |
] | |
if (start >= seed.length) { | |
throw new Error('2nd input number is too high') | |
} | |
const serie = [] | |
const frequency = {} | |
const marginOfError = 1 / n | |
const cursors = { | |
color: start, | |
compensation: 0, | |
} | |
function getIndex(key) { | |
const index = seed[cursors[key]] % n | |
cursors[key] += index + n | |
if (cursors[key] >= seed.length) { | |
cursors[key] -= seed.length | |
} | |
return index | |
} | |
for (let i = 0; i < n; i++) { | |
frequency[colors[i]] = 0 | |
} | |
return () => { | |
let color = colors[getIndex('color')] | |
if (getIndex('compensation') % 2 === 0) { | |
let pickAgain = true | |
while (pickAgain) { | |
if (frequency[color] <= marginOfError * serie.length) { | |
pickAgain = false | |
} | |
else { | |
color = colors[getIndex('color')] | |
} | |
} | |
} | |
frequency[color] += 1 | |
serie.push(color) | |
return serie | |
} | |
} | |
simon.rules = [ | |
'Inputs: 0-6, 0-98', | |
] | |
// for (let n = 2; n < 7; n++) { | |
// console.log('___') | |
// console.log(n) | |
// const generator = simon(n) | |
// let serie = generator() | |
// for (let i = 0; i < 1024; i++) { | |
// serie = generator() | |
// } | |
// let frequency = {} | |
// serie.forEach(color => { | |
// frequency[color] = (frequency[color] || 0) + 1 | |
// }) | |
// console.log(serie.slice(0, 12)) | |
// Object.keys(frequency).forEach(color => { | |
// frequency[color] /= serie.length | |
// console.log(color, `${(frequency[color] * 100).toFixed(2)}%`) | |
// }) | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment