Scanning for Pythagorean triplets in Clojure
Notes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
;; find_py_triplets.clj
(defn pythogorean-triplet?
"Returns `true` if passed arguments are pythogorean triplets.
**Usage**
```clojure
(pythogorean-triplet? 3 4 5)
```"
[a b c]
(let [[x y z] (sort [a b c])]
(=
(* z z)
(+
(* x x)
(* y y)))))
(defn number-combinations
"
Take in a range and returns combinations of numbers
**Usage**
```clojure
(number-combinations (range 1 3)) ; #{(1 1 1) (2 2 2) (1 1 2) (1 2 2)}
```"
[nums]
(set
(for [x nums
y nums
z nums]
(sort (list x y z)))))
(defn filter-triplets [num-combinations]
"
Given number combinations, filters out one those are
pythogorean triplets
**Usage**
```clojure
filter-triplets [[1 2 3] [5 3 4]]) ; ([5 3 4])
```"
(filter
#(pythogorean-triplet?
(first %)
(nth % 1)
(last %))
num-combinations))
(defn find-py-triplets
"
Finds all Pythogorean Triplets berween `start` and `end`
numbers.
**Usage**
```clojure
(find-py-triplets 1 10) ; ((3 4 5) (6 8 10))
```
"
[start end]
(let [numbers (range start (inc end))
combinations (number-combinations numbers)
triplets (filter-triplets combinations)]
(sort-by first triplets)))