From 6b2840f579322309bdfd7695fae5012e48fb25e1 Mon Sep 17 00:00:00 2001 From: Damien Chazoule Date: Sun, 3 Oct 2021 15:40:45 +0200 Subject: [PATCH] Added Fisher Yates Algorithm --- Sorts/FisherYatesShuffle.js | 24 ++++++++++++++++++++++++ Sorts/test/FisherYatesShuffle.test.js | 27 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 Sorts/FisherYatesShuffle.js create mode 100644 Sorts/test/FisherYatesShuffle.test.js diff --git a/Sorts/FisherYatesShuffle.js b/Sorts/FisherYatesShuffle.js new file mode 100644 index 000000000..d15360eef --- /dev/null +++ b/Sorts/FisherYatesShuffle.js @@ -0,0 +1,24 @@ +export const shuffle = (array) => { + let maxLength = array.length, + temp, + 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 +} + +const array = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] +console.log('array', array) + +const mixedArray = shuffle(array) +console.log('mixedArray', mixedArray) diff --git a/Sorts/test/FisherYatesShuffle.test.js b/Sorts/test/FisherYatesShuffle.test.js new file mode 100644 index 000000000..9bdc7497b --- /dev/null +++ b/Sorts/test/FisherYatesShuffle.test.js @@ -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) + }) +})