Last active
May 20, 2016 02:30
-
-
Save deltamualpha/9272d4874d2a25fa6412ddcdc426a0a3 to your computer and use it in GitHub Desktop.
This problem was presented to me: given a list of numbers, 1-1000, can you name the smallest base in which each one is a palindrome?
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
var palindrome_test = function(array) { | |
for (var i = 0; i <= array.length - 1; i++) { | |
if (array[i] !== array[array.length - i - 1]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
var int2base = function(int, base) { | |
if (int === 0 || base === 0) { | |
return [0]; | |
} | |
if (base == 1) { | |
// this really is the easiest way to fill an array with numbers in vanilla js | |
return Array.apply(null, Array(int)).map(Number.prototype.valueOf,1); | |
} | |
var digits = []; | |
while (int) { | |
digits.unshift(int % base); | |
int = Math.floor(int/base); | |
} | |
return digits; | |
} | |
// nested loops, oh no... probably a better way... | |
for (var i = 1; i <= 1000; i++) { | |
for (var j = 2; j <= i + 1; j++) { | |
if (palindrome_test(int2base(i, j))) { | |
// console.log(int2base(i, j)); | |
console.log(i + " is a palindrome in base " + j); | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or even better: compare:
arr.slice(0, Math.ceil(arr.length/2))
arr.slice(Math.floor(arr.length/2), arr.length)