我正在嘗試對一個陣列中的多個陣列進行排序(也必須對其進行洗牌)。一個簡化的例子是:
let toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
...
];
const shuffled = shuffle(toShuffle);
// outout would look something like:
// [
// [8, 6, 5, 7, 9],
// [4, 3, 1, 5, 2],
// [19, 26, 10, 67],
// ...
// ]
這需要靈活,因此具有任意數量值的任意數量的陣列都應該是有效的。
這是我嘗試過的:
function shuffle(a) {
for (let e in a) {
if (Array.isArray(a[e])) {
a[e] = shuffle(a[e]);
} else {
a.splice(e, 1);
a.splice(Math.floor(Math.random() * a.length), 0, a[e]);
}
}
return a;
}
console.log("Shuffled: " shuffle([
[1, 2, 3, 4, 5],
[5, 4, 3, 2, 1]
]))
但它沒有按預期作業。他們是更簡單的方法嗎?或者我的代碼是正確的,只是有問題。
uj5u.com熱心網友回復:
你幾乎明白了。問題是您要從陣列中洗掉一個專案,而不是捕獲已洗掉的專案并將它們放置在隨機位置:
let toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
];
function shuffle(a) {
a = [...a]; //clone array
for (let e in a) {
if (Array.isArray(a[e])) {
a[e] = shuffle(a[e]);
} else {
a.splice(~~(Math.random() * a.length), 0, a.splice(e, 1)[0]);
}
}
return a;
}
console.log(JSON.stringify(shuffle(toShuffle)))
console.log(JSON.stringify(toShuffle))
[編輯] 原始代碼沒有洗牌父陣列,如果你需要遞回洗牌一切,你可以使用這個:
let toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
];
function shuffle(a) {
a = a.map(i => Array.isArray(i) ? shuffle(i) : i); //clone array
a.sort(i => ~~(Math.random() * 2) - 1); //shuffle
return a;
}
console.log("shuffled", JSON.stringify(shuffle(toShuffle)))
console.log("original", JSON.stringify(toShuffle))
uj5u.com熱心網友回復:
您可以使用Array.from()創建一個新的淺拷貝array,然后將Array.prototype.sort()與Math.random( ) 結合使用
代碼:
const toShuffle = [
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[10, 67, 19 ,27]
]
const shuffle = a => Array.from(a).sort(() => .5 - Math.random())
const result = toShuffle.map(shuffle)
console.log('Shuffled:', JSON.stringify(result))
console.log('To shuffle:', JSON.stringify(toShuffle))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473545.html
標籤:javascript 数组 排序
