Last active
July 6, 2016 23:57
-
-
Save sairion/b8ff7ff622a232e8a874bd83387d8101 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
function pp(givenNth/*: int*/, curNth = 0/*: int*/, dir = 1 /* { 1 | -1 } */, result = 0/*: int*/) { | |
// console.log(arguments[1], arguments[2], arguments[3]); | |
'use strict'; | |
if (givenNth === curNth) { | |
return result; | |
} else { | |
return pp(givenNth, curNth + 1, isTurnAround(curNth + 1) * dir, result + dir); | |
} | |
} | |
function isTurnAround(n/*: int*/) { | |
'use strict'; | |
if (n >= 7) { | |
if (n % 7 === 0 || n % 10 === 7) { | |
return -1; | |
} else { | |
return isTurnAround(n / 10 | 0); | |
} | |
} else { | |
return 1; | |
} | |
} | |
// Test for isTurnAround(n) | |
for (let i = 0; i <= 100; i++) { | |
let expected = (i % 7 === 0 || String(i).indexOf('7') > -1) ? -1 : 1; | |
let actual = isTurnAround(i); | |
console.assert(actual === expected, i); | |
} | |
// Test for pp(nth) | |
console.assert(pp(8) === 6, 8); | |
console.assert(pp(22) === 0, 22); | |
console.assert(pp(68) === 2, 68); | |
console.assert(pp(100) === 2, 100); | |
// Using proper tail call (TCO) support in Webkit. | |
// 10000 -> around 20ms | |
// 100000 -> around 200ms | |
console.time('pp'); | |
console.log((function () { | |
'use strict'; | |
return pp(10000); | |
})()); | |
console.timeEnd('pp'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment