# How to compare two 2d arrays and check if a value is in it

so, i have a grid of objects and when the mouse enters they disappear, how ever when the mouse enters other object it reappears, I’ve searched for a solution in the 2D arrays, how ever I don’t understand them that much… so if some could help me with this problem it would be great

``````int[][] prev = {{}, {}};
int [][] pos = {{}, {}};
int objX;
int objY;
int x;
int y;
int w;
int h;
boolean appended = false;
int lastX = 1;
int lastY = 1;
void setup() {
size(400, 400);
}
void draw() {
objX = mouseX;
objY = mouseY;
x = 60;
y = 60;
h = 60;
w = 60;
background(0);
fill(255);

crate();
}

void crate() {
for (int i = 0; i < 4*w +10; i += w + 10) {
for (int j = 0; j < 2*h + 10; j += h + 10) {
if (appended == false) {
pos = (int[][]) append(pos, new int[] { i, j });
appended = true;
}
if  (objX < x + i + w && objX > x + i && objY < y + j + w && objY > y + j && !(lastX == i && lastY == Y)) {
prev = (int[][]) append(prev, new int[] { i, j });
lastX = i;
lastY = j;
println(prev);
}
if (/*comare if a value from prev is on pos*/ !(i == lastX && j == lastY)) {
ellipse(x+i, y+j, w, h); /*the efect should be the same... only that the square dosn't reappear*/
}
}
}
}

``````

Use this as a reference for your Code :

``````bool[] crates = new bool;

void setup() {
size(300,600);

//set all to true (false by default)
for (int i = 0; i < crates.length; i++) crates[i] = true;
}

void draw() {

//refresh background
background(0);

//draw the crates
drawCrates();

//check in which crate the mouse should be
checkOverlap();

}

void drawCrates() {

//loop through all crates
for (int i = 0; i < crates.length; i++) {

//check if crate is empty (false if mouse is in crate)
if (crates[i]) {

//draw the crate according to (offsetX + rowIndex (%4 means 4 per row) * width of the crate, offsetY+ columnIndex(floor(/4) means n columns with 4 each until no crates are left) * height of the crate, width, height)
ellipse(50 + i%4 * 60,50 + floor(i/4) * 60, 50, 50);
}
}
}

void checkOverlap() {

//loop through all crates
for (int i = 0; i < crates.length; i++) {

//if the mouse is within the circumference of the crate, it is inside, so we set it to false
if (dist(mouseX, mouseY, 50 + i%4 * 60, 50 + floor(i/4) * 60) < 30) {

// this part is because you said to set the crate back to empty only if it's within another crate (so if we move away from the crate without entering another, the last crate we were in won't get set to empty)
//if you don't want that, delete the loop and use "else crate[i] = true;" after the if statements closing bracket

//loop through all crates and set them to true (we only do this if we alreayy have a new crate)
for (int j = 0; j < crates.length; j++) crates[j] = true;

//set the crate we're in to false
crates[i] = false;
}
}
}
``````
1 Like