musifter

heap.dc (needed for day 8 part 1 dc sol'n)

Dec 14th, 2025
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.80 KB | Source Code | 0 0
  1. [s.q] sQ
  2. [+s.q] sX
  3. [r]  sr
  4.  
  5. 0 s0
  6. 1 s1
  7. 2 s2
  8. 3 s3
  9. 4 s4
  10. _5 s_
  11. _3 s-
  12.  
  13. # sort minmax indices
  14. [
  15.     dl3R dl3R ;hr;h            # a b -> h(b) h(a) b a
  16.     <r                       #     -> (index of max) (index of min)
  17. ] s~
  18.  
  19. # heapify: sort heap (index ->)
  20. [
  21.     dddl2*                    # left index index index
  22.     d lh !<~                 # max min(left, index) index index
  23.     s.                       # clear max
  24.     rl2*l1+                    # right min(left, index) index
  25.     d lh !<~                 # max min(left, right, index) index
  26.     s.                       # clear max
  27.  
  28.     dl3R dl3R                  # min index index min
  29.     =X                       # clear stack and quit if no change
  30.  
  31.     r
  32.     dl3R dl3R                  # min index index min
  33.     ;hr;h                    # h(index) h(min) index min
  34.  
  35.     l4Rdl_R                   # min h(index) h(min) index min
  36.     :hr:h                    # swap h(min) with h(index); min
  37.     l@x                      # recurse on min index
  38. ] s@
  39.  
  40. # insert item (item ->)
  41. [
  42.     #[insert: ]np
  43.     lh l1+ dsh                # ++end item
  44.     dl-R :h                  # h(end) = item; end
  45.  
  46.     # stack: i = end
  47.     [
  48.         dl2/dd;h l4R d ;h l3R   # h(1/2) h(i) i i/2 i/2
  49.         <X                   # parent less than child, done
  50.         dl3R dl3R              # i i/2 i/2 i i/2
  51.         ;hr;h                # h(i/2) h(i) i/2 i i/2
  52.         l4R:h r:h             # swap h(i), h(i/2); i/2
  53.         d l1<L
  54.     ] dsLx
  55.     s.
  56. ] s<
  57.  
  58. # get next (-> item) (doesn't check for empty)
  59. [
  60.     l1;h                     # item
  61.     lh dl1- sh               # end--; end item
  62.     d l1=Q                   # no items left after this, return item
  63.     ;h l1:h                  # h(1) = h(end); item
  64.     l1 l@x                   # sort heap from 1
  65. ] s>
  66.  
Advertisement
Add Comment
Please, Sign In to add comment