Created
May 10, 2024 06:04
-
-
Save rajvanshipradeep15/333e028e2cded48c4d25e48bbf3ff13f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var letterCombinations = function (digits) { | |
let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split(''); | |
let digitValues = []; | |
let calculationArr = []; | |
let resultSet = []; | |
for (let i = 2; i < 10; i++) { | |
if (i === 7 || i === 9) { | |
digitValues[i] = alphabet.splice(0, 4) | |
} else { | |
digitValues[i] = alphabet.splice(0, 3) | |
} | |
} | |
if (digits !== "" && digits.length) { | |
for (const digit of digits) { | |
calculationArr.push(digitValues[digit]); | |
} | |
resultSet = cartesian(...calculationArr); | |
} | |
return resultSet; | |
}; | |
function cartesian(...args) { | |
var r = [], max = args.length-1; | |
function helper(arr, i) { | |
for (var j=0, l=args[i].length; j<l; j++) { | |
var a = arr.slice(0); // clone arr | |
a.push(args[i][j]); | |
if (i==max) | |
r.push(a.join('')); | |
else | |
helper(a, i+1); | |
} | |
} | |
helper([], 0); | |
return r; | |
} | |
const digits = '792'; | |
const result = letterCombinations(digits); | |
console.log('result', result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment