ac-algorithm 0.2.0

Algorithm competition domain logic for ac
Documentation
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Deterministic test-case generation (A-03, issue #26).
//!
//! Ports ac-test's Level-1 generation semantics (spike #6 §2.3–§2.5)
//! onto the domain model: integer scalars and one-dimensional integer
//! arrays, boundary values plus fixed-seed pseudo-random cases, and
//! conservative skipping whenever valid input cannot be proven.
//!
//! [`spec`] parses the input-format block and constraint lines into a
//! [`GenSpec`]; [`prng`] holds the xorshift32 generator; this module
//! drives the five generation modes.

pub mod prng;
mod spec;

pub use spec::{Expr, FormatLine, GenSpec, InputFormat, SpecError, VarBounds, VarKey};

use std::collections::BTreeMap;

use prng::XorShift32;

/// ac-test's default seed base (`0xac7e57`).
pub const DEFAULT_SEED_BASE: u32 = 0x00ac_7e57;
/// Maximum array length; longer arrays discard the case (spike #6 §2.5).
pub const MAX_ARRAY_LENGTH: i64 = 2_000_000;

/// The five ac-test generation modes, in emission order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GenMode {
    /// Every value at its lower bound.
    Min,
    /// Every value at lower bound + 1.
    NearMin,
    /// Every value at upper bound - 1.
    NearMax,
    /// Every value at its upper bound.
    Max,
    /// Structure sizes at max; array elements pseudo-random in range.
    RandomMax,
}

impl GenMode {
    /// All modes in emission order.
    pub const ALL: [Self; 5] = [
        Self::Min,
        Self::NearMin,
        Self::NearMax,
        Self::Max,
        Self::RandomMax,
    ];

    /// Case-name suffix (`generated-<name>`).
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            Self::Min => "min",
            Self::NearMin => "near-min",
            Self::NearMax => "near-max",
            Self::Max => "max",
            Self::RandomMax => "random-max",
        }
    }
}

/// One generated case: deterministic input text plus its provenance.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GeneratedCase {
    /// Case name (`generated-min`, …).
    pub name: String,
    /// Generation mode that produced it.
    pub mode: GenMode,
    /// xorshift32 seed actually used (recorded for reproducibility).
    pub seed: u32,
    /// Input text, newline-terminated.
    pub input: String,
}

/// A mode that could not produce a case (e.g. array length cap).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SkippedCase {
    /// Mode that was attempted.
    pub mode: GenMode,
    /// Why the case was discarded.
    pub reason: String,
}

/// Result of [`Generator::generate`].
#[derive(Clone, Debug, Default)]
pub struct GenOutcome {
    /// Successfully generated cases, in mode order.
    pub cases: Vec<GeneratedCase>,
    /// Modes skipped with their reasons.
    pub skipped: Vec<SkippedCase>,
    /// Set when the spec itself is unsupported — no cases are produced.
    pub unsupported: Option<String>,
}

/// Runs a parsed [`GenSpec`] through the five modes.
#[derive(Clone, Debug)]
pub struct Generator {
    spec: GenSpec,
    /// Task identifier mixed into every seed (ac-test used the task
    /// name; we use the task screen name or directory label).
    task: String,
    /// Seed base; [`DEFAULT_SEED_BASE`] unless overridden.
    seed_base: u32,
}

impl Generator {
    /// Builds a generator for `spec` under `task` with `seed_base`.
    #[must_use]
    pub fn new(spec: GenSpec, task: impl Into<String>, seed_base: u32) -> Self {
        Self {
            spec,
            task: task.into(),
            seed_base,
        }
    }

    /// Generates all five modes. Deterministic: identical spec, task,
    /// and seed base always yield identical cases.
    #[must_use]
    pub fn generate(&self) -> GenOutcome {
        let mut outcome = GenOutcome::default();
        for mode in GenMode::ALL {
            let seed = self.seed_base
                ^ u32::try_from(self.task.len()).unwrap_or(u32::MAX)
                ^ u32::try_from(mode.name().len()).unwrap_or(u32::MAX);
            match self.generate_mode(mode, seed) {
                Ok(input) => outcome.cases.push(GeneratedCase {
                    name: format!("generated-{}", mode.name()),
                    mode,
                    seed,
                    input,
                }),
                Err(reason) => outcome.skipped.push(SkippedCase { mode, reason }),
            }
        }
        outcome
    }

    /// Generates one mode's input text.
    fn generate_mode(&self, mode: GenMode, seed: u32) -> Result<String, String> {
        let mut rng = XorShift32::new(seed);
        let mut chosen: BTreeMap<String, i64> = BTreeMap::new();

        // Resolve scalar values in dependency order: a variable becomes
        // ready once every variable its bound expressions reference has
        // been chosen. Unresolvable references (element vars, unknown
        // names, cycles) leave the variable stuck and skip the case.
        let scalars: Vec<(&str, &VarBounds)> = self.spec.scalar_bounds().collect();
        while chosen.len() < scalars.len() {
            let mut progressed = false;
            for &(name, bounds) in &scalars {
                if chosen.contains_key(name) || !bounds_ready(bounds, &chosen) {
                    continue;
                }
                let value = pick_scalar(mode, bounds, &chosen)?;
                chosen.insert(name.to_owned(), value);
                progressed = true;
            }
            if !progressed {
                return Err(
                    "constraint bounds are cyclic or reference unknown variables".to_owned(),
                );
            }
        }

        // Array lengths come from their (already chosen) length
        // variables; element bounds resolve once against the chosen
        // scalars, then every element picks per mode.
        let mut rendered: Vec<String> = Vec::with_capacity(self.spec.format.lines.len());
        for line in &self.spec.format.lines {
            match line {
                FormatLine::Scalars(names) => {
                    let mut parts = Vec::with_capacity(names.len());
                    for name in names {
                        parts.push(
                            chosen
                                .get(name)
                                .map(i64::to_string)
                                .ok_or_else(|| format!("scalar `{name}` has no value"))?,
                        );
                    }
                    rendered.push(parts.join(" "));
                }
                FormatLine::Array {
                    name, length_var, ..
                } => {
                    let length = *chosen.get(length_var).ok_or_else(|| {
                        format!("array length variable `{length_var}` has no value")
                    })?;
                    if !(0..=MAX_ARRAY_LENGTH).contains(&length) {
                        return Err(format!(
                            "array `{name}` length {length} exceeds the {MAX_ARRAY_LENGTH} cap"
                        ));
                    }
                    let (lowers, uppers) = self
                        .spec
                        .element_bounds(name)
                        .ok_or_else(|| format!("array `{name}` has no element bounds"))?;
                    let low = eval_bounds_low(lowers, &chosen)?;
                    let high = eval_bounds_high(uppers, &chosen)?;
                    if low > high {
                        return Err(format!("array `{name}` element range is empty"));
                    }
                    let mut elements = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
                    for _ in 0..length {
                        elements.push(pick_element(mode, low, high, &mut rng).to_string());
                    }
                    rendered.push(elements.join(" "));
                }
            }
        }

        let mut input = rendered.join("\n");
        input.push('\n');
        Ok(input)
    }
}

/// `true` when every variable referenced by `bounds` already has a
/// chosen value.
fn bounds_ready(bounds: &VarBounds, chosen: &BTreeMap<String, i64>) -> bool {
    bounds
        .lowers
        .iter()
        .chain(bounds.uppers.iter())
        .flat_map(Expr::vars)
        .all(|var| chosen.contains_key(var))
}

/// Evaluates all lower-bound expressions and returns the maximum.
fn eval_bounds_low(exprs: &[Expr], env: &BTreeMap<String, i64>) -> Result<i64, String> {
    let mut low = i64::MIN;
    for expr in exprs {
        low = low.max(expr.eval(env).map_err(|err| err.to_string())?);
    }
    Ok(low)
}

/// Evaluates all upper-bound expressions and returns the minimum.
fn eval_bounds_high(exprs: &[Expr], env: &BTreeMap<String, i64>) -> Result<i64, String> {
    let mut high = i64::MAX;
    for expr in exprs {
        high = high.min(expr.eval(env).map_err(|err| err.to_string())?);
    }
    Ok(high)
}

/// Picks a scalar value for `mode` inside the resolved `[low, high]`.
fn pick_scalar(
    mode: GenMode,
    bounds: &VarBounds,
    chosen: &BTreeMap<String, i64>,
) -> Result<i64, String> {
    let low = eval_bounds_low(&bounds.lowers, chosen)?;
    let high = eval_bounds_high(&bounds.uppers, chosen)?;
    if low > high {
        return Err(format!("constraint range [{low}, {high}] is empty"));
    }
    Ok(pick_value(mode, low, high))
}

/// Picks one array element: boundary modes reuse [`pick_value`]; only
/// [`GenMode::RandomMax`] draws from the seeded generator.
fn pick_element(mode: GenMode, low: i64, high: i64, rng: &mut XorShift32) -> i64 {
    if mode == GenMode::RandomMax {
        rng.below(low, high)
    } else {
        pick_value(mode, low, high)
    }
}

/// Mode → value inside `[low, high]` (inclusive). `random-max` yields
/// the upper bound for scalars; array elements randomize separately.
fn pick_value(mode: GenMode, low: i64, high: i64) -> i64 {
    match mode {
        GenMode::Min => low,
        GenMode::NearMin => low.saturating_add(1).min(high),
        GenMode::NearMax => high.saturating_sub(1).max(low),
        GenMode::Max | GenMode::RandomMax => high,
    }
    .clamp(low, high)
}

/// Convenience: parse a spec and generate in one call.
///
/// # Errors
///
/// Never fails; parse problems surface as [`GenOutcome::unsupported`].
#[must_use]
pub fn generate_cases(
    input_format: &str,
    constraint_lines: &[String],
    task: &str,
    seed_base: u32,
) -> GenOutcome {
    match GenSpec::parse(input_format, constraint_lines) {
        Ok(spec) => Generator::new(spec, task, seed_base).generate(),
        Err(err) => GenOutcome {
            unsupported: Some(err.to_string()),
            ..GenOutcome::default()
        },
    }
}

#[cfg(test)]
mod tests {
    use super::spec::tests_support::parse_simple_spec;
    use super::*;

    #[test]
    fn modes_emit_boundary_and_random_cases() {
        let spec = parse_simple_spec();
        let outcome = Generator::new(spec, "abc351_a", DEFAULT_SEED_BASE).generate();
        assert!(outcome.unsupported.is_none());
        assert_eq!(outcome.cases.len(), 5);
        assert_eq!(outcome.skipped, Vec::new());
        let by_mode = |m: GenMode| {
            outcome
                .cases
                .iter()
                .find(|c| c.mode == m)
                .expect("mode case")
                .input
                .clone()
        };
        // N M / A_1..A_N with N=length: min → "1 1\n1\n",
        // near-min → "2 2\n2 2\n", near-max → "9 9\n9×9\n",
        // max → "10 10\n10×10\n".
        assert_eq!(by_mode(GenMode::Min), "1 1\n1\n");
        assert_eq!(by_mode(GenMode::NearMin), "2 2\n2 2\n");
        assert_eq!(
            by_mode(GenMode::NearMax),
            format!("9 9\n{}\n", "9 ".repeat(9).trim_end())
        );
        assert_eq!(
            by_mode(GenMode::Max),
            format!("10 10\n{}\n", "10 ".repeat(10).trim_end())
        );
        // random-max: scalars/length at max, elements random in [1,10].
        let random = by_mode(GenMode::RandomMax);
        let mut lines = random.lines();
        assert_eq!(lines.next(), Some("10 10"));
        let elements: Vec<i64> = lines
            .next()
            .expect("array line")
            .split_whitespace()
            .map(|t| t.parse().expect("integer"))
            .collect();
        assert_eq!(elements.len(), 10);
        assert!(elements.iter().all(|&v| (1..=10).contains(&v)));
    }

    #[test]
    fn unsupported_spec_produces_no_cases() {
        let outcome = generate_cases("A_{i,j}\n", &[], "t", DEFAULT_SEED_BASE);
        assert_eq!(outcome.cases, Vec::new());
        assert!(outcome.unsupported.is_some());
    }

    #[test]
    fn generation_is_deterministic_per_seed() {
        // Covered above; here: a different seed base changes random-max.
        let spec = parse_simple_spec();
        let a = Generator::new(spec.clone(), "abc351_a", DEFAULT_SEED_BASE).generate();
        let b = Generator::new(spec, "abc351_a", DEFAULT_SEED_BASE ^ 0x1234_5678).generate();
        assert_ne!(a.cases[4].seed, b.cases[4].seed);
        assert_ne!(a.cases[4].input, b.cases[4].input);
        // Boundary modes are seed-independent.
        assert_eq!(a.cases[0].input, b.cases[0].input);
        assert_eq!(a.cases[3].input, b.cases[3].input);
    }

    #[test]
    fn missing_bounds_skip_generation() {
        let outcome = generate_cases("N\n", &["1 <= N <= 10".to_owned()], "t", DEFAULT_SEED_BASE);
        assert_eq!(outcome.cases.len(), 5);
        // Unbounded scalar → unsupported.
        let outcome = generate_cases(
            "N M\n",
            &["1 <= N <= 10".to_owned()],
            "t",
            DEFAULT_SEED_BASE,
        );
        assert_eq!(outcome.cases, Vec::new());
        assert!(outcome.unsupported.is_some());
    }

    #[test]
    fn oversized_array_length_skips_only_that_mode() {
        // N max = 2_000_001 > cap: min/near-min/near-max still generate.
        let outcome = generate_cases(
            "N\nA_1 A_2 ... A_N\n",
            &[
                "1 <= N <= 2000001".to_owned(),
                "1 <= A_i <= 10 (1 <= i <= N)".to_owned(),
            ],
            "t",
            DEFAULT_SEED_BASE,
        );
        assert!(outcome.unsupported.is_none());
        assert_eq!(outcome.cases.len(), 3, "min/near-min/near-max survive");
        assert_eq!(outcome.skipped.len(), 2, "max/random-max exceed cap");
        assert!(outcome.skipped.iter().all(|s| s.reason.contains("exceeds")));
    }
}