DEV Community

Cover image for Advent of Code 2020 Solution Megathread - Day 1: Report Repair
Ryan Palo
Ryan Palo

Posted on

Advent of Code 2020 Solution Megathread - Day 1: Report Repair

It's back! It's finally back! One of my favorite things on the internet is the yearly Advent of Code challenge. It's a programming challenge that runs from December 1st to December 25th. Each day, a new two-part puzzle is released. There is usually a plain text file input provided, and you have to write some code in any language you want to process it in some way. If you submit the correct answer to their question, you get a star. If you solve both parts correctly, you get two stars! The goal is to get 50 stars by Christmas day.

There are a bunch of people who get super-competitive and try to finish it as soon after midnight (when the puzzles are released) as possible. Personally, I just try to keep up and not get overwhelmed, since the second parts are usually pretty hard and require some algorithmic cleverness. (Or... and hear me out... some GPU compute. Just throw 1000 computers at the problem! πŸ™ƒ)

In any case, what we usually do here on DEV is have a post here every day where members of the community can post their solutions so you can see how a bunch of different people approached it in a bunch of different languages. So, when you've solved that day's puzzle, please join in and comment with your solution. And, if you're not ready for spoilers yet, stay away from the comments section!

Every year there is a theme, and this year, you're going on vacation! The stars are currency that you need to pay for your room at the end of your stay. I'm sure nothing bad will happen. It rarely does on these Advent of Code adventures.

The Puzzle

Here's today's puzzle: apparently your trip expense report isn't adding up! You are tasked with hunting through your expense entries to find the two that add up to 2020 exactly. The answer is the result of multiplying those two values together. A nice warm-up puzzle to get us back into the groove this year.

The Leaderboard

If anyone is interested, I've generated a leaderboard code for a little less globally competitive DEV leaderboard.
It's not an officially sponsored DEV thing, just a leaderboard that some DEV peeps have used over the last couple of years. There's still quite a bit of room, so feel free to jump in if you'd like using this code:

Ryan's Leaderboard: 224198-25048a19
Enter fullscreen mode Exit fullscreen mode

If you want to generate your own leaderboard and signal boost it a little bit, send it to me either in a DEV message or in a comment on one of these posts and I'll add it to the list above.

Previous Day's Languages

Last year, they made an effort to keep track of how many people used each language for their solutions for the previous day. I'll try to do that as time allows. I could imagine a bot that could poll each thread daily and update the following day's count. But that may be outside of what I have time for as well. If anybody wants to come up with something like that, I'm all for integrating it into the process. Otherwise, I'll do my best.

Merry Coding!

Latest comments (27)

Collapse
 
ttyago profile image
ttyago

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

from itertools import combinations
from math import prod

I = list([int(x) for x in open('input.txt', 'r').readlines()])
T = 2020

# PART01
I2 = [x for x in combinations(I,2) if sum(x) == T]
R_P01 = prod([x for x in I2[0]])

# PART02
I3 = [x for x in combinations(I,3) if sum(x) == T]
R_P02 = prod([x for x in I3[0]])
Enter fullscreen mode Exit fullscreen mode

Very good content here Ryan!

Collapse
 
saadpy profile image
Saad-py • Edited

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]);
}

Collapse
 
ranquebenoit profile image
Benoit Ranque • Edited

Bit late to the party, here is my iterator focused solution in rust. input is a Vec, aka the parsed input data

    if let Some((a, b, c)) = input.iter().find_map(|a| {
        if let Some((b, c)) = input.iter().find_map(|b| {
            if let Some(c) = input.iter().find(|c| a + b + *c == 2020) {
                Some((b, c))
            } else {
                None
            }
        }) {
            Some((a, b, c))
        } else {
            None
        }
    }) {
        println!("A: {}, B: {}, C: {} result: {}", a, b, c, a * b * c);
    } else {
        println!("Could not find numbers fullfilling the requirement")
    }
Enter fullscreen mode Exit fullscreen mode

Edit: solution 2, same concept, but more concise

    match input.iter().find_map(|a| {
        input.iter().find_map(|b| {
            input.iter().find_map(|c| {
                if a + b + c == 2020 {
                    Some((a, b, c))
                } else {
                    None
                }
            })
        })
    }) {
        Some((a, b, c)) => println!("A: {}, B: {}, C: {} result: {}", a, b, c, a * b * c),
        None => println!("Could not find numbers fullfilling the requirement"),
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
clothierdroid profile image
David Clothier

SQL works for me. Easy and fast ;)

Get this table naming 'day1':
table

1.2. Solution

SELECT
       a1.num*a2.num*a3.num
FROM
       day1 a1
     , day1 a2
     , day1 a3
WHERE
       a1.num + a2.num + a3.num = 2020
LIMIT 1
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pihentagy profile image
pihentagy

Python, why make it complicate if it is so siple?

for (a,b) in itertools.combinations([int(n) for n in open('input')], 2): 
    if a+b == 2020: 
        print(a*b) 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ttyago profile image
ttyago

My solution is the same but yours is also more slim!
Good job!

Collapse
 
thibpat profile image
Thibaut Patel

My JavaScript walkthrough:

Collapse
 
harrygibson profile image
Harry Gibson

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!

def part_one(nums, target):
    seen = set()
    possible = False
    for num in nums:
        required = target - num
        if required in seen:
            possible = True
            break
        seen.add(num)
    if possible:
        return num, required
    return -1

def part_two(nums, target):
    seen = set()
    possible = False
    for num in nums:
        for num_2 in nums:
            req_num = target - num - num_2
            if req_num in seen:
                possible = True
                break
            seen.add(num_2)
        else:
            continue
        break
    if possible:
        return num, num_2, req_num
    return -1

with open("input.txt") as input:
    nums = [int(line) for line in input]
    res = part_one(nums, 2020)
    if res != -1:
        x,y = res
        print(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)
    if res_2 != -1:
        x,y,z = res_2
        print(f"Part 2 numbers are {x}, {y}, {z} product is {x*y*z}")
    else:
        print(f"Part 2 cannot be solved from this dataset")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dirkfraanje profile image
Dirk Fraanje (the Netherlands)

My solution in C#: (The timer is just for fun ..)

    public static void Execute()
    {
        var timer = new Stopwatch();
        timer.Start();

        for (int i = 0; i < input.Count; i++)
        {
            for (int i2 = i + 1; i2 < input.Count; i2++)
            {
                var valueneeded = 2020 - input[i] - input[i2];
                if (input.Contains(valueneeded))
                {
                    timer.Stop();
                    Console.WriteLine();
                    Console.WriteLine($"Answer: {input[i] * input[i2] * valueneeded}");
                    Console.WriteLine($"Executed in: {timer.ElapsedMilliseconds} milliseconds, {timer.ElapsedTicks}  Ticks");
                }

            }
        }
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
klnjmm profile image
Jimmy Klein • Edited

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

Advent of Code - Day 1

Collapse
 
neilgall profile image
Neil Gall

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...