
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements