Skip to content

Instantly share code, notes, and snippets.

View henrik's full-sized avatar

Henrik Nyh henrik

View GitHub Profile
@henrik
henrik / 0_README.md
Last active December 22, 2024 21:00
Rails `with_conditions` proof-of-concept. Similar to `with_options`, but combines `if` and `unless` conditions.
@henrik
henrik / part1.rb
Last active December 5, 2023 18:56
Advent of Code day 5
data = DATA.read
seeds = data[/seeds: (.+)/, 1].split.map(&:to_i)
maps = data.scan(/map:\n(.+?)(?:\n\n|\z)/m).map { |(x)| x.lines.map { _1.split.map(&:to_i) } }
locations = seeds.map { |seed|
maps.reduce(seed) { |input, map|
d, s, _r = map.find { |_d, s, r| (s..(s + r)).cover?(input) }
d ? d + (input - s) : input
}
@henrik
henrik / part1.rb
Last active December 5, 2023 01:03
Advent of Code day 4
puts DATA.readlines.sum { |line|
_, winning_numbers, my_numbers = line.split(/[:|]/).map(&:split)
wins = (winning_numbers & my_numbers).length
wins.zero? ? 0 : 2**(wins - 1)
}
__END__
Data goes here
@henrik
henrik / part1_take1.rb
Last active December 3, 2023 19:12
Advent of Code day 3
grid = DATA.readlines.map(&:chomp)
max_line = grid.length - 1
max_col = grid.first.length - 1
sum = 0
grid.each_with_index do |line, i|
tokens = line.scan(/(\D*)(\d+)/).flatten
offset = 0
tokens.each.with_index do |token, j|
@henrik
henrik / part1_take1.rb
Last active December 2, 2023 14:20
Advent of Code day 2
CONSTRAINTS = { red: 12, green: 13, blue: 14 }
puts DATA.readlines.sum { |line|
game, rounds = line.match(/Game (\d+): (.+)/).captures
rounds = rounds.split("; ").map { _1.scan(/(\d+) (\w+)/) }
next 0 unless rounds.all? { |round| round.all? { |count, color| count.to_i <= CONSTRAINTS[color.to_sym] } }
game.to_i
}
@henrik
henrik / take1.rb
Last active December 2, 2023 08:35
Advent of Code day 1 part 2
# The no-frills take.
words = %w[ one two three four five six seven eight nine ]
hash = words.flat_map.with_index(1) { |word, index| [ [ word, index ], [ index.to_s, index ] ] }.to_h
puts DATA.readlines.sum { |line|
_, first_digit = hash.min_by { |string, _| line.index(string) || 999 }
_, last_digit = hash.max_by { |string, _| line.rindex(string) || -1 }
first_digit * 10 + last_digit
require "net/ssh/proxy/errors"
module TemporaryNetworkErrors
def self.all
[
*NetHttpTimeoutErrors.all,
Errno::EBADF,
IOError,
OpenSSL::SSL::SSLError,
@henrik
henrik / config__initializers__exceptions.rb
Last active October 27, 2023 11:29
Sidekiq "silence_errors_during_retries".
# Intended for silent Sidekiq retries: https://www.mikeperham.com/2017/09/29/retries-and-exceptions/
class Exception
attr_accessor :ignore_in_error_reporting
end
module ClimateControlHelpers
# Usage:
#
# describe Foo do
# stub_envs(
# FOO: "bar",
# )
#
# it "uses the ENVs"
# end