Skip to content

Instantly share code, notes, and snippets.

@ap29600
Last active August 31, 2024 14:21
Show Gist options
  • Save ap29600/e3b3f014235fbe48c35634a81a8f98f2 to your computer and use it in GitHub Desktop.
Save ap29600/e3b3f014235fbe48c35634a81a8f98f2 to your computer and use it in GitHub Desktop.
A BQN function performing associative reductions on paths of an array
# s0‿o1 𝔽_associativeReduce 𝕩: 𝔽´¨ on paths in 𝕩 of s steps with stride (=𝕩)↑o1
#
# example:
# m ≡ 4‿(¯1‿1) +_associativeReduce x
# +-------+ +-------------+
# | . . . | | . . . . . . |
# | y . . | | . . . d . . |
# +-------+ | . . c . . . |
# | . b . . . . |
# y ≡ +´a‿b‿c‿d | a . . . . . |
# +-------------+
#
# shortened forms:
# s0‿o0 𝔽_associativeReduce 𝕩 ←→ s0‿(⥊o0) 𝔽_associativeReduce 𝕩
# s0 𝔽_associativeReduce 𝕩 ←→ s0‿1 𝔽_associativeReduce 𝕩
_associativeReduce {
s‿o←2↑𝕨∾1
o<↩
i←2⋆↕1+⌊2⋆⁼s # powers of 2: step sizes
m←2|⌊s÷i # base 2 representation of s
l←»+`m/i
# <combine> <--trim to fit--> <select> <--length-i windows-->
𝔽´ (-o×s-l+m/i)↓¨(o×l)↓¨ m/ (-⊸↓𝔽↓)˜`(<𝕩)∾oׯ1↓i
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment