Skip to content

Instantly share code, notes, and snippets.

@JosiahParry
Created October 29, 2024 16:48
Show Gist options
  • Save JosiahParry/1274fa318669754b74d7848bfcd41fa5 to your computer and use it in GitHub Desktop.
Save JosiahParry/1274fa318669754b74d7848bfcd41fa5 to your computer and use it in GitHub Desktop.
cumsum_cut <- function(x, cuts) {
  x[cuts-1] <- 0
  res <- lapply(split(x, cumsum(x == 0)), \(.x) {
    cumsum(.x)
  }) |> 
    unlist() |>
    unname()
  n <- length(res)
  to_fill <- numeric(n)
  rlang::vec_poke_range(to_fill, 2, res, to = n -1)
  to_fill
}

system.time(
  cumsum_cut(c(8, 7, 0, 5, 4, 0, 2, 1), c(4, 7))
)
#>    user  system elapsed 
#>       0       0       0

# Test case
set.seed(1)
vec <- sample(80)
reset_at <- sample(80, 3)

bench::mark(
  cumsum_cut(vec, reset_at)
)
#> # A tibble: 1 × 6
#>   expression                     min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>                <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 cumsum_cut(vec, reset_at)   21.9µs   23.7µs    40010.    4.32MB     24.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment