From 122fe1f9e7c767ef036d60fd711d1cc35fd323a6 Mon Sep 17 00:00:00 2001 From: Xiwei Pan <90967972+isPANN@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:32:25 -0800 Subject: [PATCH 1/3] Reduce satisfiability directly to binary ILP Use clause rows in the fixed SAT and 3-SAT ILP pipelines. Co-Authored-By: Claude Sonnet 5.5 --- docs/paper/reductions.typ | 66 +++++++++++ src/rules/mod.rs | 2 + src/rules/satisfiability_ilp.rs | 102 +++++++++++++++++ src/solvers/pipelines.rs | 2 - .../parameter_formula_validation.rs | 41 +++++++ src/unit_tests/rules/satisfiability_ilp.rs | 105 ++++++++++++++++++ src/unit_tests/solvers/resolver.rs | 46 ++++++++ 7 files changed, 362 insertions(+), 2 deletions(-) create mode 100644 src/rules/satisfiability_ilp.rs create mode 100644 src/unit_tests/rules/satisfiability_ilp.rs diff --git a/docs/paper/reductions.typ b/docs/paper/reductions.typ index 8e0462b7a..eeb44dd5a 100644 --- a/docs/paper/reductions.typ +++ b/docs/paper/reductions.typ @@ -14926,6 +14926,72 @@ The following reductions to Integer Linear Programming are straightforward formu vertices as a Boolean vector. Target feasibility maps to the source Boolean value. ] +#let sat_ilp = load-example("Satisfiability", "ILP") +#let sat_ilp_sol = sat_ilp.solutions.at(0) +#reduction-rule("Satisfiability", "ILP", + example: true, + example-caption: [One binary variable per SAT variable and one inequality per clause], + extra: [ + #pred-commands( + "pred create --example " + rule-spec(sat_ilp) + " -o sat.json", + "pred path " + problem-spec(sat_ilp.source) + " " + problem-spec(sat_ilp.target) + " --limit 1 -o paths.json", + "jq '.paths[0]' paths.json > route.json", + "pred reduce sat.json --via route.json -o bundle.json", + "pred solve bundle.json", + "pred evaluate sat.json --config " + cli-config(sat_ilp_sol.source_config), + ) + + The source clauses, given as signed literal lists, are + #sat_ilp.source.instance.clauses.map(c => [$(#fmt-values(c.literals))$]).join(", "). + They produce #sat_ilp.target.instance.variables.len() binary variables and + #sat_ilp.target.instance.constraints.len() rows. At the stored ILP witness + $(#fmt-values(sat_ilp_sol.target_config))$, the rows evaluate to + #sat_ilp.target.instance.constraints.map(row => { + let lhs = row.terms.fold(0, (sum, (i, c)) => sum + c * sat_ilp_sol.target_config.at(i)) + $#lhs >= #row.rhs$ + }).join(", "). + Reading each bit as a truth value gives the satisfying assignment + $(#fmt-values(sat_ilp_sol.source_config))$. + Appending an empty clause adds the row $0 >= 1$, making the ILP infeasible. + ], +)[ + Encode CNF satisfiability directly with one binary variable per Boolean variable + and one inequality per clause. The encoding follows from the truth values of + the literal occurrences. +][ + _Construction._ (1) Introduce a binary variable $x_i$ for each source variable + $i$. (2) For each clause $C$, let $P$ and $N$ list the variable indices of its + positive and negative literal occurrences, respectively. Add + $ sum_(i in P) x_i - sum_(j in N) x_j >= 1 - |N|. $ + The ILP sums coefficients of repeated variables and removes zero coefficients. + Use an empty minimization objective. + + _Correctness._ ($arrow.r.double$) A satisfying assignment makes at least one + occurrence true in each clause. A positive occurrence contributes $x_i$ to + this count and a negative one contributes $1-x_i$. Moving the constant terms + to the right gives the clause row, which the assignment therefore satisfies. + ($arrow.l.double$) In a feasible binary assignment, a clause with every + literal false would have left-hand side $-|N|$, violating its row. Thus each + clause is true under the corresponding Boolean assignment. + + Repeated literals contribute according to their multiplicities. + Opposite occurrences of the same variable contribute a total of + one true literal, so any row containing such a pair is redundant, even if other + terms survive normalization. An empty clause gives the impossible row + $0 >= 1$, making the entire formula infeasible. A formula with no clauses gives + no rows and every binary assignment is feasible. + + _Overhead._ For $n$ variables, $m$ clauses, and $L$ literal occurrences, + the target has exactly $n$ variables and $m$ rows. Each occurrence contributes + at most one nonzero after normalization, giving at most $L$ nonzeros. The + magnitudes of coefficients, right-hand sides, and binary endpoints are at + most $L+1$, so $L+1$ magnitude bits suffice since $L+1 < 2^(L+1)$. + + _Solution extraction._ Validate that the target assignment is feasible and + read each $x_i = 1$ as true. Completed ILP feasibility maps to the source + Boolean value. +] + #reduction-rule("NAESatisfiability", "ILP")[ Each clause must have at least one true and at least one false literal, encoded as a pair of linear inequalities per clause. ][ diff --git a/src/rules/mod.rs b/src/rules/mod.rs index 7606f4923..cd851326d 100644 --- a/src/rules/mod.rs +++ b/src/rules/mod.rs @@ -294,6 +294,7 @@ pub(crate) mod registersufficiency_ilp; pub(crate) mod resourceconstrainedscheduling_ilp; pub(crate) mod rootedtreestorageassignment_ilp; pub(crate) mod ruralpostman_ilp; +pub(crate) mod satisfiability_ilp; pub(crate) mod schedulingtominimizeweightedcompletiontime_ilp; pub(crate) mod schedulingwithindividualdeadlines_ilp; pub(crate) mod sequencingtominimizemaximumcumulativecost_ilp; @@ -656,6 +657,7 @@ pub(crate) fn canonical_rule_example_specs() -> Vec, +} + +impl ReductionResult for ReductionSATToILP { + type Source = Satisfiability; + type Target = ILP; + + fn target_problem(&self) -> &Self::Target { + &self.target + } + + fn extract_solution(&self, solution: &Vec) -> ExtractionResult> { + crate::rules::traits::validate_target_witness( + self.target_problem(), + solution, + |value| value.value.is_some(), + "target ILP assignment is infeasible", + )?; + Ok(solution.iter().map(|&value| value == 1).collect()) + } +} + +#[crate::aggregate_reduction(ilp_feasibility)] +impl crate::rules::AggregateReductionResult for ReductionSATToILP {} + +#[reduction(transform = { + exact { + num_vars = "num_vars", + num_constraints = "num_clauses", + }, + upper_bound { + num_nonzeros = "num_literals", + max_constraint_magnitude_bits = "num_literals + 1", + }, +})] +impl ReduceTo> for Satisfiability { + type Result = ReductionSATToILP; + + fn reduce_to(&self) -> Result { + let mut constraints = Vec::with_capacity(self.num_clauses()); + for clause in self.clauses() { + let negatives = clause + .literals + .iter() + .filter(|&&literal| literal < 0) + .count(); + let negatives = >>::exact_i64( + negatives, + "counting negative clause literals", + )?; + // ILP normalization merges duplicate terms and cancels opposite terms. + let terms = clause + .variables() + .into_iter() + .zip(clause.literals.iter().map(|literal| literal.signum())) + .collect(); + constraints.push(LinearConstraint::ge(terms, 1 - negatives)); + } + let target = ILP::new( + self.num_vars(), + constraints, + vec![], + ObjectiveSense::Minimize, + ) + .map_err(>>::target_construction)?; + Ok(Self::Result { target }) + } +} + +#[cfg(feature = "example-db")] +pub(crate) fn canonical_rule_example_specs() -> Vec { + use crate::models::formula::CNFClause; + vec![crate::example_db::specs::RuleExampleSpec { + id: "satisfiability_to_ilp", + build: || { + let source = Satisfiability::new( + 3, + vec![ + CNFClause::new(vec![1, 2, 2]), + CNFClause::new(vec![-1, 3]), + CNFClause::new(vec![-2, -3]), + CNFClause::new(vec![1, -1]), + ], + ); + crate::example_db::specs::rule_example_via_ilp::<_, bool>(source) + }, + }] +} + +#[cfg(test)] +#[path = "../unit_tests/rules/satisfiability_ilp.rs"] +mod tests; diff --git a/src/solvers/pipelines.rs b/src/solvers/pipelines.rs index b9615dead..289e6ddf8 100644 --- a/src/solvers/pipelines.rs +++ b/src/solvers/pipelines.rs @@ -280,7 +280,6 @@ register_ilp_pipeline! { register_ilp_pipeline! { ("KSatisfiability", [("k", "K3")]), ("Satisfiability", []), - ("NAESatisfiability", []), ("ILP", [("variable", "bool"), ("coefficient", "i64"), ("bounds", "general")]), } @@ -724,7 +723,6 @@ register_ilp_pipeline! { register_ilp_pipeline! { ("Satisfiability", []), - ("NAESatisfiability", []), ("ILP", [("variable", "bool"), ("coefficient", "i64"), ("bounds", "general")]), } diff --git a/src/unit_tests/parameter_formula_validation.rs b/src/unit_tests/parameter_formula_validation.rs index cf42ac4b0..d9066c3f2 100644 --- a/src/unit_tests/parameter_formula_validation.rs +++ b/src/unit_tests/parameter_formula_validation.rs @@ -228,6 +228,47 @@ fn every_executable_parameter_formula_matches_a_constructed_target() { assert_eq!(checked, expected, "some formula fields were not checked"); } +#[test] +fn sat_clause_rows_match_their_parameter_transform() { + use crate::models::algebraic::ILP; + use crate::models::formula::{CNFClause, Satisfiability}; + use crate::traits::Problem; + + let entry = crate::rules::registry::reduction_entries() + .into_iter() + .find(|entry| { + entry.source_name == Satisfiability::NAME + && entry.target_name == ILP::::NAME + && entry.target_variant() == ILP::::variant() + }) + .unwrap(); + let contract = entry.parameter_contract().unwrap(); + let transform = contract.transform().unwrap(); + for (n, clauses) in [ + (0, vec![]), + (0, vec![vec![]]), + (4, vec![vec![1, -1], vec![-2, -2, -2, -2], vec![3, 4]]), + ] { + let source = Satisfiability::new(n, clauses.into_iter().map(CNFClause::new).collect()); + let predicted = transform.evaluate(&source.parameters()).unwrap(); + let actual = target_parameters(entry, &source).unwrap(); + for field in ["num_vars", "num_constraints"] { + assert_eq!(transform.relation(field), Some(ParameterRelation::Exact)); + assert_eq!(predicted.get(field).unwrap(), actual.get(field).unwrap()); + } + for field in ["num_nonzeros", "max_constraint_magnitude_bits"] { + assert_eq!( + transform.relation(field), + Some(ParameterRelation::UpperBound) + ); + assert!( + predicted.get(field).unwrap() >= actual.get(field).unwrap(), + "{field}" + ); + } + } +} + #[test] fn sparse_ilp_predictions_use_construction_counts() { use crate::models::{BiconnectivityAugmentation, Factoring, StrongConnectivityAugmentation}; diff --git a/src/unit_tests/rules/satisfiability_ilp.rs b/src/unit_tests/rules/satisfiability_ilp.rs new file mode 100644 index 000000000..06aa47a31 --- /dev/null +++ b/src/unit_tests/rules/satisfiability_ilp.rs @@ -0,0 +1,105 @@ +use super::*; +use crate::models::formula::CNFClause; +use crate::rules::test_helpers::assert_bf_vs_ilp; +use crate::rules::{ExtractionError, ReductionResult}; +use crate::solvers::{ILPSolveError, ILPSolver}; +use crate::traits::{EvaluationError, Problem}; + +#[test] +fn test_satisfiability_to_ilp_closed_loop() { + let source = Satisfiability::new( + 3, + vec![ + CNFClause::new(vec![1, 2, 2]), + CNFClause::new(vec![-1, 3]), + CNFClause::new(vec![-2, -3]), + CNFClause::new(vec![1, -1]), + ], + ); + let reduction = ReduceTo::>::reduce_to(&source).unwrap(); + assert_bf_vs_ilp(&source, &reduction); +} + +#[test] +fn clause_rows_preserve_empty_repeated_and_opposite_literals() { + let cases = [ + (vec![], LinearConstraint::ge(vec![], 1)), + ( + vec![1, 1, -2, -2], + LinearConstraint::ge(vec![(0, 2), (1, -2)], -1), + ), + (vec![1, -1], LinearConstraint::ge(vec![], 0)), + (vec![1, -1, -2], LinearConstraint::ge(vec![(1, -1)], -1)), + ]; + for (literals, row) in cases { + let source = Satisfiability::new(2, vec![CNFClause::new(literals)]); + let reduction = ReduceTo::>::reduce_to(&source).unwrap(); + let target = reduction.target_problem(); + assert_eq!(target.num_vars(), 2); + assert!(target.objective().is_empty()); + assert_eq!(target.constraints(), &[row]); + for bits in [[false, false], [false, true], [true, false], [true, true]] { + let solution: Vec<_> = bits.into_iter().map(i64::from).collect(); + assert_eq!( + target.is_feasible(&solution).unwrap(), + source.evaluate(&bits.to_vec()).unwrap().0 + ); + } + } +} + +#[test] +fn an_empty_clause_makes_the_ilp_infeasible() { + for num_vars in [0, 2] { + let source = Satisfiability::new(num_vars, vec![CNFClause::new(vec![])]); + let reduction = ReduceTo::>::reduce_to(&source).unwrap(); + assert!(matches!( + ILPSolver::new().solve(reduction.target_problem()), + Err(ILPSolveError::Infeasible) + )); + } +} + +#[test] +fn extraction_rejects_malformed_or_infeasible_assignments() { + let source = Satisfiability::new(2, vec![CNFClause::new(vec![1])]); + let reduction = ReduceTo::>::reduce_to(&source).unwrap(); + assert!(matches!( + reduction.extract_solution(&vec![1]), + Err(ExtractionError::Evaluation( + EvaluationError::InvalidConfiguration(_) + )) + )); + for invalid in [vec![1, 2], vec![0, 0]] { + assert!(matches!( + reduction.extract_solution(&invalid), + Err(ExtractionError::InvalidTargetSolution(_)) + )); + } +} + +#[test] +fn ilp_feasibility_maps_to_the_sat_value() { + use crate::rules::AggregateReductionResult; + use crate::solvers::BruteForce; + use crate::types::{Extremum, Or}; + + let solver = BruteForce::new(); + for clauses in [ + vec![], + vec![CNFClause::new(vec![1]), CNFClause::new(vec![-1])], + ] { + let source = Satisfiability::new(1, clauses); + let reduction = ReduceTo::>::reduce_to(&source).unwrap(); + let target = ReductionResult::target_problem(&reduction); + let value = match ILPSolver::new().solve(target) { + Ok(solution) => target.evaluate(&solution).unwrap(), + Err(ILPSolveError::Infeasible) => Extremum::minimize(None), + Err(error) => panic!("unexpected ILP solver error: {error}"), + }; + assert_eq!( + reduction.extract_value(value).unwrap(), + Or(solver.solve(&source).unwrap().is_some()) + ); + } +} diff --git a/src/unit_tests/solvers/resolver.rs b/src/unit_tests/solvers/resolver.rs index 7acb6dde8..f1de3fe9e 100644 --- a/src/unit_tests/solvers/resolver.rs +++ b/src/unit_tests/solvers/resolver.rs @@ -826,6 +826,52 @@ fn deterministic_solver_dispatch_fixed_multihop_pipeline_is_repeatable() { ); } +#[test] +fn sat_and_three_sat_use_clause_rows_in_the_fixed_ilp_pipeline() { + use serde_json::json; + + for (name, variant, expected_path) in [ + ( + "Satisfiability", + BTreeMap::new(), + vec!["Satisfiability", "ILP"], + ), + ( + "KSatisfiability", + BTreeMap::from([("k".into(), "K3".into())]), + vec![ + "KSatisfiability", + "Satisfiability", + "ILP", + ], + ), + ] { + let mut clauses = vec![ + json!({"literals": [-1, -1, -1]}), + json!({"literals": [1, 2, 2]}), + ]; + for feasible in [true, false] { + let loaded = + load_dyn(name, &variant, json!({"num_vars": 3, "clauses": clauses})).unwrap(); + let result = solve(&loaded, SolverRequest::Default).unwrap(); + let SolverExecution::Ilp { reduction_path } = result.solver else { + panic!("expected the default ILP solver for {name}"); + }; + assert_eq!(reduction_path, expected_path); + if feasible { + let SolveOutcome::Optimal { solution, .. } = result.outcome else { + panic!("expected a satisfying assignment for {name}"); + }; + assert_eq!(solution[0], false); + assert_eq!(solution[1], true); + clauses.push(json!({"literals": [-2, -2, -2]})); + } else { + assert_eq!(result.outcome, SolveOutcome::Infeasible); + } + } + } +} + #[test] fn deterministic_solver_dispatch_customized_default_allows_explicit_ilp_override() { use crate::models::graph::RootedTreeArrangement; From 89ca257c0fe354f0d91ea595e545d71251acf7aa Mon Sep 17 00:00:00 2001 From: Xiwei Pan <90967972+isPANN@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:17:09 -0800 Subject: [PATCH 2/3] Add a six-variable closed-loop instance for SAT to ILP Co-Authored-By: Claude Opus 5.5 --- src/unit_tests/rules/satisfiability_ilp.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/unit_tests/rules/satisfiability_ilp.rs b/src/unit_tests/rules/satisfiability_ilp.rs index 06aa47a31..a89f61bc4 100644 --- a/src/unit_tests/rules/satisfiability_ilp.rs +++ b/src/unit_tests/rules/satisfiability_ilp.rs @@ -18,6 +18,21 @@ fn test_satisfiability_to_ilp_closed_loop() { ); let reduction = ReduceTo::>::reduce_to(&source).unwrap(); assert_bf_vs_ilp(&source, &reduction); + + let source = Satisfiability::new( + 6, + vec![ + CNFClause::new(vec![1, -2, 3]), + CNFClause::new(vec![-1, 4, 4]), + CNFClause::new(vec![2, -5, 6]), + CNFClause::new(vec![-3, -4, 5]), + CNFClause::new(vec![-6, 1, -1]), + CNFClause::new(vec![-2, -6]), + CNFClause::new(vec![3, 5, -4]), + ], + ); + let reduction = ReduceTo::>::reduce_to(&source).unwrap(); + assert_bf_vs_ilp(&source, &reduction); } #[test] From bc44bb1cd4b9a9883cb9d69f6cf3a7835f77f17a Mon Sep 17 00:00:00 2001 From: Xiwei Pan <90967972+isPANN@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:52:16 -0800 Subject: [PATCH 3/3] Fix lints from newer stable Clippy Address needless_bool and needless_range_loop lints that the updated stable toolchain reports on existing code. Co-Authored-By: Claude Opus 5.5 --- src/models/graph/minimum_edge_cost_flow.rs | 6 +---- .../minimum_register_sufficiency_for_loops.rs | 6 +---- .../misc/rectilinear_picture_compression.rs | 21 ++++------------- .../ksatisfiability_preemptivescheduling.rs | 8 ++----- src/rules/unitdiskmapping/grid.rs | 23 +++++++++---------- 5 files changed, 19 insertions(+), 45 deletions(-) diff --git a/src/models/graph/minimum_edge_cost_flow.rs b/src/models/graph/minimum_edge_cost_flow.rs index a639b0c5c..ec2481785 100644 --- a/src/models/graph/minimum_edge_cost_flow.rs +++ b/src/models/graph/minimum_edge_cost_flow.rs @@ -288,11 +288,7 @@ impl MinimumEdgeCostFlow { } // (3) Flow requirement: net flow into sink >= R - if balance[self.sink] < self.required_flow { - return Ok(false); - } - - Ok(true) + Ok(balance[self.sink] >= self.required_flow) } /// Compute the edge cost for a feasible flow: sum of prices of arcs with diff --git a/src/models/misc/minimum_register_sufficiency_for_loops.rs b/src/models/misc/minimum_register_sufficiency_for_loops.rs index 838b2890a..5ac90060e 100644 --- a/src/models/misc/minimum_register_sufficiency_for_loops.rs +++ b/src/models/misc/minimum_register_sufficiency_for_loops.rs @@ -167,11 +167,7 @@ impl MinimumRegisterSufficiencyForLoops { // Check if arc1 is entirely in the gap of arc2. let gap2_start = (s2 + l2) % n; let dist_s1_in_gap2 = (s1 + n - gap2_start) % n; - if dist_s1_in_gap2 + l1 <= n - l2 { - return false; - } - - true + dist_s1_in_gap2 + l1 > n - l2 } } diff --git a/src/models/misc/rectilinear_picture_compression.rs b/src/models/misc/rectilinear_picture_compression.rs index 8fa88909b..a269fff07 100644 --- a/src/models/misc/rectilinear_picture_compression.rs +++ b/src/models/misc/rectilinear_picture_compression.rs @@ -203,25 +203,12 @@ impl RectilinearPictureCompression { continue; } // Find the rightmost column from c1 that is all-1 in row r1. - let mut c_max = n; - for c in c1..n { - if !self.matrix[r1][c] { - c_max = c; - break; - } - } + let c_max = (c1..n).find(|&c| !self.matrix[r1][c]).unwrap_or(n); // Extend downward row by row, narrowing column range. let mut c_end = c_max; // exclusive upper bound on columns - for r2 in r1..m { - // Narrow c_end based on row r2. - let mut new_c_end = c1; - for c in c1..c_end { - if self.matrix[r2][c] { - new_c_end = c + 1; - } else { - break; - } - } + for (r2, row) in self.matrix.iter().enumerate().skip(r1) { + // Narrow c_end based on this row. + let new_c_end = (c1..c_end).find(|&c| !row[c]).unwrap_or(c_end); if new_c_end <= c1 { break; } diff --git a/src/rules/ksatisfiability_preemptivescheduling.rs b/src/rules/ksatisfiability_preemptivescheduling.rs index 7d3291e2f..48a13aee7 100644 --- a/src/rules/ksatisfiability_preemptivescheduling.rs +++ b/src/rules/ksatisfiability_preemptivescheduling.rs @@ -277,17 +277,13 @@ fn construct_schedule_from_assignment( if pattern == 0 { return None; } - for pattern_index in 0..7 { + for (pattern_index, &job) in construction.clause_jobs[clause_index].iter().enumerate() { let slot = if pattern_index + 1 == pattern { source.num_vars() + 1 } else { source.num_vars() + 2 }; - set_task_slot( - &mut task_slots, - construction.clause_jobs[clause_index][pattern_index], - slot, - ); + set_task_slot(&mut task_slots, job, slot); } } diff --git a/src/rules/unitdiskmapping/grid.rs b/src/rules/unitdiskmapping/grid.rs index 3281a7995..6af4a8a30 100644 --- a/src/rules/unitdiskmapping/grid.rs +++ b/src/rules/unitdiskmapping/grid.rs @@ -172,9 +172,9 @@ impl MappingGrid { /// Get all occupied coordinates. pub fn occupied_coords(&self) -> Vec<(usize, usize)> { let mut coords = Vec::new(); - for r in 0..self.rows { - for c in 0..self.cols { - if self.content[r][c].is_occupied() { + for (r, row) in self.content.iter().enumerate() { + for (c, cell) in row.iter().enumerate() { + if cell.is_occupied() { coords.push((r, c)); } } @@ -200,9 +200,9 @@ impl MappingGrid { /// Returns a set of (row, col) for cells in the Doubled state. pub fn doubled_cells(&self) -> std::collections::HashSet<(usize, usize)> { let mut cells = std::collections::HashSet::new(); - for r in 0..self.rows { - for c in 0..self.cols { - if matches!(self.content[r][c], CellState::Doubled { .. }) { + for (r, row) in self.content.iter().enumerate() { + for (c, cell) in row.iter().enumerate() { + if matches!(cell, CellState::Doubled { .. }) { cells.insert((r, c)); } } @@ -250,9 +250,9 @@ impl MappingGrid { let pos_to_idx: HashMap<(usize, usize), usize> = if config.is_some() { let mut map = HashMap::new(); let mut idx = 0; - for r in 0..self.rows { - for c in 0..self.cols { - if self.content[r][c].is_occupied() { + for (r, row) in self.content.iter().enumerate() { + for (c, cell) in row.iter().enumerate() { + if cell.is_occupied() { map.insert((r, c), idx); idx += 1; } @@ -265,10 +265,9 @@ impl MappingGrid { let mut lines = Vec::new(); - for r in 0..self.rows { + for (r, row) in self.content.iter().enumerate() { let mut line = String::new(); - for c in 0..self.cols { - let cell = &self.content[r][c]; + for (c, cell) in row.iter().enumerate() { let s = if let Some(cfg) = config { if let Some(&idx) = pos_to_idx.get(&(r, c)) { if cfg.get(idx).copied().unwrap_or(0) > 0 {