数组中整数组合的算法

时间:2017-12-19 14:34:57

标签: java arrays arraylist multidimensional-array

我在编写一个算法时遇到了困难,该算法将从一个整数数组中创建一个数组数组。

说,我有一个

int[] intArray = new int[] {1,2,3,4,5};

我需要的是一个数组的数组,如下所示:

int[][] array = new int[][]{

    {-1,2,3,4,5},

    {1,-2,3,4,5},

    {1,2,-3,4,5},

    {1,2,3,-4,5},

    {1,2,3,4,-5};

提前谢谢!!

编辑: 如果我想只有一个负值,则以下代码适用于该情况。如果我想要2,3,4 ......负值怎么样?有没有办法让它更有活力?例如,从{1,2,3,4,5};获取:{-1,-2,3,4,5}, {-1,2,-3,4,5}, {-1,2,3,-4,5}, {-1,2,3,4,-5}, {1,-‌​2,-3,4,5},{1,-2,3,-4‌​,5}, {1,-2,3,4,-5} ....或3个负值:{-1,-2,-3,4,5}, {-1,-2,3,-4,5}, {-1,-2,3,4,-5}, {1,-2,-3,-4,5},‌ ​{1,-2,-3,4,-5}, {1,2,‌​-3,-4,-5} ...等我希望你明白我的观点!再次感谢你们!

3 个答案:

答案 0 :(得分:0)

怎么样

public class x
{
    public static int[][] convert(int in[])
    {
        int s = in.length;
        int out[][] = new int[s][s];

        for (int i = 0; i < s; ++i) {   // row loop
            for (int j = 0; j < s; ++j) {
                if (i == j)
                    out[i][j] = -in[j];
                else
                    out[i][j] = in[i];
            }
        }
        return out;
    }

    public static void print(int in[][])
    {
        for (int i = 0; i < in.length; ++i) {
            String sep = "";
            for (int j = 0; j < in[i].length; ++j) {
                System.out.print(sep + in[i][j]);
                sep = ", ";
            }
            System.out.println("");
        }
    }

    public static void main(String argv[])
    {
        int in[] = { 1, 2, 3, 4, 5 };
        int out[][];

        out = convert(in);
        print(out);
    }
}

答案 1 :(得分:0)

    int[] intArray = new int[] {1,2,3,4,5};
    int algoIntArray[][] = new int[intArray.length][intArray.length];

    for(int i = 0; i < intArray.length; i++){
        for (int j = 0; j < algoIntArray[i].length; j++){
            if (i == j){
                algoIntArray[i][j] = -intArray[j];
            } else {
                algoIntArray[i][j] = intArray[j];
            }
        }
    }

此代码适合您!

答案 2 :(得分:0)

你可以试试这个:

    int l = intArray.length;
    int[][] newArray = new int[l][l];

    for (int i = 0; i < l; i++) {
        for (int j = 0; j < l; j++) {
            newArray[i][j] = j == i ? intArray[j] * -1 : intArray[j];
        }
    }

newArray将具有您期望的值。