Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rajvanshipradeep15/333e028e2cded48c4d25e48bbf3ff13f to your computer and use it in GitHub Desktop.
Save rajvanshipradeep15/333e028e2cded48c4d25e48bbf3ff13f to your computer and use it in GitHub Desktop.
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