Skip to content

Instantly share code, notes, and snippets.

@sairion
Created October 20, 2016 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sairion/8b2e62f4811de322ffc3e841e5d633a4 to your computer and use it in GitHub Desktop.
Save sairion/8b2e62f4811de322ffc3e841e5d633a4 to your computer and use it in GitHub Desktop.
Look and say sequence - JavaScript version
/*
look-and-say-sequence by Jaeho Lee,
public domain
1 => [[1, 1]]
11 => [[1, 2]]
21 => [[2, 1], [1, 1]]
1211
111221
*/
function getLookAndSaySequence(len) {
const seq = ['1']
function getNextSeq(input) {
const split = input.split('')
const result = []
for (
let i = 0, count = 0, current = split[i];
i < split.length;
i++
) {
count += 1
const next = split[i + 1]
if (
next == null // reaches end
||
next !== current // next
) {
result.push([String(count), current])
current = next
count = 0
}
}
return result
}
function flatNumber(seq) {
return seq.reduce((prev, next) => prev.concat(next), []).join('')
}
const f = a => flatNumber(getNextSeq(a))
let i = 0
while (i < len - 1) {
seq[i + 1] = f(seq[i])
i++
}
return seq
}
const result = getLookAndSaySequence(8);
["1", "11", "21", "1211", "111221", "312211", "13112221", "1113213211"].forEach((e, i) => {
console.assert(e === result[i])
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment