aboutsummaryrefslogtreecommitdiff
path: root/2020/day03/src
diff options
context:
space:
mode:
authorjacopograndi <jacopo.grandi@outlook.it>2022-08-03 23:21:45 +0200
committerjacopograndi <jacopo.grandi@outlook.it>2022-08-03 23:21:45 +0200
commite8358006ad414c144a6260166f8d3322ca24eb20 (patch)
treebf580dc320e3379e57d8b8613a74e1bd611b109c /2020/day03/src
parent83e7790997b54e2487aa2c3242c579a5995f23e0 (diff)
day03
Diffstat (limited to '2020/day03/src')
-rw-r--r--2020/day03/src/main.rs74
1 files changed, 74 insertions, 0 deletions
diff --git a/2020/day03/src/main.rs b/2020/day03/src/main.rs
new file mode 100644
index 0000000..6e74f74
--- /dev/null
+++ b/2020/day03/src/main.rs
@@ -0,0 +1,74 @@
+fn slide(lines: Vec<Vec<char>>, vx: i32, vy: i32) -> i32 {
+ let mut x: i32 = 0;
+ let mut y: i32 = 0;
+ let mut hits: i32 = 0;
+ loop {
+ if lines[y as usize][x as usize] == '#' {
+ hits += 1;
+ }
+ x += vx;
+ y += vy;
+ if y as usize >= lines.len() {
+ break;
+ }
+ if x as usize >= lines[y as usize].len() {
+ x -= lines[y as usize].len() as i32;
+ }
+ }
+ hits
+}
+
+fn slide_everywhere(lines: Vec<Vec<char>>) -> i32 {
+ let mut hits: i32 = 1;
+ for (vx, vy) in vec![(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] {
+ hits *= slide(lines.clone(), vx, vy);
+ }
+ hits
+}
+
+fn main() {
+ let lines: Vec<Vec<char>> = include_str!("../input0.txt")
+ .trim()
+ .split("\n")
+ .map(|s| s.chars().collect())
+ .collect();
+ let hits = slide(lines.clone(), 3, 1);
+ println!("hits: {}", hits);
+ let hits_everything = slide_everywhere(lines.clone());
+ println!("hits on the five paths: {}", hits_everything);
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::*;
+
+ #[test]
+ fn small_input() {
+ let lines: Vec<Vec<char>> = include_str!("../test0.txt")
+ .trim()
+ .split("\n")
+ .map(|s| s.chars().collect())
+ .collect();
+ assert_eq!(slide(lines, 3, 1), 7);
+ }
+
+ #[test]
+ fn big_input() {
+ let lines: Vec<Vec<char>> = include_str!("../input0.txt")
+ .trim()
+ .split("\n")
+ .map(|s| s.chars().collect())
+ .collect();
+ assert_eq!(slide(lines, 3, 1), 220);
+ }
+
+ #[test]
+ fn small_input_all_slopes() {
+ let lines: Vec<Vec<char>> = include_str!("../test0.txt")
+ .trim()
+ .split("\n")
+ .map(|s| s.chars().collect())
+ .collect();
+ assert_eq!(slide_everywhere(lines), 336);
+ }
+}