Spaces:
Running

File size: 37,601 Bytes
dc746c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f47988a
dc746c4
 
 
 
 
 
 
 
 
 
 
 
 
 
f47988a
 
dc746c4
 
 
f47988a
 
 
dc746c4
 
f47988a
 
dc746c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f47988a
 
 
 
 
 
 
 
dc746c4
 
f47988a
 
 
dc746c4
 
f47988a
dc746c4
 
 
 
 
 
 
f47988a
 
 
 
 
 
dc746c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f47988a
dc746c4
f47988a
 
 
 
 
 
 
 
 
dc746c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f47988a
 
dc746c4
 
f47988a
dc746c4
 
 
 
 
 
 
 
 
 
 
 
f47988a
 
 
 
dc746c4
f47988a
dc746c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f47988a
 
 
dc746c4
f47988a
 
 
 
dc746c4
 
f47988a
dc746c4
f47988a
 
 
 
 
 
dc746c4
f47988a
 
dc746c4
 
f47988a
 
 
 
 
 
 
 
dc746c4
 
f47988a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc746c4
f47988a
dc746c4
 
f47988a
dc746c4
f47988a
 
 
 
 
 
 
 
dc746c4
 
 
f47988a
 
dc746c4
 
 
 
f47988a
 
dc746c4
 
 
 
 
 
 
 
f47988a
dc746c4
 
f47988a
dc746c4
 
 
 
f47988a
dc746c4
 
 
f47988a
 
dc746c4
f47988a
 
 
 
 
 
 
dc746c4
f47988a
 
 
 
 
 
dc746c4
 
 
 
 
 
 
 
f47988a
 
 
 
dc746c4
 
 
 
 
f47988a
dc746c4
 
 
 
 
 
 
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
362
363
364
365
366
367
368
369
370
// Visual class: Linear programming, graphical (corner point) method — CBSE 12 Applied Mathematics, Unit 8.
import { Frac, inr, rupee, Checks } from "./core.js";

export const ID = "lp";
export const TITLE = "Linear programming: the feasible region";

export const ATOMS = {
  "241-LP-A01": "Decision variables are the quantities we choose (for example x tables and y chairs); they cannot be negative, so x ≥ 0 and y ≥ 0.",
  "241-LP-A02": "Each limited resource gives a constraint: (amount used per unit of x)·x + (amount used per unit of y)·y ≤ amount available. A minimum requirement uses ≥.",
  "241-LP-A03": "The objective function Z = px + qy is what we maximise (profit) or minimise (cost); p and q are the profit or cost per unit.",
  "241-LP-A04": "To graph a constraint, draw its boundary line through its two intercepts, then shade the side that satisfies it (test the origin: for ax + by ≤ c with c > 0 the origin side is feasible).",
  "241-LP-A05": "The feasible region is the set of points satisfying every constraint, including x, y ≥ 0. Points outside it are infeasible.",
  "241-LP-A06": "Corner points are where the boundaries of the feasible region meet. An intercept of a constraint line that lies outside the region is NOT a corner point.",
  "241-LP-A07": "Corner point method: if an optimum exists, it occurs at a corner point. Evaluate Z at every corner and pick the largest (max) or smallest (min).",
  "241-LP-A08": "If Z takes the same best value at two adjacent corners, every point on the edge joining them is optimal: there are infinitely many optimal solutions. This happens when the objective line is parallel to that edge.",
  "241-LP-A09": "A feasible region is bounded if it can be enclosed in a circle; otherwise it is unbounded.",
  "241-LP-A10": "For an unbounded region, the corner value m is the minimum only if the open half-plane px + qy < m has no point in common with the region (for a maximum M: px + qy > M has none).",
  "241-LP-A11": "Changing the profit per unit tilts the objective line. The best corner changes only when the slope of the objective line passes the slope of one of the two edges that meet at that corner; a small change may leave the best plan the same while Z changes.",
  "241-LP-A12": "Increasing the amount of a resource that is used up at the optimum (a binding constraint) moves that boundary outward and can raise the best Z; more of a resource that is not used up changes nothing.",
};
export const MISCONCEPTIONS = {
  "241-LP-M01": { wrong: "A resource limit is written with ≥ (or a requirement with ≤).", atoms: ["241-LP-A02"] },
  "241-LP-M02": { wrong: "The per-unit amounts are attached to the wrong variable.", atoms: ["241-LP-A02"] },
  "241-LP-M03": { wrong: "Every intercept of every constraint line is a corner point.", atoms: ["241-LP-A06"] },
  "241-LP-M04": { wrong: "The best corner is the one farthest from the origin, or the one with the largest x, whatever the objective.", atoms: ["241-LP-A07"] },
  "241-LP-M05": { wrong: "A small change in profit per unit always changes the best plan.", atoms: ["241-LP-A11"] },
  "241-LP-M06": { wrong: "More of any resource always raises the best profit.", atoms: ["241-LP-A12"] },
  "241-LP-M07": { wrong: "For an unbounded region the corner value is always the optimum, with nothing to check.", atoms: ["241-LP-A10"] },
  "241-LP-M08": { wrong: "When two corners give the same best value there are exactly two solutions.", atoms: ["241-LP-A08"] },
  "241-LP-M09": { wrong: "The side of a ≤ constraint away from the origin is shaded.", atoms: ["241-LP-A04"] },
};

export const SCENARIOS = { max: "Maximise profit with limited resources", cap: "Maximise with a limit on one product", min: "Minimise cost while meeting requirements", absmin: "Minimise over an unbounded region",
  multiple: "Maximise when the profit line is parallel to an edge", nomax: "Maximise over an unbounded region" };

const CONTEXTS = {
  max: [
    { maker: "A carpenter", x: "tables", y: "chairs", xs: "table", ys: "chair", res: [{ name: "wood", unit: "units of wood", min: 20, max: 400 }, { name: "labour", unit: "hours of labour", min: 20, max: 240 }], cap: "the market can take at most {k} tables a week", per: "a week", bigger: "x" },
    { maker: "A home baker", x: "cakes", y: "trays of cookies", xs: "cake", ys: "tray of cookies", res: [{ name: "flour", unit: "cups of flour", min: 20, max: 300 }, { name: "decorating", unit: "hours of decorating", min: 10, max: 60, xFactor: 2 }], cap: "she can sell at most {k} cakes a week", per: "a week", bigger: "x" },
    { maker: "A tailoring unit", x: "shirts", y: "pairs of trousers", xs: "shirt", ys: "pair of trousers", res: [{ name: "cutting", unit: "hours of cutting", min: 20, max: 200 }, { name: "stitching", unit: "hours of stitching", min: 20, max: 400 }], cap: "it can sell at most {k} shirts a week", per: "a week", stitchMore: true, bigger: "y" },
  ],
  min: [
    { maker: "A dietician", x: "units of food P", y: "units of food Q", xs: "unit of P", ys: "unit of Q", res: [{ name: "vitamin A", unit: "units of vitamin A", min: 20, max: 400 }, { name: "iron", unit: "units of iron", min: 20, max: 400 }], per: "a day" },
    { maker: "A farmer", x: "bags of fertiliser F1", y: "bags of fertiliser F2", xs: "bag of F1", ys: "bag of F2", res: [{ name: "nitrogen", unit: "units of nitrogen", min: 20, max: 600 }, { name: "phosphate", unit: "units of phosphate", min: 20, max: 600 }], per: "for the field" },
  ],
};

// ---------- geometry (exact) ----------
const F = (n, d = 1) => new Frac(n, d);
function lines(inst) {   // every boundary: constraints + axes, as a·x + b·y = c
  return [...inst.cons.map((k, i) => ({ a: k.a, b: k.b, c: k.c, id: `c${i}` })), { a: 1, b: 0, c: 0, id: "x0" }, { a: 0, b: 1, c: 0, id: "y0" }];
}
const meet = (l1, l2) => { const det = l1.a * l2.b - l2.a * l1.b; if (det === 0) return null; return { x: F(l1.c * l2.b - l2.c * l1.b, det), y: F(l1.a * l2.c - l2.a * l1.c, det), on: [l1.id, l2.id] }; };
export const feasible = (inst, p) => p.x.sign() >= 0 && p.y.sign() >= 0 && inst.cons.every((k) => { const v = F(k.a).mul(p.x).add(F(k.b).mul(p.y)); return k.op === "<=" ? v.cmp(k.c) <= 0 : v.cmp(k.c) >= 0; });
const Z = (inst, p) => F(inst.obj.p).mul(p.x).add(F(inst.obj.q).mul(p.y));

export function solve(inst) {
  const L = lines(inst); const pts = [];
  for (let i = 0; i < L.length; i++) for (let j = i + 1; j < L.length; j++) { const p = meet(L[i], L[j]); if (p) pts.push(p); }
  const key = (p) => `${p.x}|${p.y}`; const seen = new Map();
  for (const p of pts) { const k = key(p); if (seen.has(k)) seen.get(k).on = [...new Set([...seen.get(k).on, ...p.on])]; else seen.set(k, p); }
  const all = [...seen.values()];
  const corners = all.filter((p) => feasible(inst, p));
  const decoys = all.filter((p) => !feasible(inst, p) && p.x.sign() >= 0 && p.y.sign() >= 0);   // intersections outside the region
  corners.forEach((p) => (p.z = Z(inst, p)));
  const sense = inst.obj.sense; const better = (a, b) => (sense === "max" ? a.cmp(b) > 0 : a.cmp(b) < 0);
  let best = null; for (const p of corners) if (!best || better(p.z, best.z)) best = p;
  const ties = corners.filter((p) => best && p.z.eq(best.z));
  const bounded = inst.cons.some((k) => k.op === "<=" && k.a > 0 && k.b > 0);
  // unbounded check (CBSE): for min, the open half-plane Z < m must not meet the region. With p, q > 0 and a region
  // in the first quadrant this holds automatically for min; for max over an unbounded region it fails.
  const optimumExists = bounded || sense === "min";
  // order corners anticlockwise for drawing
  const cx = corners.reduce((t, p) => t + p.x.val(), 0) / corners.length, cy = corners.reduce((t, p) => t + p.y.val(), 0) / corners.length;
  corners.sort((a, b) => Math.atan2(a.y.val() - cy, a.x.val() - cx) - Math.atan2(b.y.val() - cy, b.x.val() - cx));
  const binding = best ? inst.cons.map((k, i) => best.on.includes(`c${i}`)) : [];
  return { corners, decoys, best, ties, bounded, optimumExists, binding };
}
export const ptStr = (p) => `(${p.x}, ${p.y})`;

// Independent check: brute force over the integer lattice. With integer corners the lattice optimum equals the LP optimum.
export function latticeCheck(inst, sol) {
  const X = Math.max(...sol.corners.map((p) => p.x.val())) + 2, Y = Math.max(...sol.corners.map((p) => p.y.val())) + 2;
  let best = null;
  for (let x = 0; x <= X * 2; x++) for (let y = 0; y <= Y * 2; y++) {
    const p = { x: F(x), y: F(y) }; if (!feasible(inst, p)) continue; const z = Z(inst, p);
    if (!best || (inst.obj.sense === "max" ? z.cmp(best) > 0 : z.cmp(best) < 0)) best = z;
  }
  return best && sol.best && best.eq(sol.best.z) ? [] : [`lattice ${best} vs corner ${sol.best && sol.best.z}`];
}

// ---------- sensibility checks ----------
export function checkInstance(inst) {
  const c = new Checks(`lp:${inst.scenario}`); const sol = solve(inst);
  c.ok("2-3 constraints", inst.cons.length >= 2 && inst.cons.length <= 3, `${inst.cons.length} constraints`);
  c.ok("small whole per-unit amounts (0-9)", inst.cons.every((k) => [k.a, k.b].every((v) => Number.isInteger(v) && v >= 0 && v <= 9) && k.a + k.b > 0), "coefficients");
  c.ok("round right-hand sides", inst.cons.every((k) => Number.isInteger(k.c) && k.c > 0 && (k.c % 5 === 0 || k.c <= 30)), "resource amounts not round");
  c.ok("round profit or cost per unit", [inst.obj.p, inst.obj.q].every((v) => Number.isInteger(v) && (inst.ctx.abstract ? v >= 1 && v <= 10 : v >= 5 && v <= 900 && v % 5 === 0)), "objective coefficients");
  if (!inst.ctx.abstract) {
    c.ok("resource amounts realistic for the context", inst.cons.every((k) => k.res > 1 || (k.c <= inst.ctx.res[k.res].max && k.c >= inst.ctx.res[k.res].min)), inst.cons.map((k) => k.c).join(", "));
    c.ok("per-unit needs of the two products within 4× of each other", inst.cons.every((k) => k.res > 1 || !k.a || !k.b || Math.max(k.a, k.b) <= 4 * Math.min(k.a, k.b)), "one product needs far more of a resource than the other");
    const [k1, k2] = inst.cons; const { p, q } = inst.obj;
    if (inst.obj.sense === "min") c.ok("a real trade-off: each input is richer in a different nutrient", (k1.a - k1.b) * (k2.a - k2.b) < 0, "one input gives at least as much of everything");
    else c.ok("no product dominates (uses no more of every resource and earns no less)", !((k1.a <= k1.b && k2.a <= k2.b && p >= q) || (k1.b <= k1.a && k2.b <= k2.a && q >= p)), "one product dominates");
  }
  c.ok("profit/cost ratio between 1:4 and 4:1", inst.obj.p * 4 >= inst.obj.q && inst.obj.q * 4 >= inst.obj.p, `p ${inst.obj.p}, q ${inst.obj.q}`);
  c.ok("decoy crossings have whole-number coordinates", sol.decoys.every((p) => p.x.isInt() && p.y.isInt()), `decoys ${sol.decoys.map(ptStr).join(" ")}`);
  if (inst.scenario === "max" || inst.scenario === "cap") c.ok("best plan makes some of both (a real trade-off)", sol.best && sol.best.x.sign() > 0 && sol.best.y.sign() > 0, `best ${sol.best && ptStr(sol.best)}`);
  if (!inst.ctx.abstract) inst.ctx.res.forEach((rs, j) => { if (rs.xFactor) c.ok(`a ${inst.ctx.xs} needs at least ${rs.xFactor}× the ${rs.name} of a ${inst.ctx.ys}`, inst.cons[j].a >= rs.xFactor * inst.cons[j].b, "per-unit needs implausible"); });
  if (inst.ctx.stitchMore) c.ok("stitching takes at least as long as cutting for each item", inst.cons[1].a >= inst.cons[0].a && inst.cons[1].b >= inst.cons[0].b, "cutting longer than stitching");
  if (inst.ctx.bigger) {   // e.g. a table uses at least as much wood and labour as a chair, and earns at least as much
    const bx = inst.ctx.bigger === "x";
    c.ok(`a ${bx ? inst.ctx.xs : inst.ctx.ys} uses at least as much of each resource and earns at least as much`, inst.cons.filter((k) => k.res <= 1).every((k) => (bx ? k.a > k.b : k.b > k.a)) && (bx ? inst.obj.p >= inst.obj.q : inst.obj.q >= inst.obj.p), "per-unit amounts contradict the context");
  }
  c.ok("region not empty", sol.corners.length >= 3, `${sol.corners.length} corners`);
  c.ok("every corner has whole-number coordinates", sol.corners.every((p) => p.x.isInt() && p.y.isInt()), `corners ${sol.corners.map(ptStr).join(" ")}`);
  c.ok("corners within a readable graph (≤ 80)", sol.corners.every((p) => p.x.val() <= 80 && p.y.val() <= 80), "graph too large");
  c.ok("3-5 corners", sol.corners.length >= 3 && sol.corners.length <= 5, `${sol.corners.length} corners`);
  inst.cons.forEach((k, i) => c.ok(`constraint ${i + 1} shapes the region (not redundant)`, sol.corners.filter((p) => p.on.includes(`c${i}`)).length >= 2, "redundant constraint"));
  c.ok("no corner where three lines meet", sol.corners.every((p) => p.on.length === 2), "degenerate corner");
  if (inst.scenario === "nomax") {
    c.ok("region unbounded and no maximum", !sol.bounded && !sol.optimumExists, "has a maximum");
    c.ok("lattice cross-check agrees", true, "");
    return c;
  }
  if (inst.scenario === "cap") c.ok("three constraints", inst.cons.length === 3, "cap scenario needs the product limit");
  c.ok("an optimum exists", sol.optimumExists && !!sol.best, "no optimum");
  if (inst.scenario === "multiple") c.ok("exactly two corners tie for the best", sol.ties.length === 2, `${sol.ties.length} best corners`);
  else {
    c.ok("unique best corner", sol.ties.length === 1, `${sol.ties.length} best corners`);
    const zs = sol.corners.map((p) => p.z.val()).sort((a, b) => a - b); const bestV = sol.best.z.val(); const second = inst.obj.sense === "max" ? zs[zs.length - 2] : zs[1];
    c.ok("best clearly ahead (≥ 3%)", Math.abs(bestV - second) >= 0.03 * Math.abs(bestV), `best ${bestV}, next ${second}`);
  }
  if (inst.scenario !== "min") c.ok("the best plan makes some of both or is at an intercept that makes sense", sol.best.x.val() + sol.best.y.val() > 0, "best plan is to make nothing");
  c.ok("lattice cross-check agrees", latticeCheck(inst, sol).length === 0, latticeCheck(inst, sol).join(""));
  c.ok("objective not parallel to a constraint (unless that is the point)", inst.scenario === "multiple" || inst.cons.every((k) => k.a * inst.obj.q !== k.b * inst.obj.p), "parallel");
  return c;
}

// ---------- sampling ----------
export function sample(r, scenario, tries = 3000, stats = null) {
  for (let t = 0; t < tries; t++) {
    const inst = build(r, scenario); if (!inst) continue; const c = checkInstance(inst); if (c.passed) return inst;
    if (stats) for (const f of c.failures) stats[f.name] = (stats[f.name] || 0) + 1;
  }
  return null;
}
const ABSTRACT = { abstract: true, maker: "", x: "x", y: "y", xs: "unit of x", ys: "unit of y", res: [{ name: "first" }, { name: "second" }], per: "" };
function build(r, scenario) {
  if (scenario === "cap") {   // a two-resource problem plus a limit on x that cuts the region
    const base = build(r, "max"); const ix = base.cons.map((k) => k.c / k.a); const kx = r.int(2, Math.max(2, Math.floor(Math.min(...ix)) - 1));
    return { ...base, scenario, cons: [...base.cons, { a: 1, b: 0, c: kx, op: "<=", res: 2 }] };
  }
  if (scenario === "absmin") { const m = build(r, "min"); return { ...m, scenario, ctx: ABSTRACT, obj: { p: r.int(1, 10), q: r.int(1, 10), sense: "min" } }; }
  if (scenario === "nomax") {  // >= constraints, maximise: no maximum
    const m = build(r, "min"); const p = r.int(1, 10), q = r.int(1, 10);
    return { ...m, scenario, ctx: ABSTRACT, obj: { p, q, sense: "max" } };
  }
  const sense = scenario === "min" ? "min" : "max"; const ctx = r.pick(CONTEXTS[sense]);
  // choose the crossing point first so corners come out whole
  const X = r.int(2, 12) * (r.next() < 0.5 ? 1 : 2), Y = r.int(2, 12) * (r.next() < 0.5 ? 1 : 2);
  const a1 = r.int(1, 6), b1 = r.int(1, 6), a2 = r.int(1, 6), b2 = r.int(1, 6);
  const c1 = a1 * X + b1 * Y, c2 = a2 * X + b2 * Y;
  const op = sense === "max" ? "<=" : ">=";
  const cons = [{ a: a1, b: b1, c: c1, op, res: 0 }, { a: a2, b: b2, c: c2, op, res: 1 }];
  let p = r.int(1, 30) * 5, q = r.int(1, 30) * 5;
  if (sense === "max") { p *= r.pick([1, 2, 4]); q *= r.pick([1, 2, 4]); }
  if (scenario === "multiple") { const k = r.pick(cons); const m = r.int(2, 12) * 5; p = k.a * m; q = k.b * m; }
  return { cls: ID, scenario, ctx, cons, obj: { p, q, sense } };
}

// ---------- text ----------
const v = (k) => `${k}`;
export const ineqStr = (k, vx = "x", vy = "y") => `${k.a ? `${k.a === 1 ? "" : k.a}${vx}` : ""}${k.a && k.b ? " + " : ""}${k.b ? `${k.b === 1 ? "" : k.b}${vy}` : ""} ${k.op === "<=" ? "≤" : "≥"} ${k.c}`;
export const zExpr = (inst) => ineqStr({ a: inst.obj.p, b: inst.obj.q, c: "", op: "<=" }).replace(/ ≤ $/, "");
export const objStr = (inst) => `${inst.obj.sense === "max" ? "Maximise" : "Minimise"} Z = ${zExpr(inst)}`;
const q1 = (n, unit) => `${n} ${n === 1 ? unit.replace(/\b(units|hours|cups|bags)\b/, (w) => w.slice(0, -1)) : unit}`;
export function describe(inst) {
  if (inst.ctx.abstract) return `Consider the problem: ${lppStr(inst)}`;
  const C = inst.ctx; const [k1, k2] = inst.cons; const R = C.res; const cap = inst.cons[2];
  if (inst.obj.sense === "max") {
    const s = `${C.maker} makes ${C.x} (x) and ${C.y} (y). A ${C.xs} needs ${q1(k1.a, R[0].unit)} and ${q1(k2.a, R[1].unit)}; a ${C.ys} needs ${q1(k1.b, R[0].unit)} and ${q1(k2.b, R[1].unit)}. Available ${C.per}: ${k1.c} ${R[0].unit} and ${k2.c} ${R[1].unit}.${cap ? ` Also, ${C.cap.replace("{k}", cap.c)}.` : ""} Profit is ${rupee(inst.obj.p)} per ${C.xs} and ${rupee(inst.obj.q)} per ${C.ys}.`;
    return s;
  }
  return `${C.maker} mixes ${C.x} (x) and ${C.y} (y). Each ${C.xs} gives ${q1(k1.a, R[0].unit)} and ${q1(k2.a, R[1].unit)}; each ${C.ys} gives ${q1(k1.b, R[0].unit)} and ${q1(k2.b, R[1].unit)}. At least ${k1.c} ${R[0].unit} and ${k2.c} ${R[1].unit} are needed ${C.per}. Cost is ${rupee(inst.obj.p)} per ${C.xs} and ${rupee(inst.obj.q)} per ${C.ys}.`;
}
export const lppStr = (inst) => `${objStr(inst)} subject to ${inst.cons.map((k) => ineqStr(k)).join(", ")}, x ≥ 0, y ≥ 0.`;

// ---------- sensible changes ----------
export function changes(inst, r) {
  const base = solve(inst); const out = []; const sense = inst.obj.sense;
  if (inst.scenario === "multiple" || base.ties.length !== 1) return out;   // a tie has no single "best plan" to move
  const unique = (ni) => { const t = solve(ni); return t.ties.length === 1 && ni.cons.every((k) => k.a * ni.obj.q !== k.b * ni.obj.p); };
  const tryAll = (cands, pred) => { for (const ni of r.shuffle(cands)) { if (checkInstance(ni).passed && unique(ni) && pred(ni, solve(ni))) return ni; } return null; };
  {
    // 1. profit (cost) per unit of x changes enough to move the best corner
    const ps = []; for (let m = 1; m <= 180; m++) { const p = m * 5; if (p !== inst.obj.p && p >= inst.obj.p * 0.5 && p <= inst.obj.p * 2) ps.push({ ...inst, obj: { ...inst.obj, p } }); }
    const moved = tryAll(ps, (ni, s) => ptStr(s.best) !== ptStr(base.best));
    if (moved) out.push({ id: "profit-moves", inst: moved, rule: "241-LP-A11", text: `Suppose the ${sense === "max" ? "profit" : "cost"} per ${inst.ctx.xs} changes to ${rupee(moved.obj.p)}.` });
    // 2. a modest change that does NOT move the best corner (tests M05)
    const stay = tryAll(ps.filter((ni) => Math.abs(ni.obj.p - inst.obj.p) <= inst.obj.p * 0.3), (ni, s) => ptStr(s.best) === ptStr(base.best));
    if (stay) out.push({ id: "profit-stays", inst: stay, rule: "241-LP-A11", text: `Suppose the ${sense === "max" ? "profit" : "cost"} per ${inst.ctx.xs} changes to ${rupee(stay.obj.p)}.` });
  }
  // 3. more of a binding resource (max) or a higher requirement (min): the corner moves
  const bi = base.binding.findIndex((b) => b);
  if (bi >= 0) {
    const k = inst.cons[bi]; const cands = [];
    for (let c = Math.ceil(k.c * 1.1); c <= Math.floor(k.c * 1.6); c++) if (c % 5 === 0 || c <= 30) cands.push({ ...inst, cons: inst.cons.map((kk, i) => (i === bi ? { ...kk, c } : kk)) });
    const more = tryAll(cands, (ni, s) => !s.best.z.eq(base.best.z));
    if (more) out.push({ id: "resource", inst: more, idx: bi, rule: "241-LP-A12", text: `Suppose ${inst.obj.sense === "max" ? `${more.cons[bi].c} ${inst.ctx.res[bi].unit} are available` : `at least ${more.cons[bi].c} ${inst.ctx.res[bi].unit} are needed`} instead of ${k.c}.` });
  }
  // 4. max only: a market cap on x that cuts off the best corner
  if (sense === "max" && inst.cons.length === 2 && base.best.x.val() > 0) {
    const cands = []; for (let kx = 1; kx < base.best.x.val(); kx++) cands.push({ ...inst, cons: [...inst.cons, { a: 1, b: 0, c: kx, op: "<=", res: 2 }] });
    const capped = tryAll(cands, (ni, s) => ptStr(s.best) !== ptStr(base.best));
    if (capped) out.push({ id: "cap", inst: capped, rule: "241-LP-A06", text: `Suppose ${inst.ctx.cap.replace("{k}", capped.cons[2].c)}.` });
  }
  return out;
}

// ---------- questions ----------
function mcq(r, { key, distractors }) {
  const all = r.shuffle([{ text: key, key: true }, ...distractors]);
  return { options: all.map((o) => o.text), answer: all.findIndex((o) => o.key), distractors: all.filter((o) => !o.key).map((o) => ({ text: o.text, why: o.why, misconception_id: o.mis })) };
}
const fig = (inst, show, extra = {}) => ({ cls: ID, inst, show, ...extra });

export function questions(inst, r) {
  const qs = []; const sol = solve(inst); const D = describe(inst); const C = inst.ctx;
  const only = inst.scenario === "nomax" ? "extreme" : null;
  // Q1 formulate one constraint: options are a 2x2 grid (right / swapped coefficients) x (right / flipped sign)
  if (!inst.ctx.abstract && inst.scenario !== "nomax") {
    const i = r.int(0, 1); const k = inst.cons[i];
    const flip = (kk) => ({ ...kk, op: kk.op === "<=" ? ">=" : "<=" }); const swap = { ...k, a: k.b, b: k.a };
    const opts = [{ text: ineqStr(swap), why: "amounts on the wrong variable", mis: "241-LP-M02" }, { text: ineqStr(flip(k)), why: "inequality the wrong way", mis: "241-LP-M01" }, { text: ineqStr(flip(swap)), why: "both", mis: "241-LP-M01" }];
    if (k.a !== k.b) qs.push({ type: "mcq", kind: "formulate", rule: "241-LP-A02", prompt: `${D} Which inequality describes the ${C.res[i].name} ${inst.obj.sense === "max" ? "available" : "requirement"}?`,
      ...mcq(r, { key: ineqStr(k), distractors: opts }), explanation: `Each ${C.xs} ${inst.obj.sense === "max" ? "needs" : "supplies"} ${k.a} and each ${C.ys} ${k.b}, so x ${C.x} and y ${C.y} ${inst.obj.sense === "max" ? "need" : "supply"} ${ineqStr({ ...k, c: "" }).replace(/ [≤≥] $/, "")} ${C.res[i].unit}. ${inst.obj.sense === "max" ? "That cannot exceed what is available" : "That must be at least the requirement"}: ${ineqStr(k)}.`,
      atom_ids: ["241-LP-A02"], misconception_id: "241-LP-M01", figure: null, difficulty: 1, signature: `formulate:${inst.scenario}` });
  }
  // Q2 corner points (multi): 1-3 true corners among four; graph shows the lines only (no shading to read corners from)
  {
    const decoys = r.shuffle(sol.decoys);
    const kTrue = Math.max(4 - decoys.length, r.int(1, Math.min(3, sol.corners.length)));
    const keys = r.shuffle(sol.corners).slice(0, kTrue); const ds = decoys.slice(0, 4 - keys.length);
    if (keys.length >= 1 && keys.length + ds.length === 4) {
      const opts = r.shuffle([...keys.map((p) => ({ t: ptStr(p), k: true })), ...ds.map((p) => ({ t: ptStr(p), k: false }))]);
      qs.push({ type: "multi", kind: "corners", group: "core", rule: "241-LP-A06", prompt: `${D}${inst.ctx.abstract ? "" : ` The problem is: ${lppStr(inst)}`} The boundary lines are drawn. Which of these points are corner points of the feasible region? Select all that apply.`,
        options: opts.map((o) => o.t), answer: opts.map((o, i) => (o.k ? i : -1)).filter((i) => i >= 0),
        explanation: `A point is a corner only if it lies on two boundary lines AND satisfies every constraint. ${ds.map((p) => `${ptStr(p)} lies where two boundary lines cross, but it breaks ${inst.cons.map((k) => (feasible({ ...inst, cons: [k] }, p) ? null : `${ineqStr(k)}`)).filter(Boolean).join(" and ")}`).join("; ")}${ds.length ? "." : ""} The corners are ${sol.corners.map(ptStr).join(", ")}.`,
        atom_ids: ["241-LP-A05", "241-LP-A06"], misconception_id: "241-LP-M03", figure: fig(inst, ["lines"]), difficulty: 2, signature: `corners:${inst.scenario}` });
    }
  }
  // Q3 which corner is optimal: options are corners only, so the student must evaluate Z
  if (inst.scenario !== "multiple" && inst.scenario !== "nomax") {
    const others = r.shuffle(sol.corners.filter((p) => p !== sol.best));
    const pool = [...others.filter((p) => p.x.sign() || p.y.sign()), ...others.filter((p) => !(p.x.sign() || p.y.sign())), ...r.shuffle(sol.decoys)];
    const ds = pool.slice(0, 3).map((p) => ({ text: ptStr(p), why: sol.decoys.includes(p) ? "not even feasible" : "did not compare Z at every corner", mis: sol.decoys.includes(p) ? "241-LP-M03" : "241-LP-M04" }));
    if (ds.length === 3) qs.push({ type: "mcq", kind: "optimum", group: "core", rule: "241-LP-A07", prompt: `${D} The feasible region is shown. At which point is Z ${inst.obj.sense === "max" ? "greatest" : "least"}?`,
      ...mcq(r, { key: ptStr(sol.best), distractors: ds }),
      explanation: `Z = ${zExpr(inst)} at each corner: ${sol.corners.map((p) => `${ptStr(p)} → ${inr(p.z.val())}`).join("; ")}. ${inst.obj.sense === "max" ? "Largest" : "Smallest"}: ${inr(sol.best.z.val())} at ${ptStr(sol.best)}.${sol.bounded ? "" : ` The region is unbounded, so check: ${zExpr(inst)} < ${inr(sol.best.z.val())} has no point in common with it, so ${inr(sol.best.z.val())} is the minimum.`}`,
      atom_ids: ["241-LP-A07"], misconception_id: "241-LP-M04", figure: fig(inst, ["lines", "region", "corners"]), difficulty: 2, signature: `optimum:${inst.scenario}` });
  }
  // Q4b abstract problems: "what can you say about the max / min?" (sometimes it exists, sometimes not)
  if (inst.ctx.abstract) {
    const isMax = inst.obj.sense === "max"; const word = isMax ? "maximum" : "minimum";
    const top = sol.corners.reduce((b, p) => (p.z.cmp(b.z) > 0 ? p : b)); const low = sol.corners.reduce((b, p) => (p.z.cmp(b.z) < 0 ? p : b));
    const exists = sol.optimumExists; const bestP = isMax ? top : low; const otherP = isMax ? low : top;
    const mid = sol.corners.find((p) => p !== top && p !== low) || otherP;
    const key = exists ? `The ${word} is ${inr(bestP.z.val())}, at ${ptStr(bestP)}` : `Z has no ${word} value`;
    const zOf = (p) => F(inst.obj.p).mul(p.x).add(F(inst.obj.q).mul(p.y));
    const tempt = sol.decoys.filter((p) => (isMax ? zOf(p).cmp(bestP.z) > 0 : zOf(p).cmp(bestP.z) < 0))[0];
    const ds = exists
      ? [{ text: `Z has no ${word} value`, why: "thought an unbounded region never has an optimum", mis: "241-LP-M07" },
         tempt ? { text: `The ${word} is ${inr(zOf(tempt).val())}, at ${ptStr(tempt)}`, why: "used a crossing point that is not feasible", mis: "241-LP-M03" } : { text: `The ${word} is ${inr(mid.z.val())}, at ${ptStr(mid)}`, why: "did not compare all corners", mis: "241-LP-M04" },
         { text: `The ${word} is ${inr(otherP.z.val())}, at ${ptStr(otherP)}`, why: "took the wrong extreme", mis: "241-LP-M04" }]
      : [{ text: `The ${word} is ${inr(bestP.z.val())}, at ${ptStr(bestP)}`, why: "took the largest corner without the unbounded check", mis: "241-LP-M07" }, { text: `The ${word} is ${inr(mid.z.val())}, at ${ptStr(mid)}`, why: "took a middle corner", mis: "241-LP-M04" }, { text: `The ${word} is ${inr(otherP.z.val())}, at ${ptStr(otherP)}`, why: "took the smallest corner", mis: "241-LP-M04" }];
    const lhs = zExpr(inst); const M = inr(bestP.z.val());
    qs.push({ type: "mcq", kind: "extreme", group: "core", rule: "241-LP-A10", prompt: `${D} What can you say about the ${word} value of Z?`,
      ...mcq(r, { key, distractors: ds }),
      explanation: `Corners: ${sol.corners.map((p) => `${ptStr(p)} → ${inr(p.z.val())}`).join("; ")}. The region is unbounded, so the ${isMax ? "largest" : "smallest"} corner value ${M} is only a candidate. Test the half-plane ${lhs} ${isMax ? ">" : "<"} ${M}: ${exists ? `it has no point in common with the region, so the ${word} is ${M} at ${ptStr(bestP)}.` : `it contains feasible points (for example, points far out along the x-axis), so Z can be made as large as we like and has no maximum.`}`,
      atom_ids: ["241-LP-A09", "241-LP-A10"], misconception_id: "241-LP-M07", figure: fig(inst, ["lines", "region", "corners"]), difficulty: 3, signature: "extreme" });
  }
  // Q4 numeric optimum
  if (!inst.ctx.abstract) qs.push({ type: "numeric", kind: "value", group: "core", rule: "241-LP-A07", prompt: `${D} Find the ${inst.obj.sense === "max" ? "maximum profit" : "minimum cost"} (in ₹).`, answer: sol.best.z.val(), tolerance: 0, unit: "₹",
    explanation: `${lppStr(inst)} Corners: ${sol.corners.map((p) => `${ptStr(p)} → ${inr(p.z.val())}`).join("; ")}. ${inst.obj.sense === "max" ? "Maximum" : "Minimum"} ${rupee(sol.best.z.val())}${sol.ties.length > 1 ? ` (at ${sol.ties.map(ptStr).join(" and ")} and every point between)` : ` at ${ptStr(sol.best)}`}.`,
    atom_ids: ["241-LP-A07"], misconception_id: "241-LP-M04", figure: fig(inst, ["lines", "region"]), difficulty: 2, signature: `value:${inst.scenario}` });
  // Q5 multiple optima: the student must find that two corners tie (nothing in the stem or figure says so)
  if (inst.scenario === "multiple") {
    const [p1, p2] = sol.ties; const third = sol.corners.find((p) => !sol.ties.includes(p) && (p.x.sign() || p.y.sign())) || sol.corners.find((p) => !sol.ties.includes(p));
    qs.push({ type: "mcq", kind: "multiple", group: "core", rule: "241-LP-A08", prompt: `${D} Where does Z take its maximum value? (Treat x and y as continuous.)`,
      ...mcq(r, { key: `At every point of the edge from ${ptStr(p1)} to ${ptStr(p2)}`, distractors: [
        { text: `Only at the corner ${ptStr(p1)}`, why: "stopped at the first best corner", mis: "241-LP-M08" },
        { text: `Only at the corner ${ptStr(p2)}`, why: "stopped at the first best corner", mis: "241-LP-M08" },
        { text: `Only at the corner ${ptStr(third)}`, why: "did not compare Z at every corner", mis: "241-LP-M04" }] }),
      explanation: `The profit line ${zExpr(inst)} = k is parallel to the edge ${inst.cons.map((k) => ineqStr(k)).find((s, i) => inst.cons[i].a * inst.obj.q === inst.cons[i].b * inst.obj.p).replace("≤", "=")}. Every point on that edge between the two corners gives Z = ${inr(sol.best.z.val())}, so there are infinitely many optimal solutions. (If only whole numbers of items were allowed, only the whole-number points on that edge would count.)`,
      atom_ids: ["241-LP-A08"], misconception_id: "241-LP-M08", figure: fig(inst, ["lines", "region", "corners"]), difficulty: 3, signature: "multiple" });
  }
  // Q6 unbounded region (min)
  if (inst.scenario === "min") {
    const m = inr(sol.best.z.val()); const lhs = `${zExpr(inst)}`;
    qs.push({ type: "mcq", kind: "unbounded", group: "core", rule: "241-LP-A10", prompt: `${D} The feasible region is unbounded, and the smallest corner value is Z = ${m}. What must you check before concluding that ${m} is the minimum cost?`,
      ...mcq(r, { key: `That ${lhs} < ${m} has no point in common with the feasible region`, distractors: [
        { text: `That ${lhs} > ${m} has no point in common with the feasible region`, why: "wrong half-plane", mis: "241-LP-M07" },
        { text: `Nothing: the smallest corner value is always the minimum`, why: "skipped the unbounded check", mis: "241-LP-M07" },
        { text: `That the feasible region can be enclosed in a circle`, why: "that is the test for bounded, which fails here", mis: "241-LP-M07" }] }),
      explanation: `For an unbounded region a corner value is only a candidate. Draw ${lhs} = ${m} and look at the side where Z is smaller (${lhs} < ${m}). If no feasible point lies there, ${m} is the minimum. Here ${lhs} < ${m} is the side of that line containing the origin, and every feasible point lies on or beyond the line, so the two have no point in common.`,
      atom_ids: ["241-LP-A09", "241-LP-A10"], misconception_id: "241-LP-M07", figure: fig(inst, ["lines", "region", "corners"]), difficulty: 3, signature: "unbounded" });
  }
  // Q7 find the error: one constraint shaded on the wrong side
  {
    const i = r.int(0, 1);
    const rn = inst.ctx.res;
    const label = (j) => `the ${(rn[j] && rn[j].name) || "market"} constraint ${ineqStr(inst.cons[j])}`;
    const ds = [
      { text: `Nothing is wrong; the shaded region is the feasible region`, why: "missed the shading", mis: "241-LP-M09" },
      { text: inst.cons[0].op === "<=" ? `The origin (0, 0) should lie outside the feasible region` : `The origin (0, 0) should lie inside the feasible region`, why: "origin test applied the wrong way", mis: "241-LP-M09" },
      { text: `${label(1 - i).replace(/^./, (s) => s.toUpperCase())} is shaded on the wrong side`, why: "blamed the other constraint", mis: "241-LP-M09" },
    ];
    qs.push({ type: "mcq", kind: "error", rule: "241-LP-A04", prompt: `${D} A student graphed ${inst.ctx.abstract ? "this problem" : lppStr(inst).replace(/\.$/, "")} and shaded the region shown. What is wrong with the graph?`,
      ...mcq(r, { key: `${label(i).replace(/^./, (s) => s.toUpperCase())} is shaded on the wrong side`, distractors: ds }),
      explanation: `Test the origin in ${ineqStr(inst.cons[i])}: 0 ${inst.cons[i].op === "<=" ? "≤" : "≥"} ${inst.cons[i].c} is ${inst.cons[i].op === "<=" ? "true" : "false"}, so the feasible side is the one ${inst.cons[i].op === "<=" ? "containing" : "away from"} the origin. The student shaded the other side.`,
      atom_ids: ["241-LP-A04"], misconception_id: "241-LP-M09", figure: fig(inst, ["lines", "region"], { wrongSide: i }), difficulty: 2, signature: `error:${inst.scenario}` });
  }
  return qs.filter((q) => !only || q.kind === only).map((q) => ({ ...q, marks: 1 }));
}

export function whatIfQuestions(inst, r) {
  if (inst.ctx.abstract) return [];
  const base = solve(inst); const qs = [];
  for (const ch of changes(inst, r)) {
    const s = solve(ch.inst); const moved = ptStr(s.best) !== ptStr(base.best);
    const nonOrigin = (p) => p.x.sign() || p.y.sign();
    const others = r.shuffle(s.corners.filter((p) => ptStr(p) !== ptStr(s.best)));
    const oldBest = others.find((p) => ptStr(p) === ptStr(base.best));
    const pool = [oldBest, ...others.filter((p) => p !== oldBest && nonOrigin(p)), ...others.filter((p) => !nonOrigin(p))].filter(Boolean);
    const ds = pool.slice(0, 3).map((p) => ({ text: ptStr(p), why: p === oldBest ? "assumed the best plan never moves" : "did not recompare the corners", mis: p === oldBest ? (ch.id === "resource" ? "241-LP-M06" : "241-LP-M05") : "241-LP-M04" }));
    if (!moved && ds.length < 3) continue;
    if (ds.length < 3) continue;
    const D = describe(inst); const word = inst.obj.sense === "max" ? "profit" : "cost";
    const atom = inst.obj.sense === "min" ? ATOMS[ch.rule].replace("profit per unit", "cost per unit").replace("best profit", "best cost") : ATOMS[ch.rule];
    qs.push({ type: "mcq", kind: "whatif", group: "core", rule: ch.rule, change: ch.id,
      prompt: `${D} At present the best plan is ${ptStr(base.best)}, i.e. ${base.best.x} ${inst.ctx.x} and ${base.best.y} ${inst.ctx.y}. ${ch.text} Which point is now the best plan?`,
      ...mcq(r, { key: ptStr(s.best), distractors: ds }),
      explanation: `New corner values of Z (${word}): ${s.corners.map((p) => `${ptStr(p)} → ${inr(p.z.val())}`).join("; ")}. ${moved ? `The best corner moves to ${ptStr(s.best)}.` : `${ptStr(base.best)} is still best, although Z is now ${inr(s.best.z.val())}.`}${s.bounded ? "" : ` (Unbounded region: ${zExpr(ch.inst)} < ${inr(s.best.z.val())} has no point in common with it, so this is the minimum.)`} ${atom}`,
      atom_ids: [ch.rule, "241-LP-A07"], misconception_id: ds[0].mis, figure: fig(inst, ["lines", "region", "corners"], { after: ch.inst }), difficulty: 3, marks: 1, signature: `whatif:${ch.id}`,
      changeMoves: moved, changeShouldMove: ch.id !== "profit-stays" });
  }
  return qs;
}

export function checkClassQuestion(q) {
  const c = new Checks(q.id); const inst = (q.figure && q.figure.inst) || q._inst;
  if (q.kind === "whatif") {
    const b = solve(inst), a = solve(q.figure.after);
    c.ok("what-if: one best plan before and after", b.ties.length === 1 && a.ties.length === 1, `ties before ${b.ties.length}, after ${a.ties.length}`);
  }
  if (inst) c.ok("instance passes", checkInstance(inst).passed, "instance fails checks");
  if (q.kind === "whatif") {
    c.ok("changed instance passes", checkInstance(q.figure.after).passed, "changed instance not sensible");
    if (q.change === "profit-stays") c.ok("corner really stays", !q.changeMoves, "corner moved");
    else if (q.change !== "resource") c.ok("corner really moves", q.changeMoves, "corner did not move");
    else c.ok("more resource changes the best plan", q.changeMoves, "corner did not move");
  }
  if (q.kind === "corners") {
    const sol = solve(inst); const truth = q.options.map((o) => sol.corners.some((p) => ptStr(p) === o));
    c.ok("multi key matches the solver", JSON.stringify(q.answer) === JSON.stringify(truth.map((t, i) => (t ? i : -1)).filter((i) => i >= 0)), "key mismatch");
  }
  return c;
}