Advertisement
bins_on_bins

Untitled

Dec 17th, 2021
1,026
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.03 KB | None | 0 0
  1. library(tidyverse)
  2.  
  3. z = readLines("data/day17.txt") %>% str_extract_all("-?[0-9]{1,3}") %>% .[[1]] %>% as.numeric()
  4. x1 = z[1]
  5. x2 = z[2]
  6. y1 = z[3]
  7. y2 = z[4]
  8.  
  9. # Part 1
  10. y_target = abs(min(y1, y2)) - 1
  11. y_target * (y_target + 1) / 2
  12.  
  13. # Part 2
  14. # Which bounds do I have to search?
  15. quadratic_pos = function(a, b, cv) {
  16.   subv = c(
  17.     (-b + sqrt(b^2 - (4*a*cv))) / (2 * a),
  18.     (-b - sqrt(b^2 - (4*a*cv))) / (2 * a)
  19.   )
  20.  
  21.   subv[subv > 0]
  22. }
  23.  
  24. min_vx_rest = ceiling(quadratic_pos(1, 1, -(2 * x1)))
  25. max_vx_rest = floor(quadratic_pos(1, 1, -(2 * x2)))
  26.  
  27. vel_bounds_y = c(y1, y_target)
  28. yt = seq(vel_bounds_y[1], vel_bounds_y[2]) %>% map_dfr(function(vy) {
  29.   # Offsets
  30.   offset = 0
  31.   fvy = vy
  32.   if(vy == 0) {
  33.     offset = 1
  34.     fvy = -1
  35.   } else if(vy > 0) {
  36.     offset = (2 * vy) + 1
  37.     fvy = -fvy - 1
  38.   }
  39.  
  40.   # Solve the range of ts where this velocity works
  41.   min_t = ceiling(quadratic_pos(-1, 2 * fvy + 1, -2 * y2))
  42.   max_t = floor(quadratic_pos(-1, 2 * fvy + 1, -2 * y1))
  43.  
  44.   if(min_t <= max_t) {
  45.     tibble(
  46.       y = vy,
  47.       t = (min_t:max_t) + offset
  48.     )
  49.   } else { return(NULL) }
  50. }) %>% unique()
  51.  
  52. tx = unique(yt$t) %>% map_dfr(function(t) {
  53.   #
  54.   # dist = (1/2) * (t) * (2*vx - (t - 1))
  55.   # 2 * dist = t * (2vx - (t - 1))
  56.   # (2 * dist) / t = 2vx - t + 1
  57.   # ((2 * dist) / t) + t - 1 = 2vx
  58.   # (((2 * dist) / t) + t - 1) / 2 = vx
  59.  
  60.   # Solutions where the range of values are in the target
  61.   min_vx_move = ceiling((((2 * x1) / t) + t - 1) / 2)
  62.   max_vx_move = floor((((2 * x2) / t) + t - 1) / 2)
  63.  
  64.   # This is going to include illegal values (where there were some
  65.   # negative velocities) -- clip those. Those occur when t > the velocity
  66.   xrange = min_vx_move:max_vx_move %>% .[. >= t]
  67.  
  68.   # We are excluding cases where the item came to rest before t
  69.   if(min_vx_rest < t) {
  70.     xrange = c(xrange, min_vx_rest:min(t, max_vx_rest)) %>% unique()
  71.   }
  72.  
  73.   tibble(
  74.     t = t,
  75.     x = xrange)
  76. }) %>% unique()
  77.  
  78. answers = yt %>%
  79.   inner_join(tx) %>%
  80.   select(-t) %>%
  81.   unique()
  82.  
  83. nrow(answers)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement