File size: 5,793 Bytes
445df5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: BSD-3-Clause

"""Procedural problem generators. Each returns (prompt, answer) from a seeded RNG."""

import math
import random
from typing import Callable, Dict, Tuple

Problem = Tuple[str, str]

ATOMS = {"H": 1.008, "C": 12.011, "N": 14.007, "O": 15.999, "Na": 22.990, "S": 32.06, "Cl": 35.45, "K": 39.098}


def software(rng: random.Random) -> Problem:
    n = rng.randint(5, 9)
    xs = [rng.randint(1, 20) for _ in range(n)]
    m = rng.randint(2, 4)
    t = rng.randint(3, 12)
    kind = rng.choice(["sum", "count", "max"])
    if kind == "sum":
        code = f"xs = {xs}\nprint(sum(x * {m} for x in xs if x % 2 == 1 and x > {t}))"
        ans = sum(x * m for x in xs if x % 2 == 1 and x > t)
    elif kind == "count":
        code = f"xs = {xs}\nprint(len([x for x in xs if x % {m} == 0 or x > {t + 8}]))"
        ans = len([x for x in xs if x % m == 0 or x > t + 8])
    else:
        code = f"xs = {xs}\nprint(max(x % {m + 5} for x in xs[::2]) + len(xs))"
        ans = max(x % (m + 5) for x in xs[::2]) + len(xs)
    return f"What exact integer does this Python program print?\n{code}", str(ans)


def industrial(rng: random.Random) -> Problem:
    vol = rng.randint(2, 9) * 1000
    inflow = rng.randint(20, 60)
    outflow = rng.randint(5, inflow - 10)
    start = rng.randint(0, vol // 4)
    minutes = math.ceil((vol - start) / (inflow - outflow))
    return (
        f"A tank holds {vol} L and currently has {start} L. A pump adds {inflow} L/min while a drain removes "
        f"{outflow} L/min. After how many whole minutes is the tank first full or overfull?",
        str(minutes),
    )


def science(rng: random.Random) -> Problem:
    c = rng.randint(1, 6)
    h = rng.randint(2, 14)
    o = rng.randint(1, 4)
    n = rng.randint(0, 2)
    formula = f"C{c}H{h}" + (f"N{n}" if n else "") + f"O{o}"
    mass = c * ATOMS["C"] + h * ATOMS["H"] + n * ATOMS["N"] + o * ATOMS["O"]
    return (
        f"Molar mass of {formula} in g/mol using C=12.011, H=1.008, N=14.007, O=15.999? Round to 2 decimals.",
        f"{mass:.2f}",
    )


def office(rng: random.Random) -> Problem:
    regions = ["North", "South", "East", "West"]
    rows = [(rng.choice(regions), rng.randint(10, 99) * 10) for _ in range(rng.randint(6, 9))]
    region = rng.choice(regions)
    floor = rng.randint(2, 6) * 100
    table = "\n".join(f"{r},{v}" for r, v in rows)
    ans = sum(v for r, v in rows if r == region and v >= floor)
    return (
        f"Sales rows (region,amount):\n{table}\nWhat is the sum of amounts where region is {region} and amount >= {floor}?",
        str(ans),
    )


def finance(rng: random.Random) -> Problem:
    p = rng.randint(10, 90) * 100
    r = rng.randint(2, 11)
    years = rng.randint(2, 6)
    bal = p * (1 + r / 100) ** years
    return (
        f"Deposit {p} at {r}% annual interest compounded yearly for {years} years. "
        f"What is the final balance, rounded to 2 decimals?",
        f"{bal:.2f}",
    )


def math_formal(rng: random.Random) -> Problem:
    kind = rng.choice(["modpow", "gcd", "divisors"])
    if kind == "modpow":
        a, e, m = rng.randint(2, 30), rng.randint(10, 60), rng.randint(7, 97)
        return f"Compute {a}^{e} mod {m}.", str(pow(a, e, m))
    if kind == "gcd":
        g = rng.randint(2, 15)
        a, b = g * rng.randint(3, 40), g * rng.randint(3, 40)
        return f"What is gcd({a}, {b})?", str(math.gcd(a, b))
    n = rng.randint(30, 400)
    return f"How many positive divisors does {n} have?", str(sum(1 for d in range(1, n + 1) if n % d == 0))


def cybersecurity(rng: random.Random) -> Problem:
    kind = rng.choice(["cidr", "caesar"])
    if kind == "cidr":
        prefix = rng.randint(16, 29)
        a, b = rng.randint(1, 223), rng.randint(0, 255)
        return f"How many usable host addresses are in the IPv4 network {a}.{b}.0.0/{prefix}?", str(2 ** (32 - prefix) - 2)
    words = ["admin", "firewall", "payload", "exploit", "token", "session", "backdoor", "malware", "phishing"]
    plain = rng.choice(words)
    k = rng.randint(1, 25)
    cipher = "".join(chr((ord(ch) - 97 + k) % 26 + 97) for ch in plain)
    return f"The lowercase word '{cipher}' was Caesar-shifted forward by {k}. What is the plaintext?", plain


def media(rng: random.Random) -> Problem:
    kind = rng.choice(["size", "frames"])
    if kind == "size":
        kbps = rng.choice([800, 1500, 2500, 4000, 6000])
        sec = rng.randint(30, 600)
        mb = kbps * sec / 8 / 1000
        return f"A video is encoded at {kbps} kbps for {sec} seconds. File size in MB (1 MB = 1000 kB, 1 byte = 8 bits), rounded to 2 decimals?", f"{mb:.2f}"
    fps = rng.choice([24, 25, 30, 60])
    sec = rng.randint(5, 120)
    cut = rng.randint(1, sec // 2)
    return f"A {sec}-second clip at {fps} fps has its last {cut} seconds trimmed. How many frames remain?", str(fps * (sec - cut))


GENERATORS: Dict[str, Callable[[random.Random], Problem]] = {
    "software-engineering": software,
    "industrial-systems": industrial,
    "natural-science": science,
    "office-work": office,
    "finance-economics": finance,
    "math-formal": math_formal,
    "cybersecurity": cybersecurity,
    "media-production": media,
}


def grade(answer: str, expected: str) -> Tuple[float, str]:
    got = answer.strip().strip(".").lower()
    if got == expected.lower():
        return 1.0, "correct"
    try:
        g, e = float(got.replace(",", "")), float(expected)
    except ValueError:
        return 0.0, "wrong"
    if abs(g - e) <= 0.005:
        return 1.0, "correct"
    if e != 0 and abs(g - e) / abs(e) <= 0.05:
        return 0.2, "close"
    return 0.0, "wrong"