Quick actions

cmd+k|ctrl+k

Navigation

Languages

Permutation - toutes combinaisons

Snippet info

Language

JavaScript

Visibility

public

Author

bertrand

Created

2019-08-28T21:42:15Z

Updated

2019-08-28T21:50:13Z

// code qui donne toutes les combinaisons d’une chaîne de caractères 

// programme principal, initialisation de la variable globale et tri en ordre alphabétique
let soluce = [];
console.log(permutations("dojo").sort());

function permutations(string) {
  let tab = string.split(''); 
  soluce = [];
  anagramme(tab, 0);
  return doublonsEnMoins(soluce);
}

function pivot(tableau, i){
	let tampon = tableau[i];
	for(let j=i;j < tableau.length-1;j++) {
		tableau[j] = tableau[j+1];
	}
	tableau[tableau.length-1] = tampon;
	return tableau;
}

function anagramme(tableau, first) {
	if ((tableau.length - first) <= 1) {
		soluce.push(tableau.join(''));
	} else {
		for (let i = 0; i < tableau.length-first ; i++) {
			anagramme(pivot(tableau, first), first+1);
		}
	}
}

function doublonsEnMoins(tableau) {
  let i, j, len = tableau.length, out = [], obj = {};
  for (i = 0; i < len; i++) {
    obj[tableau[i]] = 0;
  }
  for (j in obj) {
    out.push(j);
  }
  return out;
}
INFO