Saving/Storing a multidimensional array

For completeness’ sake I’m posting the “finalized” version which adds the loading part: :angel:

/**
 * Conversion Arr3d to JSONArr3d (v1.0)
 * GoToLoop (2019/Dec/17)
 * Discourse.Processing.org/t/saving-storing-a-multidimensional-array/16391/5
 */

static final String FILENAME = "JArr3D.json", OPT = "compact";
static final int RANGE = 100, DIMS = 4;

double[][][] my3dArr = generateArr3d(RANGE, DIMS);
JSONArray my3dJarr;

void setup() {
  my3dJarr = arr3dToJarr3d(my3dArr);
  println(my3dJarr.format(-1));
  saveJSONArray(my3dJarr, dataPath(FILENAME), OPT);

  my3dJarr = loadJSONArray(FILENAME);
  my3dArr = jarr3dToArr3d(my3dJarr);
  println(joinArr3d(my3dArr));

  exit();
}

static final JSONArray arr3dToJarr3d(final double[][][] arr3d) {
  final JSONArray jarr3d = new JSONArray();

  for (final double[][] arr2d : arr3d) {
    final JSONArray jarr2d = new JSONArray();
    jarr3d.append(jarr2d);

    for (final double[] arr1d : arr2d) {
      final JSONArray jarr1d = new JSONArray();
      jarr2d.append(jarr1d);

      for (final double d : arr1d)  jarr1d.append(d);
    }
  }

  return jarr3d;
}

static final double[][][] jarr3dToArr3d(final JSONArray jarr3d) {
  final int lenZ = jarr3d.size();
  final double[][][] arr3d = new double[lenZ][][];

  for (int z = 0; z < lenZ; ++z) {
    final JSONArray jarr2d = jarr3d.getJSONArray(z);
    final int lenY = jarr2d.size();
    final double[][] arr2d = arr3d[z] = new double[lenY][];

    for (int y = 0; y < lenY; ++y)
      arr2d[y] = jarr2d.getJSONArray(y).getDoubleArray();
  }

  return arr3d;
}

static final String joinArr3d(final double[][][] arr3d) {
  final StringBuilder sb = new StringBuilder();
  int idxZ = 0;

  for (final double[][] arr2d : arr3d) {
    int idxY = 0;
    sb.append(ENTER);

    for (final double[] arr1d : arr2d) {
      int idxX = 0;

      for (final double d : arr1d)  sb
        .append('[').append(idxZ).append("][")
        .append(idxY).append("][").append(idxX++)
        .append("] ").append(d).append(ENTER);

      ++idxY;
    }

    ++idxZ;
  }

  return sb.toString();
}

double[][][] generateArr3d(final double valRange, final int dimsRange) {
  return generateArr3d(valRange, dimsRange, dimsRange, dimsRange);
}

double[][][] generateArr3d(
  final double valRange, 
  final int depthRange, 
  final int heightRange, 
  final int widthRange) {

  final int d = (int) random(1, depthRange + 1);
  final int h = (int) random(1, heightRange + 1);
  final int w = (int) random(1, widthRange + 1);

  final double[][][] arr3d = new double[d][h][w];
  println(d, h, w);

  for (final double[][] arr2d : arr3d)  for (final double[] arr1d : arr2d)
    for (int i = 0; i < w; arr1d[i++] = Math.random() * valRange);

  return arr3d;
}
3 Likes