Skip to content

Commit f1d257a

Browse files
committed
Added medium/permutation_step
1 parent dcc4a90 commit f1d257a

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

medium/permutation_step.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* Have the function permutationStep(num) take the num parameter being passed
3+
* and return the next number greater than num using the same digits. For
4+
* example: if num is 123 return 132, if it's 12453 return 12534. If a number
5+
* has no greater permutations, return -1 (ie. 999).
6+
*
7+
* https://www.coderbyte.com/results/bhanson:Permutation%20Step:JavaScript
8+
*
9+
* @param {number} num
10+
* @return {number}
11+
*/
12+
function permutationStep(num) {
13+
const permutations = Array.from(
14+
new Set( // use Set to filter for unique values
15+
permute(num.toString().split(''))
16+
.map(number => number.join(''))
17+
.map(Number)
18+
)
19+
);
20+
21+
permutations.sort((a, b) => a - b);
22+
23+
const largerPermutations = permutations.filter(
24+
permutation => permutation > num
25+
);
26+
27+
if (largerPermutations.length > 0) {
28+
return largerPermutations[0];
29+
}
30+
return -1;
31+
}
32+
33+
// https://en.wikipedia.org/wiki/Heap's_algorithm
34+
// Iterative
35+
function permute(arr) {
36+
let count = Array(arr.length).fill(0);
37+
38+
const results = [arr.slice()];
39+
40+
let i = 0;
41+
while (i < arr.length) {
42+
if (count[i] < i) {
43+
if (i % 2 === 0) {
44+
const temp = arr[0];
45+
arr[0] = arr[i];
46+
arr[i] = temp;
47+
} else {
48+
const temp = arr[count[i]];
49+
arr[count[i]] = arr[i];
50+
arr[i] = temp;
51+
}
52+
results.push(arr.slice());
53+
count[i]++;
54+
i = 0;
55+
} else {
56+
count[i] = 0;
57+
i++;
58+
}
59+
}
60+
return results;
61+
}
62+
63+
module.exports = permutationStep;

medium/permutation_step.test.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const permutationStep = require('./permutation_step');
2+
3+
describe('permutationStep()', () => {
4+
test('passes Coderbyte.com tests', () => {
5+
expect(permutationStep(11121)).toBe(11211);
6+
7+
expect(permutationStep(41352)).toBe(41523);
8+
9+
expect(permutationStep(456)).toBe(465);
10+
11+
expect(permutationStep(111)).toBe(-1);
12+
13+
expect(permutationStep(23514)).toBe(23541);
14+
15+
expect(permutationStep(897654321)).toBe(912345678);
16+
17+
expect(permutationStep(12)).toBe(21);
18+
19+
expect(permutationStep(9)).toBe(-1);
20+
21+
expect(permutationStep(44444444)).toBe(-1);
22+
23+
expect(permutationStep(76666666)).toBe(-1);
24+
});
25+
});

0 commit comments

Comments
 (0)