Print Keypad combination problem using JavaScript
Hello guys, today we will do the medium-level question of recursion. You can do this question with recursion as well as an iterative method but iterative is a bit hard. If you do not familiar with recursion then go and checkout recursion in javascript post. Now come to the question…
You have given a string containing digits from 2 to 9, you have to print all the possible letter combinations that the given number represents in string using JavaScript
It is similar to keypad phone keys.
You need to map the digits to the particular letters(just like shown in the keypad phone).
Note: ‘0’ is not mapping with anything.
Examples:
Input:”8″
Output:
t u v
Input: “78”
output:
pt pu pv qt qu qv rt ru rv st su sv
Algorithm to print all possible strings generated from given keypad of phone
Here, we”ll use recursion.
1. Create an array to store all characters correspond to digit in the keyboard.
2. Base case: if string length becomes ‘zero’ then print our output string.
3. We store words in the ‘ans’ string.
4. Take out the character from the string using the charAt() function and concatenate with ans string using ‘+’.
4. Try all possible characters which correspond to the current digit and recursion for the remaining digits.
let code=["",",;","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]; function kpc(str,ans){ // base if(str.length==0){ console.log(ans); return ; } let ch=code[parseInt(str.charAt(0))]; let s=str.substring(1); for(let i=0;i<ch.length;i++){ let c=ch.charAt(i); //function call kpc(s,ans+c); } } kpc("234","");
Output:
adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi
If you like the content then share it with your friend and write a comment if you’re facing any difficulty.
Also read: Guess The Number Game Using JavaScript
Leave a Reply