Created
February 16, 2022 18:13
-
-
Save nax3t/a45e09dd50731e693f065d75cb180afb to your computer and use it in GitHub Desktop.
Self Describing Number - Algorithm Solution
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
function isSelfDescribing(num) { | |
let numArray = String(num).split('').map(str => Number(str)); | |
// 123 => '123' => ['1', '2', '3'] => [1, 2, 3] | |
let i = 0; | |
for (const num of numArray) { | |
// check to see how many times the current index appears in the numArray | |
// and does that total match the current element/number for this iteration | |
if (numArray.filter(n => n === i).length !== num) { | |
return false; | |
} | |
i++; | |
} | |
return true; | |
} | |
console.log(isSelfDescribing(1210)); // true | |
console.log(isSelfDescribing(2020)); // true | |
console.log(isSelfDescribing(21200)); // true | |
console.log(isSelfDescribing(3211000)); // true | |
console.log(isSelfDescribing(42101000)); // true | |
console.log(isSelfDescribing(1)); // false | |
console.log(isSelfDescribing(100)); // false | |
console.log(isSelfDescribing(24354)); // false | |
console.log(isSelfDescribing(99999)); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment