1
0
mirror of https://github.com/janet-lang/janet synced 2024-09-28 15:08:40 +00:00
janet/examples/3sum.janet
Calvin Rose 6b95326d7c First commit removing the integer number type. This should
remove some complexity and unexpected behavior around numbers in
general as all numbers are the same number type, IEEE 754 double
precision numbers. Also update examples and tests, some of which were
out of date.

Some more testing may be needed for new changes to numbers.
2018-12-27 13:05:29 -05:00

19 lines
485 B
Plaintext

(defn sum3
"Solve the 3SUM problem in O(n^2) time."
[s]
(def tab @{})
(def solutions @{})
(def len (length s))
(for k 0 len
(put tab s.k k))
(for i 0 len
(for j 0 len
(def k (get tab (- 0 s.i 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 solutions)))
(def arr @[2 4 1 3 8 7 -3 -1 12 -5 -8])
(print "3sum of " (string/pretty arr) ":")
(print (string/pretty (sum3 arr)))