Files
freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/rosetta-code/look-and-say-sequence.md
Oliver Eyton-Williams f1c9b08cf3 fix(curriculum): add isHidden: false to challenges
This includes certificates (where it does nothing), but does not
include any translations.
2020-05-25 16:25:19 +05:30

2.5 KiB

id, title, challengeType, isHidden
id title challengeType isHidden
5e6dd14797f5ce267c2f19d0 Look-and-say sequence 5 false

Description

The Look and say sequence is a recursively defined sequence of numbers. Sequence Definition
  • Take a decimal number
  • Look at the number, visually grouping consecutive runs of the same digit.
  • Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.
This becomes the next number of the sequence. An example:
  • Starting with the number 1, you have one 1 which produces 11
  • Starting with 11, you have two 1's. I.E.: 21
  • Starting with 21, you have one 2, then one 1. I.E.: (12)(11) which becomes 1211
  • Starting with 1211, you have one 1, one 2, then two 1's. I.E.: (11)(12)(21) which becomes 111221

Instructions

Write a function that accepts a string as a parameter, processes it, and returns the resultant string.

Tests

tests:
  - text: <code>lookAndSay</code> should be a function.
    testString: assert(typeof lookAndSay == 'function');
  - text: <code>lookAndSay("1")</code> should return a string.
    testString: assert(typeof lookAndSay("1") == 'string');
  - text: <code>lookAndSay("1")</code> should return <code>"11"</code>.
    testString: assert.equal(lookAndSay("1"), "11");
  - text: <code>lookAndSay("11")</code> should return <code>"21"</code>.
    testString: assert.equal(lookAndSay("11"), "21");
  - text: <code>lookAndSay("21")</code> should return <code>"1211"</code>.
    testString: assert.equal(lookAndSay("21"), "1211");
  - text: <code>lookAndSay("1211")</code> should return <code>"111221"</code>.
    testString: assert.equal(lookAndSay("1211"), "111221");
  - text: <code>lookAndSay("3542")</code> should return <code>"13151412"</code>.
    testString: assert.equal(lookAndSay("3542"), "13151412");

Challenge Seed

function lookAndSay(str) {

}

Solution

function lookAndSay(str) {
    return str.replace(/(.)\1*/g, function(seq, p1) {
      return seq.length.toString() + p1;
    });
}