-1

I need make some width function. It take a string and must to return an arrive with changed letters. For example:

enter code here

 let word = 'letter'
 function(word) {
 // code here
 return var // {letter, etterl, tterle, terlet, erlett, rlette]
Olejanski
  • 1
  • 1
  • 3
    what have you tried so far? – Adassko Jan 04 '22 at 15:10
  • Sounds a lot like a coding challenge question – Phobos Jan 04 '22 at 15:12
  • Start by using valid syntax: every opening brace must be closed. A function statement must give the function a name. And indent your code. Where it says "code here" you should enter your attempt. We expect you to show your efforts. – trincot Jan 04 '22 at 15:12
  • check that i think you will get the answer ;) https://stackoverflow.com/questions/3943772/how-do-i-shuffle-the-characters-in-a-string-in-javascript – Yannis Haismann Jan 04 '22 at 15:13

2 Answers2

0

you can do this:

function permut(string) {
  if (string.length < 2) return string;

  const permutations = [];
  for (let i = 0; i < string.length; i++) {
    const char = string[i];

    if (string.indexOf(char) !== i) continue;

    const remainingString =
      string.slice(0, i) + string.slice(i + 1, string.length);

    for (const subPermutation of permut(remainingString))
      permutations.push(char + subPermutation);
  }
  return permutations;
}

console.log(permut("hello"));
DecPK
  • 24,537
  • 6
  • 26
  • 42
Michael
  • 947
  • 7
  • 17
0

You can easily achieve the result if you first split the string, and then loop over the character array.

All you have to do is to push the first character at the end of the array on every iteration.

let word = 'letter';

function getResult(word) {
  const wordArray = word.split('');
  const result = [];
  for (let i = 0; i < word.length; ++i) {
    result.push(wordArray.join(''));
    wordArray.push(wordArray.shift());
  }

  return result;
}

console.log(getResult(word));
DecPK
  • 24,537
  • 6
  • 26
  • 42