No Repeats Please*

Tell us what’s happening:
I want to swap the element of the str, then I want to get every combination by adding +1 to every index of every element. How can I do that.
Your code so far


function permAlone(str) {
let splittedStr=str.split("")
let lengthOfSplittedStr=splittedStr.length;
let groupfGroups=[];
//console.log(lengthOfSplittedStr)
let factorial=1; 
for(let i=1;i<=lengthOfSplittedStr;i++){
        factorial*=i
}
for(let i =1;i<=factorial;i++){
        groupfGroups.push(splittedStr.slice(i,i))

}
console.log(groupfGroups)
}

permAlone('ab');
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.86 Safari/537.36.

Challenge: No Repeats Please

Link to the challenge:

Search about permutation algorithms.

When you will be able to permute an array, check for repeatning characters.

Tip: do not store all permutations. Try to permute and check on the fly.

2 Likes

I have done it, but I have used this link: https://www.30secondsofcode.org/js/s/permutations. I did not know how to permutate the string :frowning:

function permAlone(str) {

const splittedStr=str.split("")
const arrayOfArrays=[]
const globalRegex = new RegExp('(aa)+|(bb)+|(cc)+|(dd)+|(ee)+|(ff)+|(gg)+|(hh)+|(ii)+|(jj)+|(kk)+|(ll)+|(mm)+|(nn)+|(oo)+|(pp)+|(qq)+|(rr)+|(ss)+|(tt)+|(uu)+|(vv)+|(ww)+|(yy)+|(zz)+', '');
let counterOfArr=0
const lengthOfstr=str.length;

const permutations = arr => {
  if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
  return arr.reduce(
    (acc, item, i) =>
      acc.concat(
        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
          item,
          ...val,
        ])
      ),
    []
  );
};

  //console.log(arrayOfArrays)
let permutedStr=permutations(splittedStr)
//console.log(permutedStr)
 if(lengthOfstr>1){
   for(let i=0;i<permutedStr.length;i++){
        if(!globalRegex.test(permutedStr[i].join(""))){
                   arrayOfArrays.push(permutedStr[i])      
                    counterOfArr+=1
        }
    }
                    //console.log(counterOfArr)
                    return counterOfArr;
 
 }else{
     return 1
 }
  
     
    
}

permAlone("a")

How can I improve my code? Do you know another video or documentation in order to understand recursion for getting the permutation?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.