summary refs log tree commit diff
path: root/07/src
diff options
context:
space:
mode:
authorIrene Knapp <ireneista@gmail.com>2021-12-07 03:14:11 -0800
committerIrene Knapp <ireneista@gmail.com>2021-12-07 03:14:11 -0800
commit8079dd2a895f8a55368761940eba5670e24d0411 (patch)
tree20f1da1af9ee1de1279556853520b45b978bef0e /07/src
parent84f096f97b40e7f7394b72e3b54b19804e9ab6ac (diff)
07
Diffstat (limited to '07/src')
-rw-r--r--07/src/main.rs58
1 files changed, 58 insertions, 0 deletions
diff --git a/07/src/main.rs b/07/src/main.rs
new file mode 100644
index 0000000..a22129a
--- /dev/null
+++ b/07/src/main.rs
@@ -0,0 +1,58 @@
+use advent_lib::prelude::*;
+
+
+fn main() -> Result<()> {
+  let mut args = std::env::args();
+  if args.len() != 2 {
+    eprintln!("Usage: advent input");
+  }
+  let _ = args.next();
+  let filename = args.next().unwrap();
+
+  let input = advent_lib::read_lines_file(&filename)?;
+
+  let mut start_positions = Vec::new();
+  for word in input[0].split(',') {
+    let position = word.parse::<i64>()?;
+    start_positions.push(position);
+  }
+  start_positions.sort();
+
+  {
+    let median = start_positions[start_positions.len() / 2];
+    let mut cost = 0;
+    for position in &start_positions {
+      cost += (median - position).abs();
+    }
+    println!("{}", cost);
+  }
+
+  {
+    let min = start_positions[0];
+    let max = start_positions[start_positions.len() - 1];
+    let mut best_cost = None;
+
+    for destination in min .. max + 1 {
+      let mut cost = 0;
+      for position in &start_positions {
+        let distance = (destination - position).abs();
+        cost += distance * (distance + 1) / 2;
+      }
+
+      match best_cost {
+        None => {
+          best_cost = Some(cost);
+        },
+        Some(old_best) => {
+          if cost < old_best {
+            best_cost = Some(cost);
+          }
+        },
+      }
+    }
+
+    println!("{}", best_cost.unwrap());
+  }
+
+  Ok(())
+}