2012-01-20 27 views
5

Aquí está el código que tengo hasta ahora:Convierte una matriz 2D en una matriz de 1D

public static int mode(int[][] arr) { 
     ArrayList<Integer> list = new ArrayList<Integer>(); 
     int temp = 0; 
     for(int i = 0; i < arr.length; i ++) { 
      for(int s = 0; s < arr.length; s ++) { 
       temp = arr[i][s]; 

que parecen estar atrapados en este punto sobre cómo conseguir [i][s] en una matriz unidimensional. Cuando hago un print(temp), todos los elementos de mi matriz 2D imprimen una vez en orden, pero no entiendo cómo introducirlos en la matriz 1D. Soy un novato :(

Cómo convertir una matriz 2D en una matriz de 1D?

La matriz 2D en el que estoy trabajando es un 3x3. Estoy tratando de encontrar el modo matemático de todos los números enteros en . la matriz 2D si ese fondo es de alguna importancia

+2

He editado su pregunta para que sea consistentemente 2D-> 1D. Tenga más cuidado con estos detalles en el futuro, son importantes. –

Respuesta

7

Usted ha casi lo hizo bien Sólo un pequeño cambio:.

public static int mode(int[][] arr) { 
    List<Integer> list = new ArrayList<Integer>(); 
    for (int i = 0; i < arr.length; i++) { 
     // tiny change 1: proper dimensions 
     for (int j = 0; j < arr[i].length; j++) { 
      // tiny change 2: actually store the values 
      list.add(arr[i][j]); 
     } 
    } 

    // now you need to find a mode in the list. 

    // tiny change 3, if you definitely need an array 
    int[] vector = new int[list.size()]; 
    for (int i = 0; i < vector.length; i++) { 
     vector[i] = list.get(i); 
    } 
} 
+0

muchas gracias He estado golpeando mi cabeza contra la pared sobre esto desde hace bastante tiempo, ja, ja. – Kristopher

+0

@KristopherSperlik bienvenido :) si responde su pregunta, considere aceptarla - http://meta.stackexchange.com/a/5235/170914 – alf

3

cambio a:

for(int i = 0; i < arr.length; i ++) { 
      for(int s = 0; s < arr[i].length; s ++) { 
       temp = arr[i][s]; 
+0

eso es un paso, a la derecha. – alf

2

No estoy seguro de si está tratando de convertir su matriz 2D en una matriz 1D (como lo dice su pregunta), o poner los valores de la matriz 2D en ArrayList que tiene. Asumiré el primero, pero rápidamente diré que todo lo que necesitas hacer para este último es llamar al list.add(temp), aunque temp en realidad no es necesario en tu código actual.

Si usted está tratando de tener una matriz 1D, entonces el siguiente código debería ser suficiente:

public static int mode(int[][] arr) 
{ 
    int[] oneDArray = new int[arr.length * arr.length]; 
    for(int i = 0; i < arr.length; i ++) 
    { 
    for(int s = 0; s < arr.length; s ++) 
    { 
     oneDArray[(i * arr.length) + s] = arr[i][s]; 
    } 
    } 
} 
+0

solo funciona para matrices cuadradas. – alf

+1

Esto es cierto - hice esta suposición porque esa suposición estaba en el código original - quizás debería haber dejado eso en claro. –

3

"Cómo convertir una matriz 2D en una matriz de 1D?"

 String[][] my2Darr = .....(something)...... 
     List<String> list = new ArrayList<>(); 
     for(int i = 0; i < my2Darr.length; i++) { 
      list.addAll(Arrays.asList(my2Darr[i])); // java.util.Arrays 
     } 
     String[] my1Darr = new String[list.size()]; 
     my1Darr = list.toArray(my1Darr); 
+1

No se permiten tipos primitivos aquí. –

Cuestiones relacionadas