pub fn answer(text : String) -> ( u16, u16 ) { let grid : Vec> = from_string(text); let rows = grid.len(); let cols = grid[0].len(); ( find_xmas(&grid, rows as isize, cols as isize), find_x_mas(&grid, rows, cols) ) } fn find_x_mas(grid : &Vec>, rows : usize, cols : usize) -> u16 { let mut total : u16 = 0; for y in 1..rows-1 { for x in 1..cols-1 { if grid[y][x] == 'A' { total = total + inspect_x_mas_location(&grid, x, y) } } } total } fn find_xmas(grid : &Vec>, rows : isize, cols : isize) -> u16 { let mut total : u16 = 0; for y in 0..rows { for x in 0..cols { if grid[y as usize][x as usize] == 'X' { total = total + inspect_xmas_location(&grid, x, y, rows, cols) } } } total } fn from_string(s : String) -> Vec> { s.split("\n").map(|s| s.chars().collect()).collect() } fn inspect_x_mas_location(grid : &Vec>, x : usize, y : usize) -> u16 { let c1 = grid[y-1][x-1]; let c2 = grid[y-1][x+1]; let c3 = grid[y+1][x-1]; let c4 = grid[y+1][x+1]; let horizontal = c1 == c2 && c3 == c4 && c1 != c3; let vertical = c1 == c3 && c2 == c4 && c1 != c2; let letters_match = (c1 == 'M' && c4 == 'S') || (c1 == 'S' && c4 == 'M'); if letters_match && (horizontal || vertical) { 1 } else { 0 } } fn inspect_xmas_location(grid : &Vec>, x : isize, y : isize, rows : isize, cols : isize) -> u16 { let mut total : u16 = 0; for dx in -1..=1 { for dy in -1..=1 { if dx == 0 && dy == 0 { continue; } let (s_x, s_y) = ( x + 3 * dx, y + 3 * dy ); if s_x < 0 || s_x >= rows || s_y < 0 || s_y >= cols { continue; } let m = grid[(y + 1 * dy) as usize][(x + 1 * dx) as usize]; let a = grid[(y + 2 * dy) as usize][(x + 2 * dx) as usize]; let s = grid[(y + 3 * dy) as usize][(x + 3 * dx) as usize]; if m == 'M' && a == 'A' && s == 'S' { total = total + 1; } } }; total }