Hey - I'm working on the problems in Rust this year, too! I'm putting all mine in Github, but will share here, too.
(I found a cool cargo plugin that provides helpful macros and makes doing AoC stuff easier - cargo-aoc)
useaoc_runner_derive::{aoc,aoc_generator};#[aoc_generator(day1)]fnparse_input_day1(input:&str)->Vec<usize>{input.lines().map(|v|v.parse().expect("Failed to parse input!")).collect()}#[aoc(day1,part1)]fnfind_2020_entries(input:&Vec<usize>)->usize{letpair=input.iter().enumerate().find_map(|(idx,&item)|{matchinput.iter().enumerate().find(|(idx2,&second)|idx2!=&idx&&(item+second==2020)){Some((_,second))=>Some(item*second),None=>None,}});pair.unwrap_or(1)}#[aoc(day1,part2)]fnfind_2020_entries_with_three(input:&Vec<usize>)->usize{letresult=input.iter().enumerate().find_map(|(idx,&item)|{input.iter().enumerate().find_map(|(idx2,&second)|{matchinput.iter().enumerate().find(|(idx3,&third)|{idx2!=idx&&&idx!=idx3&&&idx2!=idx3&&(item+second+third==2020)}){Some((_,third))=>Some(item*second*third),None=>None,}})});result.unwrap_or(1)}
Hey!! So excited that it's this time again here is my code. I would have just done loops without sets but the servers were down when I was trying to get my full input so I just went ahead and did a tiny optimization :).
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.
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.
Yep, this'll be another year fighting the urge to pre-optimise xmas code 🤦
Anyway, here's a nice efficient implementation in JS... (linear for part one, which is nice. Square for part two which could be improved but, like, why?)
constinput=JSON.parse(require('fs').readFileSync('1a.json','utf-8'));// sort ascendinginput.sort((a,b)=>a-b);functiongo(c,tgt){// tgt is the target sum we're aiming for// a is an index which moves through the array, // b is ahead of a but retreats to maintain a sum <= to target.for(leta=c,b=input.length-1;a<input.length;a++){let{[a]:av,[b]:bv}=input;while(av+bv>tgt&&b>=a)bv=input[--b];if(av+bv==tgt)return{a,b};}}letres;// Part 1(res=go(0,2020))&&console.log({part:1,sum:input[res.a]+input[res.b],prod:input[res.a]*input[res.b],});// Part 2for(constcininput)(res=go(c,2020-input[c]))&&console.log({part:2,sum:input[res.a]+input[res.b]+input[c],prod:input[res.a]*input[res.b]*input[c],});
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.
I'm liking Ryan's idea of using this to practice new languages and get out of the comfort zone (though JS is just so comfy now 😌 )
Plan is to make myself a twister-style spinner with 5 or so languages, and force myself to use whichever one the arrow lands on on the day.
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.
I'm going to try to do my solutions in C. C is something I'm learning, so if anybody has any pointers (LOL), please don't hesitate to critique my code.
I didn't do anything crazy today. I just threw loops at it to see if it was fast enough. It solved before I could blink, so I'm not going to work any harder at improving speed.
/// Day 1: Report Repair/// /// My expense report for my trip is messed up and entries need/// adjusting.#include <stdio.h>
#include <stdlib.h>
/// Parse the input file, which contains one positive integer per line.int*parse(constchar*filename,size_t*count){FILE*fp;fp=fopen(filename,"r");if(fp==NULL){printf("Could not open input file.\n");exit(EXIT_FAILURE);}// Count how many we needsize_tlines=0;while(!feof(fp)){if(fgetc(fp)=='\n')lines++;}lines++;// The last line has no newline, but we should count it.rewind(fp);int*entries=malloc(sizeof(int)*lines);charbuff[5];// No numbers greater than 4 digitsfor(size_ti=0;i<lines;i++){fgets(buff,6,fp);entries[i]=atoi(buff);}fclose(fp);*count=lines;returnentries;}/// Part 1 finds the two entries that add up to 2020 exactly and returns/// their product, or -1 if none are found.intpart1(int*entries,size_tcount){for(size_ti=0;i<count;i++){for(size_tj=i+1;j<count;j++){if(entries[i]+entries[j]==2020){returnentries[i]*entries[j];}}}return-1;}/// Part 2 is the same as Part 1, but we're looking for a trio of numbers/// that sum up to 2020. Returns their product or -1 if no trio is found.intpart2(int*entries,size_tcount){for(size_ti=0;i<count;i++){for(size_tj=i+1;j<count;j++){for(size_tk=j+1;k<count;k++){if(entries[i]+entries[j]+entries[k]==2020){returnentries[i]*entries[j]*entries[k];}}}}return-1;}intmain(){size_tcount;int*entries=parse("day1/day1.txt",&count);printf("The 2020 pair product is: %d\n",part1(entries,count));printf("The 2020 triplet product is: %d\n",part2(entries,count));returnEXIT_SUCCESS;}
I'm also doing it in C this year! I'm also fairly new to the language and pretty much the only thing I've done differently is use fscanf instead of fgets in conjunction with atoi
(+ I've optimised a little bit to do both parts in the same loop)
IDENTIFICATION DIVISION.
PROGRAM-ID. Advent-of-Code-2020-day-1-part-2.
AUTHOR. ANNA KOSIERADZKA.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INPUTFILE ASSIGN TO "d1.input"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD INPUTFILE.
01 INPUTRECORD PIC 9(4).
WORKING-STORAGE SECTION.
01 FILE-STATUS PIC 9 VALUE 0.
01 WS-ARRAY-LEN PIC 9(3) VALUE 200.
01 WS-ARRAY PIC 9(4) OCCURS 0 to 200 DEPENDING ON WS-ARRAY-LEN.
01 WS-SUM PIC 9(4).
01 WS-PRODUCT-1 PIC 9(8).
01 WS-PRODUCT-2 PIC 9(12).
LOCAL-STORAGE SECTION.
01 I USAGE UNSIGNED-INT VALUE 1.
01 J USAGE UNSIGNED-INT VALUE 1.
01 K USAGE UNSIGNED-INT VALUE 1.
PROCEDURE DIVISION.
001-MAIN.
OPEN INPUT INPUTFILE.
PERFORM 002-READ UNTIL FILE-STATUS = 1.
CLOSE INPUTFILE.
PERFORM 004-LOOP.
STOP RUN.
002-READ.
READ INPUTFILE
AT END MOVE 1 TO FILE-STATUS
NOT AT END PERFORM 003-WRITE-TO-TABLE
END-READ.
003-WRITE-TO-TABLE.
COMPUTE WS-ARRAY(I) = INPUTRECORD
ADD 1 to I.
004-LOOP.
PERFORM VARYING I FROM 1 BY 1 UNTIL I > WS-ARRAY-LEN
AFTER J FROM 1 BY 1 UNTIL J > WS-ARRAY-LEN
AFTER K FROM 1 BY 1 UNTIL K > WS-ARRAY-LEN
ADD WS-ARRAY(I) WS-ARRAY(J) WS-ARRAY(K) GIVING WS-SUM
IF WS-SUM = 2020 THEN
MULTIPLY WS-ARRAY(I) BY WS-ARRAY(J) GIVING WS-PRODUCT-1
MULTIPLY WS-PRODUCT-1 BY WS-ARRAY(K) GIVING WS-PRODUCT-2
DISPLAY WS-PRODUCT-2
EXIT PERFORM
END-IF
END-PERFORM.
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.
Hey Y'all!!! I thought I'd actually try making this happen this year and I completed the first challenges today!! I think in later challenges I'll actually try importing the text file as it is, but I wanted to make it fun for myself. I did the solution this time in ruby, and its a program you'd run on irb, that asks for the expenses and the factor you need to group to find the magic number (2 or 3) and it prints out the number to enter at the end.
classAdventAccountdefinitialize(expenses,factor=2)@expenses=expenses@factor=factorenddefperformfilter_big_numswinning_number(do_si_do)endprivatedeffilter_big_nums@expenses.reject!{|expense|expense>=2020}enddeffind_your_partner@expenses.combination(@factor).to_a()enddefwinning_set(group)group.sum==2020enddefdo_si_dofind_your_partner.eachdo|group|puts"Checking group #{group}"returngroupifwinning_set(group)endenddefwinning_number(group)puts"the winning number is #{group.reduce(:*)}"endendputs"Starting up the Advent Account checker"puts"Submit expenses now:"expenses=gets.chomp.split(",").map(&:to_i)puts"Thanks! Now, what factor should we search the expenses with?"factor=gets.chomp.to_itest=AdventAccount.new(expenses,factor)test.perform
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.
Only just heard of this, have some catching up to do! Here's my day 1 - similar to a couple of others already posted. Weirdly the part 1 problem came up in an interview just a couple of weeks ago!
defpart_one(nums,target):seen=set()possible=Falsefornuminnums:required=target-numifrequiredinseen:possible=Truebreakseen.add(num)ifpossible:returnnum,requiredreturn-1defpart_two(nums,target):seen=set()possible=Falsefornuminnums:fornum_2innums:req_num=target-num-num_2ifreq_numinseen:possible=Truebreakseen.add(num_2)else:continuebreakifpossible:returnnum,num_2,req_numreturn-1withopen("input.txt")asinput:nums=[int(line)forlineininput]res=part_one(nums,2020)ifres!=-1:x,y=resprint(f"Part 1 numbers are {x}, {y}, product is {x*y}")else:print(f"Part 1 cannot be solved from this dataset")res_2=part_two(nums,2020)ifres_2!=-1:x,y,z=res_2print(f"Part 2 numbers are {x}, {y}, {z} product is {x*y*z}")else:print(f"Part 2 cannot be solved from this dataset")
Hi! A little bit late, I've start with AOC this year and waiting for tomorrow I've try the past event this is my solution in python for 2020 - DAY 1:
# PART01 - Find the two number that sum == T then multiply each other
# PART02 - Find the triplets that sum == T then multiply each other
fromitertoolsimportcombinationsfrommathimportprodI=list([int(x)forxinopen('input.txt','r').readlines()])T=2020# PART01
I2=[xforxincombinations(I,2)ifsum(x)==T]R_P01=prod([xforxinI2[0]])# PART02
I3=[xforxincombinations(I,3)ifsum(x)==T]R_P02=prod([xforxinI3[0]])
I wasn't even going to do AoC this year after a bit of burnout last year. But I have no self-control. I have done day 1 in Haskell, Rust and C to compare performance. Rust wins by a hair.
Not anything difficult or complex in my code
It is in rust
use std::fs;
fn main() {
let file = fs::read_to_string("D:\Coding\AdventOfCode\day_onw\src\Data.txt").expect("Not read").to_string();
let sum = 2020;
let nums = file.lines();
let mut result = Vec::new();
let mut vector = Vec::new();
for i in file.lines() {vector.push(i.parse::().unwrap())}
for i in nums {
let num = i.parse::().unwrap();
for a in file.lines() {
let num2 = a.parse::().unwrap();
if vector.contains(&(sum - (num + num2))) {
result.push(num);
result.push(num2);
result.push((sum - (num + num2)));
}
}
}
print!("{}",result[0]*result[1]*result[2]);
}
Here is my solution in rust (minus all the code required to grab the input and parse it)
Hey - I'm working on the problems in Rust this year, too! I'm putting all mine in Github, but will share here, too.
(I found a cool cargo plugin that provides helpful macros and makes doing AoC stuff easier - cargo-aoc)
Hi! It was also my first time in Advent of Code.
There is my solution for the first day in Elixir: click, GitHub
Except input setup the code looks like:
Hey!! So excited that it's this time again here is my code. I would have just done loops without sets but the servers were down when I was trying to get my full input so I just went ahead and did a tiny optimization :).
Oooh! That's a really slick way to drop out a level of nesting. I like it!
SQL works for me. Easy and fast ;)
Get this table naming 'day1':

1.2. Solution
I am also gonna be doing aoc this year. Here is my Python solution:
Hi !
Here is my solution in PHP.
I try to make a generic function that can handle 2, 3 or more number in the expense report.
Full size here : Advent of Code - Day 1
Yep, this'll be another year fighting the urge to pre-optimise xmas code 🤦
Anyway, here's a nice efficient implementation in JS... (linear for part one, which is nice. Square for part two which could be improved but, like, why?)
I'm liking Ryan's idea of using this to practice new languages and get out of the comfort zone (though JS is just so comfy now 😌 )
Plan is to make myself a twister-style spinner with 5 or so languages, and force myself to use whichever one the arrow lands on on the day.
I'm going to try to do my solutions in C. C is something I'm learning, so if anybody has any pointers (LOL), please don't hesitate to critique my code.
I didn't do anything crazy today. I just threw loops at it to see if it was fast enough. It solved before I could blink, so I'm not going to work any harder at improving speed.
I'm also doing it in C this year! I'm also fairly new to the language and pretty much the only thing I've done differently is use
fscanfinstead offgetsin conjunction withatoi(+ I've optimised a little bit to do both parts in the same loop)
COBOL:
This is awesome! I'm so happy I get to add COBOL to the list 😁
Python, why make it complicate if it is so siple?
My solution is the same but yours is also more slim!
Good job!
Hey Y'all!!! I thought I'd actually try making this happen this year and I completed the first challenges today!! I think in later challenges I'll actually try importing the text file as it is, but I wanted to make it fun for myself. I did the solution this time in ruby, and its a program you'd run on irb, that asks for the expenses and the factor you need to group to find the magic number (2 or 3) and it prints out the number to enter at the end.
Here's the way I solved it:
Ooh filtering out numbers > 2020 is a really nice touch. I hadn’t thought of that 😁
Only just heard of this, have some catching up to do! Here's my day 1 - similar to a couple of others already posted. Weirdly the part 1 problem came up in an interview just a couple of weeks ago!
Hi! A little bit late, I've start with AOC this year and waiting for tomorrow I've try the past event this is my solution in python for 2020 - DAY 1:
Very good content here Ryan!
Bit late to the party, here is my iterator focused solution in rust. input is a Vec, aka the parsed input data
Edit: solution 2, same concept, but more concise
I wasn't even going to do AoC this year after a bit of burnout last year. But I have no self-control. I have done day 1 in Haskell, Rust and C to compare performance. Rust wins by a hair.
github.com/neilgall/advent-of-code...
Here are my solutions in Scratch. Enjoy! scratch.mit.edu/studios/28204945/
My solution in C#: (The timer is just for fun ..)
Not anything difficult or complex in my code
It is in rust
use std::fs;
fn main() {
let file = fs::read_to_string("D:\Coding\AdventOfCode\day_onw\src\Data.txt").expect("Not read").to_string();
let sum = 2020;
let nums = file.lines();
let mut result = Vec::new();
let mut vector = Vec::new();
for i in file.lines() {vector.push(i.parse::().unwrap())}
for i in nums {
let num = i.parse::().unwrap();
for a in file.lines() {
let num2 = a.parse::().unwrap();
if vector.contains(&(sum - (num + num2))) {
result.push(num);
result.push(num2);
result.push((sum - (num + num2)));
}
}
}
print!("{}",result[0]*result[1]*result[2]);
}
Hello, I solves it like this github.com/emilpriver/Advent-of-co...
My JavaScript walkthrough: