Summary Files Commits Branches @commit @diff @stats
path: root / Year 4 / Artificial Intelligence / hw02 / src / alg.rs
diff options
context:
space:
mode:
Commit2f6d79c20bb1826dc66da4365be2817408977c9b (patch)
Author
 Syndamia <kamen@syndamia.com>
2024-12-14 13:43:05 +0200
Committer
 Syndamia <kamen@syndamia.com>
2024-12-14 13:43:05 +0200
Files4258acdb69f6a00f585d66e71422ccf47dc74e6a /Year 4/Artificial Intelligence/hw02/src/alg.rs
uni-projects-2f6d79c20bb1826dc66da4365be2817408977c9b.tar
uni-projects-2f6d79c20bb1826dc66da4365be2817408977c9b.tar.gz
uni-projects-2f6d79c20bb1826dc66da4365be2817408977c9b.zip
Parentd14784e9c54d145fff5abc303f4c29dba55e4600 (diff)
hw(AI/2): Separate into files, test attacks, fix attacks, fix clear, add assertions, add example board
1 files changed, 62 insertions, 0 deletions
-rw-r--r--Year 4/Artificial Intelligence/hw02/src/alg.rs62
diff --git a/Year 4/Artificial Intelligence/hw02/src/alg.rs b/Year 4/Artificial Intelligence/hw02/src/alg.rs
new file mode 100644
index 0000000..2ee321f
--- /dev/null
+++ b/Year 4/Artificial Intelligence/hw02/src/alg.rs
@@ -0,0 +1,62 @@
+use super::Puzzle;
+use rand::Rng;
+
+impl Puzzle {
+ fn has_conflicts(&self) -> bool {
+ for i in 0..self.N {
+ if self.per_row[i] > 1 { return true; }
+ }
+ for i in 0..2 * self.N - 1 {
+ if self.per_d1[i] > 1 || self.per_d2[i] > 1 { return true; }
+ }
+ return false;
+ }
+
+ fn init_horse(&mut self) {
+ self.clear();
+
+ let (mut col, mut row) = (1, 0);
+ for _ in 0..self.N / 2 {
+ self.in_col[col] = row;
+ self.update(col, 1);
+ col += 2;
+ row += 1;
+ }
+ let (mut col, mut row) = (0, self.N / 2);
+ for _ in 0..self.N / 2 {
+ self.in_col[col] = row;
+ self.update(col, 1);
+ col += 2;
+ row += 1;
+ }
+ }
+
+ fn init_rand(&mut self) {
+ self.clear();
+
+ self.in_col[0] = self.rng.gen_range(0..self.N);
+ self.update(0, 1);
+
+ for col in 1..self.N {
+ self.in_col[col] = self.min_col_row(col);
+ self.update(col, 1);
+ }
+ }
+
+ pub fn solve(&mut self) {
+ self.init_horse();
+ loop {
+ for _ in 0..2 * self.N {
+ let col = self.max_queen_col();
+ if col == self.N { return; }
+
+ let row = self.min_col_row(col);
+ self.move_queen(col, row);
+ }
+ if !self.has_conflicts() {
+ break;
+ }
+ self.init_rand();
+ }
+ }
+}