musifter

AoC 2021, day 3 (dc part 2)

Jul 3rd, 2026 (edited)
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.07 KB | Source Code | 0 0
  1. # Command:
  2. #
  3. # highbit = 2048
  4. # dc -e`dc -e"$highbit sb" -e'2i' -finput -e"[1r-] sN" -fdc-p2.dc` \
  5. #    -e`dc -e"$highbit sb" -e'2i' -finput -e"[] sN"    -fdc-p2.dc` \
  6. #    -e'*p'
  7. #
  8. # Script takes two pieces of input code:
  9. #     1) setting b to the high bit (2048 for the input or 16 for test)
  10. #     2) an N macro to negate the logic for the Oxygen calculation
  11. #
  12.  
  13. Ai                  # back to decimal
  14.  
  15. #2048sb              # for input (pass in this or 16sb for test case)
  16.  
  17. # Quit reducing: size setIndex
  18. [
  19.     *               # clear size=1
  20.     1 r;Gx          # get first/only value in array[setIndex]
  21.     lb lo *+ p      # apply remainder if needed and print exit
  22.     q               # quit
  23. ] sq
  24.  
  25. # Macros so we can get and set to different arrays with
  26. # value index array ;Sx  -> this does array[array][index] = value
  27. # index array ;Gx        -> this returns array[array][index]
  28. [:0] 0:S [:1] 1:S
  29. [;0] 0:G [;1] 1:G
  30.  
  31. # Filter: i=size num1 num2 num3 ...
  32. [
  33.     0Sn                     # clear counts
  34.     # num1 num2 num3 ...
  35.     [
  36.         lb                  # b num
  37.         ~r                  # bit rest
  38.  
  39.         dd;n 1+ d_3Rr:n     # num[bit]++; num[bit] bit rest
  40.         r;Sx                # array[bit][num] = rest; num2 ...
  41.  
  42.         z 0<L
  43.     ] dsLx
  44.  
  45.     # 0s - 1s | +'ve  0   -'ve
  46.     # --------+---------=--------
  47.     # Oxygen  |  0    1    1
  48.     # CO2     |  1    0    0
  49.     #
  50.     # So we want d.-1/ (1 if +'ve, 0 if 0 or -'ve), and to negate (1r-) for the Oxygen
  51.     0;n 1;n- d.1-/ lNx      # do check to get index of target array
  52.     dlo 2*+ so              # append that bit to the output
  53.  
  54.     d;n                     # i=size setIndex
  55.     d1=q                    # stop if only one left
  56.  
  57.     # load passing values from successful array back onto stack
  58.     [
  59.         r d3R d3R           # set i i  set
  60.         ;Gx                 # get( set[i] ) i set
  61.         _3R 1- d0<I         # i-- set get(set[i])
  62.     ] dsIx *+               # clear i=0 and set
  63.  
  64.     lb2/dsb 0<F             # shift highbit right, loop until we quit or run off end
  65. ] dsFx
  66.  
Advertisement
Add Comment
Please, Sign In to add comment