Last active
December 11, 2024 23:38
-
-
Save iurii-kyrylenko/5bd8535558822da2111bfc46abc069b0 to your computer and use it in GitHub Desktop.
Counting of Arms
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
/* | |
* The inhabitants of Mars have 1, 2 or 3 arms. | |
* Once 5 Martians gathered and counted their arms: they had 10 arms in total. | |
* How many one-armed, two-armed and three-armed Martians gathered? | |
* Find all the options. | |
*/ | |
// (15, 5) -> [ 0, 0, 1, 2, 0 ] | |
const intToTernary = (i, size) => [...i.toString(3).padStart(size, "0")].map(Number); | |
const checkSample = (ternary, total) => { | |
const sum = ternary.reduce((acc, trit) => acc + trit + 1, 0); | |
return sum === total; | |
} | |
getStats = (ternary) => { | |
const counts = {}; | |
for (let i = 0; i < ternary.length; i++) { | |
const count = ternary[i] + 1; | |
counts[count] = counts[count] ? counts[count] + 1 : 1; | |
} | |
return counts; | |
}; | |
const getPermutations = (size, total) => { | |
const result = []; | |
for (let i = 0; i < 3 ** size; i++) { | |
const ternary = intToTernary(i, size); | |
if (checkSample(ternary, total)) { | |
const stats = getStats(ternary); | |
result.push({ ternary, stats}); | |
} | |
} | |
return result; | |
}; | |
const allOptions = getPermutations(5, 10).map((option) => JSON.stringify(option.stats)); | |
const optionsSet = new Set(allOptions); | |
const uniqueOptions = [...optionsSet].map((sOption) => JSON.parse(sOption)); | |
console.log(uniqueOptions); | |
// Unique options: | |
// [ | |
// { '1': 2, '2': 1, '3': 2 }, | |
// { '1': 1, '2': 3, '3': 1 }, | |
// { '2': 5 } | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment