Skip to content

Commit 70b2541

Browse files
committed
algos de permutations et combinaisons dans le tools.js
1 parent e4a80ed commit 70b2541

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

TOOLS/NodeJS/src/tools.js

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,4 +91,51 @@ export const substractTwoArrsMinZero = (arr1, arr2) => operateTwoArrs(arr1, arr2
9191
export const divideTwoArrsFloor = (arr1, arr2) => operateTwoArrs(arr1, arr2, (a,b) => Math.floor(a/b));
9292

9393
export const smallestInArr = arr => Math.floor(arr.sort(sortAsc)[0]);
94-
export const biggestInArr = arr => Math.floor(arr.sort(sortDesc)[0]);
94+
export const biggestInArr = arr => Math.floor(arr.sort(sortDesc)[0]);
95+
96+
// http://homepage.math.uiowa.edu/~goodman/22m150.dir/2007/Permutation%20Generation%20Methods.pdf Heap method
97+
export function permutations(permutation) {
98+
var length = permutation.length,
99+
result = [permutation.slice()],
100+
c = new Array(length).fill(0),
101+
i = 1, k, p;
102+
103+
while (i < length) {
104+
if (c[i] < i) {
105+
k = i % 2 && c[i];
106+
p = permutation[i];
107+
permutation[i] = permutation[k];
108+
permutation[k] = p;
109+
++c[i];
110+
i = 1;
111+
result.push(permutation.slice());
112+
} else {
113+
c[i] = 0;
114+
++i;
115+
}
116+
}
117+
return result;
118+
}
119+
120+
function genererCombinaisons(tableau, tailleMin=0, tailleMax=tableau.length) {
121+
let combinaisons = [];
122+
for(let i = 0; i < 2**tableau.length; i++)
123+
{
124+
let combinaison = [];
125+
let mask = i;
126+
let nombresDeUn = i.toString(2).split`1`.length - 1;
127+
if( nombresDeUn >= tailleMin && nombresDeUn <= tailleMax )
128+
{
129+
for(let j = 0; j < tableau.length; j++)
130+
{
131+
if(mask & 1)
132+
{
133+
combinaison.push(tableau[j]);
134+
}
135+
mask = mask >> 1;
136+
}
137+
combinaisons.push(combinaison);
138+
}
139+
}
140+
return combinaisons;
141+
}

0 commit comments

Comments
 (0)