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 2019-01 with R & JavaScript

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

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

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

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

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

R solution

Part one

``````# Read
# 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');

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

// 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
console.log( res.map( x => floorish(x) ).reduce( add ) );

## 3361299
## 5039071

``````