DEV Community is a community of 638,993 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Advent of Code 2020-01 with R & JavaScript

Colin Fay Originally published at colinfay.me on ・2 min read

Solving Advent of Code 2020-01 with R and JavaScript.

[Disclaimer] Obviously, this post contains a big spoiler about Advent of Code, as it gives solutions for solving day 1.

[Disclaimer bis] I’m no JavaScript expert so this might not be the perfect solution. TBH, that’s also the case for the R solution.

The JavaScript code has been written in the same RMarkdown as the R code. It runs thanks to the `{bubble}` package:https://github.com/ColinFay/bubble

Instructions

• Combine all the possible duos and trios of the input numbers

• Locate the combination that equals 2020

• Multiply the numbers from this combination to get the puzzle answer

R solution

Part one

``````# Read
library(dplyr, warn.conflicts = FALSE)
# Creating all the combinations
tidystringdist::tidy_comb_all(ipt\$V1) %>%
mutate(sum = V1 + V2) %>%
# keeping only the one that equals 2020
filter(sum == 2020) %>%
# Multiplying it
mutate(res = V1 * V2) %>%
pull(res)

## [1] 445536
``````

Part two

``````# Creating all the combinations
combn(
ipt\$V1,
3
) %>%
# Transposing the matrix and turning it to a tibble
t() %>%
as_tibble() %>%
# Same old song as step 1
mutate(sum = V1 + V2 + V3) %>%
filter(sum == 2020) %>%
mutate(res = V1 * V2 * V3) %>%
pull(res)

## [1] 138688160
``````

JS solution

Part one & Two

// Reading the file and converting it to int

``````const fs = require('fs')
var ipt = fs.readFileSync("2020-01-aoc.txt", 'utf8').split("\n").filter(x => x.length != 0);
ipt = ipt.map(x => parseInt(x));
``````

// Doing the combn

``````var ipt2 = ipt;
var comb = ipt.flatMap(i => ipt2.map(j => [i, j]))
``````

// Getting the 2020

``````var twentytwenty = comb.filter(x => (x[0] + x[1]) === 2020)
``````

// Solution

``````twentytwenty.reduce(y => y[0] * y[1])

## 445536
``````

// Same with three

``````var ipt3 = ipt;
var comb2 = ipt.flatMap(i => ipt2.flatMap(j => ipt3.map(k => [i, j, k])));
``````

// Doing the computation

``````var twentytwenty2 = comb2.filter(x => (x[0] + x[1] + x[2]) === 2020)
``````

// Solution

``````twentytwenty2.map(y => y[0] * y[1] * y[2])[0]

## 138688160
``````