Advertisement
Guest User

Untitled

a guest
Jan 25th, 2024
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.49 KB | Source Code | 0 0
  1. function getCombinations(digits) {
  2.   // Mapping digits to letter
  3.   const digitToChar = {
  4.       '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'
  5.     };
  6.  
  7.   // Store valid array
  8.   const combinations = [];
  9.  
  10.   // Recursion
  11.   function backtrack(start, path) {
  12.     // // When reached the end of the digits, add the combination to the array
  13.     if (start === digits.length) {
  14.       combinations.push(path);
  15.       return;
  16.     }
  17.     // Add letter from 1digit
  18.     const singleDigit = digits[start];
  19.     const singleDigitChar = digitToChar[singleDigit];
  20.     if (singleDigitChar) {
  21.       backtrack(start + 1, path + singleDigitChar);
  22.     }
  23.  
  24.     // Add letters from two digits if still available
  25.     if (start < digits.length - 1) {
  26.       const twoDigits = digits.slice(start, start + 2);
  27.       const twoDigitsChar = digitToChar[twoDigits];
  28.       if (twoDigitsChar) {
  29.         backtrack(start + 2, path + twoDigitsChar);
  30.       }
  31.     }
  32.   }
  33.   // Invoke recursive function initial value
  34.   backtrack(0, '');
  35.   return combinations;
  36. }
  37. const DIGITS = "1243752521494312";
  38. const combinations = getCombinations(DIGITS);
  39.  
  40. console.log(`Jumlah Kombinasi ada ${combinations.length}`);
  41. combinations.forEach((combination, index) => {
  42.   console.log(`[${index}] => ${combination}`);
  43. });
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement