This repository has been archived by the owner on Sep 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8.rs
156 lines (134 loc) · 3.51 KB
/
8.rs
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
use std::str::FromStr;
use std::convert::TryInto;
#[derive(Debug, PartialEq)]
enum Error {
UnknownOp(String),
InvalidArgument(String),
InvalidJmp(Line),
Loop,
EndOfProgram,
EmptyLine,
NoArgument,
}
#[derive(Debug, Clone, PartialEq)]
enum Op {
Acc,
Nop,
Jmp
}
impl FromStr for Op {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"nop" => Ok(Self::Nop),
"jmp" => Ok(Self::Jmp),
"acc" => Ok(Self::Acc),
_ => Err(Error::UnknownOp(s.to_string()))
}
}
}
#[derive(Debug, Clone, PartialEq)]
struct Line {
op: Op,
arg: i64,
cnt: u64
}
impl Line {
fn from_asm<T: AsRef<str>>(asm: T) -> Result<Self, Error> {
let mut asm = asm.as_ref().split(" ");
let op: Op = asm.next()
.ok_or(Error::EmptyLine)?
.parse()?;
let arg: i64 = asm.next()
.ok_or(Error::NoArgument)?
.parse().map_err(|_| Error::InvalidArgument("?".to_string()))?;
Ok(Self {
op: op,
arg: arg,
cnt: 0
})
}
}
struct Handheld {
acc: i64,
source: Vec<Line>,
ip: usize,
}
impl Handheld {
fn new() -> Self {
Self {
acc: 0,
source: vec![],
ip: 0
}
}
fn reset(&mut self) {
self.ip = 0;
self.acc = 0;
for line in self.source.iter_mut() {
line.cnt = 0;
}
}
fn load<T: AsRef<str>>(&mut self, asm: T) -> Result<(), Error> {
self.source = asm.as_ref().trim().split("\n")
.map(Line::from_asm)
.collect::<Result<Vec<Line>, Error>>()?;
self.reset();
Ok(())
}
fn advance(&mut self) -> Result<(), Error> {
let line = self.source.get_mut(self.ip)
.ok_or(Error::EndOfProgram)?;
if line.cnt != 0 {
return Err(Error::Loop);
}
self.ip += 1;
match line.op {
Op::Acc => self.acc += line.arg,
Op::Nop => (),
Op::Jmp => self.ip = (self.ip as i64 + line.arg - 1).try_into().map_err(|_| Error::InvalidJmp(line.clone()))?,
}
line.cnt += 1;
Ok(())
}
fn execute(&mut self) -> Result<(), Error> {
loop {
if let Err(e) = self.advance() {
match e {
Error::EndOfProgram => return Ok(()),
_ => return Err(e),
}
}
}
}
}
fn main() {
let asm = include_str!("8.in");
let mut handheld = Handheld::new();
handheld.load(asm).expect("Invalid asm");
assert_eq!(handheld.execute(), Err(Error::Loop));
println!("Looped at acc {}", handheld.acc);
for i in 0..handheld.source.len() {
handheld.reset();
{
let line = handheld.source.get_mut(i).unwrap();
if line.op == Op::Jmp {
line.op = Op::Nop;
} else if line.op == Op::Nop {
line.op = Op::Jmp;
}
}
if handheld.execute().is_ok() {
println!("Terminated at acc {}", handheld.acc);
break;
}
{
let line = handheld.source.get_mut(i).unwrap();
if line.op == Op::Jmp {
line.op = Op::Nop;
} else if line.op == Op::Nop {
line.op = Op::Jmp;
}
}
}
}