importjava.io.Fileimportjava.lang.Exceptionconstvalfilepath="day5.txt"funmain(){valseats=File(filepath).readLines().map{line->line.map{ch->if(chin"BR")"1"else"0"}.joinToString("").toInt(2)}valmin=seats.minOrNull()?:throwException("Min not found")valmax=seats.maxOrNull()?:throwException("Max not found")valyourSeat=IntRange(min,max).firstOrNull{it!inseats}?:throwException("Seat not found")println("Highest seat number: $max\nYour seat number: $yourSeat")}
I was curious to know if Python would let you execute a lambda immediately by wrapping it with parens and giving it the input, such as (lambda)(input) and ... sure enough you can. As such, I present this monstrosity in 1 line:
IDENTIFICATION DIVISION.
PROGRAM-ID. AOC-2020-05-1.
AUTHOR. ANNA KOSIERADZKA.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INPUTFILE ASSIGN TO "d5.input"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD INPUTFILE.
01 INPUTRECORD PIC X(10).
WORKING-STORAGE SECTION.
01 FILE-STATUS PIC 9 VALUE 0.
LOCAL-STORAGE SECTION.
01 I UNSIGNED-INT VALUE 1.
01 SEAT-ID UNSIGNED-INT VALUE 0.
01 ID-MAX UNSIGNED-INT VALUE 0.
PROCEDURE DIVISION.
001-MAIN.
OPEN INPUT INPUTFILE.
PERFORM 002-READ UNTIL FILE-STATUS = 1.
CLOSE INPUTFILE.
DISPLAY ID-MAX.
STOP RUN.
002-READ.
READ INPUTFILE
AT END MOVE 1 TO FILE-STATUS
NOT AT END PERFORM 003-PROCESS-RECORD
END-READ.
003-PROCESS-RECORD.
MOVE 0 TO SEAT-ID.
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 10
COMPUTE SEAT-ID = SEAT-ID * 2
IF INPUTRECORD(I:1) = 'B' OR INPUTRECORD(I:1) = 'R' THEN
ADD 1 TO SEAT-ID
END-IF
END-PERFORM.
IF SEAT-ID > ID-MAX THEN
MOVE SEAT-ID TO ID-MAX
END-IF.
I was hoping for a meaty one for a cold wet Saturday but this was straightforward. The insight was realising that "binary space partitioning" is just binary, swapping 1 and 0 for letters. I almost did it using string replace at first.
I'm a Staff Software Engineer at Cisco. I specialize in Python and Go, building functional, practical, and maintainable web systems leveraging Kubernetes and the cloud. Blog opinions are my own.
Oh man! Swapping letters for numbers is an amazing insight. I'm half-tempted to go back and rewrite mine using even more sneaky binary tricks! I stopped at bit shifting.
Wanting to continue with the Haskell approach of using just lists, which looks back at one of my favourite books from collage Brid and Wadler's Introduction to Functional Programming, I decided to allow my self one function, from the lens package, that is not in Haskell's standard of functions. At some point I guess it might get much of a performance issue to remain with just lists, but for now we continue.
That being said I could not face working with binary date in Haskell, directly at least, and so took a slightly lazy approach with calulating mid points, rather than going for swapping letters for 0 and 1.
-- we need to accumulate, rather than simply foldfoldl'fz[]=zfoldl'fz(x:xs)=letz'=z`f`xinseqz'$foldl'fz'xs-- calculate our half way rangehalf=(\rangesm->ifm=='F'||m=='L'thenfstrangeselsesndranges).rangeswhereranges(min,max)=letmp=(min+max)`div`2in((min,mp),(mp+1,max))-- calculate a seat numberseatis=let(rs,cs)=splitAt7is(r,_)=foldl'half(0,127)rs(c,_)=foldl'half(0,7)csin(r*8+c)main=doxs<-readFile"day5_input"<&>linesletseats=mapseatxsprint(maximumseats)print$fst$head$dropWhilesnd$dropWhile(not.snd)$zip[0..](foldrupdateemptySeatsseats)whereemptySeats=map(constFalse)[0..1023]updates=elements.~True
After discussing with my partner I thought I should do the binary version too, so here is a slightly modified version, but rather than using Haskell binary stuff, just used fold to convert the binary string to an int.
-- we need to accumulate, rather than simply foldfoldl'fz[]=zfoldl'fz(x:xs)=letz'=z`f`xinseqz'$foldl'fz'xs-- calculate our half way rangehalf=(\rangesm->ifm=='F'||m=='L'thenfstrangeselsesndranges).rangeswhereranges(min,max)=letmp=(min+max)`div`2in((min,mp),(mp+1,max))-- calculate a seat numberseat=toDec.map(\x->ifx=='F'||x=='L'then'0'else'1')wheretoDec=foldl'(\accx->acc*2+digitToIntx)0main=doxs<-readFile"day5_input"<&>linesletseats=mapseatxsprint(maximum(mapseatxs))print$fst$head$dropWhilesnd$dropWhile(not.snd)$zip[0..](foldrupdateemptySeatsseats)whereemptySeats=map(constFalse)[0..1023]updates=elements.~True
I'm a Staff Software Engineer at Cisco. I specialize in Python and Go, building functional, practical, and maintainable web systems leveraging Kubernetes and the cloud. Blog opinions are my own.
Pretty quick one today! I didn't have much problem, and once I realized that the seat ID was actually the index into a 1-D array of seats, I stopped writing my own custom seatID->index function 😂
Day5.h:
#ifndef AOC2020_DAY5_H
#define AOC2020_DAY5_H
/// Day 5: Binary Boarding/// /// Calculate Seat ID's from a binary division process.#include <stdlib.h>
/// Calculate the seat ID by parsing a 10-char FFBBFFBLRL seat string/// to a seat row/column. The seat ID is not only row * 8 + col, but/// also the index into a linearized array of seats which is nice.intseat_ID(constchar*seat);/// Run both parts for the day.intday5(void);#endif
Day5.c:
#include "Day5.h"
#include <stdio.h>
#include <stdbool.h>
#define ROWS 128
#define COLS 8
#define NUM_ROW_CHARS 7
#define NUM_COL_CHARS 3
intseat_ID(constchar*seat){intfront=0,left=0;intdepth=ROWS;intwidth=COLS;for(inti=0;i<NUM_ROW_CHARS;i++){depth>>=1;if(seat[i]=='B')front+=depth;}for(inti=NUM_ROW_CHARS;i<NUM_ROW_CHARS+NUM_COL_CHARS;i++){width>>=1;if(seat[i]=='R')left+=width;}returnfront*8+left;}/// Part 1: Calculate the highest seat ID in the list.staticintpart1(void){FILE*fp;fp=fopen("data/day5.txt","r");if(fp==NULL){printf("Couldn't open file.\n");exit(EXIT_FAILURE);}intmax_ID=0;charseat[11];while(fgets(seat,11,fp)){intthis_ID=seat_ID(seat);if(this_ID>max_ID)max_ID=this_ID;}fclose(fp);returnmax_ID;}/// Part 2: Find the only empty seat on the plane. Note: some seats/// are missing from the front and back of the grid.staticintpart2(void){boolseats[ROWS*COLS]={0};FILE*fp;fp=fopen("data/day5.txt","r");if(fp==NULL){printf("Couldn't open file.\n");exit(EXIT_FAILURE);}// Load all seats in as present.charseat[11];while(fgets(seat,11,fp)){seats[seat_ID(seat)]=true;}fclose(fp);// Run through non-present seats. Once we're into seats on the plane,// the first empty one is mine!boolinside_plane=false;for(inti=0;i<ROWS*COLS;i++){if(!inside_plane&&seats[i])inside_plane=true;if(inside_plane&&!seats[i])returni;}return-1;}intday5(void){printf("====== Day 5 ======\n");printf("Part 1: %d\n",part1());printf("Part 2: %d\n",part2());returnEXIT_SUCCESS;}
Coding since 11yo, that makes it over 30 years now ~~~
Have a PhD in Comp Sci ~~~
Love to go on bike tours ~~~
I try to stay as generalist as I can in this crazy wide place coding is at now.
require'benchmark'classBoardingPassdefself.from_binary(binary_position)rows=binary_position[0...7].tr("FB","01")columns=binary_position[7..].tr("LR","01")BoardingPass.new((rows+columns).to_i(2))enddefinitialize(seat)self.seat=seatenddefto_iself.seatendprivateattr_accessor:seatenddeffind_missing_id(passes)seat_ids=passes.map(&:to_i).sort(seat_ids.first..seat_ids.last).to_a.each_with_indexdo|expected_id,i|returnexpected_idifseat_ids[i]!=expected_idendendBenchmark.bmbmdo|b|b.report(:to_i_base_2)dopasses=File.readlines('input.txt').mapdo|line|BoardingPass.from_binary(line.chomp)endputsfind_missing_id(passes)endb.report(:binsearch)dodefbinary_position_search(l:,r:,position:)position.chars.inject([0,2**position.length-1])do|(low,high),half|mid=low+((high-low)/2.0)ifhalf==l[low,mid.floor]elsifhalf==r[mid.ceil,high]elseraise"Position character #{half} not expected. Expected #{l} or #{r}."endend.firstendpasses=File.readlines('input.txt').mapdo|line|binary_position=line.chomprow=binary_position_search(l: 'F',r: 'B',position: binary_position[0...7])column=binary_position_search(l: 'L',r: 'R',position: binary_position[7..])BoardingPass.new(row*8+column)endputsfind_missing_id(passes)endend
I see lots of complex solutions when binary data packing/unpacking should be relatively compact and optimized. Hopefully this helps give people some ideas!
# Read a line and parse it w/ convertdefparse(data)(convert(data[0..6],'F','B')*8)+convert(data[7..9],'L','R')end# Converts data into a binary 0/1 string and then gets the dec valuedefconvert(data,off_char,on_char)data.scan(/[#{off_char}|#{on_char}]/).map{|c|c==off_char?0:1}.join('').to_i(2)end# Part Oneseats=File.readlines('input.txt').map{|s|parse(s)}.sortpseats.last# Part Twoparted_seats=seats.slice_when{|i,j|i+1!=j}.to_ap(parted_seats.first.last..parted_seats.last.first).to_a[1]
My solution in python. Sometimes the challenge is just clicking what the description is actually saying, once it's obvious that these are just binary numbers then it was quite an easy one.
all_seats=[int((l.replace('B','1').replace('F','0').replace('R','1').replace('L','0')),2)forlinopen('input.txt')]print(f"Part 1: Highest seat is {max(all_seats)}")your_seat=[sforsinrange(min(all_seats),max(all_seats))ifsnotinall_seats][0]print(f"Part 2: Your seat is {your_seat}")
Hi, new to this site, and AOC. I did the last 4 in Python, but I thought I would try shell for this one (i'm not great at shell so this may be not the best):
#!/bin/bashi=0;for seat in$(cat ids)do((i=i+1))((prev=i-1))((next=i+1))if grep--silent ^${prev}$ ids
then
if grep--silent ^${next}$ ids
then
if!grep--silent ^${i}$ ids
then
echo"${i}"fi
fi
fi
done
My Haskell Solution (I just started learning Haskell so fair warning):
importData.Bool(bool)toDecimalList::[String]->[Int]toDecimalList=map(foldl1((+).(2*)).map(bool01.(`elem`"BR")))ans1::[String]->Intans1=maximum.toDecimalListfindMissing::[Int]->IntfindMissingnums=(minimumnums+maximumnums)*(lengthnums+1)`div`2-sumnumsans2::[String]->Intans2=findMissing.toDecimalListmain::IO()main=docontents<-readFile"adventofcode5input"print$ans1$linescontents-- Part 1print$ans2$linescontents-- Part 2
Python in 2 lines
And a much more legible Kotlin
I was curious to know if Python would let you execute a lambda immediately by wrapping it with parens and giving it the input, such as
(lambda)(input)and ... sure enough you can. As such, I present this monstrosity in 1 line:COBOL (part 2 on my GitHub)
How do you run your COBOL solutions? I tried it in past AoCs but failed on that.
I'm using GnuCOBOL on Windows:
I was hoping for a meaty one for a cold wet Saturday but this was straightforward. The insight was realising that "binary space partitioning" is just binary, swapping 1 and 0 for letters. I almost did it using string replace at first.
Oh man! Swapping letters for numbers is an amazing insight. I'm half-tempted to go back and rewrite mine using even more sneaky binary tricks! I stopped at bit shifting.
Yep, I noticed this too, I was like "hang on a sec" 🍒
Wanting to continue with the Haskell approach of using just lists, which looks back at one of my favourite books from collage Brid and Wadler's Introduction to Functional Programming, I decided to allow my self one function, from the lens package, that is not in Haskell's standard of functions. At some point I guess it might get much of a performance issue to remain with just lists, but for now we continue.
That being said I could not face working with binary date in Haskell, directly at least, and so took a slightly lazy approach with calulating mid points, rather than going for swapping letters for 0 and 1.
Today I had a weird day. I did an advent task in my car waiting for gf Good for me that she was so late packing our cat for the trip. :topkek:
I saw many people did the task in a different way - I've used recurrence and pattern matching and it just works.
After discussing with my partner I thought I should do the binary version too, so here is a slightly modified version, but rather than using Haskell binary stuff, just used fold to convert the binary string to an int.
This one was pretty simple.
Rust as always :D
With a bit of bitshifting:
And an alternative solution in PHP :-D
Pretty quick one today! I didn't have much problem, and once I realized that the seat ID was actually the index into a 1-D array of seats, I stopped writing my own custom seatID->index function 😂
Day5.h:
Day5.c:
Hey everyone 👋!
I've created a step-by-step tutorial for solving AoC 2020 day 5:
dev.to/kais_blog/step-by-step-tuto...
I'm using TypeScript and I explain how to use the binary representation of the boarding pass data.
I went down an easy path today, implementing it in a most straightforward way:
Here's my C implementation. Kind of glad it was a straightforward problem this time. Will do tomorrow's in Python.
Today I have two implementations in Ruby for ya.
Part 2 of the puzzle was really puzzling, though I got the answer using set theory
Ruby, Late to the party - catching up!
I see lots of complex solutions when binary data packing/unpacking should be relatively compact and optimized. Hopefully this helps give people some ideas!
My solution in python. Sometimes the challenge is just clicking what the description is actually saying, once it's obvious that these are just binary numbers then it was quite an easy one.
Haskell:
Hi, new to this site, and AOC. I did the last 4 in Python, but I thought I would try shell for this one (i'm not great at shell so this may be not the best):
I solved part 1 with this shell oneliner...
for part two, I created the list of passport ids with:
then threw this at the ids file:
My Haskell Solution (I just started learning Haskell so fair warning):
I'm sad I couldn't think of a regex solution, just a quick sort and filter. (you get the gist)
Ruby, part 2:
My JavaScript walkthrough: