Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions cspuz_rs_puzzles/src/puzzles/balance_loop.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
use crate::util;
use cspuz_rs::graph;
use cspuz_rs::serializer::{
problem_to_url, url_to_problem, Choice, Combinator, Grid, HexInt, Map, Optionalize, Spaces,
};
use cspuz_rs::solver::{Solver, FALSE};

pub fn solve_balance_loop(
clues: &[Vec<Option<(i32, bool)>>],
) -> Option<graph::BoolGridEdgesIrrefutableFacts> {
let (h, w) = util::infer_shape(clues);

let mut solver = Solver::new();
let is_line = &graph::BoolGridEdges::new(&mut solver, (h - 1, w - 1));
solver.add_answer_key_bool(&is_line.horizontal);
solver.add_answer_key_bool(&is_line.vertical);

let is_passed = &graph::single_cycle_grid_edges(&mut solver, is_line);

for y in 0..h {
for x in 0..w {
let Some((n, is_black)) = clues[y][x] else {
continue;
};

solver.add_expr(is_passed.at((y, x)));

let has_left = if x > 0 {
is_line.horizontal.at((y, x - 1)).expr()
} else {
FALSE
};
let has_right = if x < w - 1 {
is_line.horizontal.at((y, x)).expr()
} else {
FALSE
};
let has_up = if y > 0 {
is_line.vertical.at((y - 1, x)).expr()
} else {
FALSE
};
let has_down = if y < h - 1 {
is_line.vertical.at((y, x)).expr()
} else {
FALSE
};

let left_len = is_line
.horizontal
.slice_fixed_y((y, ..x))
.reverse()
.consecutive_prefix_true();
let right_len = is_line.horizontal.slice_fixed_y((y, x..)).consecutive_prefix_true();
let up_len = is_line
.vertical
.slice_fixed_x((..y, x))
.reverse()
.consecutive_prefix_true();
let down_len = is_line.vertical.slice_fixed_x((y.., x)).consecutive_prefix_true();

solver.add_expr(
(left_len.clone() + right_len.clone() + up_len.clone() + down_len.clone()).eq(n),
);

let dirs = [has_left, has_right, has_up, has_down];
let lens = [left_len, right_len, up_len, down_len];
for i in 0..4 {
for j in (i + 1)..4 {
let rel = if is_black {
lens[i].clone().ne(lens[j].clone())
} else {
lens[i].clone().eq(lens[j].clone())
};
solver.add_expr((dirs[i].clone() & dirs[j].clone()).imp(rel));
}
}
}
}

solver.irrefutable_facts().map(|f| f.get(is_line))
}

type Problem = Vec<Vec<Option<(i32, bool)>>>;

fn clue_combinator() -> impl Combinator<(i32, bool)> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh, this is in common with light and shadow, interesting

Map::new(
HexInt,
|(n, is_black): (i32, bool)| Some(2 * n + if is_black { 1 } else { 0 }),
|v: i32| Some((v / 2, v % 2 == 1)),
)
}

fn combinator() -> impl Combinator<Problem> {
Grid::new(Choice::new(vec![
Box::new(Optionalize::new(clue_combinator())),
Box::new(Spaces::new(None, 'g')),
]))
}

pub fn serialize_problem(problem: &Problem) -> Option<String> {
problem_to_url(combinator(), "balance", problem.clone())
}

pub fn deserialize_problem(url: &str) -> Option<Problem> {
url_to_problem(combinator(), &["balance"], url)
}

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

fn problem_for_tests() -> Problem {
vec![
vec![Some((4, false)), Some((2, false)), Some((4, false))],
vec![Some((2, false)), None, Some((2, false))],
vec![Some((4, false)), Some((2, false)), Some((4, false))],
]
}

#[test]
fn test_balance_loop_problem() {
let problem = problem_for_tests();
let ans = solve_balance_loop(&problem);
assert!(ans.is_some());
let ans = ans.unwrap();

let expected = graph::BoolGridEdgesIrrefutableFacts {
horizontal: crate::util::tests::to_option_bool_2d([[1, 1], [0, 0], [1, 1]]),
vertical: crate::util::tests::to_option_bool_2d([[1, 0, 1], [1, 0, 1]]),
};
assert_eq!(ans, expected);
}

#[test]
fn test_balance_loop_serializer() {
let problem = problem_for_tests();
let url = serialize_problem(&problem).unwrap();
assert_eq!(deserialize_problem(&url), Some(problem));
}
}
1 change: 1 addition & 0 deletions cspuz_rs_puzzles/src/puzzles/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod archipelago;
pub mod armyants;
pub mod ayeheya;
pub mod balloon;
pub mod balance_loop;
pub mod barns;
pub mod battleship;
pub mod bdwalk;
Expand Down
51 changes: 51 additions & 0 deletions cspuz_solver_backend/src/puzzle/balance_loop.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use crate::board::{Board, BoardKind, Item, ItemKind};
use crate::uniqueness::check_uniqueness;
use cspuz_rs_puzzles::puzzles::balance_loop;

pub fn solve(url: &str) -> Result<Board, &'static str> {
let problem = balance_loop::deserialize_problem(url).ok_or("invalid url")?;
let ans = balance_loop::solve_balance_loop(&problem);

let height = problem.len();
let width = problem[0].len();
let mut board = Board::new(BoardKind::Grid, height, width, check_uniqueness(&ans));

for y in 0..height {
for x in 0..width {
if let Some((n, is_black)) = problem[y][x] {
if is_black {
board.push(Item::cell(y, x, "black", ItemKind::FilledCircle));
board.push(Item::cell(y, x, "white", ItemKind::Num(n)));
} else {
board.push(Item::cell(y, x, "black", ItemKind::Circle));
board.push(Item::cell(y, x, "black", ItemKind::Num(n)));
}
}
}
}

if let Some(is_line) = &ans {
board.add_lines_irrefutable_facts(is_line, "green", None);
}

Ok(board)
}

#[cfg(test)]
mod tests {
use super::solve;
use cspuz_rs_puzzles::puzzles::balance_loop;

#[test]
fn test_solve() {
let problem = vec![
vec![Some((4, false)), Some((2, false)), Some((4, false))],
vec![Some((2, false)), None, Some((2, false))],
vec![Some((4, false)), Some((2, false)), Some((4, false))],
];
let url = balance_loop::serialize_problem(&problem).unwrap();
let board = solve(&url).unwrap();
assert_eq!(board.height, 3);
assert_eq!(board.width, 3);
}
}
1 change: 1 addition & 0 deletions cspuz_solver_backend/src/puzzle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ puzzle_list!(puzz_link,
(armyants, ["armyants"], "Army Ants", "ぐんたいあり"),
(ayeheya, ["ayeheya"], "Ekawayeh (Symmetry Heyawake)", "∀人∃HEYA"),
(balloon, ["balloon"], "Balloon Box (Revised)", "風船箱 (改訂版)"),
(balance_loop, ["balance"], "Balance Loop", "Balance Loop"),
(barns, ["barns"], "Barns", "バーンズ"),
(battleship, ["battleship"], "Battleship", "Battleship"),
(bdwalk, ["bdwalk"], "Building Walk", "ビルウォーク"),
Expand Down