VsSekorin
VsSekorin

Reputation: 375

Clojure create two-dimensional array with default value

How I can create two-dimensional array (matrix) with some default value in Clojure?

Example:

user=> (double-array-2d 3 4 Double/MIN_VALUE)
[[4.9E-324, 4.9E-324, 4.9E-324, 4.9E-324],
 [4.9E-324, 4.9E-324, 4.9E-324, 4.9E-324],
 [4.9E-324, 4.9E-324, 4.9E-324, 4.9E-324]]

And how I can mutate this later?

user=> (def arr2d (double-array-2d 3 4 0))
user=> (set! arr2d 1 1 5)
user=> (pprint arr2d)
[[0.0, 0.0, 0.0, 0.0],
 [0.0, 5.0, 0.0, 0.0],
 [0.0, 0.0, 0.0, 0.0]]
nil

Upvotes: 1

Views: 628

Answers (3)

Satyam Ramawat
Satyam Ramawat

Reputation: 37

For creating two-dimensional array in Clojure, You can refer predefined Function "to-array-2d" from here.

Upvotes: 1

Taylor Wood
Taylor Wood

Reputation: 16194

If you want to initialize with a default value or any other sequence input, you can feed typed arrays into into-array:

(def arr2d
  (into-array (repeat 3 (double-array 4 Double/MIN_VALUE))))

double-array and other typed array constructors can take either a default value or an input sequence.

(clojure.pprint/pprint arr2d)
[[4.9E-324, 4.9E-324, 4.9E-324, 4.9E-324],
 [4.9E-324, 4.9E-324, 4.9E-324, 4.9E-324],
 [4.9E-324, 4.9E-324, 4.9E-324, 4.9E-324]]

There's also a make-array function, you just give it a type and dimension(s), but it doesn't take a default value:

(make-array Double/TYPE 3 2)
=> #object["[[D" 0x3ae2ca60 "[[D@3ae2ca60"]
(def arr2d (make-array Double/TYPE 3 4))

You can use aset to set a value at given indices:

(aset arr2d 1 1 5)
=> 5

This has mutated the array in-place, and printing arr2d reflects that:

(clojure.pprint/pprint arr2d)
;; [[0.0, 0.0, 0.0, 0.0], [0.0, 5.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]

Upvotes: 3

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

here's an example using `java.util.Arrays/fill to fill each array

user> (defn my-array [x y]
        (let [arr (make-array Double/TYPE x y)]
          (doseq [i (range x)]
                 (java.util.Arrays/fill (aget arr i) Double/MIN_VALUE))
          arr))
#'user/my-array

user> (def thing (my-array 3 4))
#'user/thing

user> (doseq [i (range 3)
              j (range 4)]
        (println (aget thing i j)))
4.9E-324
4.9E-324
4.9E-324
4.9E-324
4.9E-324
4.9E-324
4.9E-324
4.9E-324
4.9E-324
4.9E-324
4.9E-324
4.9E-324

Upvotes: 0

Related Questions