I have to partition a 2d array (the size is given by the user) into sub-arrays given an input number by the user. The code i Wrote works well for most of the instances by there are some that I need some help with.
我必须在用户给出输入编号的情况下将2d数组(大小由用户给出)分区为子数组。我写的代码适用于大多数实例,有一些我需要一些帮助。
I do this by taking the square root of the input number. So for example: If the user inserts [10, 10, 9] it means that this is a 10 * 10 array with 9 sub-arrays. Taking the square root of 9 works fine because it gives 3. If the user inserts [8, 6, 6] it takes the square root of 6 and rounds it up for the longest side (which gives 3) and rounds it down for the shortest (which is 2). So 3 * 2 = 6. It also works fine.
我通过取输入数字的平方根来做到这一点。例如:如果用户插入[10,10,9],则意味着这是一个包含9个子阵列的10 * 10阵列。取9的平方根工作正常,因为它给出3.如果用户插入[8,6,6],它取6的平方根并将其向上舍入为最长边(给出3)并将其向下舍入为最短的(即2)。所以3 * 2 = 6.它也可以正常工作。
Then there is a situation like 8. The square root of 8 gives 3 and 2. So the array is partitioned into 6 sub-arrays. Is there another way to find a better partitioning for numbers like 8, 14? Or is there a way to find the optimal distribution for such numbers (e.g. 2 * 4 = 8, 2 * 7 = 14)?
然后有一个像8的情况.8的平方根给出3和2.所以数组被分成6个子数组。有没有其他方法可以找到更好的分区,如8,14?或者有没有办法找到这些数字的最佳分布(例如2 * 4 = 8,2 * 7 = 14)?
2 个解决方案
#1
1
You can calculate them a bit different way:
你可以用不同的方式计算它们:
int x = Math.round(Math.sqrt(n));
int y = Math.round(1. * n / x);
Thus you'll receive:
因此,您将收到:
n = 8 => x = 3, y = 3
n = 14 => x = 4, y = 4
#2
0
What you need to do is find the two nearest factors to the square root. Try this code:
你需要做的是找到平方根的两个最近因子。试试这段代码:
long n = 14;
long y = 0;
long x = Math.round(Math.sqrt(n));
while(true){
if (n % x == 0) {
y = n/x;
break;
}
else {
x--;
}
}
You might also like to put in some error checking to cope with input errors. e.g. n<1.
您可能还想进行一些错误检查以应对输入错误。例如N'。
#1
1
You can calculate them a bit different way:
你可以用不同的方式计算它们:
int x = Math.round(Math.sqrt(n));
int y = Math.round(1. * n / x);
Thus you'll receive:
因此,您将收到:
n = 8 => x = 3, y = 3
n = 14 => x = 4, y = 4
#2
0
What you need to do is find the two nearest factors to the square root. Try this code:
你需要做的是找到平方根的两个最近因子。试试这段代码:
long n = 14;
long y = 0;
long x = Math.round(Math.sqrt(n));
while(true){
if (n % x == 0) {
y = n/x;
break;
}
else {
x--;
}
}
You might also like to put in some error checking to cope with input errors. e.g. n<1.
您可能还想进行一些错误检查以应对输入错误。例如N'。