-
Notifications
You must be signed in to change notification settings - Fork 3
/
lib.rs
81 lines (65 loc) · 1.62 KB
/
lib.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
use std::fs::File;
use std::io::{BufRead, BufReader};
pub fn top1(file: &str) -> Result<i32, Box<dyn std::error::Error>> {
let reader = BufReader::new(File::open(file)?);
let mut current = 0;
let mut max = 0;
for res in reader.lines() {
let line = res?;
if line.eq("") {
if current > max {
max = current;
}
current = 0;
} else {
let n: i32 = line.to_string().parse()?;
current += n;
}
}
if current > max {
max = current;
}
Ok(max)
}
pub fn top3(file: &str) -> Result<i32, Box<dyn std::error::Error>> {
let reader = BufReader::new(File::open(file)?);
let mut current = 0;
let mut elves = vec![];
for res in reader.lines() {
let line = res?;
if line.eq("") {
elves.push(current);
current = 0;
} else {
let n: i32 = line.to_string().parse()?;
current += n;
}
}
elves.push(current);
elves.sort_by(|a, b| b.cmp(a));
Ok(elves[0] + elves[1] + elves[2])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn top1_unit() {
let result = top1("test.txt");
assert_eq!(result.unwrap(), 24000);
}
#[test]
fn top1_input() {
let result = top1("input.txt");
assert_eq!(result.unwrap(), 72718);
}
#[test]
fn top3_unit() {
let result = top3("test.txt");
assert_eq!(result.unwrap(), 45000);
}
#[test]
fn top3_input() {
let result = top3("input.txt");
assert_eq!(result.unwrap(), 72718);
}
}