Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a primitive two-dimensional (2d) array of doubles in Clojure?

Tags:

A Java API I am Clojure interoping with requires that I pass it a 2d array of doubles; double[][]. How do I create a primitive 2d array of doubles in Clojure? I am looking for something like this

(double-array-2d [[1 2] [3 4]])

This function would have a Java return type of double[][].

like image 973
Julien Chastang Avatar asked Oct 05 '10 22:10

Julien Chastang


People also ask

Are 2D arrays primitive?

Java Two Dimensional Array of Primitive Type Arrays are a collection of elements that have similar data types. Hence, we can create an array of primitive data types as well as objects. A 2D array of a primitive data type in Java (let's say int) is simply an array of Integer arrays.

How do we initialize a two dimensional array?

Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row.

Can you add to a 2D array?

You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.


2 Answers

Try this:

(into-array (map double-array [[1 2] [3 4]])) 
like image 163
fogus Avatar answered Dec 26 '22 18:12

fogus


Try this:

(defn double-array-2d [coll]   (let [w (count coll)         h (apply max (map count coll))         arr (make-array Double/TYPE w h)]     (doseq [x (range w)             y (range h)]       (aset arr x y (double (get-in coll [x y]))))     arr)) 
like image 23
Brian Carper Avatar answered Dec 26 '22 18:12

Brian Carper