Niklaus Wirth

Niklaus Wirth

Translate

(26) No repeats please

No repeats please
26-ой день программы "#100 Days Of Code"

Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique.

For example, aab should return 2 because it has 6 total permutations (aab, aab, aba, aba, baa, baa), but only 2 of them (aba and aba) don't have the same letter (in this case a) repeating.

Более подробно о первом варианте решения, можно прочитать здесь! macengr.wordpress.com



function permAlone(str) {
 
  if(str.length===0){
    return 1;
  }
   var amount=0;
  for(var i = 0; i < str.length; i++){
    if(str[i]!== arguments[1]){
      amount +=permAlone(str.substring(0,i)+str.substring(i+1),str[i]);
      
    }
  }
  return amount;
}

permAlone('aab');



Using a Heap Algorithm to generate all permutations


function permAlone(str) {
  
  var arr = str.split('');
  var permutations = [];
  var regex = /(.)\1+/g;
  
  function swap(index1, index2) {
    var aux = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = aux;
  }
  
  function generate(int) {
    if (int === 1) {
      permutations.push(arr.join(''));
    } else {
      for (var i = 0; i < int - 1; i++) {
        generate(int - 1);
        if (int % 2 === 0) {
          swap(i, int-1);
        } else {
          swap(0, int-1);
        }
      }
      generate(int - 1);
    }  
  }      
  
  generate(arr.length);
  
  var filtered = permutations.filter(function(string) {
    return !string.match(regex);
  });
  
  return filtered.length;

Ответы:

permAlone("aab")
return a number.

permAlone("aab")
return 2.

permAlone("aaa")
return 0.

permAlone("aabb")
return 8.

permAlone("abcdefa")
return 3600.

permAlone("abfdefa")
return 2640.

permAlone("zzzzzzzz")
return 0.

permAlone("a")
return 1.

permAlone("aaab")
return 0.

permAlone("aaabb")
return 12.


Комментариев нет:

Отправить комментарий