File size: 9,750 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/**
 * 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 };