我有四个数字的组合,我不希望任何重复的组合显示。 java的

时间:2014-09-25 02:22:01

标签: java

2 4 6 12和4 2 6 12在技术上不是一个组合,因为两者包含不同顺序的相同值,所以只显示2 4 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 straw1\tstarw2\tstraw3\tstraw4");

    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小时的工作。

几个笔记:

  1. 0小时内不能显示0天的吸管。

  2. 每根吸管必须是唯一的,因此它们不能重复数值。

  3. 由于这是组合,因此无法重复结果

3 个答案:

答案 0 :(得分:1)

如果您简化目标会很有帮助,因为我只有通过阅读您的代码才能知道您想要完成的任务。您的问题似乎是3 sum problem的变体。解决这类问题的一种经典方法是使用排序,而不是输入[2 4 6 12]和[4 2 6 12]在排序后是相同的。

答案 1 :(得分:0)

通常,如果您遇到复杂问题,那么已经有了一个库。查看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("]");
}

答案 2 :(得分:0)

Jade指出了解决问题的简单方法。但是,排序需要O(n logn)时间,并且在m组计算它会使复杂性变差。

由于您使用的是Java,我建议您使用TreeSet。它:

  1. 的访问时间为O(logn)
  2. 不允许重复元素
  3. 允许您以自然顺序迭代元素以比较它们并确定相等性
  4. 由此产生的复杂性只是O(logn + n)= O(n)