Advent of Code 2020

13.R 795B

1234567891011121314151617181920212223242526272829303132333435
  1. library(stringr)
  2. input <- readLines("input13.txt")
  3. v <- as.numeric(input[1])
  4. vals <- unlist(str_split(input[2], ","))
  5. bnums <- as.numeric(vals[vals != "x"])
  6. times <- bnums - (v %% bnums)
  7. bindex <- which.min(times)
  8. bnums[bindex] * times[bindex]
  9. vbt <- which(vals != "x") - 1
  10. target.mod <- (bnums - vbt) %% bnums
  11. f2 <- sapply(1:bnums[2], function(x) {
  12. c(x*bnums[1], ((x*bnums[1]) %% bnums[2]) == target.mod[2])
  13. })
  14. val.2 <- f2[1,f2[2,] == 1]
  15. tmp.v <- 0
  16. sapply(2:length(bnums), function(x) {
  17. ft <- sapply(1:bnums[x], function(y) {
  18. cand <- tmp.v + y*prod(bnums[1:(x - 1)])
  19. c(cand, (cand %% bnums[x]) == target.mod[x])
  20. })
  21. tmp.v <<- ft[1, ft[2,] == 1]
  22. tmp.v
  23. })
  24. print(tmp.v, digits = 15)