Skip to content

Instantly share code, notes, and snippets.

@cjavdev
Created December 4, 2022 16:42
Show Gist options
  • Save cjavdev/864bec6b1b6bc423be487d234009f9bf to your computer and use it in GitHub Desktop.
Save cjavdev/864bec6b1b6bc423be487d234009f9bf to your computer and use it in GitHub Desktop.
# data = DATA.readlines
data = File.readlines(ARGV.first)
# PART 1
# result = data
# .map(&:chomp)
# .map(&:chars)
# .map { _1.each_slice(_1.length / 2).to_a }
# .map {|(left, right)| left & right }
# .flatten
# .map { _1 =~ /[A-Z]/ ? _1.ord - 38 : _1.ord - 96 }
# .sum
# PART 2
result = data
.map(&:chomp)
.each_slice(3)
.map { _1.map(&:chars) }
.map { _1 & _2 & _3 }
.flatten
.map { _1 =~ /[A-Z]/ ? _1.ord - 38 : _1.ord - 96 }
.sum
p result
__END__
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
@cjavdev
Copy link
Author

cjavdev commented Dec 4, 2022

@RomanTurner
Copy link

RomanTurner commented Dec 6, 2022

#--- Day 3: Rucksack Reorganization ---
class DayThree
    attr_accessor :triage_points, :sum, :file_name
    def initialize(file_name)
        @triage_points = ((97..122).to_a + ((97-32)..(122-32)).to_a).map(&:chr).each_with_object(Hash.new(0)).with_index{|(v, hash), i| hash[v] = i + 1}
        @sum = 0
        @file_name = file_name
    end

    def problem_one
        File.readlines(@file_name, chomp: true).each_with_index do |line, index|
             first, second = line.slice!(0, line.size/2).split(''), line.split('')
             dup = first & second
             dup.each {|d| @sum += @triage_points[d]}
        end
        @sum
    end

    def problem_two
        elf_groups = []
        File.readlines(@file_name, chomp:true).each_slice(3){|group| elf_groups << group }
        elf_groups.each do |group|
          first, second, third = group
          badge = first.split(//) & second.split(//) & third.split(//)
          @sum += @triage_points[badge[0]]
        end
        @sum
    end
end

class DayThreeTest < MiniTest::Test
    def test_problem_one
        d3 = DayThree.new('day-3-test.txt')
        assert_equal(157, d3.problem_one)
    end

    def test_problem_two
        d3 = DayThree.new('day-3-test.txt')
        assert_equal(d3.problem_two, 70)
    end
end

Lol, I need to get away from the bytes!
I just made a points map.

If you use the logical & operator between arrays, it will show the join of each array.
w%(a b c d e) & w%(h i j k a) #=> ['a']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment