-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
383 lines (323 loc) · 9.12 KB
/
main.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
use std::env;
use std::fs::File;
use std::io::Error;
use std::io::*;
/*
This is my first proper program in rust.
It took me *quite* a long time to get this right, and was a massive learning curve.
The number of times I had to rewrite this program is somewhat embarassing (hence the delay ;-;)
Final result has alot of redundant stuff, and is generally very inefficient.
I tried *many* ways of doing this, but ended on a pretty inefficient result after alot of roadblocks.
*/
enum Item {
Symbol(char),
Digit(char),
Space,
}
impl Item {
fn is_symbol(&self) -> bool {
match self {
Item::Symbol(_) => true,
_ => false,
}
}
fn is_digit(&self) -> bool {
match self {
Item::Digit(_) => true,
_ => false,
}
}
fn char(&self) -> char {
match self {
Item::Symbol(c) => *c,
Item::Digit(c) => *c,
Item::Space => '.',
}
}
}
/*
Had alot of trouble with index out of bounds problems,
so I just decided to implement this as a struct and implement a bunch of checking
and safe operations functions
*/
struct Plan {
width: usize,
height: usize,
grid: Vec<Vec<Item>>,
}
impl Plan {
fn new(width: usize, height: usize) -> Plan {
let mut plan = Vec::with_capacity(height);
for i in 0..height {
// Initialize the row
plan.push(Vec::with_capacity(width));
// Fill the row with Spaces by default
for _ in 0..width {
plan[i].push(Item::Space);
}
}
Plan {
height: height,
width: width,
grid: plan,
}
}
fn get(&self, row: usize, col: usize) -> Result<&Item> {
self.check_bounds(row, col)?;
self.validate_width(row)?;
Ok(&self.grid[row][col])
}
fn set(&mut self, value: Item, row: usize, col: usize) -> Result<()> {
self.check_bounds(row, col)?;
self.grid[row][col] = value;
Ok(())
}
fn check_adjacent_symbols(&self, row: usize, col: usize) -> Result<bool> {
self.check_bounds(row, col)?;
// Check to the left and right in the same row
if col > 0 && self.grid[row][col - 1].is_symbol() {
return Ok(true);
}
if col < self.width - 1 && self.grid[row][col + 1].is_symbol() {
return Ok(true);
}
// Check below indexes, including diagonals (if the row exists)
if row > 0 {
if col > 0 && self.grid[row - 1][col - 1].is_symbol() {
return Ok(true);
}
if self.grid[row - 1][col].is_symbol() {
return Ok(true);
}
if col < self.width - 1 && self.grid[row - 1][col + 1].is_symbol() {
return Ok(true);
}
}
// Check above indexes, including diagonals (if the row exists)
if row < self.height - 1 {
if col > 0 && self.grid[row + 1][col - 1].is_symbol() {
return Ok(true);
}
if self.grid[row + 1][col].is_symbol() {
return Ok(true);
}
if col < self.width - 1 && self.grid[row + 1][col + 1].is_symbol() {
return Ok(true);
}
}
Ok(false)
}
fn find_adjacent_numbers(&self, row:usize, col:usize) -> Result<Vec<i32>> {
self.check_bounds(row, col)?;
let mut digits = Vec::new();
// Determine the coords of digits surrounding the position
if col > 0 && self.grid[row][col-1].is_digit() {
digits.push((row, col-1));
}
if self.grid[row][col].is_digit() {
digits.push((row, col));
}
if col < self.width - 1 && self.grid[row][col+1].is_digit() {
digits.push((row, col+1));
}
if row > 0 {
if col > 0 && self.grid[row-1][col-1].is_digit() {
digits.push((row-1, col-1));
}
if self.grid[row-1][col].is_digit() {
digits.push((row-1, col));
}
if col < self.width - 1 && self.grid[row-1][col+1].is_digit() {
digits.push((row-1, col+1));
}
}
if row < self.height - 1 {
if col > 0 && self.grid[row+1][col-1].is_digit() {
digits.push((row+1, col-1));
}
if self.grid[row+1][col].is_digit() {
digits.push((row+1, col));
}
if col < self.width - 1 && self.grid[row+1][col+1].is_digit() {
digits.push((row+1, col+1));
}
}
// Once digits have been found, construct numbers and eliminate duplicates
let mut nums = Vec::new();
let mut starts = Vec::new();
for (row, col) in digits {
let (i, start) = self.walk_read_number(row, col)?;
if !starts.contains(&(row, start)) {
nums.push(i);
starts.push((row, start));
}
}
Ok(nums)
}
fn walk_read_number(&self, row:usize, col:usize) -> Result<(i32, usize)> {
self.check_bounds(row, col)?;
// Find the start of the number
let mut start = col;
while start > 0 {
if self.grid[row][start - 1].is_digit() {
start -= 1;
} else {
break;
}
}
let mut num = String::new();
for i in start..self.grid[row].len() {
if self.grid[row][i].is_digit() {
num.push(self.grid[row][i].char());
} else {
break;
}
}
if num.len() == 0 {
return Err(Error::new(ErrorKind::InvalidData, "Value provided is not a number!"));
}
match num.parse::<i32>() {
Err(why) => Err(Error::new(ErrorKind::InvalidData, why.to_string())),
Ok(i) => Ok((i, start)),
}
}
fn check_bounds(&self, row: usize, col: usize) -> Result<()> {
if row < self.width && col < self.height {
self.validate_width(row)?;
Ok(())
} else {
Err(Error::new(
ErrorKind::InvalidData,
format!(
"Index {},{} out of bounds! Max: {}x{}",
row, col, self.height, self.width
),
))
}
}
fn validate_width(&self, row: usize) -> Result<()> {
// Basic bounds check
if row <= self.height && self.grid[row].len() == self.width {
Ok(())
} else {
Err(Error::new(
ErrorKind::InvalidData,
format!(
"Row {} has incorrect width {}, should be {}.",
row,
self.grid[row].len(),
self.width
),
))
}
}
}
fn open_reader(path: Option<&String>) -> Result<Vec<String>> {
// Creates both a buffered reader object and returns the number of lines in the file by pre-reading.
let mut buffer: Vec<String> = Vec::new();
let source: Box<dyn Read> = match path {
None => Box::new(stdin()),
Some(f) => Box::new(File::open(f)?),
};
for line in BufReader::new(source).lines() {
buffer.push(line?);
}
Ok(buffer)
}
fn read_the_plan(source: Vec<String>) -> Result<Plan> {
// I had to make this intermediate function to read the input into a list.
// Rust proved to be way too strict on String to allow me to read the plan in a simpler way.
// Estalish height and width values, then allocate a plan struct
let height = source.len();
let width = source[0].len();
let mut plan = Plan::new(width, height);
for row in 0..source.len() {
if source[row].len() != width {
return Err(Error::new(
ErrorKind::InvalidData,
"Inconsistent line lengths!"
));
}
let mut col = 0;
for c in source[row].chars() {
if c.is_numeric() {
plan.set(Item::Digit(c), row, col)?;
} else if c != '.' {
plan.set(Item::Symbol(c), row, col)?;
}
// Skip setting to Item::Space, as this is the default
col += 1;
}
}
return Ok(plan);
}
fn add_valid_numbers(plan: &Plan) -> Result<i32> {
let mut total = 0;
let mut adjacent = false;
let mut num = String::new();
for row in 0..plan.height {
for col in 0..plan.width {
match plan.get(row, col)? {
Item::Digit(c) => {
num.push(*c);
if plan.check_adjacent_symbols(row, col)? {
adjacent = true;
}
},
_ => {
if adjacent {
total += match num.parse::<i32>() {
Err(why) => return Err(Error::new(ErrorKind::InvalidData, why.to_string())),
Ok(i) => i,
};
adjacent = false;
}
num.clear();
}
}
}
if adjacent {
total += match num.parse::<i32>() {
Err(why) => return Err(Error::new(ErrorKind::InvalidData, why.to_string())),
Ok(i) => i,
};
adjacent = false;
}
num.clear();
}
Ok(total)
}
fn sum_gear_ratios(plan: &Plan) -> Result<i64> {
let mut total = 0;
for row in 0..plan.height {
for col in 0..plan.width {
match plan.get(row,col)? {
&Item::Symbol(c) => {
if c == '*' {
let nums = plan.find_adjacent_numbers(row, col)?;
if nums.len() == 2 {
total += (nums[0] * nums[1]) as i64;
} else {
}
}
},
_ => {},
}
}
}
Ok(total)
}
fn main() {
let args: Vec<String> = env::args().collect();
let path = if args.len() > 1 && args[1] != "-" {
Some(&args[1])
} else {
None
};
// Part 1
let source = open_reader(path).unwrap();
let plan = read_the_plan(source).unwrap();
println!("Part 1: {}", add_valid_numbers(&plan).unwrap());
// Part 2
println!("Part 2: {}", sum_gear_ratios(&plan).unwrap());
}