[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.
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:
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
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( res.map( 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.
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.
