R/advent-utils.R

#-------------------------------------------------------------------------------
# Load libraries
#-------------------------------------------------------------------------------

#' Install and load multiple R packages.
#' check to see if packages are installed.
#' Install them if they are not, then load them into the R session.
#' source: \url{https://gist.github.com/stevenworthington/3178163}
#' @param pkg character: list of R packages
#' @export
#'
#' @examples
#' pckgs <- c("here", "tidyverse", "glue", "secret", "RPostgreSQL")
#' ipak(pckgs)
ipak <- function(pkg){
    new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
    if (length(new.pkg))
        install.packages(new.pkg, dependencies = TRUE)
    sapply(pkg, require, character.only = TRUE)
}

#' For a given txt file containing rows of  numbers, calculates the sum
#' of their ranges
#' Used in Day-02 of the Advent of Code 2017
#' @param txt_file_path (character) : The path to the valid Day-02 input txt
#' file
#'
#' @export
parse_txtfile <- function(txt_file, sep = "\t", map_fun = as.numeric){
    txt_file %>%
        base::readLines(con = .) %>%
        stringr::str_split(string = ., pattern = sep) %>%
        purrr::map(map_fun) %>%
        base::return()
}
shamindras/adventofcode2017 documentation built on May 14, 2019, 7:37 a.m.