Possible combinations and convert into alphabet algorithm in JavaScript


Suppose we are given the mapping a = 1, b = 2, ... z = 26, and an encoded message. We are required to write a JavaScript function that takes in the message.

The function should count the number of ways it can be decoded.

For example, the message '111' would give 3, since it could be decoded as 'aaa, 'ka', and 'ak'.

Example

The code for this will be −

const waysToProcess = ( message, ways = 0 ) => {
   if ( message.length ) {
      ways = waysToProcess( message.slice( 1 ,message.length), ways );
      const numCurr = parseInt( message[0] );
      const numNext = "undefined" === typeof message[1] ? null :
      parseInt(message[1]);
      if ( numCurr && numNext
         && numCurr < 3
         && ( numCurr + numNext ) < 27
      ) {
         ways = waysToProcess( message.slice( 2 ,message.length), ways );
      }
   } else {
      ways++;
   }
   return ways;
}
console.log(waysToProcess('111'));

Output

And the output in the console will be −

3

Updated on: 23-Nov-2020

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements