Created
December 13, 2018 23:30
-
-
Save ndedic/b9ed73ffd9899c0549d1b51b5af9265b to your computer and use it in GitHub Desktop.
Kaprekar's constant solver
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
// https://en.wikipedia.org/wiki/6174_(number) | |
const kaprekar = 6174; | |
const routine = (input) => { | |
const res = new Map(); | |
let i = 0; | |
while (input !== kaprekar) { | |
input = cycle(input); | |
res.set(i++, input); | |
} | |
return res; | |
}; | |
const cycle = (input) => { | |
const a = numberToArray(input); | |
const s1 = sortArray(a, 'desc'); | |
const s2 = sortArray(a, 'asc'); | |
const n1 = arrayToNumber(s1); | |
const n2 = arrayToNumber(s2); | |
return n1 - n2; | |
}; | |
const numberToArray = (num) => | |
num | |
.toString() | |
.split('') | |
.map(n => parseInt(n, 10)); | |
const arrayToNumber = (arr) => parseInt(arr.join(''), 10); | |
const sortArray = (arr, direction) => { | |
const c = [...arr]; | |
switch (direction) { | |
case 'asc': | |
return c.sort((a, b) => a - b); | |
case 'desc': | |
return c.sort((a, b) => b - a); | |
default: | |
return c; | |
} | |
}; | |
const res = routine(1234); | |
console.log(res); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment