View Category
Find the distance between two points
ruby
# the hypotenuse sqrt(x**2+y**2)
distance = Math.hypot(x2-x1,y2-y1)
distance = Math.hypot(x2-x1,y2-y1)
clojure
(defstruct point :x :y)
(defn distance
"Euclidean distance between 2 points"
[p1 p2]
(Math/pow (+ (Math/pow (- (:x p1) (:x p2)) 2)
(Math/pow (- (:y p1) (:y p2)) 2))
0.5))
(distance (struct point 0 0) (struct point 1 1)) ; => 1.4142135623730951
(defn distance
"Euclidean distance between 2 points"
[p1 p2]
(Math/pow (+ (Math/pow (- (:x p1) (:x p2)) 2)
(Math/pow (- (:y p1) (:y p2)) 2))
0.5))
(distance (struct point 0 0) (struct point 1 1)) ; => 1.4142135623730951
(defn distance
"Euclidean distance between 2 points"
[[x1 y1] [x2 y2]]
(Math/sqrt
(+ (Math/pow (- x1 x2) 2)
(Math/pow (- y1 y2) 2))))
(distance [2 2] [3 3])
"Euclidean distance between 2 points"
[[x1 y1] [x2 y2]]
(Math/sqrt
(+ (Math/pow (- x1 x2) 2)
(Math/pow (- y1 y2) 2))))
(distance [2 2] [3 3])
Zero pad a number
Given the number 42, pad it to 8 characters like 00000042
ruby
42.to_s.rjust(8,"0")
"%08d" % 42
clojure
(defn pad
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
(defn pad [x]
(format "%08d" x))
(format "%08d" x))
(format "%08d" 42)
Right Space pad a number
Given the number 1024 right pad it to 6 characters
"1024 "
ruby
1024.to_s.ljust(6)
clojure
(let [s (str 1024)
l (count s)]
(str s (reduce str (repeat (- 6 l) " "))))
l (count s)]
(str s (reduce str (repeat (- 6 l) " "))))
Format a decimal number
Format the number 7/8 as a decimal with 2 places: 0.88
ruby
(7.0/8.0*100).round/100.0
(7.0/8.0).round(2)
clojure
(format "%3.2f" (/ 7.0 8))
(* 0.01 (Math/round (* 100 (float (/ 7 8)))))
Left Space pad a number
Given the number 73 left pad it to 10 characters
" 73"
ruby
73.to_s.rjust(10)
clojure
(let [s (str 73)
l (count s)]
(str (reduce str (repeat (- 10 l) " ")) s ))
l (count s)]
(str (reduce str (repeat (- 10 l) " ")) s ))
Generate a random integer in a given range
Produce a random integer between 100 and 200 inclusive
ruby
randomInt = rand(200-100+1)+100;
clojure
(+ (rand-int (- 201 100)) 100)
Generate a repeatable random number sequence
Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
ruby
srand(12345)
first = (1..5).collect {rand}
srand(12345)
second = (1..5).collect {rand}
puts first == second
first = (1..5).collect {rand}
srand(12345)
second = (1..5).collect {rand}
puts first == second
clojure
(dotimes [_ 2]
(let [r (java.util.Random. 12345)]
(dotimes [_ 5]
(println (.nextInt r 100))))
(println))
(let [r (java.util.Random. 12345)]
(dotimes [_ 5]
(println (.nextInt r 100))))
(println))
