1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-16 13:44:48 +00:00
janet/examples/3sum.dst

14 lines
387 B
Plaintext
Raw Normal View History

2018-03-15 01:46:56 +00:00
(defn sum3
2018-05-05 18:41:47 +00:00
"Solve the 3SUM problem in O(n^2) time."
2018-03-15 01:46:56 +00:00
[s]
(def tab @{})
(def solutions @{})
2018-03-15 01:46:56 +00:00
(def len (length s))
(loop [k :range [0 len]]
2018-03-15 01:46:56 +00:00
(put tab (get s k) k))
(loop [i :range [0 len], j :range [0 len]]
2018-03-15 01:46:56 +00:00
(def k (get tab (- 0 (get s i) (get s j))))
(when (and k (not= k i) (not= k j) (not= i j))
(put solutions {i true j true k true} true)))
(map keys (keys solution)))