循环遍历数组的各个部分

huangapple go评论69阅读模式
英文:

loop through sections of an array

问题

我正在寻求一些关于一个问题的帮助。我目前正在尝试循环遍历一个二维数组的各个部分,但不确定如何做。

基本上,我会有一个4x4或9x9或25x25的数组,我需要能够迭代遍历块并检查重复项。

例如,对于4x4,我会遍历4个2x2的数组。
对于9x9,会有9个3x3的数组,依此类推。

我已经尝试了一段时间,但没有成功。

任何帮助都将是很好的,
谢谢

英文:

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

答案1

得分: 1

如果数组始终是二维的,你可以这样做:

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

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

      // 初始化二维数组
      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());

      // 检查重复项
      List<Integer> seen = new ArrayList<>();
      List<Integer> 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);
  }
}

注意:我已经将代码中的一些符号进行了修正,使其更加符合Java编程语言的语法要求。

英文:

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 &lt; size; row ++)
          for (int col = 0; col &lt; 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 &lt; size; row ++) {
          for (int col = 0; col &lt; 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);
  }
}

huangapple
  • 本文由 发表于 2020年5月4日 09:22:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/61583800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定