简体   繁体   English

将二维数组转换为一维数组

[英]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.我似乎在这一点上被困在如何将[i][s]放入一维数组中。 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.当我执行print(temp) ,我的二维数组的所有元素一次按顺序打印一个,但无法弄清楚如何将它们放入一维数组中。 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.我正在使用的当前 2D 阵列是 3x3。 I am trying to find the mathematical mode of all the integers in the 2D array if that background is of any importance.如果背景有任何重要性,我试图找到二维数组中所有整数的数学模式。

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.在 Java 8 中,您可以使用对象流将矩阵映射到向量。

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 的方式,我会选择:

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.

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

change to:改成:

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

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.我不确定您是想将二维数组转换为一维数组(如您的问题所述),还是将二维数组中的值放入您拥有的 ArrayList 中。 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.我会假设第一个,但我很快就会说你需要为后者做的就是调用list.add(temp) ,尽管temp在你当前的代码中实际上是不需要的。

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

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

import java.util.*;导入 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]+" ");
     }

} }

}

System.arraycopy should be faster than anything we can write. System.arraycopy 应该比我们能写的任何东西都快。 Also use the built-in java iterator on rows.还可以在行上使用内置的 java 迭代器。 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;如果您的行长度都相同,则 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM