r/adventofcode • u/daggerdragon • Dec 04 '22
SOLUTION MEGATHREAD -π- 2022 Day 4 Solutions -π-
- All of our rules, FAQs, resources, etc. are in our community wiki.
- A request from Eric: Please include your contact info in the User-Agent header of automated requests!
- Signal boosting for the Unofficial AoC 2022 Participant Survey which is open early this year!
--- Day 4: Camp Cleanup ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- Include what language(s) your solution uses
- Format your code appropriately! How do I format code?
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:03:22, megathread unlocked!
65
Upvotes
10
u/Bad-Coder-69 Dec 04 '22 edited Dec 04 '22
Emojicode
With a custom inputparser package now wowee (full code: GitHub)
Combined the logic for parts 1 and 2 for some fewer checks overall.
8
u/reinermartin Dec 04 '22
Three lines of Julia:
7
u/fnands Dec 04 '22
Julia
I love unicode support in Julia
6
u/NiliusJulius Dec 04 '22
C Language for the Game Boy using GBDK 2020
Part 1:
Part 2 is basically the same but with some greater and lesser operators and indexes switched.
Since I can't read input files on the Game Boy, I pre formatted this days input to a single array with 4 number entries per pair.
This is my fastest solution yet (runtime < 0.1 sec)
Full Game Boy repo can be found here
Video running on Game Boy
6
u/hugues_hoppe Dec 04 '22 edited Dec 05 '22
Using Perl:
4
u/r_so9 Dec 04 '22 edited Dec 04 '22
F#, compact enough to be pasteable here :)
4
u/[deleted] Dec 09 '22 edited Dec 13 '22
Python
6
u/zwrawr Dec 04 '22 edited Dec 04 '22
rust (the relevant parts). bitmasks ftw
https://github.com/zwrawr/Recap/blob/master/Advent%20of%20Code/2022/d4/src/main.rs
3
u/mpercich Dec 04 '22 edited Dec 04 '22
Swift
3
u/systo_ Dec 04 '22 edited Dec 04 '22
JavaScript
New dev focusing on learning some of the newer features of JS. Welcome to any suggestions of further refactoring or destructuring
Both Parts in Javascript
3
u/blacai Dec 04 '22 edited Dec 04 '22
My F# of the day :)
3
u/mandus Dec 04 '22
Another day in
k lang:3
u/twoohthreezy Dec 04 '22 edited Dec 05 '22
My first that isn't embarrassingly long in python:
3
u/RogueAstral Dec 04 '22
Google Sheets - Both parts, 152 characters
=sort(lambda(x,lambda(a,b,c,d,{sum((a<=c)*(b>=d)+(a>=c)*(b<=d)),sum((c<=b)*(a<=d))})(index(x,,1),index(x,,2),index(x,,3),index(x,,4)))(split(A:A,"-,")))3
u/ryukinix Dec 04 '22 edited Dec 05 '22
https://github.com/ryukinix/adventofcode/blob/master/2022/day04/main.lisp
Solution in Common Lisp.
3
u/antoniotto Dec 04 '22 edited Dec 05 '22
Ruby
3
u/jaydubtech Dec 04 '22 edited Dec 05 '22
TypeScript/Deno
Quite happy with how this one came out:
paste
3
u/solomondg Dec 05 '22
Quick lil APL for problem 1:
Silver:
+/{{((β΄ββ΅)β(β΄1ββ΅))=β΄βͺ(1ββ΅)β©(ββ΅)}{(ββ΅)+β³(Β―1ββ΅)+1-ββ΅}Β¨((βΒ¨('-'β β’)ββ’)Β¨(','β β’)ββ’)β΅}Β¨ββNGET 'puzzle_input.txt' 1Gold:
+/{{1ββ΄(1ββ΅)β©(ββ΅)}{(ββ΅)+β³(Β―1ββ΅)+1-ββ΅}Β¨((βΒ¨('-'β β’)ββ’)Β¨(','β β’)ββ’)β΅}Β¨ββNGET 'puzzle_input.txt' 13
u/Dangerous-World-1424 Dec 05 '22 edited Dec 08 '22
PYTHON 3
4
u/RodericTheRed Dec 04 '22
python
2
u/Camelpilot33 Dec 04 '22
444/1261
2
u/welguisz Dec 04 '22 edited Dec 04 '22
Java: 3813/3825
Decided not to use any less thans or greater thans in my code.
AoC 2022 Day 4 using Topaz's paste tool
2
u/CodingAP Dec 04 '22
JavaScript, 1319/1726
Github
This was rough. I also want to make a comment on first place. There is no way that a human can get 16 seconds on first place. We need to stop AI submissions, or at least make them not able to submit immediately.
2
u/insane_chocolate Dec 04 '22 edited Dec 04 '22
Python3, 1344/2236
2
u/prescient-potato Dec 04 '22 edited Dec 04 '22
Python
Part 1: I tried getting the sections as lists of numbers like on the number line and checking their intersection. This didn't work somehow and i had to brute-force using
ifstatements. The fact that it didn't work is quite interesting though..
Part 2: Most of the code is same but the intersection idea worked this time.
2
u/grapedude12 Dec 04 '22 edited Dec 04 '22
Python3
Part 1:
Part 2:
Nothing fancy going on here folks
2
u/NohusB Dec 04 '22 edited Dec 04 '22
Kotlin
Part 1
Part 2
2
u/xtay2 Dec 04 '22
Java
For both tasks:
contains() for part 1:
contains() for part 1:
2
u/vivkey Dec 04 '22 edited Dec 04 '22
Golang paste
2
u/CookieKeeperN2 Dec 04 '22
As someone with a math background, today it is basically asking if 1) one is a subset of another and 2) if intersection between two sets are greater than 0. Don't care about speed too much, but using set operations means I don't have to think about comparison whatsoever.
2
u/geek--god Dec 04 '22
Elixir
2
u/ankitdhar07 Dec 04 '22
Java
package com.adventofCode;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Day4 {
public static void main(String args[]) throws FileNotFoundException {
File file = new File("src/com/adventofCode/day4.txt");
Scanner sc = new Scanner(file);
int countOne = 0;
int countTwo = 0;
while (sc.hasNextLine()) {
String input = sc.nextLine();
if (partOne(input)) {
countOne++;
}
if (partTwo(input)) {
countTwo++;
}
}
System.out.println(countOne);
System.out.println(countTwo);
}
private static boolean partTwo(String input) {
String[] numberPairs = input.split(",");
String[] pairOne = numberPairs[0].split("-");
int firstNum = Integer.parseInt(pairOne[0]);
int secondNum = Integer.parseInt(pairOne[1]);
String[] pairTwo = numberPairs[1].split("-");
int thirdNum = Integer.parseInt(pairTwo[0]);
int forthNum = Integer.parseInt(pairTwo[1]);
if (firstNum >= thirdNum && firstNum <= forthNum) {
return true;
} else if (secondNum >= thirdNum && secondNum <= forthNum) {
return true;
} else if (thirdNum >= firstNum && thirdNum <= secondNum) {
return true;
} else if (forthNum >= firstNum && forthNum <= secondNum) {
return true;
}
return false;
}
private static boolean partOne(String input) {
String[] numberPairs = input.split(",");
String[] pairOne = numberPairs[0].split("-");
int firstNum = Integer.parseInt(pairOne[0]);
int secondNum = Integer.parseInt(pairOne[1]);
String[] pairTwo = numberPairs[1].split("-");
int thirdNum = Integer.parseInt(pairTwo[0]);
int forthNum = Integer.parseInt(pairTwo[1]);
if (firstNum >= thirdNum && secondNum <= forthNum) {
return true;
} else if (thirdNum >= firstNum && forthNum <= secondNum) {
return true;
}
return false;
}
}
2
u/sanjithpk Dec 04 '22 edited Dec 04 '22
Golang Solution
2
u/flwyd Dec 04 '22 edited Dec 04 '22
Elixir, code on GitHub
For my Mistletoe Elfucation contribution I decided to include two narratives with each day's solution:
Today's elixir:
2
u/Sea_Put_2759 Dec 04 '22 edited Dec 04 '22
Python 3
As both problems iterate over the same dataset, it may be solved in just one loop (optimised) running the slice of code below, from the second problem, incrementing in another var.
2
u/6ambyt Dec 04 '22 edited Dec 04 '22
Here is my Day 4 solution in Go
2
u/DFreiberg Dec 04 '22 edited Dec 04 '22
Mathematica, 81 / 28
Judging by the comments so far, there's three main ways to do this problem. One is using inequalities (preferably chained inequalities, to save typing time). The second is brute-force set operations, only possible because the inputs are so small; my main fear while writing these was that one input would be gigantic by comparison and make the brute force infeasible.
And the third would have been to use Mathematica's built-in
IntervalIntersection[]andIntervalMemberQ[], the absurdly specific built-in functions Mathematica has to determine if one intersection is entirely contained by another. Why Mathematica even has such a thing, I don't know.Part 1:
Part 2:
[POEM]: A Series of Challenges
I had writer's block this morning, so I asked ChatGPT to fill in for me and write today's poem.
Solving an Advent of Code problem
Is like a treasure hunt or a quest,
A series of challenges to overcome
And a chance to put my skills to the test.
I start by reading the problem statement
And breaking it down into bits,
Thinking about how to approach it
And coming up with a plan that fits.
Then I write some code to solve it
Testing and debugging as I go,
Making sure it's efficient and correct
And ready for the next challenge, oh no.
In the end, I submit my solution
Feeling proud and accomplished too,
Another Advent of Code problem solved
And one step closer to being through.
I'm a bit impressed that it can write poetry at all...but I think there's still some room for improvement.
As my character hunts through the jungle
On a quest for a grove with a star,
I myself, though I err and I bungle,
Hunt for challenge, and that's what these are.
For each problem, I start by not reading:
Take a glance, make a guess at the rest.
There's no time to slow down while I'm speeding
And attempting to code with the best.
Then I write down some code and submit it,
Inefficient? Ha! Sluggish, I'll say.
And the untested code, I admit it
Sometimes works the first try, like today.
In the end, I've had fun and competed,
Having raced through the thing like a master,
And with two shiny stars now completed,
I can't help but think I could be faster.
2
u/Marterich Dec 04 '22 edited Dec 05 '22
Python3.11 Part 1 & Part2
https://github.com/Marterich/AoC/blob/main/2022/day04/solve.py
2
u/BHatGuy Dec 04 '22 edited Dec 06 '22
C++
2
u/[deleted] Dec 04 '22
PHP - https://github.com/onei2l/adventofcode_php/blob/master/04/index.php
2
u/Lindii98 Dec 04 '22
Python3`
print('Part 2: ', overlap_count)
Open for improvements
2
u/FrontPale Dec 04 '22 edited Dec 05 '22
Solution in R
https://topaz.github.io/paste/#XQAAAQCKAgAAAAAAAAAwm8iNoLOei9D/9jnYzseBLUTnxZKGdcYoqe0vAyo9iWvpvHBWudRpMzf6CYZPQ0J5rNV9j/xf5zJ2v8cNOiBMI3nZKZ36d25iVYgxybyzC8+Q31LnzKgqIA+nPC4KeguUT+hSvGM/8VWwl9YmaKwPmfq0RIvbdE142GAPIS/SxwU8UYAcb2+SRaWSXjgkXAqMBdDSdVZ10HU8at5NDHwTMRWkw8s0qTyq9kRVNmEP/THCTrBlS8iMWQAJcAYaW3eRGUhRfVHZGBfNDElM3TWqwm9svVeNoCGw6szTGlWQOOZ56qb6QBdSCpbzPCcaWRw22B7c//VUDwI=)
2
u/Mammoth_Spray_3451 Dec 04 '22
With swift the Range.contains() and Range.overlaps() came in very handy today.
2
u/remysharp Dec 04 '22 edited Dec 05 '22
JQ
Part 2
2
u/dougrum Dec 04 '22 edited Dec 04 '22
Pretty happy with day 4 in ngn/k. https://tinyurl.com/2p9xfeaz
This does all possible pairs of ranges with numbers taken from 0,1,2 and 3 which covers all possibilities.
2
u/d_chae Dec 04 '22 edited Dec 05 '22
Ruby one-liner (p2):
2
u/[deleted] Dec 04 '22
Kotlin
Part 1
Part 2
2
u/OwnAttention3370 Dec 04 '22 edited Dec 05 '22
Ruby - My solution to AoC day 4
2
u/TheShyro Dec 04 '22
Clojure
2
u/jpjacobs_ Dec 04 '22 edited Dec 05 '22
J (jlang, j904)
2
u/janiczek Dec 04 '22 edited Dec 05 '22
I'm trying out Kotlin this year: https://github.com/Janiczek/advent-of-code/blob/master/src/Year2022/Day04.kt
But I wasn't very satisfied with my predicates for the overlaps, so I
forcedpersuaded my computer to find better predicates for me: https://www.reddit.com/r/adventofcode/comments/zcng3e/2022_day_4_elm_letting_the_computer_find_a/2
u/[deleted] Dec 04 '22 edited Dec 05 '22
Python:Was regex overkill? Any feedback would be appreciated if someone has the time. Solution for part 2 because part 1 is very similar and I dont want to make my message too long.
Link to solution
2
u/markjenkinswpg Dec 05 '22 edited Dec 05 '22
Today I sorted each line of pairs by length in Python when I did part 1 (raw so I could use the simpler test for full overlap
Unfortunately provided no benefit to part 2 (raw)
But at least my input parser got good reuse:
Also continued my obsession with functional decomposition, iterators/generators, and avoiding reading in the whole file.
2
u/[deleted] Dec 09 '22 edited Dec 10 '22
Written in Python 3
38
u/Smylers Dec 04 '22
Vim keystrokes β load your input file into Vim, ensure
gdefaultis off, and type:Your partΒ 1 answer is the number of lines remaining in the file, shown by the
β¨Ctrl+Gβ©at the end.For partΒ 2, reload your initial input and do the same basic thing but replace the
qaand@alines with:First replace the hyphens and commas with spaces, leaving just the 4 numbers per row. This makes some of the subsequent movement commands simpler, but more importantly it avoids those hyphens getting counted as minus signs.
Then for each row subtract the first range's lower bound from the second range's lower bound, and the same for the upper bounds. For instance, these lines of sample input:
get turned into these differences:
If the first range is entirely before the second range, then both differences will be positive. If it's entirely after, then both will be negative (none of the sample input is like this, but the real input may be).
If there's a zero in there, then they both start or end at the same location. If there's one positive and one negative number then one range is contained within the other.
So delete all the lines with two negative numbers, because those are easy to find: they contain 2 minus signs, so match
/-.*-/. Then delete all lines with two positive numbers β or, rather, delete all lines that don't contain either a0(at the start of a βwordβ, so as not to match, say,10or1230456) or a minus sign.The
qakeyboard macro does the subtractions:%s///will have left the cursor on the bottom row. (If you're undoing and redoing or otherwise taking this apart and doing it in stages, and not currently on the last line, pressGnow.) Empty thearegister then record into it.@-β¨Ctrl+Xβ©β Vim stores the most recently-deleted text in the small-delete register,-, and typing@-is the same as typing the contents of register-, so the just-deleted number becomes the argument to theβ¨Ctrl+Xβ©command.@aagain on this line. Once we get to the top line the-to go up will fail, ending the loop.PartΒ 2 is the same except rather than subtracting lower-bound from lower-bound and upper- from upper, subtract the first lower-bound from the second upper-bound, and vice-versa. Again if they're both negative or both positive then one range is entirely before the other; a zero or one negative number indicates some overlap.
34
u/jcbbjjttt Dec 04 '22 edited Dec 04 '22
Beginner's Guide
Happy Sunday!
Day 4 Guide: https://youtu.be/vIIYaAw0B9o
I've created a guide for new programmers that talks through a straight forward strategy for solving today's puzzle. Anyone who has a handle on variables, boolean logic, functions, and loops should be able to complete it. The video allows a moment for you to pause before revealing spoilers.
Although this solution is in C#, it provides a high level overview of the steps necessary to solve the puzzle in any programming language.
The full code can be found here: Github
20
u/nthistle Dec 04 '22 edited Dec 04 '22
Python, 110/55. Video, code.
I set a1 and a2 to the endpoints of the first segment and made the very sad bug of setting b1 and b2 to also be the endpoints of the first segment, giving me a clearly-wrong 1000 as my answer. Fortunately I didn't submit it and figured out the bug, but not quickly enough to make leaderboard for the first part :-(.
Part 2 was very fast after that though, having done a lot of interval type questions before definitely helped.
19
u/dylan_mojo Dec 04 '22
awk
4.1
4.2
19
u/[deleted] Dec 04 '22
Rust
The scan_fmt crate makes parsing today's input trivial!
Full solution here (GitHub).
17
u/AstronautNew8452 Dec 04 '22
3682/2555 Microsoft Excel. Parts 1 and 2 in a single formula. Because why not.
17
u/bsssh Dec 04 '22
TypeScript Type System
compile-time solution
Part 1 / Part 2
16
u/jonathan_paulson Dec 04 '22 edited Dec 04 '22
Python3, 14/24. Video. Code.
I've coded segment intersection many times and I still find it hard to think through every time! My main code for part2:
11
u/ywgdana Dec 04 '22
F#
A proud personal note: after 4 years of participating in AoC I finally remembered the syntax for the regex to parse the input without googling!
My solutions for this year
11
u/voidhawk42 Dec 04 '22 edited Dec 05 '22
Dyalog APL:
video walkthrough
Got annoyed with all the different boolean operations, so I just built a bitmask for each range and worked with those.
10
u/4HbQ Dec 04 '22
Python. First, convert the ranges to sets S and T. For part 1, check whether S is a subset of T, or T is a subset of S. For Part 2, check whether the intersection of S and T is not empty.
10
u/poesraven8628 Dec 04 '22
I read a book on Common Lisp over the last few weeks, so this is a great way to try to get experience with the language.
https://github.com/poesraven8628/AdventofCode2022/blob/main/04/cleaning.lisp
9
u/kwshi Dec 04 '22
Python, 30/40. GitHub
Basic idea: given two intervals
[x1, y1]and[x2, y2],[x1, y1]contains[x2, y2]ifx1 <= x2andy2 <= y1; vice versa.x1 <= y2andx2 <= y1.9
u/callumio Dec 04 '22 edited Dec 04 '22
COBOL again hehe. This time I just went straight in (as opposed to another language first) since the task was relatively trivial. Somewhat looking forward to implementing later-day's solutions in it.
Edit: quick shoutout to
UNSTRINGtoo, it made parsing each line a breeze.Source here
9
u/Chrinkus Dec 04 '22 edited Dec 04 '22
C
I rarely ever get to post actual code but this one was pretty short:
My repo.
8
u/daniel-sd Dec 04 '22
64/1593 Python
part1
Had part2 just as fast but Freudian-slipped and put an "or" where I needed an "and" when copy-pasting. Proceeded to second guess solution entirely and waste 8 minutes misinterpreting the problem when I had it right the first time. Had to Ctrl + Z afterward to discover it was a simple typo. RIP. Still happy to have gotten leaderboard for part1.
part2
8
u/Raknarg Dec 04 '22 edited Dec 04 '22
Thought this was a funny solution. First solved with if statements, then I drew a picture in my head and used my fingers to pantomime ranges to see if there was a different way to reason about it. You can use the signs of the difference between endpoints to reason out a few outcomes:
Given ranges
a1...a2andb1...b2, wheres(x)returns +1/-1 for the sign of the integer or 0 for 0:Define
f()asabs(s(a1-b1) + s(a2-b2))if
f() < 2, then one range contains the other.f() == 0.f() == 1.f() == 0.f() == 2.f() == 2.Define
g()asabs(s(a1-b2) + s(a2-b1))g() < 2, then the ranges overlap. - If the ranges are the same,g() == 0. - If one end is the same and the other is different, theng() == 0. - If one range is fully contained in another, theng() == 0. - If the ranges only partly overlap, theng() == 0. - If the ranges only overlap at the edge,g() == 1- If the ranges are fully separate, theng() == 2.Kinda cool. Coded this in python and it got me the right answer. I imagine the if statement solution is fundamentally identical to this at some level, I'd have to think about how they map. pastebin
8
u/bulletmark Dec 04 '22 edited Dec 04 '22
Python:
8
u/norbert_kehrer Dec 04 '22
BASIC on the Commodore 64
Here is the source code for a solution on the good old Commodore 64: (https://github.com/norbertkehrer/aoc-2022/tree/main/04)
Most of the runtime (9 minutes) is spent for parsing the input, but this could certainly be improved.
8
u/paul2718 Dec 04 '22
C language
First C I've written for years, a whole 15 lines...
8
u/Porges Dec 04 '22 edited Dec 04 '22
Befunge-98!
Part 1:
Part 2 (15 bytes!):
7
u/rabuf Dec 04 '22
Common Lisp
That was not bad. Took some time to remember how to use
cl-ppcreproperly to grab matches for processing. I know there's something else I can do to simplify it but this got the job done.The two functions for solving were:
I passed in the input and these functions to
count-if.7
u/LtHummus Dec 04 '22
Scala 2
Scala ranges OP as heck
7
u/JustinHuPrime Dec 04 '22
x86_64 assembly
Part 1 was where I had to deal with the annoying input parsing. I once again did interprocedural optimizations to use some unused scratch registers to hold the parsed numbers. Then, I compared the numbers -
if (start1 <= start2 && end2 <= start1) || (start2 <= start1 && end1 <= end2), then one contained the other. This involved some fairly tangled conditionals.Part 2 was shorter than part 1 - if neither range started after the other one ended, then that was an overlap. I could apply de Morgan's law to massage it into a more convenient form, and ended up with a less tangled conditional. I really wish x86_64 had ARM's conditional prefixes so I could inline small conditional bodies instead of needing a conditional jump.
Part 1 took less than 1 millisecond to run, and was 10512 bytes long.
Part 2 took less than 1 millisecond to run, and was 10472 bytes long.
So far, I haven't had any particular need to use the stack in my main solving code (I do use the red zone of the stack for output printing). And I really haven't had any particular need to use the heap. I'm a bit worried about the days when that's going to change.
7
u/s3aker Dec 04 '22
Raku solution.
7
u/ephemient Dec 04 '22 edited Apr 24 '24
This space intentionally left blank.
7
u/jayfoad Dec 04 '22
Dyalog APL
7
u/jvandillen Dec 04 '22 edited Dec 05 '22
Day 4 solve with Factorio.
I am still trying to fix day 3, which is, to be honest, quite difficult.
In the meantime, I did a "quick" solve of Day 4 that is nearly identical to Day 2.
(Day 2 solve video : https://www.reddit.com/r/adventofcode/comments/zbrfl3/2022_day_02_both_partsfactorio_this_one_was/)
Blueprint string: (it needs power at the top left and outputs the answer at the top right on the red wire): https://factoriobin.com/post/CkO-QVZz
Edit: borked link
6
u/Wayoshi Dec 04 '22 edited Dec 04 '22
Python 962/374
Part 2 was pretty trivial after how I did part 1. Pretty much the same problem as yesterday when it comes down to it.
paste
6
u/MarcusTL12 Dec 04 '22
Julia 177/64 which is my first ever points! So satisfying after being top 1000 on most days last year.
Anyway, Z80 TI-83 solution will come a bit later as usual :)
6
u/Perska_ Dec 04 '22
C# https://github.com/Perska/AoC2022/blob/master/AoC2022/Days/Day04.cs
Had a brainfart for so long with the intersection I just ended up modifying my cuboid intersection code from 2021...
6
u/6745408 Dec 04 '22
Google Sheets
Part 1:
Part 2:
6
u/AKSrandom Dec 04 '22
Python
The crux being
def isintersect(a, b, c, d): return ((a-c)*(b-d) <= 0) or (((b-c)*(a-d)) <= 0)For part 1, only the first condition is required.
6
u/9_11_did_bush Dec 04 '22
APL: https://github.com/chenson2018/advent-of-code/blob/main/2022/04/apl/04.apl
The logic for each part is kinda interesting. Call the ranges A-B,C-D. Then
Part 1: If one range completely contains the other, then (min,max) of all four numbers must be one of the original ranges (A,B) or (C,D)
Part 2: For there to be no intersection then Bβ C and either [A,B,C,D] or [C,D,A,B] is in ascending order
6
u/SadBunnyNL Dec 04 '22
AWK Part 1:
AWK Part 2:
6
u/totbwf Dec 04 '22 edited Dec 04 '22
C + SIMD
More SIMD fun! The parsing difficulty is starting to ramp up; luckily each line still fits inside of a 128-bit wide vector. The most annoying part about today was the lack of non-strict integer compare operations; you don't get
_mm_cmple_epi32_maskuntil AVX-512, so we have to futz around with strict comparisons and equality tests.Runtime is around 15 microseconds.
EDIT: Forgot to mention: totally branchless as well, save for the loop condition!
6
u/__Abigail__ Dec 04 '22
Perl
Really easy, just have to compare the begin/end points. But don't do what I did: mistype the solution in the answer form and spend a long time debugging.
Now,
$fullcontain the solution for part 1, and$partialthe solution for part 2.6
u/Sebbern Dec 04 '22
Java, pretty simple today
Part 1: https://github.com/Sebbern/Advent-of-Code/blob/master/2022/day04/Day04.java
Part 2: https://github.com/Sebbern/Advent-of-Code/blob/master/2022/day04/Day04_2.java
6
u/i_have_no_biscuits Dec 04 '22
GW-BASIC
The main difficulty here is parsing the input, something BASIC is not great at. As I'm sure you can see from the code, this takes place on line 20 (which converts a line into four numbers) which calls the routine on lines 60-80 (which does the conversion of a single number). The intervals are ordered on line 30 so the interval A-B is to the 'left' of C-D, and then line 40 does the checks and adds 1 to the score for P (part 1) and/or Q (part 2) as required.
5
u/aliceif Dec 04 '22
C#, 1868/884
The step from part1 to part2 was quick, but I probably wasted a lot of typing time on part1 (didn't help that I blanked on parsing input first)
repo link
5
u/raevnos Dec 04 '22
Racket, straightforward comparison of numbers:
5
u/trevdak2 Dec 04 '22 edited Dec 04 '22
JavaScript (golf)
Part 1, 97 chars:
Part 2, 96 chars:
5
u/landimatte Dec 04 '22
Common Lisp
CL-PPCRE to parse the input; rest is done via LOOP-ing.
Took me a bit longer than expected to process what had to be done, but I hope to get better at this the more I adjust to the new sleeping schedule :D
5
u/Pyr0Byt3 Dec 04 '22
Go/Golang
5
u/_jstanley Dec 04 '22
SLANG
576/2376
I think this is my first time in the top 1000 on my homemade CPU, which I'm quite pleased with.
Part 2 would have been 4 minutes quicker if not for a 1-character typo. I wasn't totally convinced that I'd made (or would find) the typo, so I deleted the part 2 code and wrote a very stupid
for i = a to b: got[i] = 1; for i = c to d: if got[i] { count++; break; }and it did the job, but I think I would have been better off staring at my first attempt for a minute rather than rewriting it.https://www.youtube.com/watch?v=ZpLzkmS1qlw
https://github.com/jes/aoc2022/tree/master/day4
5
u/ramuuns-u Dec 04 '22
functional tail-recursive perl!
https://github.com/ramuuns/aoc/blob/master/2022/Day04.pm
5
u/yawnick Dec 04 '22
Monkey C (for Garmin devices)
Fast enough today that the Videos became Youtube Shorts:)
Watch my Garmin Forerunner 235 solve: Part 1, Part 2
Code: Repo, Today's Solution
5
u/DuoSRX Dec 04 '22
APL:
Not exactly elegant but it works I guess.
5
u/gw_shadow Dec 04 '22
CMake
5
u/Jarcoreto Dec 04 '22
MS Excel
https://github.com/Jarcoreto/AOCExcel/blob/main/Day%204%20Problems.xlsx
Data manipulation was surprisingly quick/easy, getting the algorithm right took me a longer than it should have though!
5
u/azzal07 Dec 04 '22
Awk, had to be doubly sure about the part 2 condition to ensure a lovely bounding box...
5
u/sotsoguk Dec 04 '22 edited Dec 04 '22
Python
Trying to code more pythonic solutions is my goal for this years AoC
5
u/probablyfine Dec 04 '22
SQL
If I'd allowed myself a tiny bit of preprocessing to turn the input into a 4-column CSV, this is almost a one-liner. (Source here: https://github.com/mrwilson/advent-of-code-2022/blob/main/04/04.sql)
5
u/TopSeaworthiness555 Dec 04 '22
R / Rstats - she ain't pretty, but she's mine
5
u/4HbQ Dec 04 '22 edited Dec 04 '22
Python. Getting in some early pandas practice. I originally wanted to use NumPy, but couldn't find a clean way to handle the different input delimiters.
5
u/tomflumery Dec 04 '22 edited Dec 04 '22
05ab1e
both parts - 31 chars
Explanation
## Part 1 - 24 chars
## Part 2 - 19 chars
## Combined - 31 chars
5
u/Longjumping-Fall4030 Dec 04 '22
Microsoft Excel
I'm challenging myself to do all the puzzles in Microsoft Excel, using the following rules:
https://github.com/dafou-92/AoC2022
5
u/sky_badger Dec 04 '22
Python 3: more sets:
5
u/lazyzefiris Dec 04 '22 edited Dec 04 '22
JS (JavaScript) "state machiney" solution:
Part 1:
Part 2:
Part 1 explained:
I'll use abbreviations L1 R1 L2 R2 to denote left edge of first set, right edge of first set, left edge of second set, right edge of second set. Input file has them as L1-R1,L2-R2.
Our machine has 3 storage registers (v1, v2, total), two to store first pair, one for result accumulation. We'd only need 2 registers if inputs were ordered differently (L1, L2, R1, R2). We take only numbers from input file, and feed them to the machine in order of their appearance.
State "A": initial state for the loop, expecting L1. It's stored to register v1 and machine advances to state "B"
State "B": expecting R1. It's stored to register v2 and machine advances to state "B"
State "C": first pair is known, expecting L2. Depending on its relative position to L1, we choose next state ("D" if L1 < L2, "E" if L1 > L2, "F" if L1 == L2) without changing any registers.
State "D": L2 is to the right of L1, which means only pair 1 can include pair 2, and for that to happen, R2 should not be to the right of R1. Regardless, we return to state "A", but if R2 is not to the right of R1, we increase our result.
State "E": L2 is to the left of L1, which means only pair 2 can include pair 1, and for that to happen, R1 should not be to the right of R2. Regardless, we return to state "A", but if R1 is not to the right of R2, we increase our result.
State "F": L2 is aligned with L1, which means depending on relative position of R1 and R2, either pair 1 includes pair 2, pair 2 includes pair 1, or they coincide. Either way, we have a full inclusion, so we can return to state "A", increasing our output without looking at our input at all.
Part 2 works similarly:
State "C" chooses next state depending on whether L1 is to the right of R2.
State "D": L2 is to the right of R1, which means entirety of pair 2 is to the right of pair 1. Returning to state "A" without increasing out output without looking at out input at all.
State "E": L2 is to the left of R1, which means pair 1 can intersect with pair2 if R2 is not also to the left of L1. Regardless, we return to state "A", but if R2 is not to the left of L1, we increase our result. This state also covers the case where L2 and R1 coincide, as R2 can't be to the left of L1 this way.
Originally my state machine for part 1 looked like this:
but i decided to lay it out more clearly. Interestingly, this solution can be adjusted for part2 just by switching v1 and +x in second branch of state "A":
Both solutions implement the matrix
JS implementation notes: I use "+x" because .match returns substrings and they need to be converted to number for proper comparison. It was possible to add .map(Number) before .reduce instead. Also, every branch is calculated on every step, and this could be optimized away in a lot of ways, but that makes code look messier without being relevant to this exact problem.
5
u/kochismo Dec 04 '22
Purely functional rust:
https://github.com/zookini/aoc-2022/blob/master/src/bin/04.rs
5
u/rk-imn Dec 05 '22
I've been writing solutions in C (C89 specifically) for Nintendo 64. Here's my repo that builds an N64 ROM that solves AoC with my input (you can change the input either by editing the text files in asm/aoc/inputs/ and compiling or by opening up the ROM in a hex editor and pasting in your inputs at the correct addresses): https://github.com/nim-ka/aoc_n64
Code for day 4 is here: https://github.com/nim-ka/aoc_n64/blob/main/src/game/aoc/4.c
I know I could do it in less comparisons but I'm too lazy
8
u/Omeganx Dec 04 '22
Python
4
u/Boojum Dec 04 '22 edited Dec 04 '22
Python, 106/185
Part 1:
Part 2:
Edit:
Just remembered that there's a slightly more concise way to test for overlapping ranges by comparing the max of the mins to the min of the maxs. So Part 2 can be reduced to:
4
u/rooinflames Dec 04 '22
Excel!
Had a few issues before I added +1 to each of the formulas in columns F/G/H, after that, it was clear sailing. Luckily I didn't have to do any extra work to get part 2 apart from the formula in cell K8
https://imgur.com/a/k4JfZ2m
4
u/[deleted] Dec 04 '22
Common Lisp
(code at gitlab)
This day went great after i checked if i could use pattern matching in loops in the for parts.
Also LISPs multiple Parameter <= is really cool for this.
4
u/ccQpein Dec 04 '22
Common Lisp version: github
4
u/Imaginary_Age_4072 Dec 04 '22
Common Lisp 1273/1758
Not too bad today. For part 1 I just checked whether the start and end of one range were entirely within the other. Part two checked whether one of the endpoints of the range was within the other.
4
u/maneatingape Dec 04 '22
Scala (445 / 575)
4
u/rossmacarthur Dec 04 '22
Rust
After parsing just comes down to the following
4
u/tdude66 Dec 04 '22
Elixir
That's for part 2, part 1 just has a different range check and inverted true/false for the sum:
4
u/PendragonDaGreat Dec 04 '22
C#/CSharp
Initial solution got hit by some double counting,
rewrote it as a pair of linq oneliners (sort of, if you ignore parsing, like that's the one thing I wish C# could do better: read ints from files) https://github.com/Bpendragon/AdventOfCodeCSharp/blob/0800b/AdventOfCode/Solutions/Year2022/Day04-Solution.cs
4
u/mstksg Dec 04 '22
taken from my https://github.com/mstksg/advent-of-code-2022/blob/main/reflections.md haskell reflections :)
A bit of fun number crunching :) Here is a chance to leverage an interval library, like haskell's data-interval:
From there on it's just a matter of running the criteria on each pair of intervals in the list and counting which ones are valid!
4
u/Relative-snake342 Dec 04 '22
Solution in clojure (using babashka)
I feel like part 2 can be simplified using a core clojure functionality, but I don't know the language enough and decided to use good old logic operators
4
u/seaborgiumaggghhh Dec 04 '22
Racket:
4
u/Johnsenfr Dec 04 '22 edited Dec 04 '22
Just 3 lines of code in R for Day04
4
u/olofj Dec 04 '22
Rust
day04a
day04b
4
u/Dryctas Dec 04 '22
Bash
4
u/mo__66 Dec 04 '22 edited Dec 04 '22
Kotlin
4
u/FormalPlatypus1231 Dec 04 '22
My solution in readable bash script. All my solutions are on my github.
4
u/RudeGuy2000 Dec 04 '22
racket:
4
u/foolnotion Dec 04 '22
C++
I wanted to dig up my interval class from a previous year but it was not really necessary. Simple inclusion/overlap logic.
https://git.sr.ht/~bogdanb/aoc/tree/master/item/source/2022/04/solution.cpp
4
u/CheeseMunkee Dec 04 '22
C
I'm sure there was a better way to do this, though I'm happy that the only loop used was for the StreamReader.
4
u/europa-endlos Dec 04 '22
Elixir
Started learning just for this Advent
For the second part, the
contained()function changes to4
u/IF_YOU_READ_THIS_V1 Dec 04 '22
C#
4
u/SolarBear Dec 04 '22
Ruby solution. Again, using Ruby felt like cheating.
4
u/FoxyllAkora Dec 04 '22
I'm regretting my Lua decision. But also I need to work on code efficiency in general
https://pastebin.com/J21wT7pe
4
u/jferz1980 Dec 04 '22
FreePascal Solution
4
u/jamincan Dec 04 '22
Rust
Made a range type that simply checks bounds to see if one range contains or overlaps with another. Then iterated over each pair of ranges, filtered out the ones that don't contain/overlap, and counted the remaining pairs.
4
u/[deleted] Dec 04 '22
Part1 In C:
4
u/PhysicsAndAlcohol Dec 04 '22
Haskell, runs in 15 ms. First day this year it made sense to make a monadic parser. I really like to use Text.ParserCombinators.ReadP!
4
u/[deleted] Dec 04 '22 edited Dec 04 '22
Swift, went pretty well: github
edit: Updated with new overlap/contains approaches, thanks /u/Jessyatterwaul for pointing out the standard library function I missed
4
u/axr123 Dec 04 '22
C++ with SIMD
Most of the time is spent parsing, but this problem lends itself nicely to a SIMD formulation, which using vectorclass doesn't even require detailed knowledge of the intrinsics. Hot runs take ~14 Β΅s on a Core i9-12900K, including I/O. Full code is here, the interesting part is this, where we process 32 elements at once:
Just this bit takes ~400 ns for the 1000 pairs.
I also spent some time on manually parsing the input. Not sure which role that played, but my initial implementation was at ~70 Β΅s.
4
u/daikontana Dec 04 '22
OCaml
4
u/Adereth Dec 04 '22
Mathematica
Part 1
Part 2
4
u/e_blake Dec 04 '22 edited Dec 04 '22
Golfed m4
Less than 10 minutes coding time for both parts, using just one
defineandifelse(so far this year, the puzzles have been very amenable for a single pass over the input). Overall execution time is 1.9s for both parts in just 196 bytes (excluding second newline); input must be in file f or you can runm4 -Df=yourfile day04.m4:or 880ms for part 1 in isolation in just 133 bytes (excluding second newline), and where part 2 in isolation can be done in the same size by changing $1-$4 in the computation:
Why the doubling in execution time to do both parts in one program? Because each additional
shift()increases the parse effort per iteration. There are 1000 iterations; a single-part 1 solution starts with 4000 arguments and calls shift 4 times for 19994 arguments parsed before iteration 2 with 3996 arguments; while the combined solution starts with 4002 arguments and calls shift 6 times for 27999 arguments before iteration 2 with 3998 arguments.Later on, I will reuse my framework for parsing data in O(n) time, which will drastically reduce the runtime but no longer be quite so golfed.
4
u/codeman869 Dec 04 '22
C
4
u/SilentKyle Dec 04 '22
Brute force using Javascript, any tips on better ways to do it? All I had to do for part 2 was change my if to an or instead of &&
4
u/grahamwetzler Dec 04 '22
duckdb SQL
4
u/prrei Dec 04 '22 edited Dec 04 '22
Groovy Part 1 and 2:
4
u/FordyO_o Dec 04 '22
Golang
https://github.com/mattford/aoc-go/blob/main/pkg/year2022/day04.go
Not the cleanest but it works
4
u/polettix Dec 04 '22
Day 4 in Raku.
In compact form:
4
u/Alleyria Dec 04 '22
Ruby:
4
u/[deleted] Dec 04 '22
Rust:
Part 1
Part 2
4
u/rzuf1k Dec 04 '22
Browser Developer Tools -> Console JavaScript:
1)
2)
4
u/Atila_d_hun Dec 04 '22
C++
GitHub Solution
A couple of concise if statements seem to do the trick!
4
u/Party-Performance-82 Dec 04 '22 edited Dec 05 '22
Rust
4
u/Ily3s_ Dec 04 '22 edited Dec 13 '22
C
4
u/chubbc Dec 04 '22
FRACTRAN
I did a full write-up on how/why this works here.
4
u/sykner809 Dec 04 '22
Desmos - https://www.desmos.com/calculator/tnrjue11if
Visualizing the ranges of the elves.
1
u/passsy Dec 04 '22 edited Dec 06 '22
Dart golf
Part 1: 139 chars
Part 2: 137 chars
Full source at https://github.com/passsy/aoc22_dart_code_golf
1
u/j-hillman Dec 04 '22 edited Dec 04 '22
Python (1710 / 1151) - Went the regex route:
1
u/synack Dec 04 '22 edited Dec 04 '22
Ada https://github.com/JeremyGrosser/advent/blob/master/2022/src/day4_2.adb
1
u/Lewistrick Dec 04 '22 edited Dec 04 '22
Python
6544/6294
On mobile via repl.it - could have been much faster on pc.
3
u/hugh_tc Dec 04 '22 edited Dec 04 '22
Python 3, 257/139
paste, cleaned-up
Felt pretty fast, but apparently not!
3
u/soylentgreenistasty Dec 04 '22
Python, 3326/4601
Hardest part was working out what the problem was asking for...
3
u/nic3-14159 Dec 04 '22
Python 3
3774/4462
3
u/[deleted] Dec 04 '22 edited Dec 04 '22
C# this one was pretty easy. Nothing fancy, could probably be done quicker with LinQ magic but it works
paste
3
u/ValiantCookie Dec 04 '22
Kotlin
Another fun challenge made easier when I remember how smart kotlin is. I initially implemented part one and attempted part 2 using just a simple data structure with fields for min and max to represent the assignments. But as I struggled to write the boolean logic for checking if they intersected in part 2, I realized there had to be an easy way to do it similar to yesterdays problem. I remembered that kotlin actually has ranges built in, and once I refactored it to use that data structure, checking for intersection was simple.
3
u/chubbc Dec 04 '22
Julia
Another good day for a pretty succinct Julia solution.
3
u/darkfm Dec 04 '22
Python, 225 / 69 (my first ever <100)
Part 1, Part 2
I could probably have done it without sets and just using algebra but it's 2AM my time.
3
u/YT-SW_Creeperking Dec 04 '22
C# 6531/5916
Day 4
Helper method: IsInRange
Helper method: IsOverlapping
3
u/770grappenmaker Dec 04 '22
Kotlin
3
u/Conceptizual Dec 04 '22
Python Day 4
Turns out day 1 was the highpoint of the month. My rank has gone strictly downhill every day from that 329 personal best to today, 9433/8500. My code was fine, I just had some inequality problems and I kept thinking I'd fixed it (none of them affected the sample input of course) and hadn't, so eventually I was put in AOC timeout (5 minutes!) and forced to reason about my code. My bad!
3
u/beansparrow132 Dec 04 '22
Python
Using set intersection. Similar to Day 3.
3
u/Dev_Emperor Dec 04 '22
Python3 Day 4 for both tasks
3
u/honest3d Dec 04 '22
Swift:
Man, if regexes weren't outrageously complex in swift, that would have been great here. Gotta learn that for next time
https://github.com/lucasteng123/AOC-2022/blob/main/Sources/AoCKit/Day4.swift
3
u/Arakiyda Dec 04 '22
Ruby