Convert 2D array to 1D array

Here is the code that I still have:

 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];

I seem to be stuck in this question on how to get [i][s]into a one-dimensional array. When I do print(temp), all the elements of my 2D array print once in order, but cannot figure out how to get them into a 1D array. I'm a newbie:(

How to convert a 2D array to a 1D array?

The current 2D array I'm working with is 3x3. I am trying to find the math mode for all integers in a 2D array if this background has any meaning.

+5
source share
4 answers

You have almost everything right. Just a tiny change:

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);
    }
}
+7
source

change to:

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

" 2D- 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);
+3

I'm not sure if you are trying to convert a 2D array to a 1D array (as indicated in your question), or put the values ​​from your 2D array into the ArrayList that you have. I'll take the first, but I'll quickly say that all you need to do for the latter is a call list.add(temp), although tempit is not actually used in your current code.

If you are trying to create a 1D array, then the following code should suffice:

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];
    }
  }
}
+2
source

All Articles