Advent of Code 2019-01 with R & JavaScript

November 30, 2019

[This article was first published on Colin Fay, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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:


Find the instructions at:

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:

floorish <- function(x, start = 0){
  loc <- floor( x / 3) - 2
  if (loc > 0){
    start <- start + loc
    floorish(loc, start)
  } else {
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 = => parseInt(x));

// Doing the floor of division less 2
var val = => Math.floor(x / 3) - 2);

// Suming
var add = (x, y) => x + y;

// Solution
console.log( val.reduce(add) );

// 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( x => floorish(x) ).reduce( add ) );
## 3361299
## 5039071

To leave a comment for the author, please follow the link and comment on their blog: Colin Fay. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)