day24 part1 input parsing

This commit is contained in:
Johannes
2018-12-26 23:22:45 +01:00
parent 2b51e67fc6
commit 097cfac516
4 changed files with 87 additions and 2 deletions

View File

@@ -1,4 +1,4 @@
fn main() {
// aoc_2018::tasks::day23::task1();
aoc_2018::tasks::day23::task2();
aoc_2018::tasks::day24::task1();
// aoc_2018::tasks::day23::task2();
}

84
src/tasks/day24.rs Normal file
View File

@@ -0,0 +1,84 @@
pub fn task1() {
let input = "Immune System:
17 units each with 5390 hit points (weak to radiation, bludgeoning) with an attack that does 4507 fire damage at initiative 2
989 units each with 1274 hit points (immune to fire; weak to bludgeoning, slashing) with an attack that does 25 slashing damage at initiative 3
Infection:
801 units each with 4706 hit points (weak to radiation) with an attack that does 116 bludgeoning damage at initiative 1
4485 units each with 2961 hit points (immune to radiation; weak to fire, cold) with an attack that does 12 slashing damage at initiative 4";
let mut groups_immune: Vec<Group> = Vec::new();
let mut groups_infection: Vec<Group> = Vec::new();
let mut to_immune = false;
for line in input.lines() {
match line {
"Immune System:" => {
to_immune = true;
}
"Infection:" => {
to_immune = false;
}
"" => (),
group => {
if let Some(group) = Group::from_str(group) {
if to_immune {
groups_immune.push(group);
} else {
groups_infection.push(group);
}
}
}
}
}
println!("Immune System:\n{:?}", groups_immune);
println!("Infection:\n{:?}", groups_infection);
}
#[derive(Debug)]
struct Group {
units: i64,
hp_each: i64,
weaknesses: Vec<String>,
immunities: Vec<String>,
attack_damage: i64,
attack_type: String,
initiative: u64,
}
impl Group {
fn from_str(input: &str) -> Option<Self> {
// 801 units each with 4706 hit points (weak to radiation) with an attack that does 116 bludgeoning damage at initiative 1
use regex::Regex;
let regex = Regex::new(r"(\d+) units each with (\d+) hit points \((.+)\) with an attack that does (\d+) (\w+) damage at initiative (\d+)").unwrap();
if let Some(m) = regex.captures(input) {
let units: i64 = m[1].parse().unwrap();
let hp_each: i64 = m[2].parse().unwrap();
let attack_damage: i64 = m[4].parse().unwrap();
let attack_type = m[5].to_string();
let initiative: u64 = m[6].parse().unwrap();
let mut weaknesses: Vec<String> = Vec::new();
let mut immunities: Vec<String> = Vec::new();
for part in m[3].split("; ") {
if part.starts_with("weak to ") {
weaknesses = part[8..].split(", ").map(|it| it.to_string()).collect();
} else if part.starts_with("immune to ") {
immunities = part[10..].split(", ").map(|it| it.to_string()).collect();
}
}
let group = Group {
units,
hp_each,
weaknesses,
immunities,
attack_damage,
attack_type,
initiative,
};
Some(group)
} else {
None
}
}
}

View File

@@ -16,3 +16,4 @@ pub mod day15;
pub mod day20;
pub mod day22;
pub mod day23;
pub mod day24;