Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple 2D array in Clojure

Tags:

clojure

I'm still learning Clojure and can't seem to find a simple answer for this. I've seen similar questions answered with complex code specific for the OP's issue so please let me know the most accurate or acceptable version of the following:

int[][] arrayTest = new int[width][height];
...
for (int x = 0; x < width; x++) {
  for (int y = 0; y < height; y++) {
    int a = arrayTest[x][y];
    if (a < 100) {
      arrayTest[x][y] = 0;
    }
  }
}
like image 271
user10185182 Avatar asked Dec 17 '25 19:12

user10185182


1 Answers

The literal translation is straightforward:

(def array-test
  (make-array Integer/TYPE width height))

(doseq [x (range width)
        y (range height)]
  (when (< (aget array-test x y) 100)
    (aset-int array-test x y 0)))

Note, however, that arrays are not commonly used in Clojure. Unless you want to do fast computations or work with existing Java code, you shouldn't normally be creating arrays and other mutable data structures. Most likely, what you want to implement can be done with Clojure's persistent collections instead.

like image 179
Aleph Aleph Avatar answered Dec 19 '25 22:12

Aleph Aleph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!