shuffle within button groups too

This commit is contained in:
Rhiannon Morris 2024-09-27 18:01:29 +02:00
parent 76f7d7c76f
commit 0f6345d66f

View file

@ -1,3 +1,18 @@
function shuffle<A>(subject: A[]): A[] {
let res = Array.from(subject);
for (let i = 0; i < res.length - 1; ++i) {
const j = i + Math.floor(Math.random() * (res.length - i));
if (i != j) {
const k = res[i]!;
res[i] = res[j]!;
res[j] = k;
}
}
return res;
}
function group<A>(subject: A[], keepTogether: A[][]): A[][] { function group<A>(subject: A[], keepTogether: A[][]): A[][] {
type Value = {array: A[], added: boolean}; type Value = {array: A[], added: boolean};
@ -14,7 +29,7 @@ function group<A>(subject: A[], keepTogether: A[][]): A[][] {
if (group?.added) { continue; } if (group?.added) { continue; }
else if (group) { else if (group) {
group.added = true; group.added = true;
res.push(group.array); res.push(shuffle(group.array));
} else { } else {
res.push([x]); res.push([x]);
} }
@ -23,24 +38,8 @@ function group<A>(subject: A[], keepTogether: A[][]): A[][] {
return res; return res;
} }
function shuffle<A>(subject: A[]): A[] {
let res = Array.from(subject);
for (let i = 0; i < res.length - 2; ++i) {
const j = i + Math.floor(Math.random() * (res.length - i));
if (i != j) {
const k = res[i]!;
res[i] = res[j]!;
res[j] = k;
}
}
return res;
}
function groupedShuffle<A>(subject: A[], keepTogether: A[][]): A[] { function groupedShuffle<A>(subject: A[], keepTogether: A[][]): A[] {
let groups = group(subject, keepTogether); return shuffle(group(subject, keepTogether)).flat();
return shuffle(groups).flat();
} }
function shuffleAll() { function shuffleAll() {