【问题标题】:permutate binary matrix java置换二进制矩阵java
【发布时间】:2014-07-09 02:41:52
【问题描述】:

我想在 Java 上获取二进制矩阵 NxM 与一个变量的所有可能组合,该变量表示它有多少个 1。

例如:

matrix = 0 0 0 0
         0 0 0 0

使用类似的方法运行该方法:

置换(矩阵,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 ...

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

【问题讨论】:

  • 不要将问题解决为矩阵,而是尝试将其建模为包含 NxM 值的单个数组并对其进行置换以获得所有可能的组合。然后你可以将它转换回矩阵格式
  • 一个 NxM 矩阵可以映射到一个 NxM 长的数组。所以只需应用此处找到的解决方案:stackoverflow.com/questions/1851134/…
  • 那么您需要技术帮助还是需要数​​学解决方案?只是另一个问题,你想要一个排列还是组合?
  • 谢谢你,你说得对!更简单的方法

标签: java matrix permutation


【解决方案1】:

您的问题在 cmets 中给出的答案是针对基于 C 的语言。这个解决方案是为 Java 设计的。调用 permute 并将矩阵作为一维数组提供给它,它会将所有排列的 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++;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 2020-04-21
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    相关资源
    最近更新 更多