Transform a multidimensional array, in a simple array

1

I'm trying to transform an array

Integer[][] mapArray = new Integer[52][52];
    for (int w = 0; w < 52; w++) {
        for (int x = 0; x < 52; x++) {
            mapArray[w][x] = -1;
        }
    }

In a single-dimension array

Integer[] mapArray1d = new Integer[52 * 52];

But the only thing I get is to do it wrong, I leave positions in null. Any ideas to solve my problem?

    
asked by Cazs 30.01.2017 в 19:47
source

3 answers

1

A simple and simple way that had not occurred to me could be the following:

Integer[][] mapArray = new Integer[52][52];
    for (int w = 0; w < 52; w++) {
        for (int x = 0; x < 52; x++) {
            mapArray[w][x] = -1;
        }
    }
Integer[] mapArray1d = new Integer[52 * 52];

    int index = 0;
    for (int w = 0; w < mapArray.length; w++) {
        for (int x = 0; x < mapArray[w].length; x++) {
            mapArray1d[index] = mapArray[w][x];
            index++;
        }
    }
    
answered by 30.01.2017 в 20:52
1
    int tamanio = 6, count = 0;  
    // inicializando la matriz
    Integer[][] mapArray = new Integer[tamanio][tamanio];
    for (int w = 0; w < tamanio; w++) {
        for (int x = 0; x < tamanio; x++) {
            mapArray[w][x] = -1;
        }
    }
    // creando el array
    Integer[] mapArray1d = new Integer[tamanio * tamanio];

    for (int w = 0; w < tamanio; w++) {
        System.arraycopy(mapArray[w], 0, mapArray1d, count, tamanio);
        count += tamanio;
    }
    // mostrando el resultado
    System.out.println(Arrays.toString(mapArray1d));

A brief description of the method

System.arrayCopy (Object src, int srcPos, Object dest, int destPos, int length)

src - The array with the source data.

srcPos - The initial position of the source array.

dest - The destination array.

destPos - The position from which to start writing in the target array.

length - The number of elements to be copied.

    
answered by 30.01.2017 в 21:05
1

public static void main (String [] agrs)     {         Integer [] [] mapArray = new Integer [52] [52];         for (int w = 0; w < 52; w ++) {             for (int x = 0; x < 52; x ++) {                 mapArray [w] [x] = -1;             }         }

    //se crea arreglo Auxiliar el cual tendra un largo de igual al largo por el alto de la matriz
    Integer []arrayAuxiliar = new Integer[mapArray.length * mapArray.length];
    int indice = 0;
    //se recorre cada subArreglo del arreglo original
    for(Integer[] arregloNumerosEnteros : mapArray )
    {
        //se recorre cada Integer del subArreglo y se añade al arreglo Auxiliar
        for(Integer numeroEntero : arregloNumerosEnteros)
        {
            arrayAuxiliar[indice] = numeroEntero;
            indice++;
        }
    }

    //se recorre el arreglo auxiliar y se imprime su contenido
    for(Integer entero : arrayAuxiliar)
        System.out.print(arrayAuxiliar.length);

}
    
answered by 06.02.2017 в 16:00