Created
September 19, 2010 23:42
-
-
Save artlung/587224 to your computer and use it in GitHub Desktop.
Challenges in nodejs
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
var fs = require("fs"); | |
var file = "file.txt"; | |
function main(contents){ | |
var sum = 0; | |
var digits = []; | |
var chars = {}; | |
for(var i=0;i<contents.length;i++) { | |
var n = contents[i]; | |
// is it a number? | |
if (parseInt(n, 10).toString() === n.toString()) { | |
sum += parseInt(n, 10); | |
digits.push(n); | |
} | |
// if key not defined, create it | |
if (typeof(chars[n]) === 'undefined') { | |
chars[n] = 1; | |
} else { | |
chars[n] += 1; | |
} | |
} | |
console.log('Sum = ' + sum); | |
for (i in chars) { | |
if (chars.hasOwnProperty(i)) { | |
console.log(i + ' = ' + chars[i]); | |
} | |
} | |
} | |
fs.readFile(file, "utf-8", function (error, data) { | |
contents = data.split("\n"); | |
main(contents); | |
}); |
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
// | |
var MAIN = { | |
reverse : function(i){ | |
return i.toString().split('').reverse().join(''); | |
}, | |
halfLength: function(i){ | |
return parseInt(i.toString().length / 2, 10); | |
}, | |
firstHalf: function(i) { | |
return i.toString().substring(0, this.halfLength(i)); | |
}, | |
secondHalf: function(i){ | |
return this.reverse(i.toString().substr(((-1)*this.halfLength(i)))); | |
}, | |
isPalindrome: function(i){ | |
if (i.toString().length == 1 ) { | |
return true; | |
} else { | |
return (this.firstHalf(i) === this.secondHalf(i)); | |
} | |
}, | |
addReverse : function(i) { | |
return (parseInt(i, 10)+(parseInt(this.reverse(i), 10))); | |
} | |
}; | |
var MAX_NUM = 10000; | |
var notfound = []; | |
for (var n=1; n<=MAX_NUM;n++){ | |
var LIMIT = 100; | |
var iterations = 0; | |
var r = n; | |
var is_palindrome = false; | |
while (iterations < LIMIT && !is_palindrome) { | |
reverse = MAIN.reverse(r); | |
sum = MAIN.addReverse(r); | |
is_palindrome = MAIN.isPalindrome(sum); | |
console.log(r + " + "+reverse+" = "+sum); | |
r = sum; | |
iterations = iterations + 1; | |
} | |
if (is_palindrome) { | |
console.log("PALINDROME FOUND! "+n+" AFTER "+iterations+" ITERATIONS"); | |
} else { | |
notfound.push(n); | |
console.log("NO PALINDROME AFTER "+LIMIT+" ITERATIONS! "+n+""); | |
} | |
} | |
console.log(''); | |
console.log(notfound.join(', ')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment