Created
January 24, 2014 02:41
-
-
Save pherris/8591182 to your computer and use it in GitHub Desktop.
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 magicNumberFinder = (function () { | |
var knownMagicNumbers = [], cacheUsedCount = 0, cacheSize = 0; | |
function stringImpl(num) { | |
var sum = 0, | |
prod = 1, | |
currentNum = "", | |
stringNum = ""+num; | |
for (i=0;i<stringNum.length;i++) { | |
currentNum = parseInt(stringNum.charAt(i)); | |
sum += currentNum; | |
prod = prod*currentNum; | |
} | |
return sum === prod; | |
} | |
function modImpl (num) { | |
var sum = 0, | |
prod = 1, | |
mod; | |
while (num>=10) { | |
mod = num%10; | |
num = Math.floor(num/10); | |
sum += mod; | |
prod = prod*mod; | |
} | |
//a little ugly doing this once more out of the loop. | |
sum += num; | |
prod = prod*num; | |
return sum === prod; | |
} | |
return { | |
isMagic: function (num, method) { | |
// console.log(num); | |
//if it is known, don't recalculate | |
if (knownMagicNumbers[num] === undefined) { | |
if (!method) { | |
knownMagicNumbers[num] = modImpl(num); | |
} else { | |
knownMagicNumbers[num] = stringImpl(num); | |
} | |
cacheSize++; | |
} else { | |
cacheUsedCount++; | |
} | |
return knownMagicNumbers[num]; | |
}, | |
cacheStats: function (maxLoops) { | |
console.log("cache size: " + cacheSize + ", used " + cacheUsedCount + " times"); | |
console.log("cache used: " + (cacheUsedCount/maxLoops)*100 + "%"); | |
}, | |
wipeCache: function () { | |
knownMagicNumbers = [], cacheUsedCount = 0, cacheSize = 0; | |
} | |
} | |
}()); | |
function testIt(method) { | |
var loopCount = 0; | |
var maxLoops = 10000000; | |
console.log((method?"STRING":"MOD") + " - creating " + maxLoops + " random numbers to see if they are magic"); | |
var start = new Date(); | |
while (loopCount<maxLoops) { | |
magicNumberFinder.isMagic(Math.floor(Math.random()*maxLoops), method); | |
loopCount++; | |
} | |
var end = new Date(); | |
magicNumberFinder.cacheStats(maxLoops); | |
console.log("time taken (ms) : " + (end.getTime() - start.getTime())); | |
console.log("------------------------------"); | |
} | |
testIt(); | |
magicNumberFinder.wipeCache(); | |
testIt("s"); | |
//console.log(magicNumberFinder.isMagic(22)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment