Recursively generating the look-and-say sequence I have a pattern where every number is counted by the number of repetitions. A new resulting number is formed by adding that repetition to the front of that value. The resulting pattern would look like this.


1
11
21
1211
111221


so:

indexnumbercomment
0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
 one +  1 ->11&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;11&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; two + 1 -> 21 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;21 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;one + 2 + one + 1 -> 1211 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

etc...

I was given a number 4, and I needed to produce the resulting number 1211.

My approach was to use a recursive function that used every subsequent iteration starting from 0 to evaluate every resulting value until I reached my target iteration. 

Runtime Complexity: I decremented the number recursively O(N) as I carried the resulting evaluation result. 

At every recursive step, I produced every result by walking the resulting values, counting the repetitions as I went along. I stored every key-value pairs along an Index represented by a synecdochic key in a line of contiguous repetition. I tallied the repetitions until I had a key-value pair at the intersection of every index.

I then assembled the value by swapping the key values pairs at every index into a new object array which I used to repeat the process. O(C) 

I then used reduce to format the results and repeat the process O(F) 

O(N *C +F) = O(N^2)

space complexity is O(N^2) since the amount of space needed to process doubles on every resulting iteration. 

Are my Time and Space analysis correct, did I miss a much simpler approach where I might have been able to take advantage of Fibonacci, XOR or some other simpler mathematical approach?  and could this have been done better programmatically by using some other type of data structure, or could it have been written in some other concise way?



function countStay(num) {
  if (num === 1) {
    return 1
  }

  return drill(num, [1])
}

function drill(exitCount, result) {
  const map = {
      0: {}
    },
    arr = [];
  let count = 0,
    index = 0;
  result = result.reduce((acc, a, i, aa) =&gt; {
    if (aa[i - 1] &amp;&amp; aa[i] &amp;&amp; a !== aa[i - 1]) {
      index += 1
      count = 0
      map[index] = {
        [a]: count
      }
    }
    if (((map || {})[index] || {})[a] &amp;&amp; count !== 0) {
      map[index][a] = count += 1
      arr[index] = [count, a]
    }
    if (!((map || {})[index] || {})[a] &amp;&amp; count === 0) {
      count += 1
      map[index] = {
        [a]: count
      }
      arr[index] = [count, a]
    }
    return acc = {
      arr
    }
  }, {})

  result = join(result)
  exitCount--
  if (exitCount &lt;= 1) {
    return result.join('')
  }
  return drill(exitCount, result)
}

function join(result) {
  return result = result.arr.reduce((acum, a) =&gt; acum.concat(a), [])
}
console.log(countStay(4))
It seems like you tried too hard to avoid all loops by limiting yourself to .reduce() and recursion.  While JavaScript supports functional programming to some extent, sticking to pure FP everywhere will likely lead to clunky code.  A better strategy would be to define some functions that look pure from the outside, but might be implemented in an imperative style.  (Your code isn't pure FP anyway: the index += 1 statements perform mutation.)

I don't think that countStay and drill are well designed functions.  It's not clear to me what each of them is supposed to accomplish.  countStay seems to be a trivial wrapper around drill.  At first glance, all I can see is that drill contains a lot of code, and that it calls itself recursively.  In particular, it's hard to read because the variable names are cryptic.  map is obviously a map, and arr is obviously an array, but what are their purpose?

Suggested solution

I would define three functions, each of which has a clear purpose and is easily testable.  Instead of recursion, I've used iterateN, which is inspired by Haskell.  Then, it's easy to compose them to obtain the result.  This solution is simpler and more readable than yours.



/**
 * Split an array of items into runs of identical values;
 * yield [item, runLength] for each run.
 *
 * runLengthEncode('bookkeeper'.split('')) =&gt;
 * ['b', 1], ['o', 2], ['k', 2], ['e', 2], ['p', 1], ['e', 1], ['r', 1]
 */
const runLengthEncode = function*(items) {
    if (items.length) {
        let groupStart = 0, groupItem = items[0];
        for (let i = 1; i &lt; items.length; i++) {
            if (items[i] != groupItem) {
                yield [groupItem, i - groupStart];
                groupStart = i;
                groupItem = items[i];
            }
        }
        yield [groupItem, items.length - groupStart];
    }
};

/**
 * Given a number (as an integer or string), produce its successor
 * in the look-and-say sequence (as a string).
 *
 * nextLookAndSay('1211') =&gt; '111221'
 */
const nextLookAndSay = (n) =&gt; {
    let accum = [];
    for (let group of runLengthEncode(n.toString().split(''))) {
        accum.push(group[1], group[0]);
    }
    return accum.join('');
};

/**
 * The result of f(f(f ... f(init))), where the function f is applied n times
 * to the initial value.
 *
 * iterateN(2, (s) =&gt; s + 'o', 'b') =&gt; 'boo'
 */
const iterateN = (n, f, init) =&gt; {
    while (n--) { init = f(init); }
    return init;
};

console.log(iterateN(3, nextLookAndSay, '1'));