给定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;
}我还把数字加为十进制,并将结果转换为三元数,并试图检查属性,但没有结果。我有第二个方法,它的作用类似于上述,但不使用String。相反,它将数字除以10000、1000等,因为不能对一个数字执行.charAt()。
真Q
我的直觉告诉我,需要有一个更简单的方法来做这件事,但我还没有发现它。我花了很多时间想出一个优雅的解决方案,但我还是被困住了。这也许更像是一道数学题,而不是编程题,但我认为这里的人也许能为我指明正确的方向。谢谢:)
发布于 2019-05-19 22:11:44
实际上,您有一个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 (在每个值上)获得最不重要的三元数字,如果它们的和不能被3整除,则返回false。
但是,我们需要将每个值除以3,从而有效地删除最小的三值位数。
这也是个人偏好,但是对a /= 3、b /= 3和c /= 3的调用可以移动到for-循环的增量部分:
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;
}https://stackoverflow.com/questions/56212235
复制相似问题