Module: AocUtils
- Defined in:
- lib/aoc_utils.rb
Overview
Desc: Utility functions for Advent of Code problems
Defined Under Namespace
Classes: MazeUtils
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
32 33 34 35 36 37 38 |
# File 'lib/aoc_utils.rb', line 32 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
9 10 11 12 13 14 15 16 |
# File 'lib/aoc_utils.rb', line 9 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
21 22 23 24 25 26 27 |
# File 'lib/aoc_utils.rb', line 21 def self.read_strings(filename) strings = [] File.open(filename).each_line do |line| strings << line.strip.split(",").map(&: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
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/aoc_utils.rb', line 45 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)..] case datatype1 when "Integer" part1 = part1.map { |line| line.scan(/-?\d+/).map(&:to_i) } when "String" part1 = part1.map { |string| string.split(",").map(&:strip) }.flatten when "Char" part1.map!(&:strip) part1 = part1.map(&: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 { |string| string.split(",").map(&:strip) }.flatten when "Char" part2.map!(&:strip) part2 = part2.map(&:chars) end [part1, part2] end |