rustoku-lib 0.15.0

Lightning-fast Sudoku solving and generation
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
408
409
//! High-level helpers intended for language bindings (`rustoku-wasm`, `rustoku-py`, …).
//!
//! Rust consumers of `rustoku-lib` should use the core [`crate::Rustoku`] API directly.
//! This module deliberately sits at `rustoku_lib::bind` and is **not** re-exported
//! at the crate root so it stays out of the way.
//!
//! These functions wrap the core [`Rustoku`] primitives and return simple, fully-owned
//! Rust types so that binding crates (`rustoku-wasm`, `rustoku-py`, …) contain no
//! solving logic of their own – they only marshal results into the target language's
//! type system.

use crate::core::{BoardGenerator, Difficulty, SolveStep, Symmetry, TechniqueFlags};
use crate::error::RustokuError;
use crate::format::format_line;
use crate::{Rustoku, generate_board_by_difficulty};
use serde::{Deserialize, Serialize};
use std::str::FromStr;

// ── Step / Solution types ─────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CandidateChange {
    pub row: usize,
    pub col: usize,
    pub before: Vec<u8>,
    pub after: Vec<u8>,
    pub removed: Vec<u8>,
    pub added: Vec<u8>,
}

/// Flat, serialisable representation of a single solve step.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SolveStepInfo {
    /// `"placement"` or `"elimination"`.
    #[serde(rename = "type")]
    pub step_type: String,
    pub row: usize,
    pub col: usize,
    pub value: u8,
    /// Human-readable name of the technique used (e.g. `"Naked Singles"`).
    pub technique: String,
    pub step_number: u32,
    pub candidates_eliminated: u32,
    pub related_cell_count: u8,
    /// Difficulty metric (0 = trivial, 10 = hardest).
    pub difficulty_point: u8,
    #[serde(default)]
    pub candidate_changes: Vec<CandidateChange>,
}

impl From<&SolveStep> for SolveStepInfo {
    fn from(step: &SolveStep) -> Self {
        match step {
            SolveStep::Placement {
                row,
                col,
                value,
                flags,
                step_number,
                candidates_eliminated,
                related_cell_count,
                difficulty_point,
            } => SolveStepInfo {
                step_type: "placement".into(),
                row: *row,
                col: *col,
                value: *value,
                technique: flags.to_string(),
                step_number: *step_number,
                candidates_eliminated: *candidates_eliminated,
                related_cell_count: *related_cell_count,
                difficulty_point: *difficulty_point,
                candidate_changes: Vec::new(),
            },
            SolveStep::CandidateElimination {
                row,
                col,
                value,
                flags,
                step_number,
                candidates_eliminated,
                related_cell_count,
                difficulty_point,
            } => SolveStepInfo {
                step_type: "elimination".into(),
                row: *row,
                col: *col,
                value: *value,
                technique: flags.to_string(),
                step_number: *step_number,
                candidates_eliminated: *candidates_eliminated,
                related_cell_count: *related_cell_count,
                difficulty_point: *difficulty_point,
                candidate_changes: Vec::new(),
            },
        }
    }
}

/// Structured output from a solve-with-steps operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SolveOutput {
    /// The solved board as an 81-character string.
    pub board: String,
    /// Ordered list of steps taken to reach the solution.
    pub steps: Vec<SolveStepInfo>,
}

fn diff_candidate_grids(before: &[Vec<Vec<u8>>], after: &[Vec<Vec<u8>>]) -> Vec<CandidateChange> {
    let mut changes = Vec::new();

    for row in 0..9 {
        for col in 0..9 {
            let before_candidates = before
                .get(row)
                .and_then(|grid_row| grid_row.get(col))
                .cloned()
                .unwrap_or_default();
            let after_candidates = after
                .get(row)
                .and_then(|grid_row| grid_row.get(col))
                .cloned()
                .unwrap_or_default();

            if before_candidates == after_candidates {
                continue;
            }

            let removed = before_candidates
                .iter()
                .copied()
                .filter(|candidate| !after_candidates.contains(candidate))
                .collect();
            let added = after_candidates
                .iter()
                .copied()
                .filter(|candidate| !before_candidates.contains(candidate))
                .collect();

            changes.push(CandidateChange {
                row,
                col,
                before: before_candidates,
                after: after_candidates,
                removed,
                added,
            });
        }
    }

    changes
}

fn replay_step_infos_with_candidate_changes(
    puzzle: &str,
    steps: &[SolveStep],
) -> Result<Vec<SolveStepInfo>, RustokuError> {
    let mut replay = Rustoku::new_from_str(puzzle)?;
    let mut infos = Vec::with_capacity(steps.len());

    for step in steps {
        let before = replay.candidate_grid_snapshot();
        replay.apply_trace_step(step);
        let after = replay.candidate_grid_snapshot();

        let mut info = SolveStepInfo::from(step);
        info.candidate_changes = diff_candidate_grids(&before, &after);
        infos.push(info);
    }

    Ok(infos)
}

// ── Helper functions ──────────────────────────────────────────────────────────

/// Maps a difficulty string to cumulative [`TechniqueFlags`].
///
/// Each level includes all techniques from lower levels:
/// `"easy"` ⊂ `"medium"` ⊂ `"hard"` ⊂ `"expert"`.
fn technique_flags_from_str(s: &str) -> Result<TechniqueFlags, RustokuError> {
    match s.to_lowercase().as_str() {
        "easy" => Ok(TechniqueFlags::EASY),
        "medium" => Ok(TechniqueFlags::EASY | TechniqueFlags::MEDIUM),
        "hard" => Ok(TechniqueFlags::EASY | TechniqueFlags::MEDIUM | TechniqueFlags::HARD),
        "expert" => Ok(TechniqueFlags::all()),
        _ => Err(RustokuError::UnknownDifficulty(s.to_string())),
    }
}

/// Solves `puzzle` and returns the first solution as an 81-char string, or `None` if unsolvable.
pub fn solve_any_str(puzzle: &str) -> Result<Option<String>, RustokuError> {
    let mut rustoku = Rustoku::new_from_str(puzzle)?;
    Ok(rustoku.solve_any().map(|s| format_line(&s.board)))
}

/// Solves `puzzle` and returns **all** solutions as 81-char strings.
pub fn solve_all_str(puzzle: &str) -> Result<Vec<String>, RustokuError> {
    let mut rustoku = Rustoku::new_from_str(puzzle)?;
    Ok(rustoku
        .solve_all()
        .into_iter()
        .map(|s| format_line(&s.board))
        .collect())
}

/// Solves `puzzle` using human techniques for the given `difficulty` and returns a full
/// step trace, or `None` if unsolvable.
///
/// `difficulty` is one of `"easy"`, `"medium"`, `"hard"`, `"expert"`.
pub fn solve_with_steps(
    puzzle: &str,
    difficulty: &str,
) -> Result<Option<SolveOutput>, RustokuError> {
    let flags = technique_flags_from_str(difficulty)?;
    let mut rustoku = Rustoku::new_from_str(puzzle)?.with_techniques(flags);
    match rustoku.solve_any() {
        Some(solution) => Ok(Some(SolveOutput {
            board: format_line(&solution.board),
            steps: replay_step_infos_with_candidate_changes(puzzle, &solution.solve_path.steps)?,
        })),
        None => Ok(None),
    }
}

/// Returns the candidate digits for every cell as a 9×9 grid.
///
/// Filled cells return an empty `Vec`. Empty cells return the digits (1–9)
/// still possible for that cell given the current constraints.
pub fn candidates_grid(puzzle: &str) -> Result<Vec<Vec<Vec<u8>>>, RustokuError> {
    let rustoku = Rustoku::new_from_str(puzzle)?;
    Ok((0..9)
        .map(|r| {
            (0..9)
                .map(|c| {
                    if rustoku.board.get(r, c) != 0 {
                        vec![]
                    } else {
                        rustoku.candidates.get_candidates(r, c)
                    }
                })
                .collect()
        })
        .collect())
}

/// Generates a puzzle for the given difficulty string and returns it as an 81-char string.
pub fn generate_str(difficulty: &str) -> Result<String, RustokuError> {
    let diff = Difficulty::from_str(difficulty)
        .map_err(|_| RustokuError::UnknownDifficulty(difficulty.to_string()))?;
    generate_board_by_difficulty(diff, 100).map(|b| format_line(&b))
}

/// Returns `true` if `puzzle` is a fully-solved, valid Sudoku board.
pub fn is_valid_solution(puzzle: &str) -> Result<bool, RustokuError> {
    Rustoku::new_from_str(puzzle).map(|r| r.is_solved())
}

/// Advanced generation with specific clues and symmetry.
pub fn generate_complex_str(
    symmetry_str: &str,
    difficulty_str: Option<&str>,
) -> Result<String, RustokuError> {
    let symmetry = match symmetry_str.to_lowercase().as_str() {
        "none" => Symmetry::None,
        "rotational180" => Symmetry::Rotational180,
        "rotational90" => Symmetry::Rotational90,
        "mirrorvertical" => Symmetry::MirrorVertical,
        "mirrorhorizontal" => Symmetry::MirrorHorizontal,
        "mirrordiagonal" => Symmetry::MirrorDiagonal,
        _ => Symmetry::None,
    };

    let mut builder = BoardGenerator::new().symmetry(symmetry).max_attempts(250);

    if let Some(diff_s) = difficulty_str {
        let diff = Difficulty::from_str(diff_s)
            .map_err(|_| RustokuError::UnknownDifficulty(diff_s.to_string()))?;
        builder = builder.difficulty(diff);
    }

    builder.generate().map(|b| format_line(&b))
}

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

    #[test]
    fn test_technique_flags_from_str_valid() {
        assert!(technique_flags_from_str("easy").is_ok());
        assert!(technique_flags_from_str("medium").is_ok());
        assert!(technique_flags_from_str("hard").is_ok());
        assert!(technique_flags_from_str("expert").is_ok());
        assert!(technique_flags_from_str("EASY").is_ok()); // case insensitive
    }

    #[test]
    fn test_technique_flags_from_str_invalid() {
        assert!(matches!(
            technique_flags_from_str("invalid"),
            Err(RustokuError::UnknownDifficulty(_))
        ));
    }

    #[test]
    fn test_solve_any_str_solvable() {
        let puzzle =
            "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......";
        let result = solve_any_str(puzzle);
        assert!(result.is_ok());
        assert!(result.unwrap().is_some());
    }

    #[test]
    fn test_solve_any_str_unsolvable() {
        // Invalid puzzle with conflicts
        let puzzle =
            "111111111111111111111111111111111111111111111111111111111111111111111111111111";
        let result = solve_any_str(puzzle);
        // All 1s creates a conflict, so it's invalid and returns an error
        assert!(result.is_err());
    }

    #[test]
    fn test_solve_any_str_invalid_input() {
        let puzzle = "invalid";
        assert!(solve_any_str(puzzle).is_err());
    }

    #[test]
    fn test_solve_all_str() {
        let puzzle =
            "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......";
        let result = solve_all_str(puzzle);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 1);
    }

    #[test]
    fn test_solve_with_steps() {
        let puzzle =
            "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......";
        let result = solve_with_steps(puzzle, "expert");
        assert!(result.is_ok());
        let output = result.unwrap().unwrap();
        assert_eq!(output.board.len(), 81);
        assert!(!output.steps.is_empty());
        assert!(
            output
                .steps
                .iter()
                .any(|step| !step.candidate_changes.is_empty())
        );
        assert!(output.steps.iter().all(|step| {
            step.candidate_changes
                .iter()
                .all(|change| change.before != change.after)
        }));
    }

    #[test]
    fn test_candidates_grid() {
        let puzzle =
            "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......";
        let result = candidates_grid(puzzle);
        assert!(result.is_ok());
        let grid = result.unwrap();
        assert_eq!(grid.len(), 9);
        assert_eq!(grid[0].len(), 9);
        // First cell is 4, so empty candidates
        assert!(grid[0][0].is_empty());
        // Some empty cell should have candidates
        assert!(!grid[0][1].is_empty());
    }

    #[test]
    fn test_generate_str_valid() {
        let result = generate_str("easy");
        assert!(result.is_ok());
        let board = result.unwrap();
        assert_eq!(board.len(), 81);
        // Should be solvable
        assert!(solve_any_str(&board).unwrap().is_some());
    }

    #[test]
    fn test_generate_str_invalid() {
        assert!(generate_str("invalid").is_err());
    }

    #[test]
    fn test_is_valid_solution_valid() {
        let solved =
            "417369825632158947958724316825437169791586432346912758289643571573291684164875293";
        assert!(is_valid_solution(solved).unwrap());
    }

    #[test]
    fn test_is_valid_solution_invalid() {
        let unsolved =
            "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......";
        assert!(!is_valid_solution(unsolved).unwrap());
    }

    #[test]
    fn test_is_valid_solution_malformed() {
        assert!(is_valid_solution("invalid").is_err());
    }
}