Kristopher
Kristopher

Reputation: 205

Convert a 2D array into a 1D array

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.

Upvotes: 14

Views: 90710

Answers (9)

GEORGE
GEORGE

Reputation: 1

The below code converts / flattens 2D array to 1D (row-wise)

(MxM)- Row Wise

 private static int[] convert2Dto1DArrayMxM(int[][] input) {

    //Get total elements to calculate the length of result Array
    //Since it is MXM totalElements calculation is = rowsLength x row[0].length

    int totalElements = input.length * input[0].length;

    //Populate the result Array

    int[] result = new int[totalElements];
    int resultIndex = 0;
    for (int row = 0; row < input.length; row++) {
        for (int col = 0; col < input[0].length; col++) {
            result[resultIndex] = input[row][col];
            resultIndex++;
        }
    }
    return result;
}

(MxN)- Row Wise

private static int[] convert2Dto1DArrayMxN(int[][] input) {
    
   //Get total elements in input array to calculate the length of result Array

    int totalElements = 0;
    for (int row = 0; row < input.length; row++) {
        for (int col = 0; col < input[row].length; col++) {
            totalElements++;
        }
    }

    //Populate the result Array

    int[] result = new int[totalElements];
    int resultIndex = 0;

    for (int row = 0; row < input.length; row++) {
        for (int col = 0; col < input[row].length; col++) {
            result[resultIndex] = input[row][col];
            resultIndex++;
        }
    }

    return result;
}

(MxM)- Column Wise

 private static int[] convert2Dto1DArrayMxMColumnWise(int[][] input) {

    //Get total elements to calculate the length of result Array
    //Since it is MXM totalElements calculation is = rowsLength x row[0].length

    int totalElements = input.length * input[0].length;

    //Populate the result Array

    int[] result = new int[totalElements];
    int resultIndex = 0;
    for (int column = 0; column < input[0].length; column++) {
        for (int row = 0; row < input.length; row++) {
            result[resultIndex] = input[row][column];
            resultIndex++;
        }
    }
    return result;
}

How to use:

  public static void main(String[] args) {

     //MXM - Row Wise

    int[][] mXm = {{2, 19}, {6, 80}, {42, 10}};
    int[] mXmResult = convert2Dto1DArrayMxM(mXm);
    System.out.println(Arrays.toString(mXmResult));

    //MXN - Row Wise

    int[][] mXn = {{2, 19, 0, 1, 4, 6, 3, 2, 1, 6}, {2, 0}, {2, 0, 1, 5}};
    int[] mXnResult = convert2Dto1DArrayMxN(mXn);
    System.out.println(Arrays.toString(mXnResult));

    //MxM - Column Wise

    int[][] mXmColumnWise = {{2, 19,10}, {6, 80,9}};
    int[] mXmResultColumnWise = convert2Dto1DArrayMxMColumnWise(mXmColumnWise);
    System.out.println(Arrays.toString(mXmResultColumnWise));
}

Sample output for the above main()

MxM - Row Wise [2, 19, 6, 80, 42, 10]

MxN - Row Wise [2, 19, 0, 1, 4, 6, 3, 2, 1, 6, 2, 0, 2, 0, 1, 5]

MxM - Column Wise [2, 6, 19, 80, 10, 9]

Upvotes: 0

Arsalan Bajwa
Arsalan Bajwa

Reputation: 11

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

}

Upvotes: 1

Matt
Matt

Reputation: 111

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

Upvotes: 2

Steve Zobell
Steve Zobell

Reputation: 884

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

Upvotes: 1

t4dohx
t4dohx

Reputation: 668

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.

Upvotes: 14

Mr. Mak
Mr. Mak

Reputation: 867

"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);

Upvotes: 3

alf
alf

Reputation: 8513

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

Upvotes: 10

epochengine
epochengine

Reputation: 2062

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

Upvotes: 5

Nir Alfasi
Nir Alfasi

Reputation: 53525

change to:

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

Upvotes: 3

Related Questions