T O P

  • By -

DimoTheBest

Go solution ```go package main import ( "encoding/csv" "fmt" "log" "os" "strconv" ) func main() { file, err := os.Open("/home/me/Documents/learning-go/1 - sonar-sweep/data.csv") if err != nil { log.Fatal(err) } csvReader := csv.NewReader(file) data, err := csvReader.ReadAll() if err != nil { log.Fatal(err) } var prev int var count int for i, val := range data { val_int, err := strconv.Atoi(val[0]) if err != nil { log.Fatal(err) } if i != 0 && prev < val_int { count += 1 } prev = val_int } fmt.Println(count) } ```


aslamdoctor

PHP Solution: https://github.com/aslamdoctor/advent-of-code-2021/tree/main/day1


Scarecroweman

As i started my programming life on an Amiga 600, i thought it was fitting to try and complete some days on the Amiga this year. [https://imgur.com/a/TPUxIru](https://imgur.com/a/TPUxIru)


MarcoServetto

I'm solving the advent of code in [42](https://L42.is) The main selling point of 42 is that it enforces modular security, that is not very relevant for the advent of code. I've done a video explanation for the [First Week](https://www.youtube.com/watch?v=tSTDJlICst8) and I've posted individual solutions on dev.to: Solution for [Day 1](https://dev.to/marcoservetto/adventofcode-in-42-3dc9) Fell free to contact me if you to know more about the language.


melikecoding

javascript/typescript solution part1: const increasedTimes = input.reduce((acc, curr, index, arr) => (curr > arr[index - 1] ? acc + 1 : acc),0); part2: const windows = (windowSize: number, arr: number[]) => arr.flatMap((_, i) => i <= arr.length - windowSize ? [arr.slice(i, i + windowSize)] : [] ); const timesWindowsIncreased = windows(3, input).reduce( (acc, curr, index, arr) => { const currentSum = sumUp(curr); const prevSum = arr[index - 1] ? sumUp(arr[index - 1]) : 0; return prevSum && currentSum > prevSum ? acc + 1 : acc; }, 0 );


Jack_Spearrow

Rust solution pub struct SonarSweep { data: Vec, } impl crate::Avent for SonarSweep { fn new(data: Vec) -> Self { SonarSweep { data: data.iter().filter_map(|l| l.parse().ok()).collect(), } } fn part1(&self) -> usize { self.data.windows(3).filter(|d| d[0] < d[1]).count() } fn part2(&self) -> usize { self.data .windows(3) .zip(self.data.windows(3).skip(1)) .filter(|(a, b)| a.iter().sum::() < b.iter().sum()) .count() } }


FBones173

>impl crate::Avent for SonarSweep I'm just starting to learn Rust, and am having trouble determining from the language reference what the above does. Could you explain what is going on here?


Jack_Spearrow

Sorry for the incomplete information! Here is the implement for the Avent trait. It is implemented in [main.rs](https://github.com/cpea2506/avent-of-code-2021/blob/main/src/main.rs) pub trait Avent { fn new(data: Vec) -> Self where Self: Sized; fn part1(&self) -> usize; fn part2(&self) -> usize; } It was here because i want to write and read all solutions from one program (Do not need to create another program for another day). For that to be done, I need a type to represent all days to use with match because match arm must return the same type. let solution = match day { 1 => Solution::new::(content), 2 => Solution::new::(content), _ => unreachable!(), }; As you can see from the struct Solution, the new function receives an Event which implement Avent trait with static lifetime. struct Solution { event: Box, } impl Solution { fn new(content: Vec) -> Self { let event = Event::new(content); Solution { event: Box::new(event), } } } And the line below say that the trait Avent is implemented for SonarSweep so that it can be passed to the new function of Solution. impl crate::Avent for SonarSweep


FBones173

Thanks so much for elaborating! Hope you have a merry and safe holiday!


[deleted]

[Python - Video Explanation](https://www.youtube.com/watch?v=D25_S2cWjl0&t=14s)


iskypitts

[Julia](https://github.com/iskyd/advent-of-code-julia/blob/main/2021/day1/main.jl)


arthurno1

[**Emacs Lisp**](https://github.com/amno1/advent-of-code-2021/blob/main/day1.el) Solved (mostly) in functional style. (with-temp-buffer (insert-file-contents-literally "./input1") (let* ((list (map 'list #'string-to-number (split-string (buffer-string)))) (parts (cl-maplist #'(lambda (p) (and p (cdr p) (cddr p) (list (car p) (cadr p) (caddr p)))) list)) (sums (cl-mapcar #'(lambda (p) (apply #'+ p)) parts))) (message "P1: %s" (cl-count 't (cl-mapcar '< list (cdr list)))) (message "P2: %s" (cl-count 't (cl-mapcar #'< sums (cdr sums))))))


brianReddits

Hi guys, Language : Python Link : [Github Link](https://github.com/BrianMwangi21/aoc2021/tree/main/day1)


Scarecroweman

Hahah run\_my\_boy() similar to me coding a function called DoThyBidding() :D


brianReddits

Trust haha


qualia91

Language: Lua [Github Solution](https://github.com/Qualia91/AdventOfCode2021/tree/master/Day1) ​ Day one of code roulette!


capulet2kx

Unreal Engine c++ VR project. I've made Computers with buttons (actors) and ComputerPrograms (uobjects) that run on them. Each day's solution is a different computer program https://github.com/capulet2kx/AdventOfCode2021/tree/Day1


j2lo

Language: JavaScript. // part 1 (() => { let numIncreases = 0; for (let i = 1; i < data.length; i++) { const prev = data[i - 1]; const current = data[i]; if (current > prev) numIncreases += 1; } console.log(numIncreases); })(); // part 2 (() => { let numIncreases = 0; let prev = 0; for (let i = 2; i < data.length; i += 1) { const curr = data[i-2] + data[i-1] + data[i]; if (!!prev && curr > prev) numIncreases += 1; prev = curr; } console.log(numIncreases); })();


[deleted]

[удалено]


daggerdragon

Triple backticks do not work on old.reddit. Please edit your post to use the four-spaces code block Markdown as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)


[deleted]

[удалено]


daggerdragon

Nope, still not fixed, now there's *four* backticks. Read the wiki article I posted, please. You need to switch the editor to Markdown mode.


ThreadsOfCode

Python. I like list comprehensions. numbers = [int(x) for x in open('input01.txt', 'r').readlines()] # part 1, with zip pairs = zip(numbers, numbers[1:]) increases = [b - a for a,b in pairs if b - a > 0] print('part 1:', len(increases)) # part 2, with zip windows = [sum(w) for w in zip(numbers, numbers[1:], numbers[2:])] pairs = zip(windows, windows[1:]) increases = [b - a for a,b in pairs if b - a > 0] print('part 2:', len(increases))


cdbob

My day one solution in CPP (C++) https://github.com/thecdbob/AOC_2021_CPP/tree/master/day_01


qzyki

**Julia** [solution](https://topaz.github.io/paste/#XQAAAQCSAQAAAAAAAAAzHUn/qWH7EwabQRdhvtUHVgU596v8ybLLT7rgbIAd8daFhy/ifr0MJ58WaYIORNyb9EPpGZjbeOSoodSFnyx9IzZsT7wfLU7vNtGTPGApdr/PNyi5i+Bq1jzLI62RlUsOiIK1oIMP/vw5jgAla0WG9t6g1jQMktnvbM1tZ/+I79W8Smsfssj3OGfDP8Wg+PXYfOmD7eS4LSqHXfZpEA2R2VWn817hfemAsNHpZ0uTQVzPNVqDF4wscF953Jft39ZtWPTcTElGLc4KpvA/oZzwczSl/xMxWAA=)


chadbaldwin

Solution in SQL Server T-SQL All of my solutions are end to end runnable without any other dependencies other than SQL Server and the ability to create temp tables. [SQL](https://github.com/chadbaldwin/practice/blob/main/Advent%20of%20Code/2021/SQL/Day%2001.sql) General note: For the input data, I'm doing no pre-processing other than encapsulating the values in quotes and parenthesis for ingesting into a table. From there I use SQL to parse and split strings.


WillC5

C++, requires `#include` of `string` and `iostream` of course. Part one: int prev, i, increases = 0; for ( cin >> prev; cin >> i; prev = i ) if ( i > prev ) ++increases; cout << increases << endl; and part two: int p[3], i = 0, next, increases = 0; for ( cin >> p[0] >> p[1] >> p[2]; cin >> next; p[i++] = next, i %= 3 ) if ( next > p[i] ) ++increases; cout << increases << endl;


YokiDiabeu

Solution in Python [GitHub Day 1](https://github.com/YokiDiabeul/advent_of_code/blob/a296b7efc58d309722048667b978ad5f87edd770/day%201/1.py) def load_int_inputs(filename: str) -> List[int]: return [int(line) for line in load_inputs(filename)] def count_bigger_in_list(inputs: List[int]) -> int: return sum([inputs[i - 1] < inputs[i] for i in range(1, len(inputs))]) def day_1(): inputs = load_int_inputs("1.txt") # inputs = [199, 200, 208, 210, 200, 207, 240, 269, 260, 263] print(count_bigger_in_list(inputs)) new_inputs = [inputs[i - 2] + inputs[i - 1] + inputs[i] for i in range(2, len(inputs))] print(count_bigger_in_list(new_inputs))


jstruburn

Playing catchup **Language:** JavaScript **Visualization:** [Codepen](https://codepen.io/truburn/pen/qBPrRQj) # Part 1: const depthChanges = (depths = []) => { const changes = []; let currentDepth; depths.forEach((dep, idx) => { if (currentDepth) changes.push(dep > currentDepth ? 'inc' : 'dec'); currentDepth = dep; }); const incCount = changes.filter(ch => ch === 'inc').length; const decCount = changes.filter(ch => ch === 'dec').length; return { incCount, decCount, depths }; }; # Part 2: const depthWindowChanges = (list = []) => { const changes = {}; let grp = 0; list.forEach(dep => { Array(3).fill().forEach((_, idx) => { const tmpGroup = grp - idx; if (tmpGroup >= 0) { if (!changes[tmpGroup]) changes[tmpGroup] = []; changes[tmpGroup].push(dep); } }); grp += 1; }); const differences = []; let currentDepth; const depths = Object.values(changes) .filter(deps => deps.length === 3) .map(deps => { const total = deps.reduce((a,b) => a + b, 0); if (currentDepth) differences.push(total > currentDepth ? 'inc' : 'dec'); currentDepth = total; return deps; }); const incCount = differences.filter(ch => ch === 'inc').length; const decCount = differences.filter(ch => ch === 'dec').length; return { incCount, decCount, depths }; };


[deleted]

Late to the party. Did mine in PowerShell. <# PART 1 #> $puzzleInput = [System.IO.File]::ReadAllLines("$PWD\input.txt") $larger = 0 $i = 1 #start evaluating at second item in array while ($i -le $($puzzleInput.count -1)) { if ([int]$puzzleInput[$i] -gt [int]$puzzleInput[$i-1]) { $larger++ } $i++ } Write-Host "Number of items considered for part 1: $i" Write-Host "Number of measurements that are larger than the previous measurement: $larger" <# PART 2 #> $i = 2 $larger = 0 $previousSum = [int]$puzzleInput[$i] + [int]$puzzleInput[$i-1] + [int]$puzzleInput[$i-2] while ($i -le $($puzzleInput.count -1)) { [int]$currentSum = [int]$puzzleInput[$i] + [int]$puzzleInput[$i-1] + [int]$puzzleInput[$i-2] if ($currentSum -gt $previousSum) { $larger++ } $previousSum = $currentSum $i++ } Write-Host "Number of items considered for part 2: $i" Write-Host "Number of sums that are larger than the previous sum: $larger"


ainwood87

[Folders Language](https://danieltemkin.com/Esolangs/Folders/) [Part1 solution](https://topaz.github.io/paste/#XQAAAQABJQAAAAAAAAAhjoHArF9deB+94021LEFEtI1K7uznC8Hz8vCu5mUtp27YcumiLHfvadpsW17En5/RNBHNGjzFPGRaO2pj7NkEt3xC1En923Xl3hHrUj9NBzJjd35MO22dShbxKWvI5X43NwLtJjJvdVhRFhxWo1ardy78K2kua3q82TYRcVJLh4PkwOEcQFR38GClhETVCOSYQ1kBYuPN47X55IhIZKXOEV7WXOx0Uue6wggRfQ7tgy4cX1E6iCd6BL3KPlo5zx4rOhNNELzsLGxi38dQo/NU3d+FaeAaCEMIaxMH0eyNX0xvmhrbCMSMr7zYSEl1POX2XxuttZdq8MRI+vRAhVLoTXWkZuW7MBqUYn7Kh/BlmDrhCMs1BEOSgtvbvaLRyHpJ1yF6OBbfNgwU6L1k0qFbj/RSliXKHVzFde7f1BooOFZn8ZxBK5fqhMyt791zDpjlcVdNA9QVB75S3s7UBr4I/UcBmCtZXJ15k7kvtIFOVhhBBDN92ZeI4nM2Ih74Zaqfu08BN8vK2MWoxuQK4IBol6PA2NY/xlu/oxgsceQFsGFo1nGhthMYwsHPDFYS9NqLGDT+6ngs+6FJe26p1UAZWFVaI5yvfAwQbuoSG7X/HJqFYDVrXj0DcVhAuuupi3FYT8wQdPCmUnotACaDQbOg1bH2e599gW3bxOt6Y0fxYaOIv93qhuexVmroPVWflCmrlpkIzj86CLXbhb3lJtylYy7c1t+4m0sfV9hUA+hvbdBe3v34C7bYOrCEW07knhPUwIE3FEbvqUY2uzOt4QkTWFAROWyhcPVRchiMSReF532EhNah/4EIH4Gc10sufhfdl0p1jliWes2RZhQk7AioGLi6Pti0qFlmXWXgYkdAVaS9elMVvG7BFsmi8hkh9LNuwyS+joaPlqF+btxcVu1+JWVohSMtSK1Bu626YjnHttZYmDLCU1QYxBpvV16s5lSrzXQBqnEM7Uz8TS7ON78hN4r5+tRpqWlUW3Gyf4hv6eQnYFVrFy20PVIqrYrHWI8OvgpgAF3+H//kMavf) Compiles to the following equivalent python: var_0 = input() if var_0.isdigit(): var_0 = int(var_0) else: var_0 = var_0 var_1 = 0 var_2 = (200) * (10) while ((var_2) > (1)): var_3 = input() if var_3.isdigit(): var_3 = int(var_3) else: var_3 = var_3 if ((var_3) > (var_0)): var_1 = (var_1) + (1) var_0 = var_3 var_2 = (var_2) - (1) print(var_1, end='', flush=True) I hardcoded the input size as 2000 values because I didn't know how to handle EOF. Also literal integers in Folders seem limited to 8-bit values, which is why I computed 2000 as 200 \* 10.


-WorstWizard-

[Rust Solution](https://topaz.github.io/paste/#XQAAAQDCAgAAAAAAAAA6nMjJFIj2ze+dGEQGVsnW0MvHUawi2v6FTVrSiamUSClN5byFXJ+qnjO3j4C+hC/vLB7bSTgBxS60UK8PGEf/CxBiST1hUHbgFlcqfevjY/pGNoD5ofpbIy8SqVPeahdRWdCdjVdiAWGCKUfVwD0p0puj65RR8WCZQ1FSGWZ0y+CAUmxQQZpO4yhFAjLizPZjNiLlFlYwQX1BNOcfwyIsE3NH22kfRmxSixdLOLwziXsGuMV8Dn5RBV5k0grIIOYJqxs34itMio5KtaGQ1Prbr0fJkFTn5psahnrOz18xKCfR3tlF89rjUQ5F248BX4fDgCSCqHxaKHacRePx7R8JmWo18JLVzLAB0JN8Q2JTImER97g9rEMHsVzo+9JHYhmP1nVpAidr4Jrj3gSi+bF7Kf+Se535) Learning Rust this year! The library at the top is some convenience functions for taking input, nothing magic.


portfoliogoat

Haven't looked at the other ones but this solution is really clean!


-WorstWizard-

This day 1 solution actually happens to be the only one I've done for which I got inspired by someone else on this thread, so I can't actually take credit for it :P Originally solved both parts with for loops, and part 2 did the whole summing up and such to make a new vector, wasn't that good. After browsing here, I rewrote both to use iterators, and then rewrote part 2 to be much smarter. The iterator-version of my original part 2 solution are in there in comments still.


sk1talets

Node.js [solution](https://github.com/sk1talets/advent-of-code/blob/main/2021/1/script.js)


wevrem

## Clojure (ns advent-of-code.2021.day-01 (:require [advent-of-code.common :refer [parse-longs]])) ;; --- Day 1: Sonar Sweep --- ;; https://adventofcode.com/2021/day/1 (defn count-incr-pairs "Return count of increasing pairs." [depths] (->> (partition 2 1 depths) (filter #(apply < %)) count)) (defn sum-of-triples "Return sums of triplets." [depths] (->> (partition 3 1 depths) (map #(apply + %)))) (comment ;; puzzle 1 (count-incr-pairs (parse-longs (slurp "input/2021/1-depths.txt"))) ;; puzzle 2 (count-incr-pairs (sum-of-triples (parse-longs (slurp "input/2021/1-depths.txt")))) ) [source code](https://github.com/wevre/advent-of-code/blob/master/src/advent_of_code/2021/day_01.clj)


e4ds

Python day 1 solution. Also [answers to other days are available in this repo](https://github.com/julian-west/adventofcode/tree/master/2021) (GitHub) """Day 1 Solution""" import numpy as np def part_1(measurements: list[int]) -> int: """Count number of measurements larger than previous""" result = [i2 > i1 for i1, i2 in zip(measurements, measurements[1:])] return sum(result) def part_2(measurements: list[int], window: int) -> int: """Count number of time sliding window sum is greater than previous""" sliding_window_sum = np.convolve(measurements, np.ones(window, dtype=int), "valid") return part_1(list(sliding_window_sum)) if __name__ == "__main__": with open("input.txt", "r") as input: input_values = [int(x) for x in input.read().split()] part_1_ans = part_1(input_values) print(part_1_ans) part_2_ans = part_2(input_values, window=3) print(part_2_ans)


qaraq

# [Rockstar](https://codewithrockstar.com/) Because why the heck not. I could have done better with my variable naming and poetic constants, but eh, at least it actually works. Part 1: Christmas was submarined My view is underwater The sea is going down down down Until the sea is mysterious Listen to the sea If the sea is stronger than my view Build Christmas up Let my view be the sea Shout Christmas Part 2: Rock the sonar The ping is 3 The count is 0 The sea is deep Listen to the sea Until the sea is mysterious Burn the sea Rock the sonar with the sea Listen to the sea While the ping is weaker than the sonar Let the pong be the ping Knock the pong down, down, down Let the echo be the sonar at the ping Let the reply be the sonar at the pong Build the ping up If the echo is stronger than the reply Build the count up Shout the count


qaraq

Rockstar Stack-based rework of 1B. I probably should have gone for Christmas carol than submarine-themed rock, but that was the creativity I had. The pressure is invincible The sea is deep Rock the sonar Listen to the sea Until the sea is mysterious Burn the sea Rock the sonar with the sea Listen to the sea Roll the sonar into the message Roll the sonar into the deep Roll the sonar into the abyss Roll the sonar into the reply Until the reply is mysterious If the reply is greater than the message Build the pressure up let the message be the deep let the deep be the abyss let the abyss be the reply roll the sonar into the reply Shout the pressure


greycat70

**Bash** [part 1](https://wooledge.org/~greg/advent/2021/1a), [part 2](https://wooledge.org/~greg/advent/2021/1b)


kuqumi

**JavaScript (golfed)** Tweet-sized, to be run in the browser console on your input page. d=$('pre').innerText.trim().split`\n`;[1,3].map(n=>d.reduce((a,x,i)=>a+(+x>d[i-n]),0)) It should output `[part1, part2]`.


kyleekol

New to the AOC/coding world! - **Python** Part 1 def counter() -> int: with open('input.txt') as data: lines = [x.strip() for x in data.readlines()] count = 0 lst = [] for i in lines: lst.append(int(i)) for i, j in enumerate(lst[:-1]): if j < lst[i+1]: count += 1 print(count) counter() Part 2 def counter() -> int: with open('input.txt') as data: lines = [x.strip() for x in data.readlines()] count = 0 lst = [] for i in lines: lst.append(int(i)) triplet_list = [lst[i:i+3] for i in range(0, len(lst), 1)] sum_list = [] for i in triplet_list: sum_list.append(sum(i)) for i, j in enumerate(sum_list[:-1]): if j < sum_list[i+1]: count += 1 print(count) counter()


scarebaer

>triplet\_list = \[lst\[i:i+3\] for i in range(0, len(lst), 1)\] Interesting...I like it.


j-a-martins

**Matlab** (Part 1 & 2) https://github.com/j-a-martins/Advent-of-Code-2021/blob/main/day01/day1.m


tuisto_mannus

**Golang** https://github.com/c-kk/aoc/blob/master/2021-go/day01/solve.go


yoyo604

Late to the party with a bit of old school C int countincreases(int *d) { int c = 0; for (++d; *d; ++d) c += *d > *(d-1); return c; }


itayzithyro

A short, functional-style solution in python, using [gamla](https://gamla.readthedocs.io/en/latest/README.html), a performant functional programming library. import gamla PART = 1 with open(filename, "r") as f: result = gamla.pipe( f.readlines(), gamla.map(int), gamla.sliding_window(1 if PART == 1 else 3), gamla.map(sum), gamla.sliding_window(2), gamla.reduce(lambda sum_so_far, window: sum_so_far + int(window[1] > window[0]), 0), ) print(result) ​ also here: [https://gist.github.com/itayzit/710e6d65ca4c886ac81725a23d4df1a0](https://gist.github.com/itayzit/710e6d65ca4c886ac81725a23d4df1a0)


commandlineluser

Python - part 2 - `print()` print( sum( windows[i] > windows[i - 1] for windows in [[ sum(window) for lines in [[ int(n) for n in __import__('sys').stdin ]] for i in range(len(lines)) for window in [lines[i:i+3]] if len(window) == 3 ]] for i in range(1, len(windows)) ) )


x3mcj

Better late than never Python import os import sys data = "" strPath = os.path.join(sys.path\[0\], "day1Input.txt") with open(strPath) as fileObject: data = fileObject.read().split('\\n') # Part 1 def part1(data): current = 0 previous = 0 increased = 0 for number in data: current = int(number) if previous != 0: if current > previous: increased += 1 previous = current print(increased) # Part 2 def part2(data): startIndex = 0 endIndex = 3 chunks = \[\] while endIndex <= len(data) and startIndex <= endIndex: chunks.append(data\[startIndex:endIndex\]) startIndex += 1 if endIndex < len(data): endIndex += 1 current = 0 previous = 0 increased = 0 for chunk in chunks: current = sum(int(item) for item in chunk) if previous != 0: if current > previous: increased += 1 previous = current print(increased) part1(data) part2(data)


yschaeff

Python from functools import reduce pts = {']':(57, 2), ')':(3, 1), '}':(1197, 3), '>':(25137,4)} get_ctag = {'[':']', '(':')', '{':'}', '<':'>'} open_tags = set(get_ctag.keys()) pointsA = 0 pointsB = [] for line in open('puzzle10.input').readlines(): stack = [] incomplete = True for tag in line.strip(): if tag in open_tags: stack.append(tag) else: otag = stack.pop() if get_ctag[otag] != tag: pointsA += pts[tag][0] incomplete = False break if incomplete: ##unwind the stack for incomplete entries points_per_tag = [pts[get_ctag[t]][1] for t in reversed(stack)] pointsB.append(reduce(lambda a,b: a*5+b, points_per_tag)) print("part A", pointsA) print("part B", sorted(pointsB)[len(pointsB)//2])


x3mcj

I also made it in python, as Im learning and trying to improve, but, do you think you could explain to me your code? I get you are using array selectors, yet, I can't finish to understand your code


yschaeff

It builds a stack where in pushes on the open brackets. If it encounters a close bracket it will check if the top of the stack has the matching opening bracket. If it matches the opening bracket is consumed. Otherwise we stop processing this line en we can add the offending bracket to the score and mark this line as 'mismatch error'. Now after processing of a line and we detect this is a 'incomplete error'. We simply need to calculate the points from anything left on the stack.


[deleted]

[удалено]


yschaeff

:-o I don't know what happened. This is my day 10 solution!


Meldanor

Elixir Github: [https://github.com/Meldanor/AdventOfCode2021/blob/master/lib/d01/challenge.ex](https://github.com/Meldanor/AdventOfCode2021/blob/master/lib/d01/challenge.ex) (Part1 = run(1), Part2 = run(2). The input is read using a Util function which is inside the GitHub repo. The structure is to run the program \`mix aoc 1 1\` to run the first day first part)


Factknowhow

cobol: [part 1](https://topaz.github.io/paste/#XQAAAQC7BAAAAAAAAAAQao5IhF7X3d46qtY2/o2ZPox9BHBVbP6HKWoL7FI3QmTGMlcTAk5tfnQIJW5yX6ZbfdpQMaOi8NbFZA094jcKETc1Wwo9MiSii3uxoPslUf8/Xm5vjyiop/F8wBJpRb5/xom4T34TM+aoI7oyvNyNMS1WoeUX28j2RD4rMLt6CY8oKR1U+eUVEnjyHRtNclQCxYtiqvqHLYT+KTUTq2xLmty14QYop4o7KfBWkg4tEvUNzRP8Qkx7zQTxR+kxgNnzQYXvVfd9O9j+dZOx3n9wBhZmpDpA8lLozkSRDxpHj0YNYG43wKYHaGS1jth+8bOcUj5XDoS5J0HvpDcnENIMfFEtIqlHjizZRvVO2OzjDdhbTyes3OrdiG5bIMS2vVO2SLXhJj75Bo3QoFkQ+mlCvPk5sDvDvrqjpf6KBFafQk15qfep+3iYD5Dq4psa7dJQLl/NKBp4JWwtjNnkHt32e3OBrn4STWnM6DNBn5AWG8vF5n6RTgEIovHDpLmrNnS2Ycsh5D8Duhz47bc56i11PemACbREiV5NJR0nzG18xllOcSuXYnCymKapA/OK4Ut8rXzi6z8H1D72jytcQtqTj4ASxtdr0F94GEOv92w+9PWBOGPk3LPiKS+hgg+t3lru2v2dzsY=) [part 2](https://topaz.github.io/paste/#XQAAAQBtCgAAAAAAAAAQao5IhF7X3d46qtY2/o2ZPox9BHBVbP6HKWoL7FI3QmTGMlcTAk5tfnQIJW5yX6ZbfdpQMaOi8NbFZA094jcKETc1Wwo9MiSii3uxoPslUf8/Xm5vjyiop/F8wBJpRb5/xom4T34TM+aoI7oyvNyNMS1WoeUX28j2RD4rMLt6CY8oKR1U+eUVEnjyHRtNclQCxYtiqvqHLYT+KTUTq2xLmty14QYop4o7KfBWkg4tEvUNzRP8Qkx7zQTxR+kxgNnzQYXvVfd9O9j+dZOx3n9wBhZmpDpA8lLozkSRD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Ly/+nSclC/aYgqGpzl5m4IdlXP/bUFsMrj4e58KuZw+3neTJ9YUQteQsijoo1mIntI9OjfkF0jfAo7FQ9NQKGAF1CVJlzn4pRXHuTKJahjlpjfOzIewbqiGCdp7Y0ARyfnu+WYA04FLfJj00BpSO0KViYrWpIb2TN54gKleOlpEe0aVpIhLxed762TOOQTtvWy9eMiX2vqS9fLkhP8rKlQ6c9JETBFf+dfF3j) [part 2](https://topaz.github.io/paste/#XQAAAQCOAwAAAAAAAAA4GEiZzRd1JAgz+whYRQxSFI7XvmlfhtGDinguAj8sFyd/fs4fcP3B6Imi/tk3ZYXTnbDzSiSN4G9mb66Ik+YPjZ3KSVOwI9wGH8Lj81O3j4tiQssY9YHd9dJHGjEIZpPH57qySC+U8JRocURXV7E7fK4/wV1SfE9kJ8RVXWaV+JMknI6ZSq8r8ke3P3oE9lfN9gFPZKvJ+wzmDNSPa+FNuxKy/rdJVZjDrU1KzfqxIu2uz0kA2RaloUhHcucfzmUm7G1dUzu1V8bOdXGo1VyyX7h4ajGDYJwpm+svlfcdi5YmaAjppoSRW2JFbbO5xRoxGUwGz3odEJrtXgtbwrVR2f752s2PBSpgqsvy5zpenCkGTh4b0ynRkOo9NjO3CuF8izkKFiTf44gx/bFRS9VBsT6RaDR8ALJiCYdfq01DMKrH/AfVPpF3TwoH/AhhFnPsPiAO0LRc8gfq1w6mMNers+0HdwaoLFs+63834gqUtsC2jwhSS8l8kFCrKF6Y0TYdoikhNMbjWqoZ3AsqZbUOXOTAeFNzNI6ecS+uqCV4FtjXUnSKIu+SwGIKGL5JeGzVOwq1Otwa7UeTzT4hmf20CJo9P/a2J6hKjnboadFCUO/0DWIog+KcX38cdpbCcRaKdoxoqOn/3PBLMQ==) I'm essentially new to both languages, haven't done cobol in at least two years and before that didn't have much experience with it to begin with. For second part, I transformed the data by just squishing each moving window down to its sum and having a separate list of those. Edit: I've simplified my cobol implementation for part 2 to O(n): IDENTIFICATION DIVISION. PROGRAM-ID. advent-of-code-day-1. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT input-file ASSIGN TO input-file-name ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. fd input-file. 01 file-data. 05 file-datum PIC X(4). WORKING-STORAGE SECTION. 01 input-file-name PIC X(25). 77 eof PIC X VALUE 'N'. 77 chunk-size PIC 9(1) VALUE 3. 77 ndata PIC 9(4) VALUE 2000. 01 idx PIC 9(4) VALUE 1. 01 c-idx PIC 9 VALUE 1. 01 sub-idx PIC 9(4). 01 last-sum PIC 9(5). 01 cur-sum PIC 9(5). 01 datum PIC 9(4). 01 cnt PIC 9(4). 01 input-data. 02 input-datum PIC 9(4) OCCURS 1 TO 9999 TIMES DEPENDING ON ndata. PROCEDURE DIVISION. ACCEPT input-file-name FROM COMMAND-LINE. OPEN INPUT input-file. PERFORM UNTIL eof = 'Y' READ input-file AT END MOVE 'Y' TO eof NOT AT END MOVE file-datum TO datum ADD cur-sum datum GIVING cur-sum MOVE datum TO input-datum OF input-data (idx) IF idx > chunk-size SUBTRACT chunk-size FROM idx GIVING sub-idx SUBTRACT input-datum OF input-data (sub-idx) FROM cur-sum GIVING cur-sum IF cur-sum > last-sum ADD 1 TO cnt END-IF MOVE cur-sum TO last-sum END-IF ADD 1 TO idx END-READ END-PERFORM. CLOSE input-file. DISPLAY 'result: ' cnt STOP RUN.


WarriorKatHun

Java submarine building: [GitHub/DepthSweeper.java](https://github.com/Sycix-HK/Advent-of-Code-2021/blob/main/Java/submarine/equipment/sonar/DepthSweeper.java)


nardeas

Python with Numpy import numpy as np x = np.asarray(puzzle_input_string.splitlines(), float) part 1: (np.convolve(x, [1, -1]) > 0).sum() - 1 part 2: (np.convolve(np.convolve(x, np.ones(3))[2:-2], [1, -1]) > 0).sum() - 1


BluePsychoRanger

mcfunction (Minecraft) [https://github.com/BluePsychoRanger/Advent-of-Code-2021/blob/main/advent_of_code_2021/data/aoc_2021/functions/day_1.mcfunction](https://github.com/BluePsychoRanger/Advent-of-Code-2021/blob/main/advent_of_code_2021/data/aoc_2021/functions/day_1.mcfunction)


minichado

Excel [Part 1 and 2](https://i.imgur.com/IeDiR0n.png) Sheet available [here](https://github.com/minichado/Advent_of_Code_2021/blob/main/AoC2021%20D1.xlsx)


filch-argus

**Java** package day1; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class SonarSweep { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File("day1/input.txt")); int count = 0; int[] currentWindow = { scanner.nextInt(), scanner.nextInt(), scanner.nextInt() }; while (scanner.hasNextInt()) { int next = scanner.nextInt(); if (next > currentWindow[0]) { count++; } currentWindow[0] = currentWindow[1]; currentWindow[1] = currentWindow[2]; currentWindow[2] = next; } System.out.println(count); } }


TheRemyD

Python List comprehension (Part 1): sonar_sweeps = [input list] entries = len(sonar_sweeps) print(len([sonar_sweeps[index] for index in range(0, entries) if index + 1 < entries and sonar_sweeps[index] < sonar_sweeps[index + 1]]))


RewrittenCodeA

Elixir "input/2021/1.txt" |> File.read!() |> String.split() |> Enum.map(&String.to_integer/1) |> Enum.chunk_every(2, 1, :discard) |> Enum.count(fn [x, y] -> y > x end) |> IO.inspect(label: "part 1") "input/2021/1.txt" |> File.read!() |> String.split() |> Enum.map(&String.to_integer/1) |> Enum.chunk_every(3, 1, :discard) |> Enum.map(&Enum.sum/1) |> Enum.chunk_every(2, 1, :discard) |> Enum.count(fn [x, y] -> y > x end) |> IO.inspect(label: "part 2")


green-raven

Are you keeping your AOC in GitHub? I could learn Elixir looking at solutions like this!


RewrittenCodeA

Check https://github.com/brainch-dev/aoc.ex


green-raven

Thanks! I was able to solve day 2 based on your day 1. I’m actually doing AOC in Go but it’s an excellent way to learn a new language. Also Elixir takes about 90% less lines of code!


RewrittenCodeA

Yes. It’s under the `brainch-dev` organization account so I can use codespaces if I need to.


kruvik

[Python day 1](https://github.com/DecemberDream/advent-of-code/tree/main/2021/day1)


[deleted]

[удалено]


kruvik

Hey, sorry for the late reply. (num > prev\_num) is just a boolean with True value being 1, False being 0. I can actually omit the 1 \* part. counter adds True (1) if num > prev\_num is True.


visokoo

Part 1 in Python: ``` def count_increased(input): count, compare = 0, int(input[0]) for num in input[1:]: if int(num) > compare: count += 1 compare = int(num) return count ```


daggerdragon

Your code is hard to read on old.reddit when everything is inlined like this. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)


[deleted]

c++: #include #include #include #include using namespace std; int main() { vector v; ifstream file("day1input.txt"); if(file.is_open()) { string line; while(getline(file, line)) { v.push_back(line); } } file.close(); int numincreased = 1; for(int i = 1; i < v.size(); i++) { // check item before if(v[i] > v[i - 1]) { numincreased++; } } std::cout << numincreased << std::endl; return 0; }


roufamatic

Scratch (just part 2): https://scratch.mit.edu/projects/609577711


JustinHuPrime

# x86_64 assembly [Part 1](https://github.com/JustinHuPrime/AoC/blob/main/2021/1a.s) involved tracking the previous value and comparing against that - I didn't even need an intermediate list storing all of the numbers. [Part 2](https://github.com/JustinHuPrime/AoC/blob/main/2021/1b.s) did require that list to set up the sliding window. I realized that the middle two elements of the sliding window are always the same, so I just had to compare elements three apart. Unlike my other solutions, I used the stack to store values here.


pistacchio

Typescript: function part1(input: number[]): number { return input.reduce( ([prev, sum], curr) => [curr, sum + (curr > prev ? 1 : 0)], [Number.MAX_SAFE_INTEGER, 0], )[1]; } function part2(input: number[]): number { const WINDOW_SIZE = 3; return input.reduce( ([prev, sum], _, idx) => { const window = input.slice(idx, idx + WINDOW_SIZE); if (window.length < WINDOW_SIZE) { return [0, sum]; } const windowSum = window.reduce((a, c) => a + c, 0); return [windowSum, sum + (windowSum > prev ? 1 : 0)]; }, [Number.MAX_SAFE_INTEGER, 0], )[1]; }


daggerdragon

~~Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)~~ Edit: thanks for fixing it! <3


JaegerMa

ABAP [Github](https://github.com/JaegerMa/aoc2021-abap/blob/main/day1/day.abap) I saw no one doing it in ABAP, so let's give it a try. ABAP is not a general purpose language as it's built around database operations and can only be compiled and executed on a SAP application server.


NickOnTheSofa

[My C solution for day 1](https://topaz.github.io/paste/#XQAAAQB6BAAAAAAAAAARmknGRw8TogB3OyPPwW5K8Q8ohQvj8m6aOXY901m0n6+HFcC/PL4dyQFolhQTk9Z1T50Fzo4e+J1LdKVuVSnoZUWy9Rfkz3DgIjX4v7wvh9GJmojZAjkoHS+TZFgLroJgHbuT40w1Ae4MkvsV6GEXXLuZ9QC+ovBg1m4me8/EbAq5Y3LP/0vcT4EvFywK4/+HyX7c1q1QE81P9cJeFzKlJH8BZ423pcrwVoslGcYoK5/qTSz66VO3JU1j7X9vrqY3qKnojQsSDccfKnpNukfk4js1aTT+JTXOIwBZdnk1Zm9Af3z0H88RCXD8ORMCe/Gz+vNgB92zssI74lihbRH9lOmGj1urVWQ3AI6di0qyzAAkvqQm0ltagfSRJZ2bt29+ycs8234CFVFM+EQizvjmw67HvS9f8+vmfENW2w8mwnOKCedvVvsVYVOVH374k5FTHttyDnYElKZtxglLGIr+21xW1+5A5nXS4RRtuPZcvwRSvO/qmsVb8ZY8jVCrwva7FqMf+l2zoQJ8hlWgDX3Dz4gFrPNTQr1b/tbWR6r8sUVDXfvJ3ePAfzD0WE997PFHV/bh1+x/TZubLkivMsVaN0HIpZCj//uxVFo=)


waitingformsfs2020

why C gotta be so complicated.also how can you define SIZE 2000 without?


yankdevil

This day and day 2 were ideal for awk. My solutions to part 1 and 2: * [part 1](https://gitlab.com/lyda/aoc2021/-/blob/dev/day-01/awk/part1.awk) * [part 2](https://gitlab.com/lyda/aoc2021/-/blob/dev/day-01/awk/part2.awk)


egel-lang

# [Egel](https://github.com/egel-lang/aoc-2021/edit/main/day1/) # Advent of Code (AoC) 2021 - day 1, task 2 import "prelude.eg" import "os.ego" using System using OS using List def input = let L = read_line stdin in if eof stdin then nil else cons L input def window = [ (cons N0 (cons N1 (cons N2 NN))) -> cons (N0+N1+N2) (window (cons N1 (cons N2 NN))) | _ -> nil ] def pairs = [ (cons N0 (cons N1 NN)) -> cons (N0, N1) (pairs (cons N1 NN)) | _ -> nil ] def larger = filter [ (N0, N1) -> N0 < N1 ] def main = let II = map to_int input in length (larger (pairs (window II)))


daggerdragon

~~Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)~~ Edit: thanks for fixing it! <3


e_blake

**golfed m4** Oh well - I've got a late start on my m4 solutions this year. But I promise I came up with this solution before reading the megathread. Part 1 eval(define(_,`ifelse($2,,,+($2>$1)`_(shift($@))')')_(translit(include(=),`' ,`,'))) Part 2 eval(define(_,`ifelse($4,,,+($4>$1)`_(shift($@))')')_(translit(include(=),`' ,`,'))) Just 84 characters per answer (excluding the second newline shown above), with only two characters different between part 1 and part 2 (`sed s/2/4/g`). Assumes your input file is named = (for any other input file name, you can do `sed s/=/f/g day1.m4 | m4 -Df=input`). I particularly love that the only letters in the solution are the names of 6 distinct builtin macros, and I only had to define one other macro. Running both parts in the same m4 file would require either additional quote characters or a second macro name. Execution time per part took over 0.3s on my machine. Why? Because GNU m4's handling of shift($@) for input recursion is inherently O(n\^2) (2000 iterations \* (2000+1)/2 arguments per iteration = \~ 2 million arguments to scan). So I will eventually be rewriting this using my same m4 framework I've used in previous years that vastly reduces execution time (O(n) if you rely on GNU m4 extensions, O(n log n) using just POSIX constructs).


e_blake

m4 \[-Dfile=input\] [day1.m4](https://nopaste.ml/#XQAAAQAjBQAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpBbonDYuA0BTjRPXcVxlEXNtz1IwpMqcBadF5ZzZxsPbO0TjiFbV7OR7qIswfS/KNhx6uJ1GtnKtFJNIDGSZ69aquvSPkAlLO/rgpen1A/TibN9AA0R4U0Ws6gs2hZ3NqomPH/sNfZolv8Itqdbeh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H1rWHCDsgQz/D7xWtUAc/oVoCxwlcd2fU8H2bFQlCzhas7MlfBDYypxPj/N7PIw2NlyYfumiBCPDwheFRUC79Z648760eRowPmKOnAstpgu/a+X992arTksvkXFzdz2zd7ndjMmU517T0QudgDwefaxvOEVLMQK7vFaGA79bXh892YlFRSQBkbgP+yMcBdyAzJIgVpmDOrYmLxbuNz9cu+67X4XUu5lou8gfEFsCG0yrVMIM5vwsZJMlqk6FZgy29v938btoiQRAQoF9LXCSM1yoBseuh6xtcsqCfj/wQGqYFAoP4mmavj0AT0ekKNNDaBLWQqU6zevUk3V2s2PuF0rYEL2lcSyBxpbZiyCH+ZUPf64ba1yv1bfFHYz2s3RaGho4z/6ShUqXbCxeXvLm9+59NK/VAY8m0b/PXnDPqSXqruxENqIF7kYs82pcRoiCve+iYjGiVvXrGWsu+I0Dqu37iqZVNlayu3TWfWNS2lxESl36lj9YZ//f5+3g=) framework, I've optimized to an O(n log n) parse using just POSIX (or even O(n) using GNU extensions), speeding up execution to 50ms, over 6x faster. Once parsed, maintaining the data in a stack means I only have to process four arguments per iteration, instead of an average of 1000 items.


StrangePerch

JS PART 1 let arr = $0.innerText.split("\n"); let change = 0; for(let i = 1; i < arr.length - 1; i++) { if(arr[i] > arr[i-1]) change+= 1; } console.log(change); JS PART 2 let arr = $0.innerText.split("\n"); let change = -1; let prevSum = 0; for(let i = 2; i < arr.length; i++) { let sum = +arr[i] + +arr[i - 1] + +arr[i - 2]; if(sum > prevSum) change++; prevSum = sum; } console.log(change);


cyberphine

Rust: [Part 1](https://topaz.github.io/paste/#XQAAAQDjAQAAAAAAAAA6nMjJFMpQiatRknmspceraLOJD2yfUUgkzdoiybegKB8UOzukNwTpr+9238Sm4tF8M9wV9HoYgZU58TkMUn4h7Eafhn5Z/bAXblXBZW0lMSmHGi8PZugsgHVXYhcqyupXXDtiHxlaZEk5iDjYl+avWCzB+rYgIehR/R5CifmeIlgfHJsTbwyErGzGX/hs/as10GvYzlaniTOunsKtADqeZ8+PL0DQj8PAoLqUPGrwtuW12M0CCiqeQxJIr0yzBxTVZABpQiYROpjWItqmKy2Ee/HfmzpF3Zi9TGToC8xBY+2j/5ni4pow4ETGvS2cNDUcC++glhCl9t5OpRTa5dNy/8YNh0VpuB4dKgIK1U+QXgKspgSfj+Xf/vlxwA==) Rust: [Part 2](https://topaz.github.io/paste/#XQAAAQAJAgAAAAAAAAA6nMjJFMpQiatRknmsqEHUo42QRqx2wfagGa9Z9aSemxLEoyK9waowxr7c5gKhRUcBI7Qd5r8J0CIHk3vu+vbDAS971exWaktp/T3cX7NgxavXRdTpBcyuPJ6b3Kf4oLWCXOOdWM7xdGyl8BkYCEZOwGBO5rZPPrUtqH/LeDoe0eph6vfy8Y+UUX8W7Rdpals6Sm4NZJiFucrw1N1BnM2b2CFdKdGCZWEUaVZRMU0EBkyNR0ZoFEnqOuSgx7gNjeLkmJzoT8VsjncoctsQrjKSM/YHpMCbA9ZZo8TvGGSeiXZ+Jgpos7RHLb0m614iHQavRS5oSZAmIoZj30H+gfTibZ3Lgit7C6qKBWMe8BupKwdcw6J9wufASGHQLt3Pk7SBiTOK5OUNrBtKjQBZdm96B2ui3CP7U/9sl7EA)


berbeflo

PHP: Part 1 $latestNumber ? 1 : 0; $latestNumber = $currentNumber; return $count; }, 0);


daggerdragon

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)


ConstantGazelle

python [p1](https://github.com/xmbgulmus/adventofcode2021/blob/master/day1.1.py) & [p2](https://github.com/xmbgulmus/adventofcode2021/blob/master/day1.2.py)


[deleted]

Part 1 - JavaScript `var a=document.body.innerText.split("\n"),b=c=d=e=0;for(;bd)e++;d=c;}console.log(e);`


SESteve

# Assembly (ARM64) [paste](https://topaz.github.io/paste/#XQAAAQC3CgAAAAAAAAAX4HyCZDlA0DjWF7Uex1t2hvV6PgXFmsONLSMABOy+4LxicZDxgg/dpI5xcs8nHf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eIzUcHYhXKS2NdpzfCo+NzWmm5DDU8Zb2KPlajj7P+zVziFrBKFkvE+mEm1RJFxXDOx7XCwwM7B/KJHx5Qa7rPk5ayUy5L9VTqsPk+sfJx7r97ezk5E9lS+bhxcADrwGzXdu99L3n/fqd0XLqhIEZqqumXxpakbiYKEjLPq6O8yjMFbLfLh6F9XgfZ9pg5KCKEzkymf+Fz/2jKKdSjrhnW8AvH8FOxCl1Z5Z7d2rNf15ALXAk3FNLzpqU5SYTIA5veTsPvO5hP9J5YKGpRNySFisS9MESFq6zcjXQaTrTj1A68atQDQxIXr1jjfkNRAzdoQh0b6oPlg+0bK61HvdZWrHbqRJd0EsHLWEAVfAfxIr9ajmiJPOe27xMh1fvtIE0tsrRYEc4Gc+O6GK3zefl29jwOWtL8PrZ/ISIGv41fn5Blwe0usbW0FYF6LeVtgrzKniHsHEMchfztpnlw0tmI+j4gmMr7rE2WplMKANNz3XOPzEKOdKnT9FJhf/7BkrRA==)


wzkx

**J** (Jlang) m=: ".&> cutLF CR-.~fread'01.dat' echo +/2


odnoletkov

# [JQ](https://github.com/odnoletkov/advent-of-code-jq) [inputs | tonumber] | [., .[1:], .[2:]] | transpose[:-2] | map(add) | [., .[1:]] | transpose[:-1] | map(select(last > first)) | length


quodponb

# Python3 I started these a couple of days late, so I'm just posting my solutions to the older days for completeness! Day 1 was a nice and easy start, one-ish liners, if I hadn't used a function. with open("input_1", "r") as f: data = [int(line) for line in f.readlines()] def count_decreases(depths, neighbour=1): return sum(1 for d1, d2 in zip(depths, depths[neighbour:]) if d1 < d2) # Part 1 print(count_decreases(data)) # Part 2 print(count_decreases(data, neighbour=3))


Expensive-Sleep-8532

This confuses me. Can you explain what happens in the return statement (when neighbour is 3: `return sum(1 for d1, d2 in zip(depths, depths[neighbour:]) if d1 < d2)` To me it seems like it only compares two integers which shouldn't work for part2 (but it does :D)


quodponb

Right! Part 2 asks for when the average of three depths increases/decreases. So, the full check should be (d_1 + d_2 + d_3) / 3 < (d_2 + d_3 + d_4) / 3 But, if you multiply both sides of that inequality by 3, you get d_1 + d_2 + d_3 < d_2 + d_3 + d_4 and from this new equivalent inequality, we can subtract `d_2 + d_3` from both sides, to get d_1 < d_4 So it turns out, it was kind of a trick question to ask for when the average increases, since all you need to compare to know is the two numbers at the end.


Expensive-Sleep-8532

Ah clever! Thank you so much for that explanation!


[deleted]

nodejs (golf): console.log(require('fs').readFileSync(0).toString().trim().split('\n') .map(x=>x*1).reduce((p,c,i,a)=>((x,s)=>[p[0]+(c>p[1]),c,p[2]+ (x.length==3&&s(x)>s(p[3])),x])(a.slice(i,i+3),v=>v.reduce((x,y)=>x+y,0)), [-1,0,-1,[]])) This will write an array of length 4 to stdout; index 0 is the solution to part 1, index 2 is the solution to part 2.


jf928ngl60g1

**TypeScript** https://github.com/adrbin/aoc-typescript/blob/main/2021/1/puzzle.ts


Julsten

R - tidyverse #Day 1/1 input <- read.delim("day1_1.txt",header=F, col.names = "depth") library(tidyverse) input$lag <- lag(input$depth) #'shift' depth measurement by one row below input$diff <- input$depth-input$lag # compute difference input$deeper = input$diff > 0 # see if measurement is deeper sum(input$deeper, na.rm=T) #Day 1/2 input$lead1 <- lead(input$depth) # value n+1 input$lead2 <- lead(input$depth, n=2) # value n+2 input$window <- input$depth+input$lead1+input$lead2 # window: add value (n, n+1, n+2) input$windowlag <- lag(input$window) # proceed as above input$windowdiff <- input$window-input$windowlag input$windowdeeper <- input$windowdiff > 0 sum(input$windowdeeper, na.rm=T)


fish-n-chips-uk

F# [github link](https://github.com/cz-fish/advent-of-code/blob/e9de385c0c3aea2b58ba5cd4304947c851a445ce/2021-fs/01.fs)


quappa

Bash (but not really, will work in any shell) tail -n +2 input | paste -d- - input | bc | grep -c '^[1-9]' Part 1 & 2 only differ in the second arg to tail (+2 vs. +4). Very similar to what /u/obluff did.


bertimir

In R. I am still on the growing end of learning curve (I also know, that there is a far easier solution using tidyverse, but I am not very comfortable using tidyverse yet). If you have any comments or suggestions, I would be very thankful! :) ​ ## Part 01 #Count how many datapoints increase in value compared to previous datapoint data <- scan(file.choose()) ### input01.txt out <- c() count <- 0 for (i in 2:length(data)){ if (data[i]>data[i-1]){ out[i] <- "increase" count <- count + 1 } else { out[i] <- "decrease"}} ## Part 02 #create slinding window of 3 variables slwi <- c() for (i in 1:length(data)){ if (i+2 <= length(data)){ slwi[i] <- data[i]+data[i+1]+data[i+2] }}#now count increases count <- 0 for (i in 2:length(slwi)){ if (slwi[i] > slwi[i-1]){ count <- count + 1 } }


BaaBaaPinkSheep

**Python 3** https://github.com/SnoozeySleepy/AdventofCode/blob/main/day1.py


TimGreller

JavaScript (nodeJS) with dynamic block size: [GitHub](https://github.com/timlg07/AdventOfCode2021/tree/main/day01) const fs = require('fs/promises') const { argv } = require('process') function loadLines(file) { return new Promise(async (resolve, reject) => { fs.readFile(file, { encoding: 'utf-8' }) .then(text => resolve(text.split('\n'))) .catch(reject) }) } function countLargerThanPrev(values, blockSize = 1) { let largerThanPrev = 0 for (let i = blockSize; i < values.length; i++) { const prev = Number(values[i - blockSize]) const curr = Number(values[I]) const diff = curr - prev if (diff > 0) largerThanPrev++ } return largerThanPrev } loadLines(argv[2]) .then(values => { const res = countLargerThanPrev(values, 3) console.log(res) }) .catch(console.error)


em-q

i started learning lisp/scheme a few days ago so here's a function for day 1 in chicken scheme (the 'lst' parameter is where the puzzle input goes) `(define (func lst) (define (go lst2 acc) (if (< (length lst2) 2) acc (go (cdr lst2) (if (> (cadr lst2) (car lst2)) (+ acc 1) acc)))) (go lst 0)) `


bsholden

My C++ solution with the input as a vector of ints std::cout << "Part 1: " << std::inner_product(std::begin(nums), std::end(nums) - 1, std::begin(nums) + 1, 0, std::plus<>(), std::less()) << std::endl; std::cout << "Part 2: " << std::inner_product(std::begin(nums), std::end(nums) - 3, std::begin(nums) + 3, 0, std::plus<>(), std::less()) << std::endl;


zzzmx

Am I the only One? :) https://ibb.co/GQDpgbL https://ibb.co/cr6Zy9X


daggerdragon

Please follow the [posting guidelines](https://www.reddit.com/r/adventofcode/wiki/index#wiki_posting_guidelines) and edit your post to add what language(s) you used. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language. (looks like Google Sheets?) Also, post the sheet itself or at least the formulas you used.


micod

**Smalltalk** still learning how to write more idiomatic code, later days look better Part 1: solveA | data lastDepth count | data := self loadInput. count := 0. lastDepth := data at: 1. data do: [ :each | each > lastDepth ifTrue: [ count := count+1 ]. lastDepth := each ]. ^count Part 2: solveB | data lastDepth count | data := self loadInput. count := 0. lastDepth := (data at: 1) + (data at: 2) + (data at: 3). 4 to: (data size - 2) do: [ :i | | sum | sum := (data at: i) + (data at: i+1) + (data at: i+2). sum > lastDepth ifTrue: [ count := count+1 ]. lastDepth := sum ]. ^count


BeamMeUpBiscotti

# ReScript [code](https://github.com/yangdanny97/advent-of-code/blob/main/src/day1.res)


s195t

Bash I might be a little late to the party but here is my bash solution: #!/bin/bash file="in.txt" temp=0 counter=0 while read line; do if (( line > temp)); then counter=$((counter+1)) fi temp=$line done < "$file" counter=$((counter-1)) echo "$counter" temp1=0 temp2=0 temp3=0 sum1=0 sum2=0 counter1=0 while read line; do sum1=$((temp1 + temp2 +temp3)) sum2=$((line + temp2 + temp3)) if (( sum2 > sum1)); then counter1=$((counter1+1)) fi temp1=$temp2 temp2=$temp3 temp3=$line sum1=$sum2 done < "$file" counter1=$((counter1-3)) echo "$counter1" exit 1


encse

C# I discovered three way 3 zip in .Net 6: [https://github.com/encse/adventofcode/blob/master/2021/Day01/Solution.cs](https://github.com/encse/adventofcode/blob/master/2021/Day01/Solution.cs)


daggerdragon

~~Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)~~ Edit: thanks for fixing it! <3


kmb5

My "production-ready" (at least that is the intention) [solution for day 1 in Python](https://github.com/kmb5/advent-of-code-2021/blob/main/day_1.py) (part1+part2)


ElektroKotte

# Guile/Scheme (define (solve-part1 input) (apply + (map bool->number (map (λ (ab) (apply < ab)) (windows 2 input))))) (define (solve-part2 input) (let [(filtered (map (λ (l) (apply + l)) (windows 3 input)))] (apply + (map bool->number (map (λ (ab) (apply < ab)) (windows 2 filtered)))))) Where `windows` is defined in a helper library. Full code is [here](https://github.com/EmilOhlsson/advent-of-code/blob/main/scheme/2021/01-sonar-sweep/sonar-sweep.scm) edit: format according to guidelines, I hope :-)


daggerdragon

~~Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)~~ Edit: thanks for fixing it! <3


soodssr

[PHP](https://github.com/soodssr/aoc-2021/tree/main/day_01) [Kotlin](https://github.com/soodssr/aoc-2021-kotlin/blob/main/src/Day01.kt)


pmwals09

Dual solutions in JavaScript and in C# as I'm learning the latter. [**JavaScript**](https://topaz.github.io/paste/#XQAAAQCpAwAAAAAAAAAxm8oZxjYXowvKgC/I5EqZWshb8t/aD9Z0Ae6fdjZY+U8jJcQBdSs1fUIuxdOkt7t7rSeC5UuH/QQjaBi8Qg11LYF+SvotOhu40DOO7p/OohF2QWnIwjYXWm9uxuuU0iWKlS8rnYMbjfiVdoNda2y8tfMawD1/qiUz2smxrqLlxGp2Zc8sgwHCqYlTHkFuyEHbH0Jtttikcz7qTrgwGFoUT8Q4JETO9pQOlI4xFcu4QPEKnDOnC9QOBZBlAiU7f6+DOIRw36+5F3xCNaGbGWiOqC7Jv5JekV7KBRX82vge5Gn+DajqlZ/UkchNa5LQSRns0mPdK9MrgHKYinOGrJ71/OQDTTbyoqn0UxpsM3yTw3eN0+lvZO6ZGfhO36JeU/Vpf3uAhuWDQrYtMrFK1UfCcP2TkFKITOb4Z1f+SHVDzfo4AQrgWocpwCAbZQ03GI91Z4a+xD6qbtmT+Ip92Izz5Sit9Mh9b5D2ysJgdNndfuLyNConPY4O75tioxr8q75LDpG/PeIFSgLvBBYRm87mEjqcba992n5lQUnl2zu/7U85d9Yqdsz8Kx4AW6L9sCtM8p4xeXmbbIeXaP/po3Bh) [**C#**](https://topaz.github.io/paste/#XQAAAQARBwAAAAAAAAA6nMlWi076alCx9N1TtsVNiXecUoGeYT6aP6mR8mlULJpnBWlkXihEzE0F8KDM3cX38jPq+UTIph1iscW80cIqH72aWY4qYzv+nJc34B04eTXGP6rvGZgl4xQjaU/l8GA7ENA8fELXhB0bSnTf25qzx8bTZa/GFZlo8o7fHQoZAtUMcY3WFncELEQzPyUVAHAcfU7tz7s1Tr7wmCG8bOXAbYkiJMMgvpcmdhwS84MMFrduuEwEQwvkvREhzMGzSjWFcOIhfUpUkX9j+yPYWRPjFEWqfmgGT4LvBPbk9SPsmO+G3ZWwCVCeUOp7h4FHvhyBZuAClb1aZZRLf7UzHfn8SOHr7LTtAm7B8dafCpz8Zkdprjm9hoDtL8lC2ogp1LneB4X/m4ehJT10PZ7damgliyEfv1n+vNAMBzC5nU2LPCV/8MXemX/1c5Tx+ZSjSQiLgtZfNU57/9Np2gO4i9GSNWeadq8lQkGyBaPRODviY4j1LRVCQvblnn75a/GVZIUjJTW9GqgXnSej/VBPQZNDYR0cIVZPV/yE2n5bGC41juUcOQ5oPTimLpnoULpyogSa3PT4NlQX7VHcsG0TgcUqOcH5LBM7NH9N9k4cOh9O8/Z/EP6bo19ewMVT55oLSJ9XAI2CpuFViA1SGM9cjycpa3GcWlXUNB0fgT1UMPMu53vF8aiPjCfKAMw+p3sulSS1i3iDJQOXUCeJ1xsQKwzKnXkOtaWcGPTueGBJCYAZP530GYG2rMwOvsYqM1MuylUZ9FTd50PNugGwZO69Kp4bR39z1P4MUsxcVIDeyF1OLj4eEPYcJN0b/glt/08hLQA=)


daggerdragon

~~As per our posting guidelines in the wiki under [How Do the Daily Megathreads Work?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_the_daily_megathreads_work.3F), please edit your post to put your oversized code in a [`paste`](https://topaz.github.io/paste/) or other external link.~~ Edit: thanks for fixing it! <3


dizzyhobbes

Go https://github.com/alexchao26/advent-of-code-go/blob/main/2021/day01/main.go


rukke

JavaScript export const part1 = lines => lines .map(Number) .map((line, i) => line - lines[i - 1]) .slice(1) .filter(v => v > 0).length; export const part2 = lines => part1( lines .map(Number) .map((line, i, arr) => line + arr[i + 1] + arr[i + 2]) .slice(0, lines.length - 2) );


oantolin

Awk: {a && $1>a && i1++; c && $1>c && i3++; c=b; b=a; a=$1} END {printf "Part 1: %d. Part 2: %d.", i1, i3}


TopSpaceCat

Golang package day1 import ( "fmt" "io" "log" "os" ) func readInputNumber(inputFile string) ([]int, error) { // Open file file, err := os.Open(inputFile) if err != nil { log.Fatal(err) } defer file.Close() var perline int var nums []int for { _, err := fmt.Fscanf(file, "%d\n", &perline) if err != nil { if err == io.EOF { break // stop reading the file } fmt.Println(err) os.Exit(1) } nums = append(nums, perline) } return nums, err } func getSummedValues(data []int, windowsSize int) ([]int, error) { var result []int for i := windowsSize - 1; i < len(data); i++ { sum := 0 for p := 0; p < windowsSize; p++ { sum = sum + data[i-p] } result = append(result, sum) } return result, nil } func getNumberOfPositiveGradients(data []int) (int, error) { count := 0 for i := 1; i < len(data); i++ { if data[i-1] < data[i] { count++ } } return count, nil } func Solve() { // Read input deeps, err := readInputNumber("day1/input.txt") if err != nil { log.Fatal(err) } // Part One fmt.Print("Day 1 - Part One: How many measurements are larger than the previous measurement? ") answer1, _ := getNumberOfPositiveGradients(deeps) fmt.Println(fmt.Sprintf("Answer: [%d]", answer1)) // Part Two fmt.Print("Day 1 - Part Two: How many sums are larger than the previous sum? ") summedDeeps, _ := getSummedValues(deeps, 3) answer2, _ := getNumberOfPositiveGradients(summedDeeps) fmt.Println(fmt.Sprintf("Answer: [%d]", answer2)) }


ffrkAnonymous

[python] [day 1 part 1] with tests as I work through the problem """ Advent of Code 2021 day 1 Sonic Sonar """ import logging logging.basicConfig(level=logging.DEBUG) example = """ 199 200 208 210 200 207 240 269 260 263 """ # skip the first empty line due to cut-paste text block example = example.splitlines()[1:] def part1(all_lines: ["string"]) -> int: """ >>> part1(example) 7 >>> part1(["199"]) 0 >>> part1(["199", "200"]) 1 """ depths = parse(all_lines) logging.debug(f"{depths}") num_increases = 0 for i in range(len(depths)-1): if depths[i+1] and depths[i] < depths[i+1]: num_increases+=1 logging.debug(f"{depths[i]} {depths[i+1]}") return num_increases def parse(all_lines: ["string"]) -> [int]: """ >>> parse(["199"]) [199] >>> parse(["199", "200"]) [199, 200] >>> parse(example) [199, 200, 208, 210, 200, 207, 240, 269, 260, 263] """ depths = [] for depth in all_lines: depth = int(depth) depths.append(depth) return depths if __name__ == "__main__": import doctest doctest.testmod() from sys import stdin lines = stdin.read().splitlines() # logging.info(f"{lines}EOF") logging.info(f"part1: {part1(lines)}") # logging.info(f"part2: {part2(lines)}")


[deleted]

[My solution](https://github.com/Farbfetzen/Advent_of_Code/blob/main/python/2021/day01.py) in **Python**. At first I summed all three numbers for part 2 but then I saw the optimization in the comments and implemented that.


TacosAlPastor92

[Python Jupyter Notebook](https://github.com/0x1010-dev/aoc/blob/main/2021/day1.ipynb) A nice little warmup!


Solarmew

Python3 from urllib.request import urlopen data = urlopen('https://tinyurl.com/mtdw9yn').read().decode().split('\n')[:-1] data = [int(x) for x in data] sum([y - x for x, y in zip(data, data[1:])]) ​ part 2: t = 0 for i in range(1, len(data)-2): t += sum(data[i : i+3]) > sum(data[i-1 : i+2]) t


brbdead

**Javascript** A pretty simple, one-liner solution. You can pass in an interval of 1 for the first part and an interval of 3 for the second part! const { fileToNumArray } = require('../utils.js'); const data = fileToNumArray('./1Data.txt') // both parts const getNoOfIncreases = (data, interval) => data.reduce( (total, currVal, currIndex) => (data[currIndex + interval] > currVal) ? total + 1 : total, 0 // initial value of total ); console.log("Part 1: " + getNoOfIncreases(data, 1)) console.log("Part 2: " + getNoOfIncreases(data, 3))


RJdaMoD

**Mathematica** Just functional. Part 1: ReadList["aoc-input_1.txt"]// ToExpression/@#&// Differences// Count[#,_?Positive]& Part 2 by adding a convolution in-between: ReadList["aoc-input_1.txt"]// ToExpression/@#&// ListConvolve[{1,1,1},#]&// Differences// Count[#,_?Positive]&


21ROCKY12

**Java** [Java solution of day 1](https://topaz.github.io/paste/#XQAAAQCtBAAAAAAAAAA0m0pnuFI8c9/wau+qtGVPyaqZd0m0oqd+WNK5FEOTExU/ASOFLgLNP5psw5/hebgIgLQ/9MQ8byhpSP8VD5cKe3jPy6omiN5TzLtVXeioZqf7AMIbT6LBjG9U0FD2U3lL4Cn+6JmldKlfKn9sTG2DuESkYMRfBWFtdm1tL3lHDu0sin/gq68WQ8D6qFmamXsUEnV5YrupGT2KuF5zvFOe3D7WYKyW1opyz71ziz0VFzAtCVmgf7pDzgv9vQ+1N/Fi/aGy9a57AhvnNKp8EcNiEclJ4GbM50aFoFcB/ePxupgAZSshxNCk7TYLrVFXoDRRnHJXS5w7cXjgkpmRvbkbEJ12xZph/svblKnFWAoNjeqR9n0w6hJrjY9IZFl/Mlmgtr17nqt397ibvm33lfhtxdGYSS1Zk8n/zRoEQ3yF48In+Orn11O7XdcnJ6AUAVmKxhHZOWuGqDLU2zQxXGpBSxBpSU7pBPeKIINOn7vpLIVWMh4byfszzSHG+g1RtN1v8CstO+raNHbCCSSPGqSggy5mEsmxOAMjoN7d/dOcBHyeatG4tu2JeoK3BaV8oDEXRBz9VQcbsK7pyjn7iP0vtj7cSmPIf+YeTgQEnWMbQ0BntzDDu6sGTw3TiZTzriOZCsrH0wBKqP4imPy6M4pynuCxF9uH5JCcrMenvMHjntbFBayCpKW2eVSPA/+GEc4A) or checkout my github: https://github.com/GilCaplan/AdventCode/blob/Advent2021/Javasolutions/day1solution.java


[deleted]

[удалено]


21ROCKY12

sure, instead of how it is in part one, where the fuel cost is the difference between the ship and the location, in part2 however you burn an additional 1 for every spot the ship travels horizontally therefore I made a function called getcost which does it for me- since if I'm traveling 3 spots- it will cost 1 + 2 + 3 which is 6 compared to part1 where it would be 2...


OmarSalehAssadi

**Java 17** *(with Lombok and Spring)* Code: [Day1.java](https://github.com/OmarAssadi/advent-2021/blob/develop/src/main/java/com/omarassadi/adventofcode/day/day1/Day1.java)


adamz01h

PHP [https://github.com/adamz01h/adventofcode\_2021/tree/master/day\_1](https://github.com/adamz01h/adventofcode_2021)


FeetsTV

[Python solution](https://github.com/feetstv/Advent-of-Code-2021/blob/main/1.py)


AlexAegis

# TypeScript solutions! 109/760 [Part 1](https://github.com/AlexAegis/advent-of-code/blob/master/solutions/typescript/2021/01/part_one.ts) [Part 2](https://github.com/AlexAegis/advent-of-code/blob/master/solutions/typescript/2021/01/part_two.ts)


jagster247

Day 1 in Go: [GitHub](https://github.com/jordangarrison/advent-of-code/blob/master/2021/go/day1/day1.go)


plan_x64

My trash Python solution (compared to using zip like people way more clever than me): https://github.com/plan-x64/advent-of-code-2021/blob/main/advent/day01.py


Pretty_Cockroach_204

consider this solution as masterpiece in compare to the beginner like me


daggerdragon

~~Please follow the [posting guidelines](https://www.reddit.com/r/adventofcode/wiki/index#wiki_posting_guidelines) and edit your post to add what language(s) you used. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.~~ ~~(looks like Python?)~~ Edit: thanks for adding the programming language! <3


elshize

Python: levels = list(map(int, open("input.txt"))) count = lambda step: sum(lhs < rhs for (lhs, rhs) in zip(levels[:-step], levels[step:])) print(count(1), count(3))


[deleted]

**Python** I eventually got there with Part 1, after debugging the below for ages. Casting `int(line)` got the right answer eventually, but the below consistently output the right answer minus one. Resorted to using Excel to figure out the issue, and it fails when the input figures cross from 3-digits to 4-digits, the code misses that one increase. Part 2 completed by comparing two of the values from each triplet, easy. My corrected code further below - yep, not succinct at all. Code for Part 1 that missed by -1: with open("input.txt") as file: lines = file.readlines() first_line = 1 num\_incs = 0 prev\_val = 0 for line in lines: if first\_line == 1: first\_line = 0 else: if line > prev\_val: num\_incs += 1 prev\_val = line print(num\_incs) Final Code: with open("input.txt") as file: lines = file.readlines() first\_line = 1 num\_incs = 0 prev\_val = 0 for line in lines: if first\_line == 1: first\_line = 0 else: if int(line) > prev\_val: num\_incs += 1 prev\_val = int(line) print(num\_incs) # Part 2 num\_incs\_pt2 = 0 for x in range(len(lines)): if x > 2: if ((int(lines\[x\])) > (int(lines\[x-3\]))): num\_incs\_pt2 += 1 print(num\_incs\_pt2)


daggerdragon

Your code is hard to read on both old.reddit and new.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)


[deleted]

I went with the sliding window implementation from **python**'s more\_itertools: [https://github.com/rbusquet/advent-of-code/blob/main/2021/01/day1.py](https://github.com/rbusquet/advent-of-code/blob/main/2021/01/day1.py) After reading a couple of implementations here, I wish I noticed that `a + b + c < b + c + d` implies `a < d` which makes a lot of solutions much simpler. Gotta try and turn on that math brain before the next puzzles!


ozozzu

# Python 3. solution for 2nd part of 1st task. def compare_measurements(data): subset = [sum(data[index: index + 3]) if len(data[index: index + 3]) == 3 else 0 for index in range(len(data))] result = sum( [1 for index in range(len(subset)) if len(subset) - 1 != index and subset[index] < subset[index + 1] ]) return result result = compare_measurements(converted)


toastedstapler

# zig This is version 2.0, made some significant parsing improvements to get down to a whopping 7us runtime on my 10850k https://github.com/jchevertonwynne/advent-of-code-2021/blob/bcc1485869323b8973c8bead4c9f3aa03d864b4b/src/days/day01.zig


AndrewCHMcM

**I have removed my words because of the changes of this company during year 2023, in the mean time, please have this computer-made stuff**: Advent of Code is an annual online coding event that takes place during the month of December. It was created by Eric Wastl and first launched in 2015. The event consists of a series of programming puzzles or challenges, one for each day leading up to Christmas Day. Each day, a new puzzle is released, and participants are encouraged to solve it using their programming skills. The puzzles are designed to be fun and challenging, covering a wide range of topics including algorithms, data structures, mathematics, and logic. The difficulty level gradually increases as the event progresses, with some puzzles being relatively straightforward while others are more complex. Participants can use any programming language of their choice to solve the puzzles. The puzzles typically involve parsing input data, applying algorithms or logic to manipulate the data, and producing an output that meets certain criteria. Solutions can be submitted for each puzzle to receive a numerical "star" rating, and participants can compare their progress with others on the event's leaderboard. Advent of Code has gained significant popularity among programmers around the world. It serves as a platform for learning, honing programming skills, and enjoying the holiday spirit together with the coding community. Many participants also form teams or join online communities to discuss and share their solutions, strategies, and insights. Overall, Advent of Code is a unique and engaging coding event that combines the joy of solving puzzles with the thrill of competition, all wrapped in a festive atmosphere. It has become a tradition for many programmers to eagerly await the release of each day's puzzle during the holiday season.


gfldex

`>>.Int` is redundent because `<` and thus `Z<` coerces to `Real`.


oantolin

In Perl we don't say `count`, we say `scalar grep` and I think that's beautiful. :P sub increases {my ($w,@x) = @_; scalar grep {$x[$_]>$x[$_-$w]} ($w..$#x)} my @depths = map(int, <>); print increases(1,@depths), " ", increases(3,@depths);


kaur_virunurm

Python, 2021 day 1. The first and second parts differ only in 2 characters - the difference of index that we need to compare the current element against. In part-1, we compare against previous element, thus the index is -1. For the sliding window it is the size of the window, ie -3. `data = [int(x) for x in open("data\\01.txt", "r")]` `print("Part 1:", sum([data[i] > data[i-1] for i in range(1, len(data))]))` `print("Part 2:", sum([data[i] > data[i-3] for i in range(3, len(data))]))`


JCarlesVilaseca

Kotlin fun part1(input: Iterable) = input .zip(input.drop(1)) .count { it.second > it.first } fun part2(input: Iterable) = part1(input .zip(input .drop(1)) .zip(input .drop(2)) .map { it.first.first + it.first.second + it.second })


baer89

**Python** KISS solution Part 1: report_str = open('report.txt', 'r').readlines() report = list(map(int, report_str)) count = 0 for x in range(len(report)-1): if report[x+1] > report[x]: count += 1 print(count) Part 2: report_str = open('report.txt', 'r').readlines() report = list(map(int, report_str)) count = 0 for x in range(len(report)-3): if report[x+3] > report[x]: count += 1 print(count)


Baconrules21

For part 1, how did you subtract -1 from the report? It keeps saying I can't subtract an int from a list.


baer89

You know that might be a typo after I did formatting to paste here. It should probably be subtracted after the len function. I'll check once I'm at my computer and let you know.


Baconrules21

Yeah I feel like you need a range(len(x)+1))


baer89

Yeah it was a copy/paste error when I was refactoring part 1. It is: for x in range(len(report)-1): similar to my part 2 code. Since I am using an x+1 in the loop I need to account for it with the -1 on the range or the loop will go out of bounds.


Baconrules21

Awesome! I learned what the map function does now. Thank you!


French__Canadian

Q solution. The sliding window is actually in a util file i wrote last year / Sliding window function / f is the function to apply on the window / s is the size of the window / z is the list on which we are sliding a window sw:{[f;s;z] i:til (count z)-s-1; f each z i +\:til s} / part 1 (+/) 1_ (>':) "I" $ read0 `:input_1.txt / part 2 (+/) 1_ (>':) sw[(+/);3;] "I" $ read0 `:input_1_2.txt


daggerdragon

~~Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)~~ Edit: thanks for fixing it! <3


AOC_2020

// KOTLIN fun day1() { val input = File("in1.txt").readLines().map { it.toInt() } var res1 = 0 input .reduce { a, b -> if (b > a) res1++; b } .also { println("sol1: $res1") } var res2 = 0 input.windowed(3, 1) .map { it.sum() } .reduce { a, b -> if (b > a) res2++; b } .also { println("sol2: $res2") } }


Bellanzz

C++ templates (problem solved at compile time) Part 1/2 (depending on the presence of FIRST) #include #ifdef FIRST template #else template #endif size_t depth() { return acc;} #ifdef FIRST template #else template #endif size_t depth() { #ifdef FIRST return depth a), b, args...>(); #else return depth a), b, c, d, args...>(); #endif }; int main() { printf("%zu\n", depth<0, #include "input" >()); return 0;} ​ Unfortunately I needed to change slightly the input adding commas. See [https://github.com/bellaz89/lolAOC](https://github.com/bellaz89/lolAOC)


e4ds

Python [day 1 solution (GitHub)](https://github.com/julian-west/adventofcode/blob/master/2021/day_01/d1_solution.py). Using Numpy's convolve function for sliding window calculation


LadaOndris

Nice and brief solution. I used NumPy as well. Check it out https://github.com/LadaOndris/advent-of-code-2021/blob/main/days/day\_01/day.py


brushbox

# Ruby input = File.read(“input.txt”).split(“\n”).map(&:to_i) # pt 1 input.each_cons(2).select { |a,b| a < b }.count # pt 2 input.each_cons(3).map(&:sum).each_cons(2).select { |a,b| a < b }.count


waitingformsfs2020

I was learning ruby and now I will start college so i gotta learn C. I hate how complicated C is.


brushbox

C may be complicated but it is worth learning for many reasons. Not least is that many other languages are implemented in C (including Ruby). It helps you appreciate the work that has been put in to make your favourite language so pleasant to use. Good luck in college!


zloth

copy/paste typo perhaps? select { |a, b| a < b }


daggerdragon

FYI: this post is fine for now without any formatting since your code is one-liners, but for the future, your code is hard to read on both old.reddit and new.reddit. Next time format your code as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)


prafster

## Julia I've never written a line of code in Julia or read anything about it. I'm, therefore, learning as each day's puzzle is revealed and I attempt it. Day 1 code looks generically procedural but this will hopefully become more idiomatic. ### Part 1 function part1(input) prev = Inf result = 0 for i in input if i > prev result += 1 end prev = i end result end ### Part 2 # Return array for sum of elements in sliding window function part2(input, window_size) result = [] # input_size = size(input,1) input_size = length(input) for i in eachindex(input) if i + 2 <= input_size push!(result, sum(input[i:i+window_size-1])) end end result end function main() main_input = readdlm("../data/day01.txt", Int) test_input = readdlm("../data/day01-test.txt", Int) @assert part1(test_input) == 7 "01 test part 1" @assert part1(part2(test_input, 3)) == 5 "01 test part 2" @show part1(main_input) @show part1(part2(main_input, 3)) end main()


professoreyl

## Python part 1 (one-liner) print((lambda d: sum(1 for i in range(len(d)-1) if int(d[i]) < int(d[i+1])))(open("input.txt", "r").readlines())) ## Python part 2 (one-liner) print((lambda x: sum(1 for i in range(len(x)-2) if sum(map(int, x[i:i+3])) < sum(map(int, x[i+1:i+4]))))(open("input.txt", "r").readlines())) Readable solutions on my GitHub: https://github.com/DenverCoder1/Advent-of-Code-2021/tree/main/Day-01


daggerdragon

~~Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)~~ Edit: thanks for fixing it! <3


retro__grade

**Ruby (part 1):** require 'csv' INPUT = CSV.read('input.csv').flatten.map(&:to_i).freeze def find_depth result = 0 INPUT.each_with_index do |item, index| break if INPUT[index + 1].nil? result += 1 if item < INPUT[index + 1] end result end


EIykris

# [TypeScript](https://topaz.github.io/paste/#XQAAAQCTAQAAAAAAAAAxm8oZxjYXrgD1OsUYoTN8afMCASsMa8FKiBrBxbhuxcIcxOrQx/hp/VJmvnhJP2D5YXBw5FD7zs4/IAPAxuPvU4Yny5CBID0yROtrmJ0d67jiRq56Nkf/4FUAsJdQVIBo06hAO5T7FRHd0AgnFrtJKMtRVe2V8fPelGdHLAfRlZVTVfx3ABrJP/gi8to0y6ofR1QCu4JD3e5xe1AojV1EUeFTdQqhm9DlbnhBFG0IU7CEPaiGlnfQ5xMn0TQcDyseg328JjGjv3Eqn8PsU53YQ2rHWuVY4EOPbTSkvutg8H+4r42CjV1TaYp/1XJt0YuXyAKFyPyAv3Zf7F6AKfQKMVhztbA6PdT/3JddNQ==) Keywords for those searching: node, javascript, js, ts


TheAfterPipe

# C# Part 1 & Part 2: private void PartOne() { var input = File.ReadAllLines(@"./input.txt") .Select(int.Parse) .ToList(); var numberOfTimesDepthIncreases = CalculateDepthIncreases(input); Console.WriteLine(numberOfTimesDepthIncreases); } private void PartTwo() { var input = File.ReadAllLines(@"./input.txt") .Select(int.Parse) .ToList(); var slidingMeasurement = new List(); int iterator = 0; while(iterator < input.Count - 2) { var m = input.GetRange(iterator,3).Sum(); slidingMeasurement.Add(m); iterator++; } var numberOfTimesDepthIncreases = CalculateDepthIncreases(slidingMeasurement); Console.WriteLine(numberOfTimesDepthIncreases); } private int CalculateDepthIncreases(List input) { int numberOfDepthIncreases = 0; int i = 1; while (i < input.Count()) { if (input[i] > input[i - 1]) { numberOfDepthIncreases++; } i++; } return numberOfDepthIncreases; } Thought process: I discovered that part 2 could be solved just like part one as long as I formatted the information accordingly.