Add combinations.

This commit is contained in:
Oleksii Trekhleb
2018-04-23 09:38:46 +03:00
parent 0af06d601b
commit cb14892e4e
16 changed files with 277 additions and 251 deletions

View File

@@ -1,55 +0,0 @@
# Combinations
When the order doesn't matter, it is a **Combination**.
When the order **does** matter it is a **Permutation**.
**"My fruit salad is a combination of apples, grapes and bananas"**
We don't care what order the fruits are in, they could also be
"bananas, grapes and apples" or "grapes, apples and bananas",
its the same fruit salad.
## Combinations without repetitions
This is how lotteries work. The numbers are drawn one at a
time, and if we have the lucky numbers (no matter what order)
we win!
No Repetition: such as lottery numbers `(2,14,15,27,30,33)`
**Number of combinations**
![Formula](https://www.mathsisfun.com/combinatorics/images/combinations-no-repeat.png)
where `n` is the number of things to choose from, and we choose `r` of them,
no repetition, order doesn't matter.
It is often called "n choose r" (such as "16 choose 3"). And is also known as the Binomial Coefficient.
## Combinations with repetitions
Repetition is Allowed: such as coins in your pocket `(5,5,5,10,10)`
Or let us say there are five flavours of icecream:
`banana`, `chocolate`, `lemon`, `strawberry` and `vanilla`.
We can have three scoops. How many variations will there be?
Let's use letters for the flavours: `{b, c, l, s, v}`.
Example selections include:
- `{c, c, c}` (3 scoops of chocolate)
- `{b, l, v}` (one each of banana, lemon and vanilla)
- `{b, v, v}` (one of banana, two of vanilla)
**Number of combinations**
![Formula](https://www.mathsisfun.com/combinatorics/images/combinations-repeat.gif)
Where `n` is the number of things to choose from, and we
choose `r` of them. Repetition allowed,
order doesn't matter.
## References
[Math Is Fun](https://www.mathsisfun.com/combinatorics/combinations-permutations.html)

View File

@@ -1,59 +0,0 @@
import combineWithRepetitions from '../combineWithRepetitions';
import factorial from '../../../math/factorial/factorial';
describe('combineWithRepetitions', () => {
it('should combine string with repetitions', () => {
expect(combineWithRepetitions(['A'], 1)).toEqual([
['A'],
]);
expect(combineWithRepetitions(['A', 'B'], 1)).toEqual([
['A'],
['B'],
]);
expect(combineWithRepetitions(['A', 'B'], 2)).toEqual([
['A', 'A'],
['A', 'B'],
['B', 'B'],
]);
expect(combineWithRepetitions(['A', 'B'], 3)).toEqual([
['A', 'A', 'A'],
['A', 'A', 'B'],
['A', 'B', 'B'],
['B', 'B', 'B'],
]);
expect(combineWithRepetitions(['A', 'B', 'C'], 2)).toEqual([
['A', 'A'],
['A', 'B'],
['A', 'C'],
['B', 'B'],
['B', 'C'],
['C', 'C'],
]);
expect(combineWithRepetitions(['A', 'B', 'C'], 3)).toEqual([
['A', 'A', 'A'],
['A', 'A', 'B'],
['A', 'A', 'C'],
['A', 'B', 'B'],
['A', 'B', 'C'],
['A', 'C', 'C'],
['B', 'B', 'B'],
['B', 'B', 'C'],
['B', 'C', 'C'],
['C', 'C', 'C'],
]);
const combinationOptions = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
const combinationSlotsNumber = 4;
const combinations = combineWithRepetitions(combinationOptions, combinationSlotsNumber);
const n = combinationOptions.length;
const r = combinationSlotsNumber;
const expectedNumberOfCombinations = factorial((r + n) - 1) / (factorial(r) * factorial(n - 1));
expect(combinations.length).toBe(expectedNumberOfCombinations);
});
});

View File

@@ -1,40 +0,0 @@
import combineWithoutRepetitions from '../combineWithoutRepetitions';
import factorial from '../../../math/factorial/factorial';
describe('combineWithoutRepetitions', () => {
it('should combine string without repetitions', () => {
expect(combineWithoutRepetitions('AB', 3)).toEqual([]);
expect(combineWithoutRepetitions('AB', 1)).toEqual(['A', 'B']);
expect(combineWithoutRepetitions('A', 1)).toEqual(['A']);
expect(combineWithoutRepetitions('AB', 2)).toEqual(['AB']);
expect(combineWithoutRepetitions('ABC', 2)).toEqual(['AB', 'AC', 'BC']);
expect(combineWithoutRepetitions('ABC', 3)).toEqual(['ABC']);
expect(combineWithoutRepetitions('ABCD', 3)).toEqual([
'ABC',
'ABD',
'ACD',
'BCD',
]);
expect(combineWithoutRepetitions('ABCDE', 3)).toEqual([
'ABC',
'ABD',
'ABE',
'ACD',
'ACE',
'ADE',
'BCD',
'BCE',
'BDE',
'CDE',
]);
const combinationOptions = 'ABCDEFGH';
const combinationSlotsNumber = 4;
const combinations = combineWithoutRepetitions(combinationOptions, combinationSlotsNumber);
const n = combinationOptions.length;
const r = combinationSlotsNumber;
const expectedNumberOfCombinations = factorial(n) / (factorial(r) * factorial(n - r));
expect(combinations.length).toBe(expectedNumberOfCombinations);
});
});

View File

@@ -1,38 +0,0 @@
/**
* @param {*[]} combinationOptions
* @param {number} combinationLength
* @return {*[]}
*/
export default function combineWithRepetitions(combinationOptions, combinationLength) {
// If combination length equal to 0 then return empty combination.
if (combinationLength === 0) {
return [[]];
}
// If combination options are empty then return "no-combinations" array.
if (combinationOptions.length === 0) {
return [];
}
// Init combinations array.
const combos = [];
// Find all shorter combinations and attach head to each of those.
const headCombo = [combinationOptions[0]];
const shorterCombos = combineWithRepetitions(combinationOptions, combinationLength - 1);
for (let combinationIndex = 0; combinationIndex < shorterCombos.length; combinationIndex += 1) {
const combo = headCombo.concat(shorterCombos[combinationIndex]);
combos.push(combo);
}
// Let's shift head to the right and calculate all the rest combinations.
const combinationsWithoutHead = combineWithRepetitions(
combinationOptions.slice(1),
combinationLength,
);
// Join all combinations and return them.
return combos.concat(combinationsWithoutHead);
}

View File

@@ -1,67 +0,0 @@
/*
@see: https://stackoverflow.com/a/127898/7794070
Lets say your array of letters looks like this: "ABCDEFGH".
You have three indices (i, j, k) indicating which letters you
are going to use for the current word, You start with:
A B C D E F G H
^ ^ ^
i j k
First you vary k, so the next step looks like that:
A B C D E F G H
^ ^ ^
i j k
If you reached the end you go on and vary j and then k again.
A B C D E F G H
^ ^ ^
i j k
A B C D E F G H
^ ^ ^
i j k
Once you j reached G you start also to vary i.
A B C D E F G H
^ ^ ^
i j k
A B C D E F G H
^ ^ ^
i j k
...
*/
/**
* @param {string} combinationOptions
* @param {number} combinationLength
* @return {string[]}
*/
export default function combineWithoutRepetitions(combinationOptions, combinationLength) {
// If combination length is just 1 then return combinationOptions.
if (combinationLength === 1) {
return Array.from(combinationOptions);
}
// Init combinations array.
const combinations = [];
for (let i = 0; i <= (combinationOptions.length - combinationLength); i += 1) {
const smallerCombinations = combineWithoutRepetitions(
combinationOptions.substr(i + 1),
combinationLength - 1,
);
for (let j = 0; j < smallerCombinations.length; j += 1) {
combinations.push(combinationOptions[i] + smallerCombinations[j]);
}
}
// Return all calculated combinations.
return combinations;
}

View File

@@ -1,42 +0,0 @@
# Permutations
When the order doesn't matter, it is a **Combination**.
When the order **does** matter it is a **Permutation**.
**"The combination to the safe is 472"**. We do care about the order. `724` won't work, nor will `247`.
It has to be exactly `4-7-2`.
## Permutations without repetitions
A permutation, also called an “arrangement number” or “order”, is a rearrangement of
the elements of an ordered list `S` into a one-to-one correspondence with `S` itself.
Below are the permutations of string `ABC`.
`ABC ACB BAC BCA CBA CAB`
Or for example the first three people in a running race: you can't be first and second.
**Number of combinations**
```
n * (n-1) * (n -2) * ... * 1 = n!
```
## Permutations with repetitions
When repetition is allowed we have permutations with repetitions.
For example the the lock below: it could be `333`.
![Permutation Lock](https://www.mathsisfun.com/combinatorics/images/combination-lock.jpg)
**Number of combinations**
```
n * n * n ... (r times) = n^r
```
## References
[Math Is Fun](https://www.mathsisfun.com/combinatorics/combinations-permutations.html)

View File

@@ -1,53 +0,0 @@
import permutateWithRepetition from '../permutateWithRepetitions';
describe('permutateWithRepetition', () => {
it('should permutate string with repetition', () => {
const permutations0 = permutateWithRepetition('');
expect(permutations0).toEqual([]);
const permutations1 = permutateWithRepetition('A');
expect(permutations1).toEqual(['A']);
const permutations2 = permutateWithRepetition('AB');
expect(permutations2).toEqual([
'AA',
'AB',
'BA',
'BB',
]);
const permutations3 = permutateWithRepetition('ABC');
expect(permutations3).toEqual([
'AAA',
'AAB',
'AAC',
'ABA',
'ABB',
'ABC',
'ACA',
'ACB',
'ACC',
'BAA',
'BAB',
'BAC',
'BBA',
'BBB',
'BBC',
'BCA',
'BCB',
'BCC',
'CAA',
'CAB',
'CAC',
'CBA',
'CBB',
'CBC',
'CCA',
'CCB',
'CCC',
]);
const permutations4 = permutateWithRepetition('ABCD');
expect(permutations4.length).toBe(4 * 4 * 4 * 4);
});
});

View File

@@ -1,69 +0,0 @@
import permutateWithoutRepetitions from '../permutateWithoutRepetitions';
import factorial from '../../../math/factorial/factorial';
describe('permutateString', () => {
it('should permutate string', () => {
const permutations0 = permutateWithoutRepetitions('');
expect(permutations0).toEqual([]);
const permutations1 = permutateWithoutRepetitions('A');
expect(permutations1).toEqual(['A']);
const permutations2 = permutateWithoutRepetitions('AB');
expect(permutations2.length).toBe(2);
expect(permutations2).toEqual([
'BA',
'AB',
]);
const permutations6 = permutateWithoutRepetitions('AA');
expect(permutations6.length).toBe(2);
expect(permutations6).toEqual([
'AA',
'AA',
]);
const permutations3 = permutateWithoutRepetitions('ABC');
expect(permutations3.length).toBe(factorial(3));
expect(permutations3).toEqual([
'CBA',
'BCA',
'BAC',
'CAB',
'ACB',
'ABC',
]);
const permutations4 = permutateWithoutRepetitions('ABCD');
expect(permutations4.length).toBe(factorial(4));
expect(permutations4).toEqual([
'DCBA',
'CDBA',
'CBDA',
'CBAD',
'DBCA',
'BDCA',
'BCDA',
'BCAD',
'DBAC',
'BDAC',
'BADC',
'BACD',
'DCAB',
'CDAB',
'CADB',
'CABD',
'DACB',
'ADCB',
'ACDB',
'ACBD',
'DABC',
'ADBC',
'ABDC',
'ABCD',
]);
const permutations5 = permutateWithoutRepetitions('ABCDEF');
expect(permutations5.length).toBe(factorial(6));
});
});

View File

@@ -1,41 +0,0 @@
/**
* @param {string} str
* @return {string[]}
*/
export default function permutateWithRepetition(str) {
// There is no permutations for empty string.
if (!str || str.length === 0) {
return [];
}
// There is only one permutation for the 1-character string.
if (str.length === 1) {
return [str];
}
// Let's create initial set of permutations.
let previousPermutations = Array.from(str);
let currentPermutations = [];
let permutationSize = 1;
// While the size of each permutation is less then or equal to string length...
while (permutationSize < str.length) {
// Reset all current permutations.
currentPermutations = [];
for (let pemIndex = 0; pemIndex < previousPermutations.length; pemIndex += 1) {
for (let charIndex = 0; charIndex < str.length; charIndex += 1) {
const currentPermutation = previousPermutations[pemIndex] + str[charIndex];
currentPermutations.push(currentPermutation);
}
}
// Make current permutations to be the previous ones.
previousPermutations = currentPermutations.slice(0);
// Increase permutation size counter.
permutationSize += 1;
}
return currentPermutations;
}

View File

@@ -1,39 +0,0 @@
/**
* @param {string} str
* @return {string[]}
*/
export default function permutateWithoutRepetitions(str) {
if (str.length === 0) {
return [];
}
if (str.length === 1) {
return [str];
}
const permutations = [];
// Get all permutations of string of length (n - 1).
const previousString = str.substring(0, str.length - 1);
const previousPermutations = permutateWithoutRepetitions(previousString);
// Insert last character into every possible position of every previous permutation.
const lastCharacter = str.substring(str.length - 1);
for (
let permutationIndex = 0;
permutationIndex < previousPermutations.length;
permutationIndex += 1
) {
const currentPermutation = previousPermutations[permutationIndex];
// Insert strLastCharacter into every possible position of currentPermutation.
for (let positionIndex = 0; positionIndex <= currentPermutation.length; positionIndex += 1) {
const permutationPrefix = currentPermutation.substr(0, positionIndex);
const permutationSuffix = currentPermutation.substr(positionIndex);
permutations.push(permutationPrefix + lastCharacter + permutationSuffix);
}
}
return permutations;
}