简体   繁体   中英

loop through sections of an array

Was looking to see if i can get a bit of help with a problem. So i am currently trying to loop through sections of a 2d array and unsure how to do it.

essentially I'm going to have an array 4x4 or 9x9 or 25x25, and i need to be able to iterate over blocks and check for duplicates.

for example 4x4, i would iterate over 4 2x2 arrays. the 9x9 would be 9 3x3 arrays etc.

been trying for a while but have had no luck i have tried this

any help would be great, cheers

If the arrays are always 2d then you could do something like this:

import java.util.ArrayList;
import java.util.List;

class Main {
  public static void main(String[] args) {

      // Initialize the 2d array
      int size = 3;
      int[][] table = new int[size][size];
      for (int row = 0; row < size; row ++)
          for (int col = 0; col < size; col++)
              table[row][col] = (int) (20.0 * Math.random());

      // Scan for duplicates
      List seen = new ArrayList();
      List duplicates = new ArrayList();

      for (int row = 0; row < size; row ++) {
          for (int col = 0; col < size; col++) {
            boolean exists = seen.contains(table[row][col]);
            if (!exists) {
              seen.add(table[row][col]);
              continue;
            }
            duplicates.add(table[row][col]);
          }
      }

      System.out.println(seen);
      System.out.println (duplicates);
  }
}

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