Created
September 18, 2022 20:39
-
-
Save chrisryan/4383b0c323e326db639319f8dd17bc26 to your computer and use it in GitHub Desktop.
Solution to See And Say - 50 Challenge
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
'use strict'; | |
const debug = true; | |
const start = process.hrtime(); | |
let seq = '1'; | |
let results = [seq]; | |
const runto = 50; | |
while (results.length < runto) { | |
results.push(seeandsay(results[results.length - 1])); | |
} | |
console.log('sequence', results[results.length - 1]); | |
console.log('sum', sumdigits(results[results.length - 1])); | |
if (debug) { | |
const end = process.hrtime(start); | |
console.log('total took %d seconds and %d nanoseconds', end[0], end[1]); | |
} | |
function seeandsay(seq) { | |
const start = process.hrtime(); | |
if (debug) { } | |
const parts = seq.split(''); | |
let count = 0; | |
let last = parts[0]; | |
let newSeq = ''; | |
for (const part of parts) { | |
if (part != last) { | |
newSeq = newSeq.concat(count, last); | |
count = 0; | |
last = part; | |
} | |
count++; | |
} | |
newSeq = newSeq.concat(`${count}${last}`); | |
if (debug) { | |
const end = process.hrtime(start); | |
console.log('seeandsay took %d seconds and %d nanoseconds', end[0], end[1]); | |
} | |
return newSeq; | |
} | |
function sumdigits(seq) { | |
const start = process.hrtime(); | |
if (debug) { } | |
const parts = seq.split(''); | |
let sum = 0; | |
for (const part of parts) { | |
sum += parseInt(part); | |
} | |
if (debug) { | |
const end = process.hrtime(start); | |
console.log('sumdigits took %d seconds and %d nanoseconds', end[0], end[1]); | |
} | |
return sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment