summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/bin/day1.rs29
-rw-r--r--src/lib.rs12
2 files changed, 41 insertions, 0 deletions
diff --git a/src/bin/day1.rs b/src/bin/day1.rs
new file mode 100644
index 0000000..eb4ee6a
--- /dev/null
+++ b/src/bin/day1.rs
@@ -0,0 +1,29 @@
+fn main() {
+ let input = advent::read_numbers(1);
+ println!("1a: {}", count_increasing(&input));
+ println!("1b: {}", count_increasing_window(&input, 3));
+}
+
+fn count_increasing(numbers: &[usize]) -> usize {
+ count_increasing_window(numbers, 1)
+}
+
+fn count_increasing_window(numbers: &[usize], window_size: usize) -> usize {
+ numbers[window_size..].iter()
+ .zip(numbers.iter())
+ .map(|(&x,&y)| (x as isize) - (y as isize))
+ .filter(|&x| x.is_positive())
+ .count()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test() {
+ let numbers = [199, 200, 208, 210, 200, 207, 240, 269, 260, 263];
+ assert_eq!(count_increasing(&numbers), 7);
+ assert_eq!(count_increasing_window(&numbers, 3), 5);
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..6befee8
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,12 @@
+
+pub fn read_file(day: u8) -> String {
+ let filename = format!("inputs/day{}", day);
+ std::fs::read_to_string(filename).unwrap()
+}
+
+pub fn read_numbers(day: u8) -> Vec<usize> {
+ read_file(day).split('\n')
+ .filter(|n| !n.is_empty())
+ .map(|n| n.parse::<usize>().unwrap())
+ .collect()
+}