Something went wrong. Try again.
Code for the Advent of Code event
aoc advent-of-code
Something went wrong. Try again.
1.3 kB · 63 lines
Ruby
at rust
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364#!/usr/bin/env ruby# frozen_string_literal: true
require 'digest'require 'matrix'
# ########## #S| | | ## #-#-#-#-## # | | | ## #-#-#-#-## # | | | ## #-#-#-#-## # | | |# ####### V
WIDTH = 4HEIGHT = 4START = Vector[0, 0]GOAL = Vector[3, 3]PASSCODE = (ARGV[0] || 'pgflpeqp').freezeDIRECTIONS = [ [Vector[0, -1], :U], [Vector[0, 1], :D], [Vector[-1, 0], :L], [Vector[1, 0], :R]].freezeOPEN = %w[b c d e f].to_set.freeze
def wall?(pos) x, y = *pos x < 0 || x >= WIDTH || y < 0 || y >= HEIGHTend
def valid_positions(pos, moves) moves = moves.map(&:to_s).join data = PASSCODE + moves md5 = Digest::MD5.hexdigest data first = md5[..3] valid_dirs = DIRECTIONS.select.with_index { |_, i| OPEN.include? first[i] } valid_dirs.map { |p, d| [pos + p, d] }.reject { |p, _| wall? p }end
def shortest(pos, path) return path if pos == GOAL move_to = valid_positions(pos, path) return nil if move_to.empty? # dead end move_to.map do |p, d| shortest(p, path + [d]) end.compact.min_by(&:size)end
def longest(pos, path) return path if pos == GOAL move_to = valid_positions(pos, path) return nil if move_to.empty? # dead end move_to.map do |p, d| longest(p, path + [d]) end.compact.max_by(&:size)end
puts shortest(START, []).joinputs longest(START, []).size