Skip to content

Commit 6b2840f

Browse files
committed
Added Fisher Yates Algorithm
1 parent fb763c4 commit 6b2840f

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

Sorts/FisherYatesShuffle.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
export const shuffle = (array) => {
2+
let maxLength = array.length,
3+
temp,
4+
idx
5+
6+
// While there remain elements to shuffle...
7+
while (maxLength) {
8+
// Pick a remaining element...
9+
idx = Math.floor(Math.random() * maxLength--)
10+
11+
// And swap it with the current element
12+
temp = array[maxLength]
13+
array[maxLength] = array[idx]
14+
array[idx] = temp
15+
}
16+
17+
return array
18+
}
19+
20+
const array = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
21+
console.log('array', array)
22+
23+
const mixedArray = shuffle(array)
24+
console.log('mixedArray', mixedArray)

Sorts/test/FisherYatesShuffle.test.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { shuffle } from '../fisherYatesShuffle'
2+
3+
describe('shuffle', () => {
4+
it('expects to have a new array with same size', () => {
5+
const fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
6+
const mixedArray = shuffle(fibonacci)
7+
8+
expect(mixedArray).toHaveLength(fibonacci.length)
9+
})
10+
11+
it('expects to have a new array with same values', () => {
12+
const fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
13+
const mixedArray = shuffle(fibonacci)
14+
15+
expect(mixedArray).toContain(0)
16+
expect(mixedArray).toContain(1)
17+
expect(mixedArray).toContain(2)
18+
expect(mixedArray).toContain(3)
19+
expect(mixedArray).toContain(5)
20+
expect(mixedArray).toContain(8)
21+
expect(mixedArray).toContain(13)
22+
expect(mixedArray).toContain(21)
23+
expect(mixedArray).toContain(34)
24+
expect(mixedArray).toContain(55)
25+
expect(mixedArray).toContain(89)
26+
})
27+
})

0 commit comments

Comments
 (0)