Skip to content

Commit 21221c4

Browse files
committed
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
1 parent 5c39e87 commit 21221c4

2 files changed

Lines changed: 7 additions & 7 deletions

File tree

Conversions/RgbHslConversion.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ const rgbToHsl = (colorRgb) => {
2222
throw new Error('Input is not a valid RGB color.')
2323
}
2424

25-
let colorHsl = colorRgb
25+
// Work on a copy so the caller's RGB array is not mutated
26+
let colorHsl = colorRgb.slice()
2627

2728
let red = Math.round(colorRgb[0])
2829
let green = Math.round(colorRgb[1])

Sorts/BogoSort.js

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,13 @@ export function isSorted(array) {
1212
}
1313

1414
/**
15-
* Shuffles the given array randomly in place.
15+
* Unbiased Fisher–Yates shuffle of the given array in place.
16+
* Each permutation is equally likely.
1617
*/
1718
function shuffle(array) {
18-
for (let i = array.length - 1; i; i--) {
19-
const m = Math.floor(Math.random() * i)
20-
const n = array[i - 1]
21-
array[i - 1] = array[m]
22-
array[m] = n
19+
for (let i = array.length - 1; i > 0; i--) {
20+
const j = Math.floor(Math.random() * (i + 1))
21+
;[array[i], array[j]] = [array[j], array[i]]
2322
}
2423
}
2524

0 commit comments

Comments
 (0)