提供一个逻辑问题的算法!(最近打的大家参考一下)

来源:互联网 发布:oracle常用sql语句 编辑:程序博客网 时间:2024/05/22 02:01

/*有人邀请A,B,C,D,E,F,去参加会议,这6个人有些奇怪,因为他们有很多要求,已知
 * 1.A,B两人至少有一个人参加会议
 * 2.A,E,F 三人中有两人参加会议
 * 3.B,C一致决定要么两人一起去,要么两人都不去
 * 4.A,D两人中只有一个人参加
 * 5.C,D两人中也只要一个人参加
 * 6.如果D不去,那么E也决定不去
 * 那么最后究竟都有谁参加会议
 */
public class HuiYi {
 public static void main(String[] args)
 {
  method mt=new method();
  mt.display();
 }

}
class method
{
 
 public int countGo(int ... as)
 {
  int sum=0;
  for(int a : as)
  {
   if(a==1)
    sum++;
  }
  return sum;
 }
 public boolean tm1(int a1,int a2,int a3,int a4,int a5,int a6)
 {
  if(countGo(a1,a2)>0)
  {
   return true;
  }
  return false;
 }
 public boolean tm2(int a1,int a2,int a3,int a4,int a5,int a6)
 {
  if(countGo(a1,a5,a6)==2)
  {
   return true;
  }
  return false;
 }
 public boolean tm3(int a1,int a2,int a3,int a4,int a5,int a6)
 {
  if(countGo(a2,a3)==0||countGo(a2,a3)==2)
  {
   return true;
  }
  return false;
 }
 public boolean tm4(int a1,int a2,int a3,int a4,int a5,int a6)
 {
  if(countGo(a1,a4)==1)
  {
   return true;
  }
  return false;
 }
 public boolean tm5(int a1,int a2,int a3,int a4,int a5,int a6)
 {
  if(countGo(a3,a4)==1)
  {
   return true;
  }
  return false;
 }
 public boolean tm6(int a1,int a2,int a3,int a4,int a5,int a6)
 {
  if(countGo(a4)==0)
  {
   if(countGo(a5)==0)
   return true;
  }else{
   return false;
  }
  return true;
 }
 public void display()
 {
  for(int A=0;A<=1;A++)
   for(int B=0;B<=1;B++)
    for(int C=0;C<=1;C++)
     for(int D=0;D<=1;D++)
      for(int E=0;E<=1;E++)
       for(int F=0;F<=1;F++)
       {
        if(tm1(A,B,C,D,E,F)
           &&tm2(A,B,C,D,E,F) 
           &&tm3(A,B,C,D,E,F)
           &&tm4( A,B,C,D,E,F)
           &&tm5( A,B,C,D,E,F)
           &&tm6( A,B,C,D,E,F)
        )
        {
         System.out.println("A="+A+",B="+B+",C="+C+
           ",D="+D+",E="+E+",F="+F);
        }
       }
  
 }
}

        大家在看到的问题的时候是不是在想要用穷举法来实现啊!例如if(){}else if(){}·····这样的形式啊!其实这样不好,浪费时间和精力!呵呵!还是变写一个方法去实现好,还有我们在用java解决某一个问题的时候不要用面向过程的形式来编写程序,不要忘了java是面向对象的语言啊!

       这个程序对大家好像有点难,就现在我来讲解一下吧!countGO(int ... as)方法它是用来计算每个条件中到底有多少个人去参加会议,也是下面方法tm1、tm2···中的if()语句的判断条件,具体自己看一下方法体,如果不懂就留言吧!还有有些人会问int ... as是什么来的啊?这里是来表示相当于定义了一个int[] as数组,但是没有规定数组的大小,也就是说输入多少个都行!恩恩!现在有点困啦!如果还有什么不明白的就Q我或者留言吧!

原创粉丝点击