Advent of Code 202001 with R & JavaScript
Solving Advent of Code 202001 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.
About the JavaScript code
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
ipt < read.delim( "202001aoc.txt", header = FALSE )
library(dplyr, warn.conflicts = FALSE)
# Creating all the combinations
tidystringdist::tidy_comb_all(ipt$V1) %>%
# Adding them together
mutate(sum = V1 + V2) %>%
# keeping only the one that equals 2020
filter(sum == 2020) %>%
# Multiplying it
mutate(res = V1 * V2) %>%
# Getting the answer
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("202001aoc.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
What do you think?