-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathint_code_program.rb
More file actions
66 lines (54 loc) · 1.18 KB
/
int_code_program.rb
File metadata and controls
66 lines (54 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# frozen_string_literal: true
module IntCodeParser
ADD = 1
MULT = 2
IN = 3
OUT = 4
IF = 5
UNLESS = 6
LESS = 7
EQUALS = 8
HALT = 99
POSITION = 0
IMMEDIATE = 1
OP_CODES = {
ADD => :add,
MULT => :mult,
IN => :in,
OUT => :out,
IF => :if,
UNLESS => :unless,
LESS => :less,
EQUALS => :equals,
HALT => :halt
}.freeze
PARAMETER_MODES = {
POSITION => :position,
IMMEDIATE => :immediate
}.freeze
def input_mode_analyzer(input_mode)
parameter_hash = input_mode.digits.reverse
op_code = parse_op_code(parameter_hash[-2, 2]&.join || parameter_hash[-1])
mode_1 = OP_CODES[parameter_hash[-3]]
mode_2 = OP_CODES[parameter_hash[-4]]
mode_3 = OP_CODES[parameter_hash[-5]]
[op_code, mode_1, mode_2, mode_3]
end
def parse_op_code(op_code)
OP_CODES[op_code.to_i]
end
end
class Program
include IntCodeParser
attr_reader :program
attr_accessor :needle
def initialize(program)
@program = program
@needle = 0
end
def next
op_code = input_mode_analyzer(program[needle])
send(op_code[0], op_code.slice(1, op_code.length))
end
def in(params); end
end