Merge pull request #719 from MrDoomy/feat/shuffle-algorithm

Added Fisher Yates Algorithm
This commit is contained in:
Omkarnath Parida
2021-10-03 20:15:07 +05:30
committed by GitHub
2 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,18 @@
export const shuffle = (array) => {
let maxLength = array.length
let temp
let idx
// While there remain elements to shuffle...
while (maxLength) {
// Pick a remaining element...
idx = Math.floor(Math.random() * maxLength--)
// And swap it with the current element
temp = array[maxLength]
array[maxLength] = array[idx]
array[idx] = temp
}
return array
}

View File

@ -0,0 +1,27 @@
import { shuffle } from '../FisherYatesShuffle'
describe('shuffle', () => {
it('expects to have a new array with same size', () => {
const fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
const mixedArray = shuffle(fibonacci)
expect(mixedArray).toHaveLength(fibonacci.length)
})
it('expects to have a new array with same values', () => {
const fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
const mixedArray = shuffle(fibonacci)
expect(mixedArray).toContain(0)
expect(mixedArray).toContain(1)
expect(mixedArray).toContain(2)
expect(mixedArray).toContain(3)
expect(mixedArray).toContain(5)
expect(mixedArray).toContain(8)
expect(mixedArray).toContain(13)
expect(mixedArray).toContain(21)
expect(mixedArray).toContain(34)
expect(mixedArray).toContain(55)
expect(mixedArray).toContain(89)
})
})