2024 shuffle
js
// 뒤에서부터 시작하면서 자리를 바꿀 유닛을 무작위로 구해서 교체하는 방식
const shuffle = (arr) => {
for (let unitIndex = arr.length - 1; unitIndex > 0; unitIndex--) {
const swapIndex = Math.round(Math.random() * unitIndex);
if (swapIndex === unitIndex) continue;
[arr[swapIndex], arr[unitIndex]] = [arr[unitIndex], arr[swapIndex]];
}
};
const arr = Array.from({ length: 10 }, (_, i) => i);
console.log(arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
shuffle(arr); // [7, 0, 5, 9, 1, 8, 6, 2, 4, 3]
shuffle.js
js
const compare = () => 0.5 - Math.random()
const shuffle = arr => arr.concat().sort(compare)
module.exports = shuffle
shuffle-2.js
js
const repeat = (arr, length) => {
return Array
.from({length}, () => arr)
.reduce((acc, arr) => acc.concat(arr))
}
const rand = () => Math.random() - .5
const stepper = (max) => {
let index = -1
return () => {
index = index == max ? 0 : index + 1
return index
}
}
const compare = (() => {
const dataset = repeat([-1, 0, 1], 3)
const next = stepper(dataset.length)
dataset.sort(rand)
return () => dataset[next()]
})()
const shuffle = arr => arr.slice().sort(compare)
module.exports = shuffle
shuffle-2-2.js
js
const repeat = (arr, length) => {
return Array
.from({length}, () => arr)
.reduce((acc, arr) => acc.concat(arr))
}
const rand = () => Math.random() - .5
const stepper = (max) => {
let index = -1
return () => {
index = index == max ? 0 : index + 1
return index
}
}
const compare = (() => {
const dataset = repeat([-1, 0, 1], 3)
const next = stepper(dataset.length)
dataset.sort(rand)
return () => dataset[next()]
})()
const shuffle = arr => arr.concat().sort(compare)
module.exports = shuffle
shuffle-3.js
js
const rand = () => Math.random() - .5 > 0 ? 1 : -1
const stepper = (max) => {
let index = -1
return () => {
index = index == max ? 0 : index + 1
return index
}
}
const compare = (() => {
const dataset = Array.from({length: 9}).map(rand)
const next = stepper(dataset.length)
return () => dataset[next()]
})()
const shuffle = arr => arr.slice().sort(compare)
module.exports = shuffle