summaryrefslogtreecommitdiff
path: root/d03/src
diff options
context:
space:
mode:
Diffstat (limited to 'd03/src')
-rw-r--r--d03/src/main.rs89
1 files changed, 89 insertions, 0 deletions
diff --git a/d03/src/main.rs b/d03/src/main.rs
new file mode 100644
index 0000000..d168a44
--- /dev/null
+++ b/d03/src/main.rs
@@ -0,0 +1,89 @@
+use std::fs;
+
+fn solve_part1(rows: &Vec<Vec<usize>>) -> usize {
+ let mut num_valid: usize = 0;
+
+ for row in rows {
+ let mut sides = row.clone();
+
+ sides.sort();
+ if sides[0] + sides[1] > sides[2] {
+ num_valid += 1;
+ }
+ }
+
+ num_valid
+}
+
+fn solve_part2(rows: &Vec<Vec<usize>>) -> usize {
+ let mut num_valid: usize = 0;
+
+ // For each 3 consecutive rows of data
+ for i in 0..(rows.len() / 3) {
+ // For each of the 3 numbers per row
+ for j in 0..3 {
+ let mut sides = Vec::new();
+ // For each row in this group of 3 rows
+ for k in 0..3 {
+ sides.push(rows[3 * i + k][j]);
+ }
+
+ sides.sort();
+ if sides[0] + sides[1] > sides[2] {
+ num_valid += 1;
+ }
+ }
+ }
+
+ num_valid
+}
+
+fn main() {
+ // Read and parse triangle data from input text file
+ let input = fs::read_to_string("input.txt").unwrap();
+ let lines: Vec<&str> = input.lines().collect();
+ let words: Vec<Vec<&str>> = lines
+ .into_iter()
+ .map(|l| l.split_ascii_whitespace().collect())
+ .collect();
+ let rows: Vec<Vec<usize>> = words
+ .into_iter()
+ .map(|w123| w123
+ .into_iter()
+ .map(|s| s.parse().unwrap())
+ .collect())
+ .collect();
+
+ // Part 1 gives 993 for me
+ println!("Part 1 solution: {}", solve_part1(&rows));
+
+ // Part 2 gives 1849 for me
+ println!("Part 2 solution: {}", solve_part2(&rows));
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn part1_example1() {
+ let rows = vec![
+ vec![5, 10, 25],
+ vec![3, 4, 5],
+ ];
+ assert_eq!(solve_part1(&rows), 1);
+ }
+
+ #[test]
+ fn part2_example1() {
+ let rows = vec![
+ vec![101, 301, 501],
+ vec![102, 302, 502],
+ vec![103, 303, 503],
+ vec![201, 401, 601],
+ vec![202, 402, 602],
+ vec![203, 403, 603],
+ ];
+ assert_eq!(solve_part2(&rows), 6);
+ }
+}