Advent of Code 2019-04 with R & JavaScript

December 3, 2019
By

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-04 with R and JavaScript.

of Code, as it gives solutions for solving day 4.

[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.

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

R solution

Part one

``````test <- 156218:652527
library(magrittr)
cond <- function(vec){
splt <- strsplit(
as.character(vec),
"")[[1]] %>% as.numeric()
incre <- (splt >= dplyr::lag(splt))[-1]
}
vapply(test, cond, logical(1)) %>% sum()
``````
``````## [1] 1694
``````

Part two

``````cond2 <- function(vec){
splt <- strsplit(
as.character(vec),
"")[[1]] %>% as.numeric()
}
incre <- (splt >= dplyr::lag(splt))[-1]
}
vapply(test, cond2, logical(1)) %>% sum()
``````
``````## [1] 1148
``````

JS solution

Part one & Two

// Generating the array (from
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)

``````const range = (start, stop, step = 1) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
var test = range(156218, 652527)
``````
``````function lag(vec){
var res = [];
res.push(null);
for (var i = 0; i < vec.length - 1; i ++){
res.push(vec[i])
}
return res
}

function cond(vec){
var vec = vec.toString().split("").map(x => parseInt(x));
var laged = lag(vec);
var adj_eq = vec.map( (x, i) => x == laged[i] )
var incre = vec.map( (x, i) => x >= laged[i] )
incre.shift()
var incre = incre.every(z => z);
var all = [incre, adj_eq].every(z => z);
return all
}
``````
``````test.map(cond).filter(v => v).length
``````
``````## 1694
``````
``````function table(vec){
var tbl = {}
vec.map(function(x){
if (tbl[x]){
tbl[x] = tbl[x] + 1;
} else {
tbl[x] = 1;
}
})
return tbl
}
function cond2(vec){
var vec = vec.toString().split("").map(x => parseInt(x));
var laged = lag(vec);
var adj_eq = vec.map( (x, i) => x == laged[i] )
var tb = table(vec);
var res = [];
for (i in tb){
res.push(tb[i] == 2);
}
var adj_eq = res.some(x => x);
}

var incre = vec.map( (x, i) => x >= laged[i] );
incre.shift();
var incre = incre.every(z => z);
var all = [incre, adj_eq].every(z => z);
return all;
}
``````
``````test.map(cond2).filter(v => v).length;
``````
``````## 1148
``````

R-bloggers.com 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.