/* 五、分析以下需求,并用代码实现: (1) 打印由 7,8,9 三个数组成的三位数,要求该三位数中任意两位数字不能相同; (2) 打印格式最后的三位数字以空格分隔,如 789 798 879 897 978 987。 注:要求使用 StringBuilder 来完成 */ public class HomeWork05 { public static void main(String[] args) throws IOException { // 输入值并简单处理 Scanner sc = new Scanner(System.in); System.out.println(" 请输入起始值 (0~9):"); int start=sc.nextInt(); System.out.println(" 请输入结束值 (0~9):"); int end=sc.nextInt(); int bound=end-start+1; StringBuilder stringBuilder = new StringBuilder(); HashSet<String> set = new HashSet<>(); int cout=0; Random r = new Random(); long bCount=boundCount(bound); if (bCount>10000){ System.out.println(" 结果数超过 10000 为 "+bCount+" 计算会很慢, 请按任意键继续 "); System.in.read(); } // 穷举各种可能,小于正确结果个数持续执行 直到达到正确个数 while (set.size()<bCount) { int number = r.nextInt(bound) + start; if (!stringBuilder.toString().contains(String.valueOf(number))&&stringBuilder.toString().length()<bound){ stringBuilder.append(number); }else if (stringBuilder.toString().length()==bound){ set.add(stringBuilder.toString()); stringBuilder=new StringBuilder(); } } List ts = new ArrayList<>(set); Collections.sort(ts); // 排序 System.out.println(" 结果数:"+ts.size()); System.out.println(ts.toString().replace("[","") .replace("]","") .replace(","," ")); } /** * 计算笛卡尔积运算去重后个数 * @param bound * @return */ public static long boundCount(int bound){ int sum=1; for (int i = 1; i <= bound; i++) { sum*=i; } return sum; } }