From 98d809cab73e2b35683392e90dcc5d213e7bdbd5 Mon Sep 17 00:00:00 2001 From: Divyansh Seth Date: Tue, 28 May 2024 16:29:32 +0530 Subject: [PATCH] deck: used fisher-yates algorithm to shuffle deck array --- backend/uno-game-engine/deck.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/backend/uno-game-engine/deck.ts b/backend/uno-game-engine/deck.ts index 9e113f5..068916b 100644 --- a/backend/uno-game-engine/deck.ts +++ b/backend/uno-game-engine/deck.ts @@ -55,7 +55,11 @@ export function getShuffledCardDeck(): Array { * Helper function to make a card object. * @returns {UNOCard} The composed UNO card. */ -export function makeCard(type: CardType, color: CardColor, value: CardValue): UNOCard { +export function makeCard( + type: CardType, + color: CardColor, + value: CardValue +): UNOCard { //todo: Implement unique identification of cards by assigning an id to each card return { type, color, value, id: undefined }; } @@ -64,7 +68,10 @@ export function makeCard(type: CardType, color: CardColor, value: CardValue): UN * This function shuffles the elements of the given array *in place* . The function behaves in a type-agnostic way. * Time complexity: O(n) */ -export function shuffle(deck: Array) { - //todo: Implement a generic shuffling algorithm - [deck[0], deck[1]] = [deck[1], deck[0]]; +function shuffle(deck: Array) { + // Fisher-Yates shuffle algorithm to shuffle card deck + for (let i = deck.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * i); + [deck[i], deck[j]] = [deck[j], deck[i]]; + } }