title: Possible combinations and convert into alphabet algorithm - Javascript (asked by Facebook)
body: <p>I am studying algorithm for my next interview, And i found this problem. </p>
  
  <p>Which was asked by Facebook</p>
  
  <p>Here's the problem. </p>
  
  <hr>
  
  <p>Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.</p>
  
  <p>For example, the message '111' would give 3, since it could be decoded as 'aaa, 'ka', and 'ak'.</p>
  
  <hr>
  
  <p>I think I can handle with the mapping and converting to alphabet part. But making combinations is not easy for me. </p>
  
  <p>Consider that it took me several hours to come up with this code below. </p>
  
  <pre><code>function combinations(str) {
  var fn = function(active, rest, a) {
  
      // if nothing, just return
      if (!active &amp;&amp; !rest)
          return;
  
  
      // there is nothing left in rest add active to A
      if (rest.length == 0) {
          a.push(active);
      } else {
  
          // append first number of rest to the end of the active item
          // [1] + 1 =&gt; 111
          // [1,2] + [3,4] = [1,2,3] + [4]
          if (rest.length &gt; 0){
              fn(active.concat(rest[0]), rest.slice(1), a);
          }else {}
  
  
          // join 
  
          fn((active+rest[0]).split(","), rest.slice(1), a);
      }
      return a;
    }
    return fn([], str, []);
  }
  
  // run it
  combinations(1,2,3);
  </code></pre>
  
  <p>I only got this. </p>
  
  <pre><code>[ [ 1, 2, 3 ],
  [ '1', '23' ],
  [ '12', 3 ],
  [ '123' ],
  [ '1', 2, 3 ],
  [ '1', '23' ],
  [ '12', 3 ],
  [ '123' ] ]
  </code></pre>
  
  <p>See the duplicate item. I think I can now divide by 2 and get answers I want. Still it is not really a good answer. </p>
  
  <p>Can you make it into better code? </p>
  
  <p>Thank you</p>
  
  <hr>
  
  <p>The code above is almost from this <strong><a href="https://codereview.stackexchange.com/questions/7001/generating-all-combinations-of-an-array">link</a></strong></p>