-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor: Move solver logic to separate module
This commit refactors the Klotski solver logic by moving it from `main.rs` to a new `solver.rs` module. The changes include: 1. Create a new `solver.rs` file containing the `solve_klotski` function and its associated test. 2. Update `main.rs` to use the new `solver` module and remove the moved code. 3. Adjust imports in `main.rs` to reflect the new structure. 4. Fix a documentation comment in `coordinates.rs` by changing the code block type to "test". These changes improve code organization and modularity, making the project structure cleaner and more maintainable. *Commit message written with Claude 3.5 Sonnet.*
- Loading branch information
1 parent
55f91e5
commit 15581d7
Showing
3 changed files
with
45 additions
and
40 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
use crate::{ | ||
board::{Board, SOLUTION}, | ||
coordinates::Coor, | ||
}; | ||
use pathfinding::directed::astar; | ||
|
||
/// Solves a given Klotski board state using an A* algorithm | ||
pub fn solve_klotski(state: Board) -> Option<(Vec<Board>, i32)> { | ||
astar::astar( | ||
&state, | ||
|p| p.next_states(), | ||
|s| { | ||
// Manhattan distance | ||
let Coor { | ||
row: target_row, | ||
col: target_col, | ||
} = s.target_piece().coor; | ||
|
||
let Coor { | ||
row: sol_row, | ||
col: sol_col, | ||
} = SOLUTION; | ||
|
||
(target_row as i32 - sol_row as i32).abs() + (target_col as i32 - sol_col as i32).abs() | ||
}, | ||
|s| s.is_solution(), | ||
) | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use crate::{board::Board, solve_klotski}; | ||
|
||
#[test] | ||
fn can_solve_default_klotski() { | ||
// This test may take a few seconds to complete | ||
let board = Board::new(); | ||
let finished = solve_klotski(board); | ||
assert!(finished.is_some()); | ||
} | ||
} |