Advent of Code (Day 10)


Check out out day 10 here.

Challenge One

Man, it really paid off to use OOP and break down each part so I can make sure each part does what I think it was supposed to do.

The hardest part was the ‘twist’ because of reversing elements that are wrapped past the end of the array back to the beginning. To make this easy, I just had three steps in the twist that made sense to me:

  1. copy a sublist over n positions of the array from the current_position allowing for a wrap to the beginning of the array if needed.
  2. reverse this sublist. Super easy part
  3. copy BACK this sublist onto the original array

Everything else fell into place after that.


class Knot
  attr_reader :knot, :skip_size, :current_position

  def initialize
    @knot = (0..255).to_a
    @current_position = 0
    @skip_size = 0
  end

  def tye(length)
    twist(length)
    move_current_position(length)
    increase_skip_size
    knot
  end

  def twist(length)
    # Reverse the order of that length of elements in the list, starting with
    # the element at the current position.
      # copy over list from knot
    sublist = list(length)
      # reverse list
    sublist.reverse!
      # copy the list back onto knot
    copy_list(sublist)
  end

  def list(length)
    sublist = []
    positions = length

    positions.times do |position|
      sublist << knot[(current_position + position) % knot.length]
    end

    sublist
  end

  def copy_list(current_list)
    positions = current_list.size

    positions.times do |position|
      knot[(current_position + position) % knot.length] = current_list[position]
    end
  end

  def move_current_position(positions)
    @current_position += ((positions + skip_size) % knot.length)
  end

  def increase_skip_size
    @skip_size += 1
  end
end

lengths = File.read('input.txt').split(',').map(&:to_i)

@knot = Knot.new

test_lengths.each do |length|
  @knot.tye(length)
end

print @knot.knot

Challenge Two

We work with the Knot Hash Algorithm

When I first read part 2, I was like wtf? Yeah, this was a weird one. Part 2 made me touch things I don’t really touch:

Reusing challenge one

The nice thing was we didn’t have to do things much differently except:

Over all, here is a summary of different parts for part 2


input = File.read('input.txt').gsub("\n", '')
lengths = input.chars.map {|char| char.ord} + [17, 31, 73, 47, 23]

@knot = Knot.new

64.times do
  lengths.each do |length|
    @knot.tye(length)
  end
end

sparse_hash = @knot.knot

dense_hash_numbers = sparse_hash.each_slice(16).map do |group|
  group.inject(&:^)
end

print dense_hash_numbers.map { |n| sprintf('%02x', n) }.join('')

Anyway, yeah fun times. Have an eggnog and grab photos with Santa today. I’m not sure why one would use the Knot Hash Algorithm, but I don’t care enough to Google it. Bye for now.