RotNot / src /lib /puzzles /sequences.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
9.75 kB
/**
* Number sequence puzzle generator.
* Generates sequences with hidden terms that the player must deduce.
*
* Sequence types by difficulty:
* easy: arithmetic (constant difference), simple geometric (×2, ×3)
* medium: geometric (larger ratios), triangular, square numbers, Fibonacci-like
* hard: polynomial (quadratic), prime-based, alternating operations, composite
*/
export type SequenceDifficulty = "easy" | "medium" | "hard";
export type SequenceType =
| "arithmetic"
| "geometric"
| "fibonacci"
| "triangular"
| "square"
| "prime"
| "quadratic"
| "alternating";
export interface SequencePuzzle {
/** The displayed sequence with nulls for hidden terms */
sequence: (number | null)[];
/** The full correct sequence */
solution: number[];
/** Indices of the hidden terms the player must fill */
hiddenIndices: number[];
/** The type of sequence (for metadata/scoring) */
type: SequenceType;
/** Difficulty level */
difficulty: SequenceDifficulty;
/** Human-readable hint about the pattern */
hint: string;
/** Number of terms in the full sequence */
length: number;
}
// ---------- sequence generators ----------
/** Arithmetic: a, a+d, a+2d, ... */
function generateArithmetic(difficulty: SequenceDifficulty): number[] {
const length = difficulty === "easy" ? 6 : difficulty === "medium" ? 7 : 8;
const start = randomInt(1, difficulty === "easy" ? 10 : 20);
const diff =
difficulty === "easy"
? randomInt(2, 5)
: difficulty === "medium"
? randomInt(3, 12)
: randomInt(5, 25);
// Allow negative differences on medium/hard
const d = difficulty !== "easy" && Math.random() < 0.3 ? -diff : diff;
const result: number[] = [];
for (let i = 0; i < length; i++) {
result.push(start + d * i);
}
return result;
}
/** Geometric: a, a*r, a*r^2, ... */
function generateGeometric(difficulty: SequenceDifficulty): number[] {
const length = difficulty === "easy" ? 6 : 7;
const start = randomInt(1, 5);
const ratio =
difficulty === "easy"
? randomFromArray([2, 3])
: difficulty === "medium"
? randomFromArray([2, 3, 4, 5])
: randomFromArray([2, 3, 4, 5, 6]);
const result: number[] = [];
let val = start;
for (let i = 0; i < length; i++) {
result.push(val);
val *= ratio;
// Cap to prevent huge numbers
if (val > 1_000_000) {
return result;
}
}
return result;
}
/** Fibonacci-like: each term is sum of previous two */
function generateFibonacci(difficulty: SequenceDifficulty): number[] {
const length = difficulty === "medium" ? 8 : 9;
const a = randomInt(1, 5);
const b = randomInt(1, 5);
const result = [a, b];
for (let i = 2; i < length; i++) {
result.push(result[i - 1] + result[i - 2]);
}
return result;
}
/** Triangular numbers: 1, 3, 6, 10, 15, ... (n*(n+1)/2) */
function generateTriangular(): number[] {
const offset = randomInt(0, 3);
const length = 7;
const result: number[] = [];
for (let n = 1 + offset; n < length + 1 + offset; n++) {
result.push((n * (n + 1)) / 2);
}
return result;
}
/** Square numbers: 1, 4, 9, 16, 25, ... */
function generateSquare(): number[] {
const offset = randomInt(1, 4);
const length = 7;
const result: number[] = [];
for (let n = offset; n < length + offset; n++) {
result.push(n * n);
}
return result;
}
/** Primes starting from a random offset */
function generatePrime(): number[] {
const allPrimes = sievePrimes(200);
const startIdx = randomInt(0, Math.min(10, allPrimes.length - 8));
return allPrimes.slice(startIdx, startIdx + 8);
}
/** Quadratic: a*n^2 + b*n + c */
function generateQuadratic(): number[] {
const a = randomInt(1, 3);
const b = randomInt(-2, 5);
const c = randomInt(0, 10);
const length = 8;
const result: number[] = [];
for (let n = 1; n <= length; n++) {
result.push(a * n * n + b * n + c);
}
return result;
}
/** Alternating: two interleaved arithmetic sequences */
function generateAlternating(): number[] {
const startA = randomInt(1, 10);
const startB = randomInt(10, 20);
const diffA = randomInt(2, 5);
const diffB = randomInt(3, 7);
const length = 8;
const result: number[] = [];
for (let i = 0; i < length; i++) {
if (i % 2 === 0) {
result.push(startA + diffA * (i / 2));
} else {
result.push(startB + diffB * Math.floor(i / 2));
}
}
return result;
}
// ---------- difficulty → type mapping ----------
const TYPES_BY_DIFFICULTY: Record<SequenceDifficulty, SequenceType[]> = {
easy: ["arithmetic", "geometric"],
medium: ["geometric", "fibonacci", "triangular", "square"],
hard: ["prime", "quadratic", "alternating", "fibonacci"],
};
const HINTS: Record<SequenceType, string> = {
arithmetic: "Each term changes by a constant amount.",
geometric: "Each term is multiplied by a constant.",
fibonacci: "Each term is the sum of the two before it.",
triangular: "These are triangular numbers.",
square: "Think about perfect squares.",
prime: "These are prime numbers.",
quadratic: "The differences between terms are increasing.",
alternating: "Two separate patterns are interleaved.",
};
// How many terms to hide per difficulty
const HIDDEN_COUNT: Record<SequenceDifficulty, number> = {
easy: 1,
medium: 2,
hard: 3,
};
// ---------- helpers ----------
function randomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomFromArray<T>(arr: T[]): T {
return arr[Math.floor(Math.random() * arr.length)];
}
/** Sieve of Eratosthenes up to `limit`. */
function sievePrimes(limit: number): number[] {
const sieve = new Array(limit + 1).fill(true);
sieve[0] = sieve[1] = false;
for (let i = 2; i * i <= limit; i++) {
if (sieve[i]) {
for (let j = i * i; j <= limit; j += i) {
sieve[j] = false;
}
}
}
const primes: number[] = [];
for (let i = 2; i <= limit; i++) {
if (sieve[i]) primes.push(i);
}
return primes;
}
// ---------- public API ----------
/**
* Pick which indices to hide. Strategy:
* - easy: hide the last term
* - medium: hide 2 terms (one middle, one near end)
* - hard: hide 3 terms (spread across the sequence)
*/
function pickHiddenIndices(
seqLength: number,
count: number,
difficulty: SequenceDifficulty,
): number[] {
if (count >= seqLength) {
// Fallback: hide last `count` terms
return Array.from({ length: count }, (_, i) => seqLength - count + i);
}
if (difficulty === "easy") {
return [seqLength - 1];
}
if (difficulty === "medium") {
const mid = Math.floor(seqLength / 2);
return [mid, seqLength - 1];
}
// hard: spread across sequence, avoiding first 2 terms to give context
const candidates = Array.from(
{ length: seqLength - 2 },
(_, i) => i + 2,
);
shuffle(candidates);
return candidates.slice(0, count).sort((a, b) => a - b);
}
/** Fisher-Yates shuffle (in-place). */
function shuffle<T>(arr: T[]): T[] {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
/**
* Generate a number sequence puzzle.
*/
export function generateSequence(
difficulty: SequenceDifficulty = "medium",
requestedType?: SequenceType,
): SequencePuzzle {
const allowedTypes = TYPES_BY_DIFFICULTY[difficulty];
const type =
requestedType && allowedTypes.includes(requestedType)
? requestedType
: randomFromArray(allowedTypes);
let solution: number[];
switch (type) {
case "arithmetic":
solution = generateArithmetic(difficulty);
break;
case "geometric":
solution = generateGeometric(difficulty);
break;
case "fibonacci":
solution = generateFibonacci(difficulty);
break;
case "triangular":
solution = generateTriangular();
break;
case "square":
solution = generateSquare();
break;
case "prime":
solution = generatePrime();
break;
case "quadratic":
solution = generateQuadratic();
break;
case "alternating":
solution = generateAlternating();
break;
default:
solution = generateArithmetic(difficulty);
}
const hiddenCount = HIDDEN_COUNT[difficulty];
const hiddenIndices = pickHiddenIndices(
solution.length,
hiddenCount,
difficulty,
);
const sequence: (number | null)[] = solution.map((val, idx) =>
hiddenIndices.includes(idx) ? null : val,
);
return {
sequence,
solution,
hiddenIndices,
type,
difficulty,
hint: HINTS[type],
length: solution.length,
};
}
/**
* Validate the player's answers for a sequence puzzle.
* Returns true if all hidden terms match the solution.
*/
export function validateSequence(
playerAnswers: number[],
solution: number[],
hiddenIndices: number[],
): boolean {
if (playerAnswers.length !== hiddenIndices.length) return false;
return playerAnswers.every(
(answer, i) => answer === solution[hiddenIndices[i]],
);
}
/**
* Score a sequence answer: partial credit for getting some terms right.
* Returns a 0-1 quality score.
*/
export function scoreSequence(
playerAnswers: number[],
solution: number[],
hiddenIndices: number[],
): number {
if (playerAnswers.length === 0 || hiddenIndices.length === 0) return 0;
let correct = 0;
for (let i = 0; i < hiddenIndices.length; i++) {
if (
i < playerAnswers.length &&
playerAnswers[i] === solution[hiddenIndices[i]]
) {
correct++;
}
}
return correct / hiddenIndices.length;
}
// Re-export helpers for testing
export { sievePrimes, TYPES_BY_DIFFICULTY, HINTS, HIDDEN_COUNT };