# Advent of Code 2020-01 with R & JavaScript

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

Find the complete instructions at: https://adventofcode.com/2020/day/1.

## 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)
``````
``````##  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)
``````
``````##  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 + x) === 2020)
``````

// Solution

``````twentytwenty.reduce(y => y * y)
``````
``````## 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 + x + x) === 2020)
``````

// Solution

``````twentytwenty2.map(y => y * y * y)
``````
``````## 138688160
``````

Categories:

Updated: