循环遍历数组的各个部分

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

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

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

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. class Main {
  4. public static void main(String[] args) {
  5. // 初始化二维数组
  6. int size = 3;
  7. int[][] table = new int[size][size];
  8. for (int row = 0; row < size; row++)
  9. for (int col = 0; col < size; col++)
  10. table[row][col] = (int) (20.0 * Math.random());
  11. // 检查重复项
  12. List<Integer> seen = new ArrayList<>();
  13. List<Integer> duplicates = new ArrayList<>();
  14. for (int row = 0; row < size; row++) {
  15. for (int col = 0; col < size; col++) {
  16. boolean exists = seen.contains(table[row][col]);
  17. if (!exists) {
  18. seen.add(table[row][col]);
  19. continue;
  20. }
  21. duplicates.add(table[row][col]);
  22. }
  23. }
  24. System.out.println(seen);
  25. System.out.println(duplicates);
  26. }
  27. }

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

英文:

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

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. class Main {
  4. public static void main(String[] args) {
  5. // Initialize the 2d array
  6. int size = 3;
  7. int[][] table = new int[size][size];
  8. for (int row = 0; row &lt; size; row ++)
  9. for (int col = 0; col &lt; size; col++)
  10. table[row][col] = (int) (20.0 * Math.random());
  11. // Scan for duplicates
  12. List seen = new ArrayList();
  13. List duplicates = new ArrayList();
  14. for (int row = 0; row &lt; size; row ++) {
  15. for (int col = 0; col &lt; size; col++) {
  16. boolean exists = seen.contains(table[row][col]);
  17. if (!exists) {
  18. seen.add(table[row][col]);
  19. continue;
  20. }
  21. duplicates.add(table[row][col]);
  22. }
  23. }
  24. System.out.println(seen);
  25. System.out.println (duplicates);
  26. }
  27. }

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:

确定