1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列, 如:512234、212345等. 要求:”4”不能在第三位,”3”与”5”不能相连。

时间:2023-03-09 13:18:54
1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列, 如:512234、212345等. 要求:”4”不能在第三位,”3”与”5”不能相连。

private static String[] mustExistNumber = new String[] { “1”, “2”, “2”, “3”, “4”, “5” };

private static boolean isValidNumber(String str) {
// 检查是否包含12345这五个数,不包含返回false
for (String number : mustExistNumber) {
if (str.indexOf(number) < 0)
return false;
}
// 检查是否有两个2,只有一个返回false
if (str.lastIndexOf("2") == str.indexOf("2")) {
return false;
}
// 检查4在不在第三位,是返回false
if (str.charAt(2) == '4') {
return false;
}
// 检查是否存在35在一起,有返回false
if (str.indexOf("35") >= 0 || str.indexOf("53") >= 0) {
return false;
}
return true;
} public static void main(String[] args) {
int count=0;
for (int i = 122345; i <=543221; i++) {
if (isValidNumber(String.valueOf(i))) {
System.out.println(i);
count++;
}
}
System.out.println(count);
}