summaryrefslogtreecommitdiffstats
path: root/src/2020/8/mod.rs
diff options
context:
space:
mode:
authorJesse Luehrs <doy@tozt.net>2021-12-18 13:21:42 -0500
committerJesse Luehrs <doy@tozt.net>2021-12-18 13:21:42 -0500
commitd16795e44aeac17bee08363bd08c1a9672edf3d4 (patch)
tree3f70ddaf74b10db3f0e38c8a81838607f4e26a2c /src/2020/8/mod.rs
parentd1cacab50a8cab269da867ae900e903648b42cff (diff)
downloadadvent-of-code-d16795e44aeac17bee08363bd08c1a9672edf3d4.tar.gz
advent-of-code-d16795e44aeac17bee08363bd08c1a9672edf3d4.zip
factor out parsing
Diffstat (limited to 'src/2020/8/mod.rs')
-rw-r--r--src/2020/8/mod.rs30
1 files changed, 17 insertions, 13 deletions
diff --git a/src/2020/8/mod.rs b/src/2020/8/mod.rs
index 0756fe5..052538e 100644
--- a/src/2020/8/mod.rs
+++ b/src/2020/8/mod.rs
@@ -21,7 +21,7 @@ impl std::str::FromStr for OpType {
}
#[derive(Clone, Copy)]
-struct Op {
+pub struct Op {
ty: OpType,
arg: i64,
}
@@ -43,9 +43,13 @@ impl std::str::FromStr for Op {
}
}
-pub fn part1() -> anyhow::Result<i64> {
- let input = data_str!()?;
- let opcodes = parse(&input)?;
+pub fn parse(fh: std::fs::File) -> anyhow::Result<Vec<Op>> {
+ crate::util::parse::lines(fh)
+ .map(|line| line.parse())
+ .collect()
+}
+
+pub fn part1(opcodes: Vec<Op>) -> anyhow::Result<i64> {
let (acc, success) = run(&opcodes)?;
if success {
return Err(anyhow::anyhow!("unexpectedly succeeded"));
@@ -53,9 +57,7 @@ pub fn part1() -> anyhow::Result<i64> {
Ok(acc)
}
-pub fn part2() -> anyhow::Result<i64> {
- let input = data_str!()?;
- let opcodes = parse(&input)?;
+pub fn part2(opcodes: Vec<Op>) -> anyhow::Result<i64> {
for i in 0..opcodes.len() {
match opcodes[i].ty {
OpType::Nop => {
@@ -80,10 +82,6 @@ pub fn part2() -> anyhow::Result<i64> {
Err(anyhow::anyhow!("failed to find corrupted opcode"))
}
-fn parse(input: &str) -> anyhow::Result<Vec<Op>> {
- input.lines().map(|line| line.parse()).collect()
-}
-
fn run(opcodes: &[Op]) -> anyhow::Result<(i64, bool)> {
let mut seen = vec![false; opcodes.len()];
let mut pc = 0;
@@ -126,6 +124,12 @@ fn run(opcodes: &[Op]) -> anyhow::Result<(i64, bool)> {
#[test]
fn test() {
- assert_eq!(part1().unwrap(), 1928);
- assert_eq!(part2().unwrap(), 1319);
+ assert_eq!(
+ part1(parse(crate::util::data(2020, 8).unwrap()).unwrap()).unwrap(),
+ 1928
+ );
+ assert_eq!(
+ part2(parse(crate::util::data(2020, 8).unwrap()).unwrap()).unwrap(),
+ 1319
+ );
}