#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# How do I write to empty 2d/3d arrays?

edited July 2016

I want to use an array in my program, but I don't know how to write to it initially so I used a for loop to write to it:

``````  if (inc == 0){
for(int h = 0; h < 8; h++){
for(int j = 0; j < 8; j++){
for(int k = 0; k < 8; k++){
bx[h][j][k] = 0;
}
}
}
inc = 1;
}
``````

bx is a 3d array that I made earlier.

Tagged:

## Answers

• ``````// forum.Processing.org/two/discussion/17506/
// how-do-i-write-to-empty-2d-3d-arrays

// GoToLoop (2016-Jul-13)

static final int MIN_VAL = 1, MAX_VAL = 10;
static final int DEPTHS = 2, ROWS = 10, COLS = 4;
final int[][][] three = new int[DEPTHS][ROWS][COLS];

void setup() {
for (int[][] two : three)  for (int[] one : two)
for (int i = 0; i < one.length;
one[i++] = (int) random(MIN_VAL, 1 + MAX_VAL));

println(three); // row from depth: #1, row: #5
exit();
}
``````
• there is a tutorial on arrays and one on 2D arrays --- see section tutorials!

What are 1D, 2D and 3D arrays?

The normal array is a 1D array (or just called array) that is a list - that is enough for most use cases by the way. One index (the row number) accesses one line in the list holding one number / item. Think of a shopping list.

A 2D array stores also only one value / item in each slot, but takes two indexes to access one slot. Think of a chess board: you need row and column number to access one field (or cell in a grid as it is often called). On that field there is one number / item that can be accessed or changed. This 2D array is a grid.

A 3D array are several (e.g. eight) chess boards upon each other. You need row, column and floor-number (etage). That is your example above. This 2D array is a cube.

Remark 1

When you have e.g. 10 cars with x-position, y-position, xspeed, yspeed you don't need a 4D array but 4 parallel 1D arrays to store data for one car in each array in the same row. PM me if you need this.

see

https://forum.processing.org/two/discussion/8082/from-several-variables-to-arrays

A more advanced way of tackle a bunch of variables for one entity (e.g. a car) is a object / class (see tutorial).

see also:

https://forum.processing.org/two/discussion/8081/from-several-arrays-to-classes

Remark 2

Now you don't ask a specific question as far as I can see - or you found the solution already since you define and fill the array correctly (answering your question in the headline).

You could use data from random as gotoloop shows above, or just use an increasing value val++

Or when you have values from excel or so load them from hard drive and put them in your array.

Or just write the data in your code as plain text and read from there, a bit tricky, PM me if you need that.

Remark 3

Next step is to display the 3D array nicely. PM me if you need that.

Best, Chrisir ;-)

• Here is a 3D array with a class

``````// spheres
SphereClass[][][] spheres = new SphereClass;

// data to read and build the the from
String testData = "The quick brown fox jumps over the lazy dog.";

// rotation and Scale
float currentAngle1 = 0;
float zoomScale1    = 1.7;

// Misc
PFont font1;

boolean mouseOnLetterFound=false;

// --------------------------------------------------------
// main funcs

void setup() {
size(1400, 800, OPENGL);
background(111);

// the core :
definespheres();

font1 = createFont("Arial", 14);
textFont(font1);
} // func ---

void draw() {

background(111);

// 3D part ---------------------------------------------------
lights();

camera(0, 0, 810,
0, 0, 0,
0, 1, 0);

scale (zoomScale1);
rotateY(radians(currentAngle1));

showTheGridDependingOnCurrentView();

// rotation
if (keyPressed&&key=='r')
currentAngle1++;
if (keyPressed&&key=='l')
currentAngle1--;

currentAngle1++;

// 2D part / HUD  ---------------------------------------------
camera();
noLights();
fill(0);
text("Hold 'l' to stop rotation. Use mouse wheel to zoom. ", 10, 20 );
} // func

// ------------------------------------------------------------------

void showTheGridDependingOnCurrentView() {
// show spheres : all

mouseOnLetterFound=false;

for (int i = 0; i < spheres.length; i++) {
for (int j = 0; j < spheres[i].length; j++) {
for (int k = 0; k < spheres[i][j].length; k++) {
//
spheres[i][ j][k].show();
//
}// for
}// for
}// for
} // func

// ----------------------------------------------------
// input funcs

void keyPressed () {

if (key!=CODED) {

// not CODED -----------------------------------

if (key=='x'||key=='X') {
// reset
definespheres();
} else if (key == 'h' ) {
//
// do nothing
}
} else {

// if (key==CODED) { --------------------------------------------
//
switch (keyCode) {

case java.awt.event.KeyEvent.VK_PAGE_UP :
zoomScale1-=.01;
break;

case java.awt.event.KeyEvent.VK_PAGE_DOWN :
zoomScale1+=.01;
break;

default :
// do nothing
break;
} // switch
} // else
//
} // func

// ----------------------------------------------------
// misc funcs

void definespheres() {

// define spheres

// distance between spheres
float distanceBetween = (height/10);

// a couter for all cells
int counter = 0;

// triple nested for loop to cover a 3D array
for (int i = 0; i < spheres.length; i++) {
for (int j = 0; j < spheres[i].length; j++) {
for (int k = 0; k < spheres[i][j].length; k++) {

// prepare values
color currentCol = color (0, 0, 255);
boolean exist = true;

// define the random word
String randomWord="";

// different ways to set a value to the word
// randomWord = char(int(random(65, 90))) + ""; // random letter
randomWord = testData.charAt(counter)+"";       // from test data variable
// randomWord = str(counter);     // directly from counter

// increase counter
counter++;

// when using test data, we need to reset counter when we reached
// the end of the testData String:
if (counter>testData.length()-1) {
println("test data to short");
counter = 0; // reset
}

// to make longer random words:
// randomWord+=""+char(int(random(65, 150)));
//randomWord+=""+char(int(random(65, 150)));
//randomWord+=""+char(int(random(65, 150)));

// create a sphere
spheres[ i][ j][ k] = new SphereClass(
-200 + i*distanceBetween,
-185 + j*distanceBetween,
-200 + k*distanceBetween,
currentCol,
exist,
randomWord);
}
}
} // for
} // func

// ----------------------------------------

void mouseWheel(MouseEvent event) {

//This method controls zoomScale1 variable

if (event.getCount()==-1)
zoomScale1 += 0.1;
else if (event.getCount()==1) {
if (zoomScale1>=.1)
zoomScale1 -= 0.1;
}

// check lower boundary
if (zoomScale1<.1)
zoomScale1 = .1;
}

// =====================================================
// classes

class SphereClass {

// this class represents one Cell

// 3D position in pixel
float x;
float y;
float z;

// current 2D position
float scX;
float scY;

color col;
color defaultCol;
boolean exist;

String textSphere;

// control the output
boolean showRect   = false;
boolean showSphere = false;

// constr
SphereClass(float x_, float y_, float z_,
color col_,
boolean exist_,
String word_) {

x = x_;
y = y_;
z = z_;

// println (z);

col = col_;
defaultCol = col;

exist = exist_;
textSphere=word_;
} // constr

void show() {
pushMatrix();
translate(x, y, z);

rotateY( - radians(currentAngle1));

fill(col);
noStroke();

if (showSphere) {
sphere(6);
}

if (showRect) {
noFill();
stroke(col);
int radius=14;
rect ( -3, -radius, radius+3, radius+4);
}

text(textSphere, 0, 0);

// the sphere / box was drawn at (0, 0, 0), store that location as 2D
scX = screenX(0, 0, 0);
scY = screenY(0, 0, 0);

if (dist(mouseX, mouseY, scX, scY)<22&&!mouseOnLetterFound) {
col=color(255, 2, 2);
mouseOnLetterFound=true;
} else {
col=color (0, 0, 255);
}

popMatrix();
} // method
} // class

// ==============================================================

class PVectorInt {
// It's like a PVector but int (not float).
//
// This is a compact form to store a 3D index
// for the 3D grid.
//
int x, y, z;

PVectorInt(int x_, int y_, int z_) {
x=x_;
y=y_;
z=z_;
} // constr
} // class
// ============================================================
``````
• edited July 2016 Answer ✓

we can use our data String `testData` to define a cube of boxes.

We can let the String determine

• which boxes inside the cube exist and which doesn't and

• which boxes are red and which are blue.

The letter stores this data. The letter itself doesn't need to be displayed here.

``````// spheres
SphereClass[][][] spheres = new SphereClass;

// data to read and build the the from
// String testData = "The quick brown fox jumps over the lazy dog. ";
String testData =
" he qu  k brown fox       ove     ee"+
"                 o                 e" +
"      v           x        v       e" +
" he     k brown    x   ps      the l"+
"x                          v        " +
"  e        v      dd       v     eex" +
"D" ; // last letter D is a dummy
// String testData = "The quickbrown foxjumpsoverthelazydog ";

// rotation and Scale
float currentAngle1 = 0;
float zoomScale1    = 1.7;

// Misc
PFont font1;

boolean mouseOnLetterFound=false;

// --------------------------------------------------------
// main funcs

void setup() {
size(1400, 800, OPENGL);
background(111);

// the core :
definespheres();

font1 = createFont("Arial", 14);
textFont(font1);
} // func ---

void draw() {

background(111);

// 3D part ---------------------------------------------------

camera(0, 0, 810,
0, 0, 0,
0, 1, 0);

lights();
directionalLight(255, 222, 255, 0, -1, 0);

scale (zoomScale1);
rotateY(radians(currentAngle1));

showTheGridDependingOnCurrentView();

// rotation
if (keyPressed&&key=='r')
currentAngle1++;
if (keyPressed&&key=='l')
currentAngle1--;

currentAngle1++;

// 2D part / HUD  ---------------------------------------------
camera();
noLights();
fill(0);
text("Hold 'l' to stop rotation. Use mouse wheel to zoom. ", 10, 20 );
} // func

// ------------------------------------------------------------------

void showTheGridDependingOnCurrentView() {
// show spheres : all

mouseOnLetterFound=false;

for (int i = 0; i < spheres.length; i++) {
for (int j = 0; j < spheres[i].length; j++) {
for (int k = 0; k < spheres[i][j].length; k++) {
//
if (spheres[i][ j][k]!=null)
spheres[i][ j][k].show();
//
}// for
}// for
}// for
} // func

// ----------------------------------------------------
// input funcs

void keyPressed () {

if (key!=CODED) {

// not CODED -----------------------------------

if (key=='x'||key=='X') {
// reset
definespheres();
} else if (key == 'h' ) {
//
// do nothing
}
} // if
} // func

// ----------------------------------------------------
// misc funcs

void definespheres() {

// define spheres

// distance between spheres
float distanceBetween = (height/10);

// a couter for all cells
int counter = 0;

// triple nested for loop to cover a 3D array
for (int i = 0; i < spheres.length; i++) {
for (int j = 0; j < spheres[i].length; j++) {
for (int k = 0; k < spheres[i][j].length; k++) {

// prepare values
color currentCol = color (0, 0, 255);
boolean exist = true;

// define the random word
String randomWord="";

// different ways to set a value to the word
// randomWord = char(int(random(65, 90))) + ""; // random letter
randomWord = testData.charAt(counter)+"";       // from test data variable
// randomWord = str(counter);     // directly from counter

// increase counter
counter++;

// when using test data, we need to reset counter when we reached
// the end of the testData String:
if (counter>testData.length()-1) {
println("test data to short");
counter = 0; // reset
return;
}

// to make longer random words:
// randomWord+=""+char(int(random(65, 150)));
//randomWord+=""+char(int(random(65, 150)));
//randomWord+=""+char(int(random(65, 150)));

// create a sphere
spheres[ i][ j][ k] = new SphereClass(
-200 + i*distanceBetween,
-185 + j*distanceBetween,
-200 + k*distanceBetween,
currentCol,
exist,
randomWord);
}
}
} // for
} // func

// ----------------------------------------

void mouseWheel(MouseEvent event) {

//This method controls zoomScale1 variable

if (event.getCount()==-1)
zoomScale1 += 0.1;
else if (event.getCount()==1) {
if (zoomScale1>=.1)
zoomScale1 -= 0.1;
}

// check lower boundary
if (zoomScale1<.1)
zoomScale1 = .1;
}

// =====================================================
// classes

class SphereClass {

// this class represents one Cell

// 3D position in pixel
float x;
float y;
float z;

// current 2D position
float scX;
float scY;

color col;
color defaultCol;
boolean exist;

String textSphere;

// control the output
boolean showRect   = false;
boolean showSphere = false;

// constr
SphereClass(float x_, float y_, float z_,
color col_,
boolean exist_,
String word_) {

x = x_;
y = y_;
z = z_;

// println (z);

col = col_;
defaultCol = col;

exist = exist_;
textSphere=word_;
} // constr

void show() {
pushMatrix();
translate(x, y, z);

// we rotate the letter against (hence the minus) the general rotation of the cube so that
// the letter always faces the camera (so the user can better read the letter) :
// rotateY( - radians(currentAngle1));

// color
fill(col);
noStroke();

// optional sphere
if (showSphere) {
sphere(6);
}

// optional rect
if (showRect) {
noFill();
stroke(col);
int radius=14;
rect ( -3, -radius, radius+3, radius+4);
}

// optional box
if (true && !textSphere.equals(" ")) {
float distanceBetween = (height/10);
//println (distanceBetween);
noFill();
stroke(0);
// noStroke();

if (textSphere.equals("e"))
fill(255, 2, 2); // red
else
fill(col);  // normal color / blue or so

int radius=14;
box ( distanceBetween );
}

// the text
pushMatrix();
translate(-62, 0, 0);
fill(col);
text(textSphere, 0, 0);
popMatrix();

// the sphere / box was drawn at (0, 0, 0), store that location as 2D
scX = screenX(0, 0, 0);
scY = screenY(0, 0, 0);

// optional: compare to mouse position; make the first found letter red
if (dist(mouseX, mouseY, scX, scY)<22 && !mouseOnLetterFound) {
col=color(255, 2, 2); // red
mouseOnLetterFound=true;
} else {
col=defaultCol; // blue
}

popMatrix();
} // method
} // class

// ==============================================================

class PVectorInt {
// It's like a PVector but int (not float).
//
// This is a compact form to store a 3D index
// for the 3D grid.
//
int x, y, z;

PVectorInt(int x_, int y_, int z_) {
x=x_;
y=y_;
z=z_;
} // constr
} // class
// ===============================================================
``````
Sign In or Register to comment.