#!/usr/bin/env ruby # frozen_string_literal: true require 'pry' def sorted?(sequence) test = sequence.each_cons(2).map { |left, right| left < right } return true if test.uniq.length == 1 false end def safe?(sequence) test = sequence.each_cons(2).map { |left, right| (left - right).abs } test.reject { |num| num.positive? && num < 4 }.empty? end # sample = '7 6 4 2 1 # 1 2 7 8 9 # 9 7 6 2 1 # 1 3 2 4 5 # 8 6 4 4 1 # 1 3 6 7 9' input = File.readlines('./input').map(&:strip).map { |line| line.split.map(&:to_i) } # input = sample.split("\n").map{ | line | line.split.map(&:to_i) } # Part 1 solution = input.map { |report| sorted?(report) and safe?(report) }.count(true) puts solution # Part 2 second_run = input.zip(input.map { |report| sorted?(report) and safe?(report) }).reject { |_, test| test }.transpose second_run.delete_at(-1) second_run.flatten!(1) permutations = second_run.map { |report| report.map.with_index { |_number, i| report.dup.tap { |j| j.delete_at(i) } } } solution2 = permutations.map do |line| line.map do |report| sorted?(report) and safe?(report) end end.map(&:uniq).flatten.count(true) puts solution + solution2