From 582b512e28ef8779893a1716fcf4c1da5d7f63fe Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Sat, 4 Jun 2022 23:47:01 +0100 Subject: [PATCH] n-queens --- n-queens/sol.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 n-queens/sol.rs diff --git a/n-queens/sol.rs b/n-queens/sol.rs new file mode 100644 index 0000000..15b499a --- /dev/null +++ b/n-queens/sol.rs @@ -0,0 +1,49 @@ +// TODO : Tidy up?? This is quite the unreadable mess at the moment +impl Solution { + pub fn search(board: Vec>) -> Vec> { + if board.len() == 1 { + return board[0].iter() + .map(|n| vec![*n]) + .collect(); + } + board[0].iter() + .map(|¤t| + Solution::search( + board[1..].iter() + .enumerate() + .map(|(idx, row)| { + row.iter() + .filter_map(|n| if *n != current && + *n != current - idx as i32 - 1 && + *n != current + idx as i32 + 1 { + Some(*n) + } else { None }) + .collect() + }) + .collect() + ) + .into_iter() + .map(|mut row| { + row.insert(0, current); + row + }) + .collect::>>() + ) + .flatten() + .collect() + } + pub fn solve_n_queens(n: i32) -> Vec> { + Solution::search(vec![(0..n).collect(); n as usize]) + .into_iter() + .map(|solution| solution.into_iter() + .map(|position| { + let mut converted = ".".repeat(position as usize); + converted.push('Q'); + converted.push_str(".".repeat(n as usize - position as usize - 1).as_str()); + converted + }) + .collect() + ) + .collect() + } +} \ No newline at end of file