#!/usr/bin/env ruby # frozen_string_literal: true require 'pry' def diagonal(array, x, y) x_limit = array.size - 1 - x y_limit = array[0].size - 1 - y limit = x_limit < y_limit ? x_limit : y_limit (0..limit).map { |i| array[x + i][y + i] } end def diagonal2(array, x, y) x_limit = array.size - 1 - x y_limit = y limit = x_limit < y_limit ? x_limit : y_limit (0..limit).map { |i| array[x + i][y - i] } end def xmas_slice(array, x, y) out = [] out.append(array[x][y] + array[x + 1][y + 1] + array[x + 2][y + 2]) out.append(array[x][y + 2] + array[x + 1][y + 1] + array[x + 2][y]) (out[0].match?(/MAS|SAM/) and out[1].match?(/MAS|SAM/)) end # input = 'MMMSXXMASM # MSAMXMSMSA # AMXSXMAAMM # MSAMASMSMX # XMASAMXAMM # XXAMMXXAMA # SMSMSASXSS # SAXAMASAAA # MAMMMXMMMM # MXMXAXMASX'.split input = File.readlines('./input').map(&:strip) vertical = input.map(&:chars).transpose.map(&:join) d1_coords = (0..(input.size - 1)).map { [0, _1] } d2_coords = d1_coords.dup d1_coords += (1..(input.size - 1)).map { [_1, 0] } d2_coords += (1..(input.size - 1)).map { [_1, (input.size - 1)] } diagonal = d1_coords.map { |x, y| diagonal(input, x, y) }.map(&:join) diagonal2 = d2_coords.map { |x, y| diagonal2(input, x, y) }.map(&:join) # binding.pry count = 0 count += input.map { |line| line.scan('XMAS') }.flatten.length count += input.map { |line| line.scan('SAMX') }.flatten.length count += vertical.map { |line| line.scan('XMAS') }.flatten.length count += vertical.map { |line| line.scan('SAMX') }.flatten.length count += diagonal.map { |line| line.scan('XMAS') }.flatten.length count += diagonal.map { |line| line.scan('SAMX') }.flatten.length count += diagonal2.map { |line| line.scan('XMAS') }.flatten.length count += diagonal2.map { |line| line.scan('SAMX') }.flatten.length # binding.pry puts count # Part 2 p2 = (0..input.size - 3).map { |x| (0..input.size - 3).map { |y| xmas_slice(input, x, y) } }.flatten.count(true) puts p2