1

i have a code that create 2d array using user input and it work fine but now i have 2 questions

the first one: how to convert 2d array to 1d array?

second question: how to choose or trace the elements above the right diagonal in the 2d array?

anyone can help me to fix this code?

this my code

package question3;

import java.util.Arrays;
import java.util.Collection;
import java.util.Scanner;

public class Array2d {

    public static void main(String[] args) {
        int[][] matrix = new int[3][3];

        int[] array = new int[matrix.length * matrix.length];

        Scanner sc = new Scanner(System.in);

        System.out.print("Please enter 9 integers separated by spaces:");
        for (int i = 0; i < matrix.length; i++) {

            for (int j = 0; j < matrix.length; j++) {
                matrix[i][j] = sc.nextInt();
            }

        }

        int idx = 0;

        for (int row = 0; row < matrix.length; row++) {
            for (int column = 0; column < matrix.length; column++) {
                System.out.print(matrix[row][column] + " "); // Outputs the // array in a // 5x5 grid.


            }
            System.out.println();
        }

        for (int column = 0; column < matrix.length; column++) {
            for (int row = column + 1; row < matrix.length+column ; row++){
                // populate your array here
                array[idx] = matrix[row][column];
                // increment index
                idx++;

                System.out.println(matrix[row][column]);
            }

        }       

    }
}

output

Please enter 9 integers separated by spaces: 1 2 3 4 5 6 7 8 9

1 2 3

4 5 6

7 8 9

4 7 8

but what i expect 2 , 3 , 6

where the change that i need to make because i am stuck and i know that is in the third for loop

ttt ttt
  • 23
  • 1
  • 1
  • 5

5 Answers5

4

Well if you run the following code,

public class Main {
    public static void main(String[] args) {
        int[][] matrix = new int[5][6];
        System.out.println(matrix.length);
        int[] matrix2 = matrix[4];
        System.out.println(matrix2.length);
    }
}

You will see that it prints out

5
6

So initially you have an array that has a length of 5, and there contains 5 int[] that have a length of ˛6 each.

Therefore it is stored in the pattern of

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30

So what do you want to do in order to put these into an array? You need to go from topleft to right, and then down a row each time.

    int newArray[] = new int[matrix.length*matrix[0].length];
    for(int i = 0; i < matrix.length; i++) {
        int[] row = matrix[i];
        for(int j = 0; j < row.length; j++) {
            int number = matrix[i][j];
            newArray[i*row.length+j] = number;
        }
    }

And that should work.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 

Complete code to see for yourself:

public class Main {
    public static void main(String[] args) {
        int[][] matrix = new int[5][6];

        int counter = 1;
        for(int i = 0; i < 5; i++) {
            for(int j = 0; j < 6; j++) {
                matrix[i][j] = counter++;
            }
        }

        int newArray[] = new int[matrix.length*matrix[0].length];
        for(int i = 0; i < matrix.length; i++) {
            int[] row = matrix[i];
            for(int j = 0; j < row.length; j++) {
                int number = matrix[i][j];
                newArray[i*row.length+j] = number;
            }
        }
        for(int i = 0; i < newArray.length; i++) {
            System.out.print(newArray[i] + " ");
        }
    }
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
0

use loop and assign 1-d array as:

 int[] array = new int[matrix.length * matrix[0].length];

    int k = 0;

    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix.length; j++) {
            array[k++] = matrix[i][j];
        }
    }
Prashant
  • 2,556
  • 2
  • 20
  • 26
  • array is of length 3 , So your code will give [ArrayIndexOutOfBoundsException](http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html) – Neeraj Jain Feb 03 '15 at 18:01
0

matrix.length and array.length both will return 3 , So your 1D array will be of size 3 whereas you have total of 9 elements

So you cannot use this , Now if your 2D array is a square matrix then you have to create 1 DArray of size

  int[] array = new int[matrix.length * matrix.length];

Then Simply traverse the 2 D Array and insert each element in 1 D Array as @Prashant suggested with a little bit of modification

int k = 0;
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        array[k++] = matrix[i][j];
    }
}
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

You have defined the array size equal to the number of rows of the matrix. It needs to have row * column elements. Populate the array as you traverse the matrix in the order you see fit. This is an example:

package question3;

import java.util.Arrays;
import java.util.Scanner;

public class Array2d {

    public static void main(String[] args) {
        int[][] matrix = new int[3][3];

        // array must have row * col elements to hold the entire matrix
        int[] array = new int[matrix.length * matrix[0].length];

        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter 9 integers separated by spaces:");
        for (int i = 0; i < matrix.length; i++) {

            for (int j = 0; j < matrix.length; j++) {
                matrix[i][j] = sc.nextInt();
            }

        }

        // Index to step through array
        int idx = 0;

        for (int row = 0; row < matrix.length; row++) {
            for (int column = 0; column < matrix.length; column++) {
                System.out.print(matrix[row][column] + " ");

                // populate your array here
                array[idx] = matrix[row][column];
                // increment index
                idx++;
            }
            System.out.println();
        }

        System.out.println("the Matrix becomes " + Arrays.toString(array));


        for (int row = 0; row < matrix.length; row++) {
            for (int column = 0; column < matrix[row].length - row - 1; column++) {
                // Work with matrix above right diagonal here, matrix[row][column]; 
                System.out.println(matrix[row][column]);
            }
        }
    }
}

The first index of a two-dimensional array is the row, the second is the column. You have them named incorrectly in the second for loop.

To access the everything above the diagonal that runs from bottom-left to top-right, excluding the diagonal, step through each row and then each column up to but not including row length - row index. Something like this:

for (int row = 0; row < matrix.length; row++) {
    for (int column = 0; column < matrix[row].length - row - 1; column++) {
        // Work with matrix above right diagonal here, matrix[row][column]; 
        System.out.println(matrix[row][column]);
    }
}
Sean Kuhlman
  • 502
  • 3
  • 13
  • @ Sean Kuhlman i tried your solution for the diagonal elements but it did not display what i want can you help me the Matrix becomes [1, 4, 7, 5, 8, 9, 0, 0, 0] what i want to display 1, 2, 4 only – ttt ttt Feb 03 '15 at 18:26
  • See the edit which outputs 1, 2, 3, 5, 6, 9 as expected. Are you reusing `array`? You might want to make a third array with 6 elements if you need to store the values above the right diagonal. – Sean Kuhlman Feb 03 '15 at 18:31
  • i tried after you update the solution but still did not work as it should the output of the 1d array 1 2 3 5 6 9 what i expect 1, 2, 4 – ttt ttt Feb 03 '15 at 18:39
  • When you say right diagonal I assume main diagonal which is top left to bottom right. You're referring to the other diagonal and you'd like the diagonal excluded. – Sean Kuhlman Feb 03 '15 at 18:42
  • Ohh sorry for the misunderstanding i mean top right to bottom left but also if i am working on the other diagonal the output will be 2,3,6 – ttt ttt Feb 03 '15 at 18:45
  • yes i tried and the result is 1,2 it did not work – ttt ttt Feb 03 '15 at 18:57
  • It works on my machine, can you post what's not working in your question? – Sean Kuhlman Feb 03 '15 at 19:44
0

With Kotlin, you could just do;

fun Array<IntArray>.toVector(): IntArray {
  if (this.isEmpty()) return IntArray(0)
  return this.reduce { firstArr, nextArr ->
    firstArr.plus(nextArr)
  }
}

This would return an int array comprising of all rows of the 2D array.

bebe
  • 114
  • 2
  • 5