Convert a 2D array into a 1D array

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

If you're trying to have 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];
    }
  }
}

You've almost got it 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);
    }
}

In Java 8 you can use object streams to map a matrix to vector.

Convert any-type & any-length object matrix to vector (array)

String[][] matrix = {
    {"a", "b", "c"},
    {"d", "e"},
    {"f"},
    {"g", "h", "i", "j"}
};

String[] array = Stream.of(matrix)
                       .flatMap(Stream::of)
                       .toArray(String[]::new);

If you are looking for int-specific way, I would go for:

int[][] matrix = {
    {1, 5, 2, 3, 4},
    {2, 4, 5, 2},
    {1, 2, 3, 4, 5, 6},
    {}
};

int[] array = Stream.of(matrix) //we start with a stream of objects Stream<int[]>
                    .flatMapToInt(IntStream::of) //we I'll map each int[] to IntStream
                    .toArray(); //we're now IntStream, just collect the ints to array.

change to:

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

Tags:

Java

Arrays