给定 3 个长度相等的三进制(基数为 3)数字(它们可以在左边用零填充),是否有一种快速简单的方法来比较每个位值(或列),使得每列由 3不同的数字或 3 个相同的数字。
例如:
Good pairs: || Bad pairs:
________________||________________
101 | 000 | 012 || 111 | 012 | 002
212 | 111 | 112 || 122 | 120 | 022
020 | 222 | 212 || 120 | 202 | 102
到目前为止我尝试了什么
我目前最好的解决方案是将 3 个数字相加,但将它们相加时像十进制数而不是(因此第一个好的对将变为 333 而不是 1110)。然后我检查每个单独的数字并检查它是否可以被 3 整除。
起初我在检查整个数字是否可以被 3 整除,但是很多数字都失败了。
00
10
11
--
21 % 3 == 0
如您所见,仅除以 3 还不够好,因为您可以快速浏览一下,这些列实际上不符合我设置的规则。 这是我编写的以我解释的正确方式检查它的方法:
//The 3 numbers are originally decimal numbers
private static boolean ternary(int a, int b, int c)
{
//Convert each number to a ternary number, add them and assign the result to a string
//This is the best base conversion code I was able to find using native java
String ternary = Integer.toString(Integer.parseInt(Integer.toString(a, 3))
+ Integer.parseInt(Integer.toString(b, 3))
+ Integer.parseInt(Integer.toString(c, 3)));
//For each digit in the number, check if it is divisible by 3. If not, return false
for (int i = 0; i < ternary.length(); i++)
if (Integer.parseInt(ternary.charAt(i) + "") % 3 != 0)
return false;
//If all the numbers passed the test, return true
return true;
}
我也搞砸了将数字添加为十进制并将结果转换为三进制数并尝试检查属性无济于事。 我有第二种方法,它的作用与上述类似,但不使用字符串。相反,它将数字除以 10000、1000 等,因为您不能对数字执行 .charAt()。
真正的问题
我的直觉告诉我需要有一种更简单的方法来做到这一点,但我还没有发现它。我花了太多时间试图想出一个优雅的解决方案,但我被困住了。这可能更像是一个数学问题而不是编程问题,但我认为这里的某个人可能能够为我指明正确的方向。 谢谢:)
最佳答案
您基本上有一个 3x3 矩阵,其中每一列的总和必须等于 0
(列中的所有元素都是 0
),3
(列中的所有元素都是 1
或 列中的元素是 0
、 1
和 2
的排列),或 6
(列中的所有元素都是 2
)。
因为列的总和必须等于 0
, 3
, 或 6
,我们可以简单地检查总和是否可以被 3
整除。 .
检查这个的代码如下:
private static boolean ternary(int a, int b, int c) {
for (int i = 0; i < 3; i++) {
if ((a % 3 + b % 3 + c % 3) % 3 != 0) {
return false;
}
a /= 3;
b /= 3;
c /= 3;
}
return true;
}
因为 a
, b
, 和 c
输入为十进制(以 10 为底),我们可以使用 n % 3
(在每个值上)获取最低有效的三进制数字,并返回 false
如果它们的总和不能被 3
整除.
但是,我们需要将每个值除以 3
有效地删除最低有效的三进制数字。
这也是个人喜好,但是调用a /= 3
, b /= 3
, 和 c /= 3
可以移动到 for 循环的 increment 部分:
private static boolean ternary(int a, int b, int c) {
for (int i = 0; i < 3; i++, a /= 3, b /= 3, c /= 3) {
if ((a % 3 + b % 3 + c % 3) % 3 != 0) {
return false;
}
}
return true;
}
关于java - 有没有一种根据简单规则集比较 3 个三元数的快速方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56212235/