Skip to content

Instantly share code, notes, and snippets.

@jquerius
Created December 7, 2018 17:11
Show Gist options
  • Save jquerius/366eef644c5ac34c6adc4b69111db0c9 to your computer and use it in GitHub Desktop.
Save jquerius/366eef644c5ac34c6adc4b69111db0c9 to your computer and use it in GitHub Desktop.
Can a number eat itself?
/**
* Given a positive integer, output a truthy/falsy value as to whether the number can eat itself.
*
* Rules:
* Leftmost is the head, rightmost is the tail
* If the head is greater than or equal to the tail, the head eats the tail and the new head becomes their sum.
* If sum >= 10 then the head is replaced by sum % 10 sum=0 cannot be ignored, input number will never have any zeroes to the left.
*
* Test Cases:
* True:
* [2632, 92258, 60282, 38410,3210, 2302, 2742, 8628, 6793, 1, 2, 10, 100, 55, 121]
* False:
* [6724, 47, 472, 60247, 33265, 79350, 83147, 93101, 57088, 69513, 62738, 54754, 23931, 7164, 5289, 3435, 3949, 8630, 5018, 6715, 340, 2194]
*/
let f = (n) => { return (n.length === 1) ? { 'result': true, 'num': n } :
(n[0] >= n[n.length - 1] ? f(((n[0] * 1 + n[n.length - 1] * 1) % 10) + n.slice(1, -1))
: { 'result': false, 'num': n }); }
console.log('Should be true;');
[2632, 92258, 60282, 38410,3210, 2302, 2742, 8628, 6793, 1, 2, 10, 100, 55, 121]
.forEach(n => console.log(f(n + '')));
console.log('\n\n\nShould be false;');
[6724, 47, 472, 60247, 33265, 79350, 83147, 93101, 57088, 69513, 62738, 54754, 23931, 7164, 5289, 3435, 3949, 8630, 5018, 6715, 340, 2194].forEach(n => console.log(f(n + '')));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment