Last active
July 16, 2018 14:00
-
-
Save mykhailokrainik/838173692962438cfeea3ef955e57ec9 to your computer and use it in GitHub Desktop.
Chess Board Cell Color
This file contains hidden or 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
// Task | |
// Given two cells on the standard chess board, determine whether they have the same color or not. | |
// | |
// Example | |
// For cell1 = "A1" and cell2 = "C3", the output should be true. | |
const BOARD_SIZE: usize = 9; | |
fn chessboard_cell_color(cell1: &str, cell2: &str) -> bool { | |
let mut board = [false; BOARD_SIZE * BOARD_SIZE]; | |
for (i, e) in board.iter_mut().enumerate() { | |
if i % 2 == 0 { | |
*e = !*e | |
} | |
} | |
let pos = |x: usize, y: usize| y * BOARD_SIZE + x; | |
let conver_letter_to_num = |l| match l { | |
"A" => 1, | |
"B" => 2, | |
"C" => 3, | |
"D" => 4, | |
"E" => 5, | |
"F" => 6, | |
"G" => 7, | |
"H" => 8, | |
_ => panic!("Out of boundaries"), | |
}; | |
let (x1, y1) = { | |
let (x1, y1) = cell1.split_at(1); | |
(conver_letter_to_num(x1), y1.parse().unwrap()) | |
}; | |
let (x2, y2) = { | |
let (x2, y2) = cell2.split_at(1); | |
(conver_letter_to_num(x2), y2.parse().unwrap()) | |
}; | |
let pos_a = pos(x1, y1); | |
let pos_b = pos(x2, y2); | |
board[pos_a] == board[pos_b] | |
} | |
#[test] | |
fn basic_tests() { | |
assert_eq!(chessboard_cell_color("A1", "C3"), true); | |
assert_eq!(chessboard_cell_color("A1", "H1"), false); | |
assert_eq!(chessboard_cell_color("A2", "H2"), false); | |
assert_eq!(chessboard_cell_color("A3", "H3"), false); | |
assert_eq!(chessboard_cell_color("A4", "H4"), false); | |
assert_eq!(chessboard_cell_color("A5", "H5"), false); | |
assert_eq!(chessboard_cell_color("A6", "H6"), false); | |
assert_eq!(chessboard_cell_color("A7", "H7"), false); | |
assert_eq!(chessboard_cell_color("A4", "H4"), false); | |
assert_eq!(chessboard_cell_color("A1", "H3"), false); | |
assert_eq!(chessboard_cell_color("A1", "A2"), false); | |
assert_eq!(chessboard_cell_color("A1", "C1"), true); | |
assert_eq!(chessboard_cell_color("A1", "A1"), true); | |
} |
Author
mykhailokrainik
commented
Jul 16, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment