Class: AocUtils
- Inherits:
-
Object
- Object
- AocUtils
- Defined in:
- lib/aoc_utils.rb
Overview
Desc: Utility functions for Advent of Code problems
Class Method Summary collapse
-
.read_chars(filename) ⇒ Array<Array<String>>
extracts all characters from the specified file.
-
.read_ints(filename, other_characters = []) ⇒ Array<Array<Integer>>
extracts all integers from the specified file.
-
.read_strings(filename) ⇒ Array<String>
extracts all strings from the specified file.
-
.read_two_parts(filename, datatype1, datatype2) ⇒ Array<Array>
extracts all lines from the specified file and splits them into two parts based on an empty line.
Class Method Details
.read_chars(filename) ⇒ Array<Array<String>>
extracts all characters from the specified file
30 31 32 33 34 35 36 |
# File 'lib/aoc_utils.rb', line 30 def self.read_chars(filename) chars = [] File.open(filename).each_line do |line| chars << line.strip.chars end chars end |
.read_ints(filename, other_characters = []) ⇒ Array<Array<Integer>>
extracts all integers from the specified file
7 8 9 10 11 12 13 14 |
# File 'lib/aoc_utils.rb', line 7 def self.read_ints(filename, other_characters = []) ints = [] File.open(filename).each_line do |line| ints << line.scan(/-?\d+/).map(&:to_i) other_characters << line[/[^0-9\s]/] end ints end |
.read_strings(filename) ⇒ Array<String>
extracts all strings from the specified file
19 20 21 22 23 24 25 |
# File 'lib/aoc_utils.rb', line 19 def self.read_strings(filename) strings = [] File.open(filename).each_line do |line| strings << line.strip end strings end |
.read_two_parts(filename, datatype1, datatype2) ⇒ Array<Array>
extracts all lines from the specified file and splits them into two parts based on an empty line
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/aoc_utils.rb', line 43 def self.read_two_parts(filename, datatype1, datatype2) lines = File.open(filename).readlines.map(&:strip) index = lines.index("") part1 = lines[0...index] part2 = lines[(index + 1)..-1] case datatype1 when "Integer" part1 = part1.map { |line| line.scan(/-?\d+/).map(&:to_i) } when "String" part1 = part1.map(&:strip) when "Char" part1 = part1.map(&:strip.chars) else raise "Invalid datatype" end case datatype2 when "Integer" part2 = part2.map { |line| line.scan(/-?\d+/).map(&:to_i) } when "String" part2 = part2.map(&:strip) when "Char" part2 = part2.map(&:chars) end [part1, part2] end |