Refactor Neighbor Sum Avoidance interactive

This commit is contained in:
gpt-engineer-app[bot] 2025-09-30 19:34:48 +00:00
parent 10fec3a3f6
commit 2f7212587a

View file

@ -3,6 +3,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch'; import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { Slider } from '@/components/ui/slider';
import { Timer, RotateCcw } from 'lucide-react'; import { Timer, RotateCcw } from 'lucide-react';
import confetti from 'canvas-confetti'; import confetti from 'canvas-confetti';
import { toast } from 'sonner'; import { toast } from 'sonner';
@ -15,15 +16,18 @@ interface NeighborSumAvoidanceProps {
const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceProps) => { const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceProps) => {
const [mode, setMode] = useState<'default' | 'guided'>('default'); const [mode, setMode] = useState<'default' | 'guided'>('default');
const [isActive, setIsActive] = useState(false); const [isActive, setIsActive] = useState(false);
const [numberCount, setNumberCount] = useState(9);
const [slots, setSlots] = useState<(number | null)[]>(Array(9).fill(null)); const [slots, setSlots] = useState<(number | null)[]>(Array(9).fill(null));
const [availableNumbers, setAvailableNumbers] = useState<number[]>([1, 2, 3, 4, 5, 6, 7, 8, 9]); const [availableNumbers, setAvailableNumbers] = useState<number[]>([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const [draggedNumber, setDraggedNumber] = useState<number | null>(null); const [draggedNumber, setDraggedNumber] = useState<number | null>(null);
const [draggedFrom, setDraggedFrom] = useState<number | null>(null); const [draggedFrom, setDraggedFrom] = useState<number | null>(null);
const [draggedSlot, setDraggedSlot] = useState<number | null>(null); const [draggedSlot, setDraggedSlot] = useState<number | null>(null);
const [dragPosition, setDragPosition] = useState<{ x: number; y: number } | null>(null);
const [time, setTime] = useState(0); const [time, setTime] = useState(0);
const [swaps, setSwaps] = useState(0); const [swaps, setSwaps] = useState(0);
const [isComplete, setIsComplete] = useState(false); const [isComplete, setIsComplete] = useState(false);
const timerRef = useRef<NodeJS.Timeout | null>(null); const timerRef = useRef<NodeJS.Timeout | null>(null);
const svgRef = useRef<SVGSVGElement>(null);
useEffect(() => { useEffect(() => {
if (isActive && !isComplete) { if (isActive && !isComplete) {
@ -87,11 +91,11 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
setIsComplete(false); setIsComplete(false);
if (selectedMode === 'default') { if (selectedMode === 'default') {
setSlots(Array(9).fill(null)); setSlots(Array(numberCount).fill(null));
setAvailableNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9]); setAvailableNumbers(Array.from({ length: numberCount }, (_, i) => i + 1));
} else { } else {
// Guided mode: random arrangement // Guided mode: random arrangement
const shuffled = [...Array(9)].map((_, i) => i + 1).sort(() => Math.random() - 0.5); const shuffled = Array.from({ length: numberCount }, (_, i) => i + 1).sort(() => Math.random() - 0.5);
setSlots(shuffled); setSlots(shuffled);
setAvailableNumbers([]); setAvailableNumbers([]);
} }
@ -100,15 +104,37 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
const restart = () => { const restart = () => {
setIsActive(false); setIsActive(false);
setIsComplete(false); setIsComplete(false);
setSlots(Array(9).fill(null)); setSlots(Array(numberCount).fill(null));
setAvailableNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9]); setAvailableNumbers(Array.from({ length: numberCount }, (_, i) => i + 1));
setTime(0); setTime(0);
setSwaps(0); setSwaps(0);
setDragPosition(null);
}; };
const handleDragStart = (num: number, fromSlot: number | null) => { const handleDragStart = (num: number, fromSlot: number | null, e?: React.MouseEvent) => {
setDraggedNumber(num); setDraggedNumber(num);
setDraggedFrom(fromSlot); setDraggedFrom(fromSlot);
if (e && mode === 'guided') {
e.preventDefault();
}
};
const handleMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
if (mode === 'guided' && draggedNumber !== null && svgRef.current) {
const rect = svgRef.current.getBoundingClientRect();
setDragPosition({
x: e.clientX - rect.left,
y: e.clientY - rect.top
});
}
};
const handleMouseUp = () => {
if (mode === 'guided') {
setDraggedNumber(null);
setDraggedFrom(null);
setDragPosition(null);
}
}; };
const handleDrop = (toSlot: number) => { const handleDrop = (toSlot: number) => {
@ -134,6 +160,7 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
setDraggedNumber(null); setDraggedNumber(null);
setDraggedFrom(null); setDraggedFrom(null);
setDragPosition(null);
}; };
const handleSlotClick = (slotIndex: number) => { const handleSlotClick = (slotIndex: number) => {
@ -145,24 +172,17 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
newSlots[slotIndex] = null; newSlots[slotIndex] = null;
setSlots(newSlots); setSlots(newSlots);
} }
} else if (mode === 'guided') {
// Swap in guided mode
if (draggedSlot === null) {
setDraggedSlot(slotIndex);
} else if (draggedSlot !== slotIndex) {
const newSlots = [...slots];
const temp = newSlots[slotIndex];
newSlots[slotIndex] = newSlots[draggedSlot];
newSlots[draggedSlot] = temp;
setSlots(newSlots);
setSwaps(s => s + 1);
setDraggedSlot(null);
} else {
setDraggedSlot(null);
}
} }
}; };
const getSlotPosition = (index: number, radius: number, centerX: number, centerY: number) => {
const angle = (index * 360 / slots.length - 90) * Math.PI / 180;
return {
x: centerX + radius * Math.cos(angle),
y: centerY + radius * Math.sin(angle)
};
};
const renderCircle = () => { const renderCircle = () => {
const radius = 150; const radius = 150;
const centerX = 200; const centerX = 200;
@ -170,14 +190,21 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
const violations = getViolations(); const violations = getViolations();
return ( return (
<svg width="400" height="400" className="mx-auto"> <svg
ref={svgRef}
width="400"
height="400"
className="mx-auto"
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
>
{/* Draw circle */} {/* Draw circle */}
<circle cx={centerX} cy={centerY} r={radius} fill="none" stroke="hsl(var(--border))" strokeWidth="2" /> <circle cx={centerX} cy={centerY} r={radius} fill="none" stroke="hsl(var(--border))" strokeWidth="2" />
{/* Draw violation arcs */} {/* Draw violation arcs */}
{violations.map(i => { {violations.map(i => {
const angle1 = (i * 360 / 9 - 90) * Math.PI / 180; const angle1 = (i * 360 / slots.length - 90) * Math.PI / 180;
const angle2 = ((i + 1) * 360 / 9 - 90) * Math.PI / 180; const angle2 = ((i + 1) * 360 / slots.length - 90) * Math.PI / 180;
const x1 = centerX + radius * Math.cos(angle1); const x1 = centerX + radius * Math.cos(angle1);
const y1 = centerY + radius * Math.sin(angle1); const y1 = centerY + radius * Math.sin(angle1);
const x2 = centerX + radius * Math.cos(angle2); const x2 = centerX + radius * Math.cos(angle2);
@ -196,26 +223,28 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
{/* Draw edges in guided mode */} {/* Draw edges in guided mode */}
{mode === 'guided' && slots.every(s => s !== null) && slots.map((num1, i) => { {mode === 'guided' && slots.every(s => s !== null) && slots.map((num1, i) => {
// Skip if this slot is being dragged
if (draggedFrom === i) return null;
return slots.slice(i + 1).map((num2, j) => { return slots.slice(i + 1).map((num2, j) => {
const idx2 = i + j + 1; const idx2 = i + j + 1;
// Skip if the other slot is being dragged
if (draggedFrom === idx2) return null;
if (num1 !== null && num2 !== null && !isDivisible(num1, num2)) { if (num1 !== null && num2 !== null && !isDivisible(num1, num2)) {
const angle1 = (i * 360 / 9 - 90) * Math.PI / 180; const pos1 = getSlotPosition(i, radius, centerX, centerY);
const angle2 = (idx2 * 360 / 9 - 90) * Math.PI / 180; const pos2 = getSlotPosition(idx2, radius, centerX, centerY);
const x1 = centerX + radius * Math.cos(angle1);
const y1 = centerY + radius * Math.sin(angle1);
const x2 = centerX + radius * Math.cos(angle2);
const y2 = centerY + radius * Math.sin(angle2);
// Check if this forms part of the cycle (adjacent positions on circle) // Check if this forms part of the cycle (adjacent positions on circle)
const isAdjacentOnCircle = Math.abs(i - idx2) === 1 || Math.abs(i - idx2) === 8; const isAdjacentOnCircle = Math.abs(i - idx2) === 1 || Math.abs(i - idx2) === slots.length - 1;
return ( return (
<line <line
key={`${i}-${idx2}`} key={`${i}-${idx2}`}
x1={x1} x1={pos1.x}
y1={y1} y1={pos1.y}
x2={x2} x2={pos2.x}
y2={y2} y2={pos2.y}
stroke={isAdjacentOnCircle ? "hsl(var(--primary))" : "hsl(var(--muted-foreground))"} stroke={isAdjacentOnCircle ? "hsl(var(--primary))" : "hsl(var(--muted-foreground))"}
strokeWidth={isAdjacentOnCircle ? "2" : "1"} strokeWidth={isAdjacentOnCircle ? "2" : "1"}
opacity={isAdjacentOnCircle ? "0.8" : "0.3"} opacity={isAdjacentOnCircle ? "0.8" : "0.3"}
@ -226,36 +255,60 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
}); });
})} })}
{/* Draw slots */} {/* Draw edges from dragged slot */}
{slots.map((num, i) => { {mode === 'guided' && draggedFrom !== null && dragPosition && slots.map((num, i) => {
const angle = (i * 360 / 9 - 90) * Math.PI / 180; if (i === draggedFrom) return null;
const x = centerX + radius * Math.cos(angle); const draggedNum = slots[draggedFrom];
const y = centerY + radius * Math.sin(angle); if (draggedNum !== null && num !== null && !isDivisible(draggedNum, num)) {
const pos = getSlotPosition(i, radius, centerX, centerY);
const isAdjacentOnCircle = Math.abs(draggedFrom - i) === 1 || Math.abs(draggedFrom - i) === slots.length - 1;
const isSelected = mode === 'guided' && draggedSlot === i; return (
<line
key={`drag-${i}`}
x1={dragPosition.x}
y1={dragPosition.y}
x2={pos.x}
y2={pos.y}
stroke={isAdjacentOnCircle ? "hsl(var(--primary))" : "hsl(var(--muted-foreground))"}
strokeWidth={isAdjacentOnCircle ? "2" : "1"}
opacity={isAdjacentOnCircle ? "0.8" : "0.3"}
/>
);
}
return null;
})}
{/* Draw slots (non-dragged) */}
{slots.map((num, i) => {
// Skip rendering if this is being dragged
if (mode === 'guided' && draggedFrom === i) return null;
const pos = getSlotPosition(i, radius, centerX, centerY);
return ( return (
<g key={i}> <g key={i}>
<circle <circle
cx={x} cx={pos.x}
cy={y} cy={pos.y}
r="25" r="25"
fill={isSelected ? "hsl(var(--primary))" : "hsl(var(--background))"} fill="hsl(var(--background))"
stroke={isSelected ? "hsl(var(--primary))" : "hsl(var(--border))"} stroke="hsl(var(--border))"
strokeWidth="2" strokeWidth="2"
onDragOver={(e) => e.preventDefault()} onDragOver={(e) => e.preventDefault()}
onDrop={() => handleDrop(i)} onDrop={() => handleDrop(i)}
onMouseDown={(e) => mode === 'guided' && num !== null && handleDragStart(num, i, e as any)}
onClick={() => handleSlotClick(i)} onClick={() => handleSlotClick(i)}
className="cursor-pointer" className="cursor-pointer"
/> />
{num !== null && ( {num !== null && (
<text <text
x={x} x={pos.x}
y={y} y={pos.y}
textAnchor="middle" textAnchor="middle"
dominantBaseline="middle" dominantBaseline="middle"
className="text-xl font-bold select-none pointer-events-none" className="text-xl font-bold select-none pointer-events-none"
fill={isSelected ? "hsl(var(--primary-foreground))" : "hsl(var(--foreground))"} fill="hsl(var(--foreground))"
> >
{num} {num}
</text> </text>
@ -263,6 +316,31 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
</g> </g>
); );
})} })}
{/* Draw dragged slot */}
{mode === 'guided' && draggedFrom !== null && dragPosition && (
<g>
<circle
cx={dragPosition.x}
cy={dragPosition.y}
r="25"
fill="hsl(var(--primary))"
stroke="hsl(var(--primary))"
strokeWidth="2"
opacity="0.8"
/>
<text
x={dragPosition.x}
y={dragPosition.y}
textAnchor="middle"
dominantBaseline="middle"
className="text-xl font-bold select-none pointer-events-none"
fill="hsl(var(--primary-foreground))"
>
{slots[draggedFrom]}
</text>
</g>
)}
</svg> </svg>
); );
}; };
@ -273,7 +351,7 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
<CardHeader> <CardHeader>
<CardTitle>Neighbor Sum Avoidance</CardTitle> <CardTitle>Neighbor Sum Avoidance</CardTitle>
<CardDescription> <CardDescription>
Can you arrange the numbers 1-9 in a circle so that the sum of two neighbors is never divisible by 3, 5, or 7? Can you arrange the numbers 1-{numberCount} in a circle so that the sum of two neighbors is never divisible by 3, 5, or 7?
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-6"> <CardContent className="space-y-6">
@ -289,6 +367,21 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
<Label htmlFor="mode-switch">Guided Mode</Label> <Label htmlFor="mode-switch">Guided Mode</Label>
</div> </div>
<div className="space-y-4">
<div className="flex items-center gap-4">
<Label className="whitespace-nowrap">Number of items:</Label>
<Slider
value={[numberCount]}
onValueChange={(value) => setNumberCount(value[0])}
min={5}
max={15}
step={1}
className="flex-1"
/>
<span className="font-mono w-8 text-center">{numberCount}</span>
</div>
</div>
<div className="space-y-4 text-center"> <div className="space-y-4 text-center">
<div className="text-sm text-muted-foreground space-y-2"> <div className="text-sm text-muted-foreground space-y-2">
{mode === 'default' ? ( {mode === 'default' ? (
@ -300,7 +393,7 @@ const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceP
) : ( ) : (
<> <>
<p>Numbers are connected by edges if their sum is NOT divisible by 3, 5, or 7.</p> <p>Numbers are connected by edges if their sum is NOT divisible by 3, 5, or 7.</p>
<p>Click two slots to swap their numbers and form a cycle on the circle's edge.</p> <p>Drag circles to move numbers and form a cycle on the circle's edge.</p>
</> </>
)} )}
</div> </div>