mirror of
https://github.com/Xevion/100prisoners.git
synced 2025-12-17 08:11:10 -06:00
Smarter shuffling, stateful box count & memoize
This commit is contained in:
@@ -3,7 +3,7 @@ import BoxGraphic from "./BoxGraphic";
|
|||||||
import Xarrow from "react-xarrows";
|
import Xarrow from "react-xarrows";
|
||||||
|
|
||||||
import Chance from "chance";
|
import Chance from "chance";
|
||||||
import {useState} from "react";
|
import {useMemo, useState} from "react";
|
||||||
|
|
||||||
const chance = new Chance();
|
const chance = new Chance();
|
||||||
const colors = [
|
const colors = [
|
||||||
@@ -26,11 +26,23 @@ const colors = [
|
|||||||
"#F43F5E",
|
"#F43F5E",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
const smartShuffle = (n: number[]): number[] => {
|
||||||
|
let shuffled: number[] | null = null;
|
||||||
|
while (shuffled == null || shuffled.some((v, i) => v == i + 1)) {
|
||||||
|
shuffled = chance.shuffle(n)
|
||||||
|
}
|
||||||
|
return shuffled;
|
||||||
|
}
|
||||||
|
|
||||||
const BoxTable = () => {
|
const BoxTable = () => {
|
||||||
const [sources] = useState<number[]>(range(1, 100));
|
const [count, setCount] = useState<number>(100);
|
||||||
const [destinations] = useState<number[]>(chance.shuffle(sources));
|
const {sources, boxes, boxesBySource} = useMemo(() => {
|
||||||
const [boxes] = useState<[number, number][]>(sources.map((e, i) => [e, destinations[i] as number]))
|
const sources: number[] = range(1, count);
|
||||||
const [boxesBySource] = useState<Record<number, number>>(Object.fromEntries(boxes));
|
const destinations: number[] = smartShuffle(sources);
|
||||||
|
const boxes: [number, number][] = sources.map((e, i) => [e, destinations[i] as number]);
|
||||||
|
const boxesBySource: Record<number, number> = Object.fromEntries(boxes);
|
||||||
|
return {sources, destinations, boxes, boxesBySource};
|
||||||
|
}, [count])
|
||||||
|
|
||||||
const extractLoop = (start: number): number[] => {
|
const extractLoop = (start: number): number[] => {
|
||||||
const results: number[] = [];
|
const results: number[] = [];
|
||||||
|
|||||||
Reference in New Issue
Block a user