58 lines
		
	
	
		
			1023 B
		
	
	
	
		
			Ruby
		
	
	
	
	
	
		
		
			
		
	
	
			58 lines
		
	
	
		
			1023 B
		
	
	
	
		
			Ruby
		
	
	
	
	
	
|  | #!/usr/bin/env ruby | ||
|  | 
 | ||
|  | require_relative '../common' | ||
|  | 
 | ||
|  | class Day02 < Day | ||
|  |   def part1 | ||
|  |     input.each_with_object(Position.new) { |cmd, position| position.process cmd }.result | ||
|  |   end | ||
|  | 
 | ||
|  |   def part2 | ||
|  |     input.each_with_object(Position.new(use_aim: true)) { |cmd, position| position.process cmd }.result | ||
|  |   end | ||
|  | 
 | ||
|  |   class Position | ||
|  |     def initialize(use_aim: false) | ||
|  |       @use_aim = use_aim | ||
|  | 
 | ||
|  |       @horizontal_position = 0
 | ||
|  |       @depth = 0
 | ||
|  |       @aim = 0
 | ||
|  |     end | ||
|  | 
 | ||
|  |     def process command | ||
|  |       direction, value = command.match(/\A(forward|down|up) ([0-9]+)\z/).captures | ||
|  |       send direction, value.to_i | ||
|  |     end | ||
|  | 
 | ||
|  |     def result | ||
|  |       @horizontal_position * @depth | ||
|  |     end | ||
|  | 
 | ||
|  |     private | ||
|  | 
 | ||
|  |     def forward value | ||
|  |       @horizontal_position += value | ||
|  |       @depth += @aim * value if @use_aim | ||
|  |     end | ||
|  | 
 | ||
|  |     def down value | ||
|  |       if @use_aim | ||
|  |         @aim += value | ||
|  |       else | ||
|  |         @depth += value | ||
|  |       end | ||
|  |     end | ||
|  | 
 | ||
|  |     def up value | ||
|  |       if @use_aim | ||
|  |         @aim -= value | ||
|  |       else | ||
|  |         @depth -= value | ||
|  |       end | ||
|  |     end | ||
|  |   end | ||
|  | end | ||
|  | 
 | ||
|  | Day02.run |