一个面试题。。。

     用1,2,2,3,4,5六个数字,组成一个6位数。
   要求:

             第三位数不能是2;

             3和5不能相邻。 
    编写java程序显示所有的数字。

我自己的答案可能有点麻烦,但总归是搞出来了。。求简便的答案。。

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.junit.Test;

public class TT {
 /**
  * 1.用1,2,2,3,4,5六个数字,组成一个6位数。
  *  要求: 第三位数不能是2; 3和5不能相邻。
  *  编写java程序显示所有的数字。
  * 123245
  */
 @Test
 public void test1() {

  int[] a1 = { 1, 2, 2, 3, 4, 5 };
  int[] a2 = { 1, 2, 2, 3, 4, 5 };
  int[] a3 = { 1, 2, 2, 3, 4, 5 };
  int[] a4 = { 1, 2, 2, 3, 4, 5 };
  int[] a5 = { 1, 2, 2, 3, 4, 5 };
  int[] a6 = { 1, 2, 2, 3, 4, 5 };
  Set<String> set = new HashSet<String>();
  for (int r1 : a1) {
   int j = 0;
   String str = "";
   str += r1;
   for (int r2 : a2) {
    if (str.length() >= 2) {
     str = str.substring(0, 1);
    }
    str += r2;
    for (int r3 : a3) {
     if (r3 == 2) {
      continue;
     }
     if (str.length() >= 3) {
      str = str.substring(0, 2);
     }
     str += r3;
     for (int r4 : a4) {
      if (str.length() >= 4) {
       str = str.substring(0, 3);
      }
      str += r4;
      for (int r5 : a5) {
       if (str.length() >= 5) {
        str = str.substring(0, 4);
       }
       str += r5;
       for (int r6 : a6) {
        if (str.length() >= 6) {
         str = str.substring(0, 5);
        }
        str += r6;
        // 判断 -- 3和5 相邻的
        if ((!str.matches("[1-5]*[5|3][3|5][1-5]*"))
          && str.matches("[2-5]*[1][2-5]*")
          && str.matches("[1-5]*[2][1-5]*[2][1-5]*")
          && str.matches("[1-5]*[3][1-5]*")
          && str.matches("[1-5]*[4][1-5]*")
          && str.matches("[1-4]*[5][1-4]*")) {
         set.add(str);
        }

       }
      }
     }
    }
   }
  }
  Iterator<String> it = set.iterator();
  int i = 0;
  while (it.hasNext()) {
   if (i++ % 10 == 0) {
    System.out.println();
    System.out.print("第"+ (i/10+1) +"行: ");
   }
   System.out.print(it.next() + " ");
  }
  System.out.println();
  System.out.println();
  System.out.println("一共"+set.size());
 }

}

原文地址:https://www.cnblogs.com/pangblog/p/3320266.html