2 4 6 12和4 2 6 12在技术上不是一个组合,因为它们都包含不同顺序的相同值,所以只显示2 4 6 6 12
我不知道如何删除具有相同数字的组合。
import java.util.Scanner;
public class drawingStraws {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
int hour =0;
int hourTwo=0;
int hourThree=0;
int hourFour=0;
int x,m,d,f;
System.out.println(" straw drawing program!n straw1tstarw2tstraw3tstraw4");
for(x=1;x<=14;x++)
{
for(m=1;m<=14;m++)
{
for(d=1;d<=14;d++)
{
for(f=1;f<=14;f++)
{
sum=0;
hour=x*x;
sum=sum+hour;
hourTwo=m*m;
sum=sum+hourTwo;
hourThree=d*d;
sum=sum+hourThree;
hourFour=f*f;
sum=sum+hourFour;
if(sum==200)
{
if (x==m||x==d||x==f || m==x||m==d||m==f || d==x||d==f||d==m || f==m||f==d||f==x)
{
break;
}
else
{
System.out.println(x+"t"+m+"t"+d+"t"+f);
}
}
}
}
}
}
}
}
此输出将显示(2 4 6 12、4 12 6 2、12 6 4 2等)
这就是问题所在,球员们会抽吸管。吸管上会标记一个数字,指示玩家必须工作多少天和每天工作多少小时。例如,一个玩家画一根标有3的吸管,将连续3天每天工作3个小时,总共工作9个小时。懒惰的游戏者说服了其他人同意这个计划,并通过诡计抽到了最好的稻草。
问题是要根据这个方案来确定所有可能的分工方式。
您将不得不使用嵌套循环来测试4个数字的所有可能组合,这将导致正好200小时的工作。
注意事项:
0吸管不能表示0天0小时。
每根吸管都必须是唯一的,这样它们就不能重复值。
由于这是组合,您不能有重复的结果
如果你简化你的目标会很有帮助,因为我不知道你只想通过阅读代码来实现什么。你的问题似乎是3和问题的变体。解决这类问题的一种经典方法是使用排序,而输入[2 4 6 12]和[4 2 6 12]在排序后将是相同的。
通常,如果您有一个复杂的问题,已经有了一个库。查看Apache Commons Math。
// Instantiate the Combinations; we want numbers up to 14 in sets of 4
Combinations combinationSet = new Combinations(14, 4);
// Iterate over each of the combinations, represented as int[]s
Iterator<int[]> iterator = combinationSet.iterator();
while(iterator.hasNext()) {
System.out.print("[ ");
for(int number : iterator.next()) {
System.out.print(number + " ");
}
System.out.println("]");
}
Jade指出了解决问题的简单方法。然而,排序需要O(n-logn)时间,并且在m个集合上进行计算会使复杂性更糟。
由于您使用的是Java,我建议您使用TreeSet。它:
- 访问时间为O(logn)
- 不允许重复元素
- 允许您按自然顺序迭代元素,以比较它们并确定相等性
由此产生的复杂性仅为O(logn+n)=O(n)