繁体   English   中英

隐蔽2D数组到1D数组,用于存储2D数组的位置(行,行)和1D数组中的值

[英]Covert 2D array to 1D array storing the 2D array position (col, row) and the value in a 1D array

我设法将其转换为从2D数组输出值,但不知道如何获取位置。

这是我的代码:

public static int[] convert(int [][]twodarray)
{
    int[] onedarray = new int[twodarray.length * twodarray.length];
    for(int i = 0; i < twodarray.length; i ++)
    {
        for(int s = 0; s < twodarray.length; s ++)
        {
            onedarray[(i * twodarray.length) + s] = twodarray[i][s];
        }
    }
    return onedarray;
}

public static int [] printonedarray(int [] onedarray)
{
    System.out.print("onedarray: ");

    for(int i = 0; i < onedarray.length; i++) 
    {

            System.out.print(onedarray[i] + "\t");

    }
    System.out.println();
    return onedarray;
}

假设您的2-d数组不是锯齿状数组,则A[i]的原始A[i/x][i%x]应为A[i/x][i%x] ,其中x是2 / d的最低有效列的原始长度数组

好吧,我不确定我能否得到你的帮助。 但是我这样理解:
您有2个昏暗的地方。 数组,并希望将其转换为1暗。 数组。
因此,您需要准备第一行和第一行。
然后,您想将此值添加到1暗淡的最前位置。 数组。
然后,您阅读下一行,并希望添加此值,依此类推。
如果我是对的,我建议您为1个昏暗的数组使用arrayList。 因为您不知道对话的深度。 并且ArrayList是动态的。 您只需添加一个元素即可,而无需指定职位。
您的代码建议非常好,我只是将其转换为ArrayList。

import java.util.ArrayList;

    public class test
    {

    public static ArrayList<Integer> convert(int [][]twodarray)
    {
        ArrayList<Integer> onedarray = new ArrayList<Integer> ();
        for(int i = 0; i < twodarray.length; i ++)
        {
            for(int s = 0; s < twodarray[i].length; s ++)
            {
                onedarray.add(twodarray[i][s]);
            }
        }
        return onedarray;
    }

    public static ArrayList<Integer> printonedarray(ArrayList<Integer> onedarray)
    {
        System.out.print("onedarray: ");

        for(int i = 0; i < onedarray.size(); i++) 
        {

                System.out.print(onedarray.get(i) + "\t");

        }
        System.out.println();
        return onedarray;
    }
}

如果我错过了您的问题,对于“错误”的回答,我们深表歉意。
希望对您有帮助!

暂无
暂无

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

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