Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function getCombinations(digits) {
- // Mapping digits to letter
- const digitToChar = {
- '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'
- };
- // Store valid array
- const combinations = [];
- // Recursion
- function backtrack(start, path) {
- // // When reached the end of the digits, add the combination to the array
- if (start === digits.length) {
- combinations.push(path);
- return;
- }
- // Add letter from 1digit
- const singleDigit = digits[start];
- const singleDigitChar = digitToChar[singleDigit];
- if (singleDigitChar) {
- backtrack(start + 1, path + singleDigitChar);
- }
- // Add letters from two digits if still available
- if (start < digits.length - 1) {
- const twoDigits = digits.slice(start, start + 2);
- const twoDigitsChar = digitToChar[twoDigits];
- if (twoDigitsChar) {
- backtrack(start + 2, path + twoDigitsChar);
- }
- }
- }
- // Invoke recursive function initial value
- backtrack(0, '');
- return combinations;
- }
- const DIGITS = "1243752521494312";
- const combinations = getCombinations(DIGITS);
- console.log(`Jumlah Kombinasi ada ${combinations.length}`);
- combinations.forEach((combination, index) => {
- console.log(`[${index}] => ${combination}`);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement