Add Neighbor Sum Avoidance interactive
This commit is contained in:
parent
e398e1e267
commit
10fec3a3f6
4 changed files with 495 additions and 5 deletions
|
|
@ -56,6 +56,7 @@ import SubtractionGamePage from './pages/SubtractionGamePage';
|
|||
import StackingBlocksPage from './pages/StackingBlocksPage';
|
||||
import ParityBitsGamePage from './pages/ParityBitsGamePage';
|
||||
import CrapsGamePage from './pages/CrapsGamePage';
|
||||
import NeighborSumAvoidancePage from './pages/NeighborSumAvoidancePage';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
|
|
@ -81,6 +82,7 @@ const App = () => (
|
|||
<Route path="/themes/discrete-math/structures" element={<Structures />} />
|
||||
<Route path="/themes/discrete-math/numbers" element={<Numbers />} />
|
||||
<Route path="/themes/discrete-math/graphs" element={<Graphs />} />
|
||||
<Route path="/themes/discrete-math/graphs/neighbor-sum-avoidance" element={<NeighborSumAvoidancePage />} />
|
||||
<Route path="/themes/social-choice" element={<SocialChoice />} />
|
||||
<Route path="/themes/advanced-algorithms" element={<AdvancedAlgorithms />} />
|
||||
<Route path="/themes/data-structures" element={<DataStructures />} />
|
||||
|
|
|
|||
373
src/components/NeighborSumAvoidance.tsx
Normal file
373
src/components/NeighborSumAvoidance.tsx
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Timer, RotateCcw } from 'lucide-react';
|
||||
import confetti from 'canvas-confetti';
|
||||
import { toast } from 'sonner';
|
||||
import SocialShare from '@/components/SocialShare';
|
||||
|
||||
interface NeighborSumAvoidanceProps {
|
||||
showSocialShare?: boolean;
|
||||
}
|
||||
|
||||
const NeighborSumAvoidance = ({ showSocialShare = false }: NeighborSumAvoidanceProps) => {
|
||||
const [mode, setMode] = useState<'default' | 'guided'>('default');
|
||||
const [isActive, setIsActive] = useState(false);
|
||||
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 [draggedNumber, setDraggedNumber] = useState<number | null>(null);
|
||||
const [draggedFrom, setDraggedFrom] = useState<number | null>(null);
|
||||
const [draggedSlot, setDraggedSlot] = useState<number | null>(null);
|
||||
const [time, setTime] = useState(0);
|
||||
const [swaps, setSwaps] = useState(0);
|
||||
const [isComplete, setIsComplete] = useState(false);
|
||||
const timerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isActive && !isComplete) {
|
||||
timerRef.current = setInterval(() => {
|
||||
setTime(t => t + 1);
|
||||
}, 1000);
|
||||
} else if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
}
|
||||
return () => {
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
};
|
||||
}, [isActive, isComplete]);
|
||||
|
||||
const isDivisible = (a: number, b: number) => {
|
||||
const sum = a + b;
|
||||
return sum % 3 === 0 || sum % 5 === 0 || sum % 7 === 0;
|
||||
};
|
||||
|
||||
const getViolations = () => {
|
||||
const violations: number[] = [];
|
||||
for (let i = 0; i < 9; i++) {
|
||||
const current = slots[i];
|
||||
const next = slots[(i + 1) % 9];
|
||||
if (current !== null && next !== null && isDivisible(current, next)) {
|
||||
violations.push(i);
|
||||
}
|
||||
}
|
||||
return violations;
|
||||
};
|
||||
|
||||
const checkWin = () => {
|
||||
if (slots.every(s => s !== null) && getViolations().length === 0) {
|
||||
setIsComplete(true);
|
||||
confetti({
|
||||
particleCount: 100,
|
||||
spread: 70,
|
||||
origin: { y: 0.6 }
|
||||
});
|
||||
toast.success(`Congratulations! Completed in ${formatTime(time)}${mode === 'guided' ? ` with ${swaps} swaps` : ''}!`);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (isActive) {
|
||||
checkWin();
|
||||
}
|
||||
}, [slots, isActive]);
|
||||
|
||||
const formatTime = (seconds: number) => {
|
||||
const mins = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
return `${mins}:${secs.toString().padStart(2, '0')}`;
|
||||
};
|
||||
|
||||
const startGame = (selectedMode: 'default' | 'guided') => {
|
||||
setMode(selectedMode);
|
||||
setIsActive(true);
|
||||
setTime(0);
|
||||
setSwaps(0);
|
||||
setIsComplete(false);
|
||||
|
||||
if (selectedMode === 'default') {
|
||||
setSlots(Array(9).fill(null));
|
||||
setAvailableNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
} else {
|
||||
// Guided mode: random arrangement
|
||||
const shuffled = [...Array(9)].map((_, i) => i + 1).sort(() => Math.random() - 0.5);
|
||||
setSlots(shuffled);
|
||||
setAvailableNumbers([]);
|
||||
}
|
||||
};
|
||||
|
||||
const restart = () => {
|
||||
setIsActive(false);
|
||||
setIsComplete(false);
|
||||
setSlots(Array(9).fill(null));
|
||||
setAvailableNumbers([1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
setTime(0);
|
||||
setSwaps(0);
|
||||
};
|
||||
|
||||
const handleDragStart = (num: number, fromSlot: number | null) => {
|
||||
setDraggedNumber(num);
|
||||
setDraggedFrom(fromSlot);
|
||||
};
|
||||
|
||||
const handleDrop = (toSlot: number) => {
|
||||
if (draggedNumber === null) return;
|
||||
|
||||
if (mode === 'default') {
|
||||
// Default mode: place number in slot
|
||||
const newSlots = [...slots];
|
||||
newSlots[toSlot] = draggedNumber;
|
||||
setSlots(newSlots);
|
||||
setAvailableNumbers(availableNumbers.filter(n => n !== draggedNumber));
|
||||
} else {
|
||||
// Guided mode: swap numbers
|
||||
if (draggedFrom !== null && draggedFrom !== toSlot) {
|
||||
const newSlots = [...slots];
|
||||
const temp = newSlots[toSlot];
|
||||
newSlots[toSlot] = newSlots[draggedFrom];
|
||||
newSlots[draggedFrom] = temp;
|
||||
setSlots(newSlots);
|
||||
setSwaps(s => s + 1);
|
||||
}
|
||||
}
|
||||
|
||||
setDraggedNumber(null);
|
||||
setDraggedFrom(null);
|
||||
};
|
||||
|
||||
const handleSlotClick = (slotIndex: number) => {
|
||||
if (mode === 'default') {
|
||||
// Remove from slot in default mode
|
||||
if (slots[slotIndex] !== null) {
|
||||
setAvailableNumbers([...availableNumbers, slots[slotIndex]!].sort((a, b) => a - b));
|
||||
const newSlots = [...slots];
|
||||
newSlots[slotIndex] = null;
|
||||
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 renderCircle = () => {
|
||||
const radius = 150;
|
||||
const centerX = 200;
|
||||
const centerY = 200;
|
||||
const violations = getViolations();
|
||||
|
||||
return (
|
||||
<svg width="400" height="400" className="mx-auto">
|
||||
{/* Draw circle */}
|
||||
<circle cx={centerX} cy={centerY} r={radius} fill="none" stroke="hsl(var(--border))" strokeWidth="2" />
|
||||
|
||||
{/* Draw violation arcs */}
|
||||
{violations.map(i => {
|
||||
const angle1 = (i * 360 / 9 - 90) * Math.PI / 180;
|
||||
const angle2 = ((i + 1) * 360 / 9 - 90) * Math.PI / 180;
|
||||
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);
|
||||
|
||||
return (
|
||||
<path
|
||||
key={i}
|
||||
d={`M ${x1} ${y1} A ${radius} ${radius} 0 0 1 ${x2} ${y2}`}
|
||||
fill="none"
|
||||
stroke="hsl(var(--destructive))"
|
||||
strokeWidth="4"
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Draw edges in guided mode */}
|
||||
{mode === 'guided' && slots.every(s => s !== null) && slots.map((num1, i) => {
|
||||
return slots.slice(i + 1).map((num2, j) => {
|
||||
const idx2 = i + j + 1;
|
||||
if (num1 !== null && num2 !== null && !isDivisible(num1, num2)) {
|
||||
const angle1 = (i * 360 / 9 - 90) * Math.PI / 180;
|
||||
const angle2 = (idx2 * 360 / 9 - 90) * Math.PI / 180;
|
||||
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)
|
||||
const isAdjacentOnCircle = Math.abs(i - idx2) === 1 || Math.abs(i - idx2) === 8;
|
||||
|
||||
return (
|
||||
<line
|
||||
key={`${i}-${idx2}`}
|
||||
x1={x1}
|
||||
y1={y1}
|
||||
x2={x2}
|
||||
y2={y2}
|
||||
stroke={isAdjacentOnCircle ? "hsl(var(--primary))" : "hsl(var(--muted-foreground))"}
|
||||
strokeWidth={isAdjacentOnCircle ? "2" : "1"}
|
||||
opacity={isAdjacentOnCircle ? "0.8" : "0.3"}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
})}
|
||||
|
||||
{/* Draw slots */}
|
||||
{slots.map((num, i) => {
|
||||
const angle = (i * 360 / 9 - 90) * Math.PI / 180;
|
||||
const x = centerX + radius * Math.cos(angle);
|
||||
const y = centerY + radius * Math.sin(angle);
|
||||
|
||||
const isSelected = mode === 'guided' && draggedSlot === i;
|
||||
|
||||
return (
|
||||
<g key={i}>
|
||||
<circle
|
||||
cx={x}
|
||||
cy={y}
|
||||
r="25"
|
||||
fill={isSelected ? "hsl(var(--primary))" : "hsl(var(--background))"}
|
||||
stroke={isSelected ? "hsl(var(--primary))" : "hsl(var(--border))"}
|
||||
strokeWidth="2"
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={() => handleDrop(i)}
|
||||
onClick={() => handleSlotClick(i)}
|
||||
className="cursor-pointer"
|
||||
/>
|
||||
{num !== null && (
|
||||
<text
|
||||
x={x}
|
||||
y={y}
|
||||
textAnchor="middle"
|
||||
dominantBaseline="middle"
|
||||
className="text-xl font-bold select-none pointer-events-none"
|
||||
fill={isSelected ? "hsl(var(--primary-foreground))" : "hsl(var(--foreground))"}
|
||||
>
|
||||
{num}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Neighbor Sum Avoidance</CardTitle>
|
||||
<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?
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{!isActive ? (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-center gap-4">
|
||||
<Label htmlFor="mode-switch">Default Mode</Label>
|
||||
<Switch
|
||||
id="mode-switch"
|
||||
checked={mode === 'guided'}
|
||||
onCheckedChange={(checked) => setMode(checked ? 'guided' : 'default')}
|
||||
/>
|
||||
<Label htmlFor="mode-switch">Guided Mode</Label>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 text-center">
|
||||
<div className="text-sm text-muted-foreground space-y-2">
|
||||
{mode === 'default' ? (
|
||||
<>
|
||||
<p>Drag numbers from below into the circle slots.</p>
|
||||
<p>Adjacent numbers that sum to a multiple of 3, 5, or 7 will show a red arc.</p>
|
||||
<p>Click a filled slot to remove the number.</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>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<Button onClick={() => startGame(mode)} size="lg">
|
||||
Start {mode === 'default' ? 'Default' : 'Guided'} Mode
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Timer className="w-4 h-4" />
|
||||
<span className="font-mono">{formatTime(time)}</span>
|
||||
</div>
|
||||
{mode === 'guided' && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Swaps: {swaps}
|
||||
</div>
|
||||
)}
|
||||
<Button variant="outline" size="sm" onClick={restart}>
|
||||
<RotateCcw className="w-4 h-4 mr-2" />
|
||||
Restart
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{renderCircle()}
|
||||
|
||||
{mode === 'default' && availableNumbers.length > 0 && (
|
||||
<div className="flex flex-wrap justify-center gap-4">
|
||||
{availableNumbers.map(num => (
|
||||
<div
|
||||
key={num}
|
||||
draggable
|
||||
onDragStart={() => handleDragStart(num, null)}
|
||||
className="w-12 h-12 rounded-full border-2 border-primary bg-background flex items-center justify-center text-lg font-bold cursor-move hover:scale-110 transition-transform"
|
||||
>
|
||||
{num}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isComplete && (
|
||||
<div className="text-center space-y-4">
|
||||
<p className="text-lg font-semibold text-primary">
|
||||
🎉 Congratulations! You solved it in {formatTime(time)}
|
||||
{mode === 'guided' && ` with ${swaps} swaps`}!
|
||||
</p>
|
||||
<Button onClick={restart}>Play Again</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
{showSocialShare && (
|
||||
<div className="mt-8">
|
||||
<SocialShare
|
||||
url={window.location.href}
|
||||
title="Neighbor Sum Avoidance - Interactive Graph Puzzle"
|
||||
description="Can you arrange numbers 1-9 in a circle avoiding forbidden sums?"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default NeighborSumAvoidance;
|
||||
11
src/pages/NeighborSumAvoidancePage.tsx
Normal file
11
src/pages/NeighborSumAvoidancePage.tsx
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import NeighborSumAvoidance from "@/components/NeighborSumAvoidance";
|
||||
|
||||
const NeighborSumAvoidancePage = () => {
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
<NeighborSumAvoidance showSocialShare={true} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default NeighborSumAvoidancePage;
|
||||
|
|
@ -1,11 +1,115 @@
|
|||
import ComingSoon from "@/components/ComingSoon";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Search } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import Layout from '@/components/Layout';
|
||||
import { useState } from 'react';
|
||||
import NeighborSumAvoidance from '@/components/NeighborSumAvoidance';
|
||||
|
||||
interface Interactive {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
tags: string[];
|
||||
component: React.ComponentType<{ showSocialShare?: boolean }>;
|
||||
}
|
||||
|
||||
const interactives: Interactive[] = [
|
||||
{
|
||||
id: 'neighbor-sum-avoidance',
|
||||
title: 'Neighbor Sum Avoidance',
|
||||
description: 'Arrange numbers 1-9 in a circle so that the sum of two neighbors is never divisible by 3, 5, or 7. Two modes: default and guided!',
|
||||
tags: ['graphs', 'cycles', 'constraints', 'puzzle', 'graph-theory'],
|
||||
component: NeighborSumAvoidance
|
||||
},
|
||||
];
|
||||
|
||||
const Graphs = () => {
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [selectedInteractive, setSelectedInteractive] = useState<Interactive | null>(null);
|
||||
|
||||
const filteredInteractives = interactives.filter(interactive =>
|
||||
interactive.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
interactive.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
interactive.tags.some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
);
|
||||
|
||||
if (selectedInteractive) {
|
||||
const InteractiveComponent = selectedInteractive.component;
|
||||
return (
|
||||
<ComingSoon
|
||||
title="Graphs"
|
||||
description="Discover graph theory, algorithms on graphs, trees, and network analysis through interactive graph manipulation and visualization tools."
|
||||
<div className="min-h-screen bg-background">
|
||||
<div className="container mx-auto px-4 py-8 space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={() => setSelectedInteractive(null)}
|
||||
className="text-primary hover:text-primary/80 font-medium"
|
||||
>
|
||||
← Back to Graphs
|
||||
</button>
|
||||
</div>
|
||||
<InteractiveComponent showSocialShare={true} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="max-w-7xl mx-auto p-6">
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-3xl font-bold text-foreground">Graphs</h1>
|
||||
<p className="text-muted-foreground text-lg">
|
||||
Discover graph theory, algorithms on graphs, trees, and network analysis through interactive graph manipulation and visualization tools.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Search bar */}
|
||||
<div className="relative max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
|
||||
<Input
|
||||
placeholder="Search interactives..."
|
||||
value={searchTerm}
|
||||
onChange={e => setSearchTerm(e.target.value)}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Gallery */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{filteredInteractives.map(interactive => (
|
||||
<Card
|
||||
key={interactive.id}
|
||||
className="cursor-pointer hover:shadow-lg transition-all duration-200 hover:scale-105"
|
||||
onClick={() => setSelectedInteractive(interactive)}
|
||||
>
|
||||
<CardHeader className="space-y-3">
|
||||
<CardTitle className="text-xl text-foreground">{interactive.title}</CardTitle>
|
||||
<CardDescription className="text-muted-foreground line-clamp-3">
|
||||
{interactive.description}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{interactive.tags.map(tag => (
|
||||
<Badge key={tag} variant="secondary" className="text-xs">
|
||||
{tag}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{filteredInteractives.length === 0 && (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-muted-foreground text-lg">No interactives found matching your search.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue