How to iterate with two-dimensional array?

Asked

Viewed 1,637 times

4

Hello, I am making a library to help in the creation of games and for that I would like to know how to iterate in two-dimensional arrays, I know that the array for one-dimensional is just to do:
for(String string :strings)
, but I don’t know how to do that with two-dimensional arrays. Help me please!
Edit1:
I think my question is unclear, my mistake, thank you for your help. I created two classes.
Java tile.:

public class Tile {  

   Bitmap bmp;  
   int width = bmp.getWidth();
   int height = bmp.getHeight();

   public Tile(Bitmap bmp) {  
     this.bmp = bmp;  
   }  
}

Tileset.java:

public class TileSet {  

  Tile[][] tileset;  
  Bitmap bmp;
  int bmp_columns, bmp_rows;

  public TileSet(Bitmap bmp, int bmp_columns, int bmp_rows) {  

    this.bmp = bmp;  
    this.bmp_columns = bmp_columns;  
    this.bmp_rows = bmp_rows;  
    tileset = new Tile[bmp_columns][bmp_rows];  

    //o erro acontece nesse trecho:  
    for(Tile tile :tileset) {  
      tile.width = bmp.getWidth() / bmp_columns;  
      tile.height = bmp.getHeight() / bmp_rows;
    }
  }
}

Well, that’s it, excuse the previous lack of clarity, thank you for the answers and I hope it’s clearer now.
Edit2
Thank you all, my doubt has already been answered!

  • I made an update on the answer according to the information asked in the question. See if it clarifies.

  • Thank you! Thank you very much!

3 answers

8


First, it is important to bear in mind that a two-dimensional array is nothing more than a one-way array that contains a one-dimensional array at each of its positions, i.e., it is an array of arrays.

Imagem que ilustra que um array bidimenciona é apenas um array de arrays
source: A bit of arrays | Java and Object Orientation

Therefore, to traverse a two-dimensional array a chained loop or recursion is required.

Traversing two-dimensional arrays with chained loop:
When making a simple loop, with each interaction, you will have access to the array saved at the respective position of the iterated array. If we analogise to a matrix, it would be to obtain each of the lines of a matrix for each interaction. Once this is done we need a second loop within the first to traverse the innermost array and thus access the elements.

NOTE: Although a two-dimensional array can store the representation of an array, we CANNOT consider a two-dimensional array as an array, since most languages allow the internal arrays stored by the outermost array to be of different size, which means that in each row can contain a number of different columns and this has to be taken into account when traversing a two-dimensional array.

Example that prints the elements of a bidimencional array in Python:

a = [[1,2],[3,4],[5,6]]
for i in a:
    for j in i:
        print(j)

Example that prints the elements of a bidimencional array in java using traditional and foreach:

public class ExemploListaBidimencional {
    public static void main(String[] args) {
        int[][] lista = {{1,2},{3,4},{5,6}};

        // Usando for
        for (int i = 0; i < lista.length; i++) {
            for (int j = 0; j < lista[i].length; j++) {
                System.out.println(lista[i][j]);
            }
        }

        // Usando foreach
        for (int[] i : lista) {
            for (int j : i) {
                System.out.println(j);
            }
        }
    }
}

Traversing two-dimensional arrays using recursion:
The concept is the same, but instead of using a throw let’s call a function to treat the first element and call the same function recursively to treat the next element paying attention to the stop condition that in this case is the end of the array.

Example that prints the elements of a bidimencional array recursively in java:

public class ExemploListaBidimencional {
    public static void main(String[] args) {
        int[][] lista = {{1,2},{3,4},{5,6}};

        percorreArrayBidimencional(lista, 0, lista.length);
    }

    private static void percorreArrayBidimencional(int[][] lista, int inicio, int fim) {
        if(inicio < fim) {
            percorreArray(lista[inicio], 0, lista[inicio].length);
            percorreArrayBidimencional(lista, inicio + 1, fim);
        }
    }

    private static void percorreArray(int[] lista, int inicio, int fim) {
        if(inicio < fim) {
            System.out.println(lista[inicio]);
            percorreArray(lista, inicio + 1, fim);
        }
    }
}

Traversing the array of your case:

    for(Tile[] tilesRows :tileset) {
        for(Tile tile : tilesRows){
            tile.width = bmp.getWidth() / bmp_columns;  
            tile.height = bmp.getHeight() / bmp_rows;
        }
    }
  • Thanks, thanks! I’ll try it here but I think you solved my doubt!

  • I updated my response. But you need to realize one thing: When you create the matrix, all the elements in it are null, so you’re trying to access all the null elements.

  • Intendi, thank you!

5

4

Two-dimensional arrays use nested iteration loops.

It is common to use the mathematical matrix definition for two-dimensional arrays:

Matrices are information organizations in a table rectangular formed by rows and columns.

This organization in a table makes it easier to carry out several simultaneous calculations with the information contained in the matrix.

The matrix has the format m x n (read: m per n, with m and n N*), where m is the number of lines and n the number of columns.

The normal is to iterate by your row and another iteration by your columns.

Some examples of iteration:

import java.util.Arrays;

class Main {

  //Inicializa uma matriz quadrada de ordem 3x3
  public static char[][] bidArray = new char[][]{{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

  public static void main(String[] args) {

    System.out.println("Iterando pelas linhas sem o auxilio de um contador:");
    for(char[] linha: bidArray){            
       System.out.println(Arrays.toString(linha));
    }
    System.out.println("");

    System.out.println("Iterando pelas linhas com o auxilio de um contador:");    
    for(int i = 0; i < bidArray.length; i++){            
       System.out.println("linha " + i + ": " +Arrays.toString(bidArray[i]));
    }

    System.out.println("Iterando por todos elementos sem o auxilio de contadores:");
    for(char[] linha: bidArray){     
       for(char elemento: linha){      
          System.out.println(elemento);
       }
    }
    System.out.println("");

    System.out.println("Iterando por todos elementos com o auxilio de contadores:");
    for(int i = 0; i < bidArray.length; i++){   
       for(int j = 0; j < bidArray[i].length; j++){
         System.out.println("elemento " + i + "x" + j + ": " + bidArray[i][j]);
       }
    }


  }
}

In the example you placed first you must iterate through the lines getting a one-dimensional array Tile[] tiles and then iterates and iterates again for each of these lines to get the elements individually Tile tile.

// Itera sobre o array bidimensional obtendo as linhas
for(Tile[] tiles :tileset) {  

  // Itera sobre as linhas obtendo os elementos
  for (Tile tile: tiles){

    tile.width = bmp.getWidth() / bmp_columns;  
    tile.height = bmp.getHeight() / bmp_rows;
  }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.