15 votes

Day 1: Sonar Sweep

Today's problem description: https://adventofcode.com/2021/day/1

Please post your solutions in your own top-level comment. Here's a template you can copy-paste into your comment to format it nicely, with the code collapsed by default inside an expandable section with syntax highlighting (you can replace python with any of the "short names" listed in this page of supported languages):

<details>
<summary>Part 1</summary>

```python
Your code here.
```

</details>

22 comments

  1. pnutzh4x0r
    Link
    Python Repo Link Part 1 List comprehensions, yay! report = [int(depth) for depth in sys.stdin] increases = sum(1 for i in range(1, len(report)) if report[i] > report[i - 1]) print(increases) Part...

    Python

    Repo Link

    Part 1

    List comprehensions, yay!

    report    = [int(depth) for depth in sys.stdin]
    increases = sum(1 for i in range(1, len(report)) if report[i] > report[i - 1])
    print(increases)
    
    Part 2

    This took me longer than it should have, but once I realized that if I could just form the windows separately, then I could re-use the method for counting the increases from Part A.

    report    = [int(depth) for depth in sys.stdin]
    windows   = [sum(report[i:i+3]) for i in range(0, len(report) - 2)]
    increases = sum(1 for i in range(1, len(windows)) if windows[i] > windows[i - 1])
    print(increases)
    
    10 votes
  2. PapaNachos
    Link
    Oh shit, I completely forgot about this! I love Advent of Code. Last year I worked through them and did a write up for as long as I was able to stick with it. And I think folks responded pretty...

    Oh shit, I completely forgot about this! I love Advent of Code. Last year I worked through them and did a write up for as long as I was able to stick with it. And I think folks responded pretty positively to that, so I'm going to try to do it again

    Day 1 Part A – Python

    Just a text parser and a loop. Nothing particularly fancy

    prev_val = None
    count = 0
    
    #data = test_data
    data = real_data
    data = data.split('\n')
    data = [int(i) for i in data]
    
    #print(data)
    
    for val in data:
        if prev_val and prev_val < val:
            count = count + 1
        prev_val = val
    
    print(count)
    
    Day 1 Part B – Python

    This one is slightly more tricky in that you need to combine the elements into a sliding window. This could definitely be done in place as you move through the list by keeping a running sum, but I just made a new list by adding every element to itself and the next 2 spots, then shortening the list back down to cut off the extra end pieces

    #data = test_data
    data = real_data
    data = data.split('\n')
    data = [int(i) for i in data]
    
    sliding_window = list([0] * (len(data) + 2))
    
    for index, val in enumerate(data):
        sliding_window[index] = sliding_window[index] + val
        sliding_window[index + 1] = sliding_window[index + 1] + val
        sliding_window[index + 2] = sliding_window[index + 2] + val
        
    sliding_window = sliding_window[2:-2]
    
    #print(sliding_window)
    
    prev_val = None
    count = 0
    
    for val in sliding_window:
        if prev_val and prev_val < val:
            count = count + 1
        prev_val = val
        
    print(count)
    
    
    Tips
    • The biggest challenge here is going to be getting your text parser up and running and converting your input into a form you can work with.

    • Part 2 builds on part 1. See how you can reuse what you've already figured out. This is going to be a recurring theme for Advent of Code. Many problems build upon other problems

    • There are multiple ways to do it, if you get stuck on one particular method, try something else

    • With early Advent of Code problems you usually don't need to worry about making your code efficient. It's still good to think about because later problems will require you to use efficient methods or your code will never finish on time.

    • Even if you're able to solve a problem right away, it's still good to think about other ways to approach it. They may help you out later

    9 votes
  3. DataWraith
    Link
    This is my first year participating. My goal is to improve my working Rust knowledge as well as experiment with software quality tools. To that end, I'm learning to use or use better: Nix for...

    This is my first year participating. My goal is to improve my working Rust knowledge as well as experiment with software quality tools. To that end, I'm learning to use or use better:

    • Nix for reproducible builds
    • GitLab continuous integration
    • Pre-commit hooks with Lefthook that spell-check everything and make sure the tests pass
    • Various tools such as the Just task runner and Watchexec
    Day 01 — Part A (Rust)
    use itertools::Itertools;
    
    fn main() {
        println!(
            "{}",
            include_str!("../input.txt")
                .lines()
                .map(|line: &str| line.parse::<usize>().unwrap())
                .tuple_windows::<(_, _)>()
                .filter(|(a, b)| b > a)
                .count()
        );
    }
    
    Day 01 — Part B (Rust)
    use itertools::Itertools;
    
    fn main() {
        println!(
            "{}",
            include_str!("../input.txt")
                .lines()
                .map(|line: &str| line.parse::<usize>().unwrap())
                .tuple_windows::<(_, _, _, _)>()
                .filter(|(a, b, c, d)| (a + b + c) < (b + c + d))
                .count()
        );
    }
    
    9 votes
  4. tomf
    Link
    I'm back with Sheets... seeing as I haven't learned a single thing over the past year. Part 1 =ARRAYFORMULA( SUM( IF(ISBLANK(A3:A),, IF(A3:A<A2:A,,1)))) Part 2 =ARRAYFORMULA( SUM( IFERROR(...

    I'm back with Sheets... seeing as I haven't learned a single thing over the past year.

    Part 1
    =ARRAYFORMULA(
      SUM( 
       IF(ISBLANK(A3:A),,
        IF(A3:A<A2:A,,1))))
    
    Part 2
    =ARRAYFORMULA(
      SUM(
       IFERROR(
        IF(ISBLANK(A2:A),,
         IF(A5:A<=A2:A,,1)))))
    
    9 votes
  5. bhrgunatha
    Link
    Part 1 in Racket (for/sum ([x input] [y (drop input 1)] #:when (> y x)) 1) I would normally use (rest input) to skip the first element of a list but I'm using drop instead to highlight the...
    Part 1 in Racket
    (for/sum ([x input]
              [y (drop input 1)]
              #:when (> y x))
      1)
    

    I would normally use (rest input) to skip the first element of a list but I'm using drop instead to highlight the similarity to part 2.

    Part 2 in Racket It's identical but instead drop the first 3 elements
    (for/sum ([x input]
              [y (drop input 3)]
              #:when (> y x))
      1)
    
    Explanation

    For part 2, there's no need to sum or maintain any sliding windows since for any 4 consecutive values [a b c d] you have two windows with a common pair of values [a B C] vs [B C d] so the window sum increases when d>a.

    It turns out both parts can be solved by simply comparing the list of values that lag by 1 or 3 places.
    Racket's for can iterate through lists either nested or in parallel so you can compare consecutive values (that lag by 1 place) by iterating through the same list and dropping the first element. You can compare values that lag by 3 places by iterating through the same list but dropping the first 3 values.
    It works because the iteration stops when any list is empty.
    I use this technique to compare consecutive items of a list regularly.

    8 votes
  6. ras
    (edited )
    Link
    I'm going to use Javascript this year. Part 1 // I'm going to leave out getting the data from the input. I just put the data into an array called data. const result = data.reduce((total, current,...

    I'm going to use Javascript this year.

    Part 1
    // I'm going to leave out getting the data from the input. I just put the data into an array called data.
    const result = data.reduce((total, current, i, lines) => {
      if (lines[i + 1] > current) {
        total++;
      }
      return total;
    }, 0);
    
    Part 2
    const result = data.reduce((total, amount, index, array) => {
      let currentWindow = array.slice(index, index + 3).reduce((a, b) => a + b, 0);
      let nextWindow = array.slice(index + 1, index + 4).reduce((a, b) => a + b, 0);
      if (nextWindow > currentWindow) {
        total++;
      }
      return total;
    }, 0);
    

    Not totally satisfied with this. I got the correct answers, but I realize I'm ignoring some efficiencies.

    7 votes
  7. kari
    Link
    I'm sort of trying to re-learn Rust because I like it, so my code is pretty terrible, but here's my code for both parts (in one). rust use crate::lib::aoc; pub fn run1() { let lines =...

    I'm sort of trying to re-learn Rust because I like it, so my code is pretty terrible, but here's my code for both parts (in one).

    rust
    use crate::lib::aoc;
    
    pub fn run1() {
        let lines = aoc::get_lines("./inputs/day1.in");
    
        let mut times_increased_1 = 0;
        let mut times_increased_2 = 0;
        let mut last: u32 = u32::MAX;
        // last3.0 and last3.1 can be 0 since we will never reach an actual sum of u32::MAX
        let mut last3: (u32, u32, u32) = (0, 0, u32::MAX);
        let mut last3_sum: u32 = sum_triple(last3);
    
        for line in lines {
            let current = line.parse::<u32>().unwrap();
            let current3 = (last3.1, last3.2, current);
            let current3_sum = sum_triple(current3);
    
            if current > last {
                times_increased_1 += 1;
            }
    
            if current3_sum > last3_sum {
                times_increased_2 += 1;
            }
    
            last = current;
            last3 = current3;
            last3_sum = current3_sum;
        }
    
        // Output
        println!("~~~ Day 1 ~~~");
        println!("Part 1 - times increased: {}", times_increased_1);
        println!("Part 2 - times increased: {}", times_increased_2);
    }
    
    fn sum_triple(triple: (u32, u32, u32)) -> u32 {
        if triple.0 == u32::MAX || triple.1 == u32::MAX || triple.2 == u32::MAX {
            u32::MAX
        } else {
            triple.0 + triple.1 + triple.2
        }
    }
    
    6 votes
  8. Kremor
    Link
    I will post my solutions in Go, that means that I don't have to worry about writing anything fancy because the inability of writing fancy stuff is a Go feature, right? Part 1 package main import (...

    I will post my solutions in Go, that means that I don't have to worry about writing anything fancy because the inability of writing fancy stuff is a Go feature, right?

    Part 1
    package main
    
    import (
    	"bufio"
    	"fmt"
    	"os"
    	"strconv"
    )
    
    func main () {
    	file, err := os.OpenFile("data-test.txt", os.O_RDONLY, 0644)
    	if err != nil {
    		fmt.Println(err)
    		os.Exit(1)
    	}
    
    	count := 0
    	prev := 2147483647
    	s := bufio.NewScanner(file)
    	for s.Scan() {
    		tmp, _ := strconv.Atoi(s.Text())
    
    		if tmp > prev {
    			count += 1
    		}
    
    		prev = tmp
    	}
    
    	file.Close()
    	fmt.Println(count)
    }
    
    Part 2
    package main
    
    import (
    	"bufio"
    	"fmt"
    	"os"
    	"strconv"
    )
    
    func GetIncrements (a *[]int) int {
    	count := 0
    	prev := 2147483647
    	for _, n := range *a {
    		if prev < n {
    			count += 1
    		}
    		prev = n
    	}
    	return count
    }
    
    func ProcessWindows (data *[]int) []int {
    	windows := []int{}
    	buffer := [][]int{}
    
    	for _, n := range *data {
    		for i, b := range buffer {
    			buffer[i] = append(b, n)
    		}
    
    		buffer = append(buffer, []int{n})
    
    		if len(buffer[0]) == 3 {
    			windows = append(windows, SumSlice(&buffer[0]))
    			buffer = buffer[1:]
    		}
    	}
    
    	return windows
    }
    
    func ReadData () []int {
    	file, err := os.OpenFile("data.txt", os.O_RDONLY, 0644)
    	if err != nil {
    		fmt.Println(err)
    		os.Exit(1)
    	}
    
    	res := []int{}
    	s := bufio.NewScanner(file)
    	for s.Scan() {
    		n, _ := strconv.Atoi(s.Text())
    		res = append(res, n)
    	}
    
    	file.Close()
    
    	return res
    }
    
    func SumSlice (s *[]int) int {
    	res := 0
    	for _, n := range *s {
    		res += n
    	}
    	return res
    }
    
    func main () {
    	d := ReadData()
    	w := ProcessWindows(&d)
    	n := GetIncrements(&w)
    	fmt.Println(n)
    }
    
    6 votes
  9. Crespyl
    Link
    Going with Ruby again this year. Might try to brush up a bit on my Rust as we get going, but for now I'll stick with what I know I can do fast. Part 1 Ruby, not unlike Python, is great for this...

    Going with Ruby again this year. Might try to brush up a bit on my Rust as we get going, but for now I'll stick with what I know I can do fast.

    Part 1 Ruby, not unlike Python, is great for this sort of thing because it's so "batteries included"; tools like "each_cons" are easy to reach for these types of problems.
    def compute_p1(input)
      input.lines.map(&:to_i).each_cons(2).reduce(0) do |sum, pair|
        pair.last > pair.first ? sum + 1 : sum
      end
    end
    
    Part 2
    def compute_p2(input)
      input
        .lines
        .map(&:to_i)
        .each_cons(3)
        .map(&:sum)
        .each_cons(2)
        .reduce(0) { |sum, pair| pair.last > pair.first ? sum + 1 : sum }
    end
    

    Just for good measure I'll throw in my full file with all the minitest scaffolding that helps me move a little faster when it comes to checking test cases and so on, since this sort of thing has been helpful to me in the past.

    Full solution file
    #!/usr/bin/env ruby
    
    require 'benchmark'
    require 'minitest'
    require 'pry-byebug'
    
    TEST_STR = "\
    199
    200
    208
    210
    200
    207
    240
    269
    260
    263
    "
    
    class Test < MiniTest::Test
      def test_p1
        assert_equal(7, compute_p1(TEST_STR))
      end
    
      def test_p2
        assert_equal(5, compute_p2(TEST_STR))
      end
    end
    
    def compute_p1(input)
      input.lines.map(&:to_i).each_cons(2).reduce(0) do |sum, pair|
        pair.last > pair.first ? sum + 1 : sum
      end
    end
    
    def compute_p2(input)
      input
        .lines
        .map(&:to_i)
        .each_cons(3)
        .map(&:sum)
        .each_cons(2)
        .reduce(0) { |sum, pair| pair.last > pair.first ? sum + 1 : sum }
    end
    
    if MiniTest.run
      puts 'Test case OK, running...'
    
      @input = File.read(ARGV[0] || 'input.txt')
    
      Benchmark.bm do |bm|
        bm.report('Part 1:') { @p1 = compute_p1(@input) }
        bm.report('Part 2:') { @p2 = compute_p2(@input) }
      end
    
      puts "\nResults:"
      puts 'Part 1: %i' % @p1
      puts 'Part 2: %i' % @p2
    
    else
      puts 'Test case ERR'
    end
    
    6 votes
  10. Moonchild
    Link
    here are solutions in j: part 1: +/2</\x part 2: +/2</\3+/\x The latter solution could be cleverer.

    here are solutions in j:

    part 1: +/2</\x

    part 2: +/2</\3+/\x

    The latter solution could be cleverer.

    6 votes
  11. tesseractcat
    Link
    Here's Befunge. I had to stop pretty quickly last time because the programs got too complex. Part I >099*9*9*9*9*9*9*9*v > >&: 01 p v v _v#:< \ >$$.@ ` ! ^g10<_1+v ^ <

    Here's Befunge. I had to stop pretty quickly last time because the programs got too complex.

    Part I
    >099*9*9*9*9*9*9*9*v                                                                                 
                  >    >&: 01 p v                                                                               
                       v    _v#:<                                                                        
                       \     >$$.@
                       `                                                                                 
                       !
                  ^g10<_1+v                                                                              
                      ^   <      
    
    5 votes
  12. wycy
    Link
    Rust Solution use std::env; use std::io::{self, prelude::*, BufReader}; use std::fs::File; fn main() { let args: Vec<String> = env::args().collect(); let filename = &args[1];...

    Rust

    Solution
    use std::env;
    use std::io::{self, prelude::*, BufReader};
    use std::fs::File;
    
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        day01(&filename).unwrap();
    }
    
    fn day01(input: &str) -> io::Result<()> {
        let file = File::open(input).expect("Input file not found.");
        let reader = BufReader::new(file);
    
        // Input
        let input: Vec<String> = match reader.lines().collect() {
            Err(err) => panic!("Unknown error reading input: {}", err),
            Ok(result) => result,
        };
        let input: Vec<i64> = input
            .iter()
            .map(|x| x.parse::<i64>().unwrap())
            .collect();
    
        // Solutions
        println!("Part 1: {}", sonar(&input, 1)); // 1301
        println!("Part 2: {}", sonar(&input, 3)); // 1346
    
        Ok(())
    }
    
    fn sonar(input: &Vec<i64>, winsize: usize) -> usize {
        input
            .windows(winsize)
            .map(|x| x.iter().sum::<i64>())
            .collect::<Vec<_>>()
            .windows(2)
            .filter(|x| x[1] > x[0])
            .count()
    }
    
    5 votes
  13. googs
    Link
    Here's my (slightly gross and very lazy) JavaScript implementation Part 1 const m = [/* given input values */] console.log(m.reduce((a, c, i) => m[i-1] < c ? a + 1 : a, 0)) Part 2 const m = [/*...

    Here's my (slightly gross and very lazy) JavaScript implementation

    Part 1
    const m = [/* given input values */]
    console.log(m.reduce((a, c, i) => m[i-1] < c ? a + 1 : a, 0))
    
    Part 2
    const m = [/* given input values */]
    console.log(m.reduce((a, c, i) => m[i-1] + m[i-2] + m[i-3] < m[i] + m[i-1] + m[i-2] ? a + 1 : a, 0))
    
    4 votes
  14. [3]
    Eabryt
    (edited )
    Link
    I've never done this before, but I saw lots of people use it to learn a language so I figured I would check out Rust since it's always the most popular language on the StackOverflow census Part I...

    I've never done this before, but I saw lots of people use it to learn a language so I figured I would check out Rust since it's always the most popular language on the StackOverflow census

    Part I
        use std::fs::File;
        use std::io::{BufReader, BufRead, Error};
    
        fn main() -> Result<(), Error> {
            let path = "input.txt";
    
            let input = File::open(path)?;
            let buffered = BufReader::new(input);
    
            let mut x = -1;
            let mut val = 0;
    
            for line in buffered.lines() {
                let line  = line.unwrap().parse::<i32>().unwrap();
                println!("line: {}, val:{}",line,val);
                if line > val{
                    x += 1;
                }
                val = line;
            }
        println!("Final Result: {}",x);
    
        Ok(())
        }
    

    I really wanted to just get the first line to initialize val before entering the loop but couldn't figure out how to do that.

    I'd be curious to know what simple ways there might be to improve.

    4 votes
    1. [2]
      blitz
      (edited )
      Link Parent
      If you make your iterator outside of the for loop you have more control over it, so you could do something like let mut lines_iter = buffered.lines(); let mut val =...

      I really wanted to just get the first line to initialize val before entering the loop but couldn't figure out how to do that.

      If you make your iterator outside of the for loop you have more control over it, so you could do something like

      let mut lines_iter = buffered.lines();
      let mut val = lines_iter.next().unwrap().parse . . .;
      
      for line in lines_iter { // will continue with the same iterator, skipping the first line
      . . .
      

      It seems to me your code would always produce an answer that one one more than the correct answer, since you're starting the comparator value at 0 and the next value will always be higher than that. If you start at i32::MAX, the first value will be set in the loop and then you will have correctly initialized the variables without extra code.

      2 votes
      1. Eabryt
        Link Parent
        Ahh, I didn't think about the iterator being outside the loop. I'm coming in to this language totally blind and it's been quite the trip so far so I appreciate the tip! As for the answer being one...

        Ahh, I didn't think about the iterator being outside the loop. I'm coming in to this language totally blind and it's been quite the trip so far so I appreciate the tip!

        As for the answer being one higher, I'm not sure but it accepted the answer I got, so not sure.

        1 vote
  15. Gyrfalcon
    Link
    Like many others, I am using this year's Advent of Code to get more familiar with a language I am interested in, which is Nim for me. Maybe I'll try Rust next year, since it seems popular. Anyway,...

    Like many others, I am using this year's Advent of Code to get more familiar with a language I am interested in, which is Nim for me. Maybe I'll try Rust next year, since it seems popular. Anyway, solutions:

    Part 1
    import strutils, std/strformat
    
    var input: seq[string] = strutils.split(readFile("input.txt"),  "\n")
    var clean_input: seq[int] = @[]
    
    for value in input[0 .. ^2]:
        clean_input.add(parseInt(strutils.strip(value)))
    
    
    var previous: int = clean_input[0]
    var increases: int = 0
    
    for value in clean_input[1 .. ^1]:
        if value > previous:
            inc increases
        previous = value
    
    echo &"The number of increases is {increases}"
    
    Part 2
    var summed_increases: int = 0
    
    for idx in 3 ..< clean_input.len:
        if clean_input[idx] > clean_input[idx - 3]:
            inc summed_increases
    
    echo &"The number of summed increases is {summed_increases}"
    

    This is probably not great Nim code, but I've only barely played around with the language so I'm not too worried.

    4 votes
  16. Crestwave
    Link
    Quick and dirty AWK as usual. Part 1 #!/usr/bin/awk -f { if (i != "" && $0 > i) n += 1 i = $0 } END { print n } Part 2 #!/usr/bin/awk -f { arr[NR] = $0 } END { for (i = 3; i <= NR; ++i) { j =...

    Quick and dirty AWK as usual.

    Part 1
    #!/usr/bin/awk -f
    {
    	if (i != "" && $0 > i) n += 1
    	i = $0
    }
    
    END { print n }
    
    Part 2
    #!/usr/bin/awk -f
    { arr[NR] = $0 }
    
    END {
    	for (i = 3; i <= NR; ++i) {
    		j = arr[i-2] + arr[i-1] + arr[i]
    		if (k != "" && j > k) n += 1
    		k = j
    	}
    
    	print n
    }
    
    4 votes
  17. spit-evil-olive-tips
    Link
    fun with zip in Python Part 1 with open('001.txt') as file: lines = file.readlines() numbers = [int(line) for line in lines] increments = 0 for prev, cur in zip(numbers, numbers[1:]): if cur >...

    fun with zip in Python

    Part 1
    with open('001.txt') as file:
        lines = file.readlines()
    
    numbers = [int(line) for line in lines]
    
    increments = 0
    
    for prev, cur in zip(numbers, numbers[1:]):
        if cur > prev:
            increments += 1
    
    print(increments)
    
    Part 2
    with open('001.txt') as file:
        lines = file.readlines()
    
    numbers = [int(line) for line in lines]
    
    increments = 0
    
    windows = list(zip(numbers, numbers[1:], numbers[2:]))
    
    for prev, cur in zip(windows, windows[1:]):
        if sum(cur) > sum(prev):
            increments += 1
    
    print(increments)
    
    4 votes
  18. Liru
    Link
    I was bored, so I decided to make a metaproject involving name choices (which isn't really going anywhere), and this gave me an idea. I am now officially a Rockstar programmer. Part 1 My world is...

    I was bored, so I decided to make a metaproject involving name choices (which isn't really going anywhere), and this gave me an idea.

    I am now officially a Rockstar programmer.

    Part 1
    My world is nothing.
    
    Listen to your soul.
    Listen to your heart.
    While your heart isn't mysterious,
    If your heart is greater than your soul,
    Build my world up.
    (guitar solo)
    Put your heart into your soul!
    Listen to your heart!
    (bass solo)
    Build my world up!
    
    Whisper my world.
    
    Part 2
    Our fire is smoldering...
    
    Listen to the rhythm.
    Listen to the wilfulness.
    Listen to the guitar.
    Listen to the wilderness.
    (strong drums)
    Burn the rhythm!
    Burn the wilfulness!
    Burn the guitar!
    (guitar riff)
    While the wilderness isn't mysterious,
    Burn the wilderness!
    Put the rhythm with the wilfulness with the guitar into the cities!
    Put the wilfulness with the guitar with the wilderness into the forests!
    If the cities are less than the forests,
    Build our fire up!
    (guitar solo)
    Put the wilfulness into the rhythm.
    Put the guitar into the wilfulness.
    Put the wilderness into the guitar.
    Listen to the wilderness!
    (throw guitar at drummer)
    Whisper our fire.
    

    I probably shouldn't pursue a career in songwriting, though.

    The interpreter can be found in the above link.

    4 votes
  19. asterisk
    Link
    Python count = 0 with open("input.txt") as file: arr = [int(item) for item in file] for i in range(1, len(arr)): if arr[i] > arr[i - 1]: count += 1 print("Part One: ", count) count = 0 three =...
    Python
    count = 0
    
    with open("input.txt") as file:
        arr = [int(item) for item in file]
    
    for i in range(1, len(arr)):
        if arr[i] > arr[i - 1]:
            count += 1
    
    print("Part One: ", count)
    
    count = 0
    three = list()
    
    for i in range(0, len(arr) - 2):
        three.append(sum(arr[i : i + 3]))
    
    for i in range(1, len(three)):
        if three[i] > three[i - 1]:
            count += 1
    
    print("Part Two: ", count)
    
    3 votes
  20. 3d12
    Link
    Late entry, just catching up this weekend! I'll be doing this in Javascript (Node) this year again, since I'm getting better at using the language, and would like to potentially start using it...

    Late entry, just catching up this weekend! I'll be doing this in Javascript (Node) this year again, since I'm getting better at using the language, and would like to potentially start using it professionally in 2022.

    Repo is here

    Part 1
    const fs = require('fs');
    const readline = require('readline');
    
    let depthArr = [];
    
    async function openFileForReading(file) {
    	const fileStream = fs.createReadStream(file);
    
    	const rl = readline.createInterface({
    		input: fileStream,
    		crlfDelay: Infinity
    	});
    
    	for await (const line of rl) {
    		try {
    			depthArr.push(parseInt(line));
    		} catch(e) {
    			console.error(e);
    		}
    	}
    }
    
    (async function mainExecution() {
    	await openFileForReading('input.txt');
    	let currentDepth = 0;
    	let firstDepth = true;
    	let numIncreases = 0;
    	for (const depth of depthArr) {
    		if (firstDepth != true) {
    			diff = depth - currentDepth;
    			if (diff > 0) {
    				console.log("Depth increased from " + currentDepth + " to " + depth);
    				numIncreases++;
    			}
    		}
    		currentDepth = depth;
    		firstDepth = false;
    	}
    	console.log("Answer found! " + numIncreases);
    })();
    
    Part 2
    const fs = require('fs');
    const readline = require('readline');
    
    let depthArr = [];
    
    async function openFileForReading(file) {
    	const fileStream = fs.createReadStream(file);
    
    	const rl = readline.createInterface({
    		input: fileStream,
    		crlfDelay: Infinity
    	});
    
    	for await (const line of rl) {
    		try {
    			depthArr.push(parseInt(line));
    		} catch(e) {
    			console.error(e);
    		}
    	}
    }
    
    (async function mainExecution() {
    	await openFileForReading('input.txt');
    	let currentDepth = 0;
    	let currentWindowIndex = 0;
    	let firstDepth = true;
    	let numIncreases = 0;
    	for (let currentWindowIndex = 0; currentWindowIndex < depthArr.length-2; currentWindowIndex++) {
    		if (firstDepth != true) {
    			depthSum = depthArr[currentWindowIndex] + depthArr[currentWindowIndex+1] + depthArr[currentWindowIndex+2];
    			diff = depthSum - currentDepth;
    			if (diff > 0) {
    				console.log("Depth increased from " + currentDepth + " to " + depthSum);
    				numIncreases++;
    			}
    		}
    		currentDepth = depthArr[currentWindowIndex] + depthArr[currentWindowIndex+1] + depthArr[currentWindowIndex+2];
    		firstDepth = false;
    	}
    	console.log("Answer found! " + numIncreases);
    })();
    
    3 votes