diff options
| author | Federico Igne <git@federicoigne.com> | 2021-01-04 13:59:27 +0000 |
|---|---|---|
| committer | Federico Igne <git@federicoigne.com> | 2021-11-03 18:55:08 +0000 |
| commit | fc1d4fbb98323b34829da9393f366fb07d2f1605 (patch) | |
| tree | 4931923557f7976ba89f374b0c13cdf614b1984f /rust/queen-attack/src | |
| parent | b296156206a9b1bc4473c163bff44e6f2bc95573 (diff) | |
| download | exercism-fc1d4fbb98323b34829da9393f366fb07d2f1605.tar.gz exercism-fc1d4fbb98323b34829da9393f366fb07d2f1605.zip | |
[rust] Queen Attack
Diffstat (limited to 'rust/queen-attack/src')
| -rw-r--r-- | rust/queen-attack/src/lib.rs | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/rust/queen-attack/src/lib.rs b/rust/queen-attack/src/lib.rs new file mode 100644 index 0000000..cbdc2c7 --- /dev/null +++ b/rust/queen-attack/src/lib.rs | |||
| @@ -0,0 +1,36 @@ | |||
| 1 | #[derive(Debug)] | ||
| 2 | pub struct ChessPosition { | ||
| 3 | rank: i32, | ||
| 4 | file: i32, | ||
| 5 | } | ||
| 6 | |||
| 7 | #[derive(Debug)] | ||
| 8 | pub struct Queen { | ||
| 9 | pos: ChessPosition, | ||
| 10 | } | ||
| 11 | |||
| 12 | fn in_range<T: Ord>(n: T, min: T, max: T) -> bool { | ||
| 13 | min <= n && n < max | ||
| 14 | } | ||
| 15 | |||
| 16 | impl ChessPosition { | ||
| 17 | pub fn new(rank: i32, file: i32) -> Option<Self> { | ||
| 18 | if in_range(rank, 0, 8) && in_range(file, 0, 8) { | ||
| 19 | Some(ChessPosition { rank, file }) | ||
| 20 | } else { | ||
| 21 | None | ||
| 22 | } | ||
| 23 | } | ||
| 24 | } | ||
| 25 | |||
| 26 | impl Queen { | ||
| 27 | pub fn new(pos: ChessPosition) -> Self { | ||
| 28 | Queen { pos } | ||
| 29 | } | ||
| 30 | |||
| 31 | pub fn can_attack(&self, other: &Queen) -> bool { | ||
| 32 | self.pos.file == other.pos.file | ||
| 33 | || self.pos.rank == other.pos.rank | ||
| 34 | || (self.pos.rank - other.pos.rank).abs() == (self.pos.file - other.pos.file).abs() | ||
| 35 | } | ||
| 36 | } | ||
