R/day-01.R

#' Function to split the input value as a vector of integers
#'
#' @param inp_val : An input character string of an integer value
#'
#' @return (integer) : Integer vector of individual \code{input_val}
#' digits
#' @export
inp_to_intvec <- function(inp_val){
    inp_val %>%
        # Just do the coercion to character in case
        base::as.character(x = .) %>%
        stringr::str_split(string = ., pattern = "") %>%
        base::unlist() %>%
        base::as.integer() %>%
        base::return()
}

#' Calculate the sum of the digits in the input vector that matched
#' in sequence
#'
#' @param split_vec
#'
#' @return (numeric) : sum of the digits in the input vector that matched
#' in sequence
#' @export
calc_sum <- function(inp_val){
    # Split the input value into a vector of integers
    parse_vec <- inp_to_intvec(inp_val)

    # Get the lagged differences, correct for the final one by manually
    # appending the difference between the first value and the last value
    lag_diff_vec <- c(base::diff(parse_vec)
                      , parse_vec[1] - utils::tail(parse_vec, 1))

    # Calculate the sum wherever the difference value is 0
    # We do not need to make index adjustments here. If the
    # diff values are 0, then just pick either of the corresponding
    # values to sum up
    sum(parse_vec[which(lag_diff_vec == 0)], na.rm = TRUE)
}

#' Calculate the sum of the digits in the input vector that matched
#' in sequence
#'
#' @param split_vec
#'
#' @return (numeric) : sum of the digits in the input vector that matched
#' in sequence
#' @export
calc_sum_lag <- function(inp_val, lag_val_fixed = TRUE){
    # Split the input value into a vector of integers
    parse_vec <- inp_to_intvec(inp_val)
    lag_val <- ifelse(lag_val_fixed, 1, floor(length(parse_vec)/2))
    parse_vec_append <- c(parse_vec, parse_vec[1:lag_val])

    # Get the lagged differences, correct for the final one by manually
    # appending the difference between the first value and the last value
    lag_diff_vec <- base::diff(parse_vec_append, lag = lag_val)

    # Calculate the sum wherever the difference value is 0
    # We do not need to make index adjustments here. If the
    # diff values are 0, then just pick either of the corresponding
    # values to sum up
    sum(parse_vec[which(lag_diff_vec == 0)], na.rm = TRUE)
}
shamindras/adventofcode2017 documentation built on May 14, 2019, 7:37 a.m.