Advent of Code 2019-01 with R & JavaScript
Solving Advent of Code 2019-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.
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
Find the instructions at: https://adventofcode.com/2019/day/1
R solution
Part one
# Read
ipt <- read.delim( "input1.txt", header = FALSE )
# Get the sum of each element, divided by 3, rounded down, and substracted 2
sum( floor( ipt$V1 / 3) - 2 )
## [1] 3361299
Part two
Using a recursive function: https://en.wikipedia.org/wiki/Recursion_(computer_science)
floorish <- function(x, start = 0){
loc <- floor( x / 3) - 2
if (loc > 0){
start <- start + loc
floorish(loc, start)
} else {
return(start)
}
}
sum( purrr::map_dbl(ipt$V1, floorish) )
## [1] 5039071
JS solution
Part one & Two
var fs = require('fs')
// Reading the file
var res = fs.readFileSync("input1.txt", 'utf8').split("\n").filter(x => x.length != 0);
// Turning to integer
res = res.map(x => parseInt(x));
// Doing the floor of division less 2
var val = res.map(x => Math.floor(x / 3) - 2);
// Suming
var add = (x, y) => x + y;
// Solution
val.reduce(add)
## 3361299
// Creating the recursive function
function floorish(val, start = 0){
loc = Math.floor(val / 3) - 2;
if (loc > 0){
start += loc;
return floorish(loc, start);
} else {
return start;
}
}
// Doing the computation
res.map( x => floorish(x) ).reduce( add )
## 5039071
What do you think?