permutate二进制矩阵java

时间:2014-07-09 02:41:53

标签: java matrix permutation

试图将二进制矩阵NxM的所有可能组合与一个变量相结合,即在Java上有多少1个。

例如:

matrix = 0 0 0 0
         0 0 0 0

使用like:

运行方法

置换(基质,3);

result list = 1 1 1 0 1 0 1 1 0 1 1 1 1 0 0 0 1 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 1 0 ...

我尝试通过矩阵的数组来做,但我认为这是一个坏主意。必须有一个更简单的方法。

1 个答案:

答案 0 :(得分:2)

对您的问题的评论中给出的答案是基于C语言。此解决方案适用于Java。调用置换并将矩阵作为一维数组赋予它,它将返回所有排列的ArrayList作为MyMatrix对象,因此如果需要,可以包含更多关于矩阵的数据。如果你想提高内存效率,你可以使用char的所有字节并使用位移,但是这段代码没有。这是一种解决问题的递归算法。我很确定这有效,我希望它有所帮助!

public ArrayList<MyMatrix> permute(char[] array, int num)   //array is the 2D matrix as a single 1D array that is NxM big
{
    ArrayList<MyMatrix> permutations = new ArrayList<MyMatrix>();
    getPermutation(0, num, 0, array.clone(), permutations);  //clone so we don't break the original
    return permutations;
}

public void getPermutation(int depth, int maxDepth, int index, char[] array, ArrayList<MyMatrix> permutations)
{
    if ((index == array.length) || (depth == maxDepth))
    {
        //have to clone because we generate all permutations from the same array
        MyMatrix permutation = new MyMatrix(array.clone());
        permutations.add(permutation);
        return;
    }

    for (int i = index; i < (array.length - (maxDepth-depth)); i++)
    {
        getPermutation(depth+1, maxDepth, index+1, array, permutations);
        array[index] = 1;
        getPermutation(depth+1, maxDepth, index+1, array, permutations);
        array[index] = 0;   //make it as if nothing happened to the number
    }
}

public class MyMatrix
{
    char[] matrix;
    int numOnes;

    public MyMatrix(char[] array)
    {
        matrix = array;
        numOnes = 0;
        for (int i = 0; i < matrix.length; i++)
        {
            if (matrix[i] = 1)
            {
                numOnes++;
            }
        }
    }
}