From 21221c4efe422d1228a20d7259074f5854d63be0 Mon Sep 17 00:00:00 2001 From: Zeeshan Date: Sun, 2 Aug 2026 04:07:53 +0200 Subject: [PATCH] fix: unbiased Fisher-Yates in bogoSort; stop mutating RGB input - shuffle() used Math.random() * i and swapped with i-1, which is a biased shuffle that cannot produce all permutations. Use standard Fisher-Yates over [0, i]. - rgbToHsl aliased the input array and overwrote it with HSL values. Copy the input first so callers keep their RGB data. Fixes #1867 Fixes #1907 --- Conversions/RgbHslConversion.js | 3 ++- Sorts/BogoSort.js | 11 +++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Conversions/RgbHslConversion.js b/Conversions/RgbHslConversion.js index 7e014f1318..d09fc76531 100644 --- a/Conversions/RgbHslConversion.js +++ b/Conversions/RgbHslConversion.js @@ -22,7 +22,8 @@ const rgbToHsl = (colorRgb) => { throw new Error('Input is not a valid RGB color.') } - let colorHsl = colorRgb + // Work on a copy so the caller's RGB array is not mutated + let colorHsl = colorRgb.slice() let red = Math.round(colorRgb[0]) let green = Math.round(colorRgb[1]) diff --git a/Sorts/BogoSort.js b/Sorts/BogoSort.js index eeb4f7feeb..2b6652fed2 100644 --- a/Sorts/BogoSort.js +++ b/Sorts/BogoSort.js @@ -12,14 +12,13 @@ export function isSorted(array) { } /** - * Shuffles the given array randomly in place. + * Unbiased Fisher–Yates shuffle of the given array in place. + * Each permutation is equally likely. */ function shuffle(array) { - for (let i = array.length - 1; i; i--) { - const m = Math.floor(Math.random() * i) - const n = array[i - 1] - array[i - 1] = array[m] - array[m] = n + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)) + ;[array[i], array[j]] = [array[j], array[i]] } }