首页 > 解决方案 > 如何在 Java 中返回 3x6 矩阵的所有可能结果?

问题描述

第一步:我想返回一个 3x6 矩阵的所有可能结果,其中可能的值为 0 或 1。

例如: 可能性一:

0 0 0
0 0 0
0 0 0 
0 0 0
0 0 0
0 0 0

可能性二:

0 0 1
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0

ETC...

第二步:我想给每个位置一个结果为 1 或 0 的概率,因此能够计算整个矩阵结果的概率。

我已经尝试了以下代码作为开始,但它还没有工作,我无法正确理解它是如何工作的:

int counter = 0;
String [][] actualOutcome = {{"0","0","0"}, {"0","0","0"}, {"0","0","0"}, {"0","0","0"}, {"0","0","0"}, {"0","0","0"}, {"0","0","0"}, {"0","0","0"}};
String[] possibleOutcomes = {"0","1"};
for(int rowOne = 0; rowOne < 6; rowOne++) {
    for(int rowTwo = 0; rowTwo < 3; rowTwo++) {
        for (int possibilitiesCounter = 0; possibilitiesCounter < possibleOutcomes.length; possibilitiesCounter++) {
            actualOutcome[rowOne][rowTwo] = possibleOutcomes[possibilitiesCounter];
            System.out.println("Possibility " + counter + ": \n" + actualOutcome[0][2] +  actualOutcome[0][1] +  actualOutcome[0][0] + "\n" +
                                                                   actualOutcome[1][2] +  actualOutcome[1][1] +  actualOutcome[1][0] + "\n" +
                                                                   actualOutcome[2][2] +  actualOutcome[2][1] +  actualOutcome[2][0]);
            counter++;
        }
    }
}
    

先感谢您!

标签: javaalgorithmmatrix

解决方案


最简单的方法是在二进制系统中设置一个计数器,0而不是使用矩阵进行放置和操作,只需使用数字即可。511111111111

    for (int i = 0; i < 512; i++) {
        System.out.println("Possibility " + (i + 1) + ": ");
        for (int j = 0; j < 9; j++) {
            System.out.print((i & (1 << j)) >> j);
            if (j % 3 == 2) 
                System.out.println();
            else 
                System.out.print(" ");
        }
    }

推荐阅读