简体   繁体   中英

Deep copy between two 2D Arrays in Processing

For a project i'm working on, I have two grids formed by 2D Arrays, one of which allows the user to draw an image into it, the other displays the last image submited. However my code is making a shallow copy of it instead of a deep one, and I need to find a way to deep copy in Processing. Here's a snippet of my shallow copy code:

   for (int i = 0; i < cols; i++) {
     for (int j = 0; j < rows; j++) {
     mainGrid[i][j] = userGrid[i][j];
    }
  }

What's the simplest way of doing this in Processing? I've been searching extensively for the simplest way for me to deep copy all the contents of my userGrid into my mainGrid, such as using the Java Deep-Copy library, but I'm not quite sure how to use the tools of this library to copy a 2D array into another one.

Simplest option I see using arrayCopy() which is flexible and designed for that. Here's a quick demo:

int nx = 5;
int ny = 5;
int[][] mainGrid;
int[][] userGrid;

void setup(){
  //init
  mainGrid = new int[nx][ny];
  userGrid = new int[nx][ny];
  //populate with dummy data to test
  for(int y = 0 ; y < ny; y++){
    for(int x = 0; x < nx; x++){
      userGrid[x][y] = round(random(nx)+random(ny));
    }
  } 

  println("userGrid:\n"+print2DArray(userGrid,nx,ny,true));

  arrayCopy(userGrid,mainGrid);//copy userGrid into mainGrid

  println("mainGrid:\n"+print2DArray(mainGrid,nx,ny,true));
}
//utility to pretty print 2D arrays 
String print2DArray(int[][] arr,int sx,int sy,boolean printIds){
  String out = "";
  for(int i = 0 ; i < sx*sy; i++){
    int x = i/sx;
    int y = i%sx;
    boolean isLastOnLine = i%sx == sx-1;
    out += (printIds ? "["+x+"]"+"["+y+"]:" : "")+arr[x][y]+(isLastOnLine ? "":",");
    if(isLastOnLine) out += "\n"; 
  }
  return out;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM