-1

I'm a coding beginner & basically trying to modify the javascript code below (which I found online - Permutations in JavaScript?) to do the following:

  • return only the permuted numbers in a mixed string & in descending order (e.g. If the provided input is: “D 3fs m4q”, then the solution should return "43, 34".
  • return an error exception message if the input provided does not contain any numbers (e.g. If the provided input is: “GFA”, return null)

P.S I already figured out how to implement the descending function, however, when I try to use the .replace method to extract just the numbers in the string, it doesn't work for me. What am I doing wrong?

var permArr = [], usedChars = [];
function permute(input) {
  permArr.sort(function(a, b) {return b - a})
  permArr.replace(/\D/g);
  var i, ch, chars = input.split("");
  for (i = 0; i < chars.length; i++) {
    ch = chars.splice(i, 1);
    usedChars.push(ch);
    if (chars.length == 0)
      permArr[permArr.length] = usedChars.join("");
    permute(chars.join(""));
    chars.splice(i, 0, ch);
    usedChars.pop();
  }
  return permArr
};

console.log(solution("458")); //console.log(result);

Can the solution please be in javascript, as I am trying to get a grasp of the language? Any assistance would be greatly appreciated. Thanks for your help in advance.

D.O
  • 13
  • 2

1 Answers1

0

I would suggest that your best bet would be to break this into pieces. Below we have a simpler permutations function, using the helper excluding. And we have a function to extract the digits from a number. Then we write the main function on top of these two. That main function extracts the digits, creates the permutations, sorts them, and joins them back into a comma-separated string.

const excluding = (i) => (xs) => 
  [... xs .slice (0, i), ... xs .slice (i + 1)]

const permutations = ([...xs]) => 
  xs .length == 0 
    ? [[]] 
    : xs .flatMap ((x, i) => permutations (excluding (i) (xs)) .map (p => x + p))

const extractDigits = ([...s]) =>
  s .filter (c => /\d/ .test (c)) .join ('')

const homework = (s, digits = extractDigits (s)) =>
  digits .length 
    ? permutations (digits) .sort ((a, b) => b - a) .join (', ')
    : 'Your error message here'

console .log (homework ('D 3fs m4q'))
console .log (homework ('GFA'))

Although the numeric sorting is not appropriate for arbitrary digit-based strings, it should be good enough for any collection of digits not too big to overflow with permutations, since there are n! of them for a length-n string.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103