14

Here is the code I have so far:

 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 at this point on how to get [i][s] into a single dimensional array. When I do a print(temp) all the elements of my 2D array print out one a time in order but cannot figure out how to get them into the 1D array. I am a novice :(

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

The current 2D array I am working with is a 3x3. I am trying to find the mathematical mode of all the integers in the 2D array if that background is of any importance.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Kristopher
  • 205
  • 2
  • 3
  • 7
  • 2
    I edited your question so that it was consistently 2D->1D. Please take more care with such details in future, they are important. – Andrew Thompson Jan 20 '12 at 00:44

8 Answers8

13

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.
t4dohx
  • 675
  • 4
  • 24
10

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);
    }
}
alf
  • 8,377
  • 24
  • 45
5

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];
    }
  }
}
epochengine
  • 2,072
  • 17
  • 21
  • 1
    This is true - I made this assumption because that assumption was in the original code - perhaps I should have made that clear. – epochengine Jan 20 '12 at 01:19
3

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

        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);
Mr. Mak
  • 837
  • 1
  • 11
  • 25
3

change to:

 for(int i = 0; i < arr.length; i ++) {
          for(int s = 0; s < arr[i].length; s ++) {
              temp = arr[i][s];
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
2

I know its already been answered but here is my take. This function will take a 2d array input and return a 1d array output.

public int[] output(int[][] input){
    int[] out = new int[input.length * input[0].length]
    for (int i = 0; i < input.length; i++) {
        for (int j = 0; j < input[i].length; j++) { 
            out[i + (j * input.length)] = input[i][j]
        }
    }
    return out;
}
Matt
  • 111
  • 7
1
import java.util.*;


public class Main {
    
    public static int A[][] = new int[3][3];
    public static int B[] = new int[9];

    
    
    
    public static void main(String[] args) {
        
        
        int temo = 0,t;
        
        Scanner s = new Scanner(System.in);
         
         System.out.println("Enter No for Matrix A");
         
         for (int row = 0; row < A.length; row++) {
                for (int col = 0; col < A.length; col++) {
                    A[row][col] = s.nextInt();
                }
                System.out.print("\n");
            }
         
        
         for (int row = 0; row < A.length; row++) {
                for (int col = 0; col < A.length; col++) {
                        t= A[row][col];
                        B[temo]= t;
                        temo++;
                    
                }
                System.out.print("\n");
            }
         
         System.out.print("After Converted to one d \n");
         for(int i =0;i<B.length;i++) {
             System.out.print(" "+B[i]+" ");
         }
         
    }

}
Alexey Ismagilov
  • 187
  • 2
  • 11
1

System.arraycopy should be faster than anything we can write. Also use the built-in java iterator on rows. Here is an example for double arrays. You should be able to use any type or class. If your rows are all the same length, then totalNumberElements = array2D.length * array2D[0].length;

static double[] doubleCopyToOneD(double[][] array2D, int totalNumberElements) {
    double[] array1D = new double[totalNumberElements];
    int pos = 0;
    for (double[] row: array2D) {
        System.arraycopy(row, 0, array1D, pos, row.length);
        pos += row.length;
    }
    return array1D;
}
Steve Zobell
  • 896
  • 10
  • 13