#' For a given input list of vectors, calculate sum of all their ranges
#' Used in Day-02 of the Advent of Code 2017
#'
#' @param list_num_vec (list) : list of numeric vectors
#'
#' @export
get_range_numvec <- function(list_num_vec){
list_num_vec %>%
purrr::map(range) %>%
purrr::map(diff) %>%
base::unlist() %>%
sum(na.rm = TRUE) %>%
base::return()
}
#' 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
get_range_txtfile <- function(txt_file){
txt_file %>%
adventofcode2017::parse_txtfile(txt_file = .
, sep = "\t"
, map_fun = as.numeric) %>%
get_range_numvec(list_num_vec = .) %>%
base::return()
}
#' Returns the first time an element divides another in an integer vector
#'
#' @param num_vec (integer) : An integer vector
#'
#' @export
get_even_divisor <- function(num_vec){
num_vec <- base::as.integer(num_vec)
# Set the dummy value of no divisor found to be -99
DEFAULT_EMPTY_DIVISOR_OUT <- -99
# Initialize the output of whole number divisors and no divisors
whole_divisors <- base::integer()
no_divisors <- base::integer()
for(i in seq_along(num_vec)){
divisor <- num_vec[i]
div_vec <- num_vec[-i]
out_division <- div_vec %% divisor
# Get the index of whole divisors
# Set the dummy value of no whole divisor found to be -1
div_idx0 <- ifelse(base::length(which(out_division == 0)) > 0
, base::which(out_division == 0)
, -1)
# If a whole divisor is found then increment our whole divisor
# vector
if(div_idx0 != -1){
whole_divisors <- c(whole_divisors
, div_vec[min(div_idx0)]/divisor)
} else{
# Increment by the dummy division value
no_divisors <- c(no_divisors
, DEFAULT_EMPTY_DIVISOR_OUT)
}
}
# We want to return the first whole divisor or the dummy value of -99
# In the Advent of Code 2017, we should always hit this value
out_val <- base::ifelse(base::length(whole_divisors) > 0
, whole_divisors[1]
, no_divisors[1])
base::return(out_val)
}
#' Returns sum of all even division values from a collection of integer vectors
#'
#' @param txt_file (character) : A text file containing tab separated integer
#' values split across new lines for each vector
#'
#' @export
get_even_divisor_txtfile <- function(txt_file){
txt_file %>%
adventofcode2017::parse_txtfile(txt_file = .
, sep = "\t"
, map_fun = as.numeric) %>%
purrr::map(get_even_divisor) %>%
base::unlist() %>%
base::sum() %>%
base::return()
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.