day12 task 1

This commit is contained in:
Johannes
2019-12-12 16:27:27 +01:00
parent 8849191a6b
commit eb7467f615
6 changed files with 157 additions and 1 deletions

View File

@@ -1,5 +1,5 @@
mod tasks;
fn main() {
tasks::day11::run();
tasks::day12::run();
}

101
src/tasks/day12.rs Normal file
View File

@@ -0,0 +1,101 @@
use regex::Regex;
#[allow(dead_code)]
pub fn run() {
let regex = Regex::new("<x=(-?\\d+),\\sy=(-?\\d+),\\sz=(-?\\d+)").unwrap();
let input: Vec<Point> = std::fs::read_to_string("input/day12.txt")
.unwrap()
.lines()
.map(|line| {
let m = regex.captures(&line).unwrap();
let x: i32 = m[1].parse().unwrap();
let y: i32 = m[2].parse().unwrap();
let z: i32 = m[3].parse().unwrap();
Point { x, y, z }
})
.collect();
task1(input.clone());
}
fn task1(input: Vec<Point>) {
let moons: Vec<_> = input
.into_iter()
.map(|pos| Moon {
pos: pos,
vel: Point::new(0, 0, 0),
})
.collect();
let finals = (0..1000).fold(moons, |moons, _run| {
let gravities: Vec<Point> = moons
.iter()
.map(|base| {
moons.iter().fold(Point::new(0, 0, 0), |grav, other_moon| {
grav.add(base.pos.gravity(other_moon.pos))
})
})
.collect();
let moons = moons
.into_iter()
.zip(gravities.into_iter())
.map(|(mut moon, grav)| {
moon.vel = moon.vel.add(grav);
moon.pos = moon.pos.add(moon.vel);
moon
})
.collect();
//println!("{}: {:?}", run, moons);
moons
});
let energy: i32 = finals
.iter()
.map(|moon| moon.pos.energy() * moon.vel.energy())
.sum();
println!("Task 1: sum of energy is {}", energy);
//392 too low
}
#[derive(Debug)]
struct Moon {
pos: Point,
vel: Point,
}
#[derive(Clone, Copy, Debug)]
struct Point {
x: i32,
y: i32,
z: i32,
}
impl Point {
fn new(x: i32, y: i32, z: i32) -> Self {
Point { x, y, z }
}
fn add(&self, other: Self) -> Self {
Point {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
}
}
fn gravity(&self, other: Self) -> Self {
fn d(a: i32, b: i32) -> i32 {
use std::cmp::Ordering;
match a.cmp(&b) {
Ordering::Less => 1,
Ordering::Equal => 0,
Ordering::Greater => -1,
}
}
Point {
x: d(self.x, other.x),
y: d(self.y, other.y),
z: d(self.z, other.z),
}
}
fn energy(&self) -> i32 {
self.x.abs() + self.y.abs() + self.z.abs()
}
}

View File

@@ -8,3 +8,4 @@ pub mod day08;
pub mod day09;
pub mod day10;
pub mod day11;
pub mod day12;