Skip to content

Instantly share code, notes, and snippets.

@sairion
Last active July 6, 2016 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sairion/b8ff7ff622a232e8a874bd83387d8101 to your computer and use it in GitHub Desktop.
Save sairion/b8ff7ff622a232e8a874bd83387d8101 to your computer and use it in GitHub Desktop.
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