I am solving some java algorithm-analysis questions and this problem has me stumped. This particular problem asks for the value that is returned by x(10) where is x is the following function:
public static int x(int n)
{
int count = 0;
for(int i = 0; i <= n; i++)
{
for (int j = 0; j <= n; j++)
{
for (int k = 0; k <= n; k++)
{
System.out.println(i+","+j+","+k);
if (i + j + k > 2 * n)
count++;
}
}
}
return count;
}
Essentially, the problem is asking for the number of combinations of 3 integers less than n whose sum is greater than n * 2.
What is the fastest problem-solving technique for this problem, and just general "complicated" nested loop problems?
I set up a variable table and kept track of variables a, b, and c representing the 3 integers and a count variable which increments each time 'a+b+c > n*2' but after n=3, the tables became unnecessarily tedious. There must be a mathematical solution.
x(10) returns 220, but I do not know how the algorithm arrives at that answer and how to find, say, x(7).
Your code is incorrect.
i < n,
j < n,
k < n,
because you mentioned "less than".
As you mentioned "Combination", but your code doesn't remove some repeated combinations, for example, if n = 5, there are only two combinations which satisfise the conditions, they are (4, 4, 4) and (4, 4, 3), thus the result is 2, apparently your code will return a bigger number which is incorrect.
Could the result of this problem be a mathmatic expression ? think about this follow equation:
n1 + n2 + n3 = 2 * n
this equation is a typical se called "Diophantine Equation", which is proved that there doesn't exist general algorithm to resolve all of them, and this equation is so relative to the origin problem, so i guess no.
I've changed your code, using hashset to remove all repeated combinations, hope is helpful.
public static int getCombinationNumber(int num) { HashSet<String> hs = new HashSet(); // To save the unic form (or representation) for each combination int count = 0; for (int i = 0; i < num; i++) for (int j = 0; j < num; j++) for (int k = 0; k < num; k++) { int[] nums = {i, j, k}; sort(nums); // To ensure all the combinations of i, j, k form a unic array String unicForm = Arrays.toString(nums); // Convert array to string in order to compare and save if (i + j + k > 2 * num && !hs.contains(unicForm)) { count++; hs.add(unicForm); System.out.println(i + ", " + j + ", " + k); } } return count; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.