Click Below to subscribe

Generate look and say sequence - Look-and-Say

Given a number n, generate look and say sequence.  1, 11, 21, 1211...... n;

function lookSay(digits) {
    
    let chars = (digits + ' ').split(''),
        lastChar = chars[0], 
        result = '', 
        times = 0; 
 
    for(const nextChar of chars){ 
        if (nextChar === lastChar) {
            times++;
        } else {
            result += (times + '') + lastChar;
            lastChar = nextChar;
            times = 1; 
        }
    }
    return result;
}
 
function sequence(n) {
	let seed = "1"
    for (let i = 0; i < n; i++) {
        console.log(seed);        //  1 ->  11 -> 21
        seed = lookSay(seed);
    }
}

#Testing:-

sequence(10);
// output-                  look and say
/*
    1                       one times one  ->  11
    11                      two times one  ->  21
    21                      one times two one times one  -> 1211
    1211
    111221
    312211
    13112221
    1113213211
    31131211131221
    13211311123113112211
*/

Leave Your Comment