Advent of Code 2021-01 with R & JavaScript

1 minute(s) read

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

I’ll try in this post to write R code that looks like the JavaScript one, using {purrr}, to show how both syntaxes can look alike. The idea is to highlight how you can leverage your {purrr} knowledge when writting JavaScript code.

Disclaimer

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

  • Count the number of times n is larger that n-1

  • Count the number of times n + n-1 + n-2 is larger that n-1 + n-2 + n-3

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

Reading inputs

# Read
library(purrr)
ipt <- read.delim("2021-01-aoc.txt", header = FALSE)$V1

// Reading the file and converting it to int

const fs = require('fs')
var ipt = fs.readFileSync("2021-01-aoc.txt", 'utf8').split("\n").filter(x => x.length != 0);
ipt = ipt.map(x => parseInt(x));

Part one

R solution

2:length(ipt) |>
  map_dbl(
    ~ ipt[.x] - ipt[.x - 1]
  ) |>
  keep(
    ~ .x > 0
  ) |>
  length()
## [1] 1154

JS solution

ipt.map(
  // inside map() in JS, the second argument to the anonymous
  // function is the index inside the array.
  // It mimics what we have in map(2:length(ipt)) in R
  (x, y) => ipt[y] - ipt[y-1]
  ).filter(
    // filter() will keep the element that matches the anonymous
    // predicate function
    x => x >= 0
    ).length;
## 1154

Part two

R solution

tmp <- 3:length(ipt) |>
  map_dbl(
    ~ ipt[.x] + ipt[.x - 1] + ipt[.x - 2]
  )

2:length(tmp) |>
  map_dbl(
    ~ tmp[.x] - tmp[.x - 1]
  ) |>
  keep(
    ~ .x > 0
  ) |>
  length()
## [1] 1127

JS solution

var tmp = ipt.
  map(
    // Creating n + n-1 + n-2
    (x, y) => ipt[y] + ipt[y-1] + ipt[y-2]
    );

tmp.
  map(
    // Same as part 1
    (x, y) => tmp[y] - tmp[y-1]
    ).
  filter(
    // keeping the ones that have raised
    x => x > 0
  ).
  length;
## undefined
## undefined
## 1127

What do you think?