Skip to content

Instantly share code, notes, and snippets.

@oantolin
Created June 24, 2025 16:33
Show Gist options
  • Select an option

  • Save oantolin/8b1c3bea3dc65e714a799fb00aa47a57 to your computer and use it in GitHub Desktop.

Select an option

Save oantolin/8b1c3bea3dc65e714a799fb00aa47a57 to your computer and use it in GitHub Desktop.
A* implementation in BQN
Heap ⇐ {𝕀
items ← ⟨⟩
Lt ← 1+2Γ—βŠ’ β‹„ Rt ← 2Γ—1+⊒ β‹„ Up ← (⌊÷⟜2)-(Β¬2⊸|)
Swap ← {items (⌽⌾(π•¨β€Ώπ•©βŠΈβŠ))↩ β‹„ 𝕩}
SiftUp ← Swap⟜Up β€’_while_ {𝕩>0?<β—‹(βŠ‘βŠ‘βŸœitems)⟜Up 𝕩;0}
MinChild ← {(Rt𝕩)<β‰ items? {Lt⊸(<β—‹(βŠ‘βŠ‘βŸœitems))⟜Rt 𝕩? Lt𝕩; Rt𝕩}𝕩; Lt𝕩}
SiftDown ← {π•Š:Swap⟜MinChildβ€’_while_{(Lt𝕩)<β‰ items?>β—‹(βŠ‘βŠ‘βŸœitems)⟜MinChild 𝕩;0} 0}
Add ⇐ {items βˆΎβ†© βŸ¨π•¨β€Ώπ•©βŸ© β‹„ SiftUp (β‰ items)-1 β‹„ @}
PopMin ⇐ {π•Š: tβ†βŠ‘items β‹„ 0 Swap Β―1 β‹„ itemsβ†“Λœβ†©Β―1 β‹„ SiftDown@ β‹„ t}
Empty ⇐ {π•Š:βŸ¨βŸ©β‰‘items}
𝕨 AddΒ¨ 𝕩
}
_path_ ⇐ {
Moves _𝕣_ Goal s0: 3=β€’Type goal? Moves _𝕣_ Goalβ€Ώ0 s0;
Moves _𝕣_ Goalβ€ΏH s0:
costβ€Ώfromβ€Ώopen ← ⟨⟨s0⟩ β€’HashMap ⟨0⟩, ⟨⟩ β€’HashMap ⟨⟩, ⟨0⟩ Heap ⟨s0⟩⟩
end ← {𝕀
s ← 1βŠ‘open.PopMin@
{nβ€Ώc:
d ← c+cost.Get s,
{d<∞ cost.Get n? n cost.Set d β‹„ n from.Set s β‹„ (d + H n) open.Add n; @}
}˘ (1==)β—ΆβŸ¨βŠ’,β‰βŸœ1˘⟩ Moves s
s
} β€’_while_ {Β¬(open.Empty@)∨Goal 𝕩} s0
{Goal end? (cost.Get end) β‹ˆ from.Getβˆ˜βŠ‘βŠΈβˆΎ β€’_while_ (from.Hasβˆ˜βŠ‘) ⟨end⟩}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment