Displays all possible combinations of alphabets from the data set for a given input number

What I'm trying to achieve is to get a combination of alphabets from a given input number. E.g. if I give input 111, the output should be ['AAA','KA','AK'] . If the input signal is 1111, the output should be ['AAAA','KAA','AKA','AAK','KK'] . Partial working code is as follows, where I get ['K','K'] for input 111:

  <html> <head> <h1>Javascript</h1> </head> <body> <script> var dataset = {A:'1',B:'2',C:'3',D:'4',E:'5',F:'6',G:'7',H:'8',I:'9', J:'10',K:'11',L:'12',M:'13',N:'14',O:'15',P:'16',Q:'17',R:'18', S:'19',T:'20',U:'21',V:'22',W:'23',X:'24',Y:'25',Z:'26'}; var arr = []; var z; var result = []; var find = function(input){ for(var key in dataset) { if(dataset[key] === input) { return key; } } } var foo = function(x){ z = x.toString(); for(var i=0;i<z.length;i++){ arr.push(z.charAt(i)); } for(var i=0;i<arr.length;i++){ if(arr[i]+arr[i+1] <= 26){ var returnedkey = find(arr[i]+arr[i+1]); result.push(returnedkey); } } } foo(111); console.log(arr); console.log(result); </script> </body> 

I am confused how to proceed further, and which is the correct method, Thanks in advance!

+5
source share
1 answer

This sentence uses an object to search and rollback to iterate through the string.

Example getCombination('1111') with a call to c()

First, iterate over one character, and then, if possible, iterate over two characters.

 left right letter result ---- ----- ------ ----- 1111 one 111 A one 11 AA one 1 AAA one AAAA one AAAA 11 AA one AAK two AAK 111 A one 1 AK two AKA one AKA 11 K two 1 KA one KAA one KAA 11 K two KK two KK 

 function getCombination(s) { function c(left, right) { if (!left) { result.push(right); return; } // checks if the first character of left is in the letter object // then call c without the first letter of left // and right with the letter from the letter object of the first character letters[left[0]] && c(left.substring(1), right + letters[left[0]]); // it is basically the same as above, but with two characters left.length > 1 && letters[left.substring(0, 2)] && c(left.substring(2), right + letters[left.substring(0, 2)]); } var letters = { 1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L', 13: 'M', 14: 'N', 15: 'O', 16: 'P', 17: 'q', 18: 'R', 19: 'S', 20: 'T', 21: 'U', 22: 'V', 23: 'W', 24: 'X', 25: 'Y', 26: 'Z' }, result = []; c(s, ''); return result; } document.write('<pre>' + JSON.stringify(getCombination('1111'), 0, 4) + '</pre>'); document.write('<pre>' + JSON.stringify(getCombination('1011121314'), 0, 4) + '</pre>'); 
+3
source

Source: https://habr.com/ru/post/1246148/


All Articles