[Java] 纯文本查看 复制代码
import java.util.ArrayList;
public class MemoryBox {
private MemoryBox(){}
private static ArrayList<Integer> list = new ArrayList<>();
private static boolean judgeADJ = false;
private static int n1,n2;
public static boolean setNum(int num){
for (int i = 0; i < list.size(); i++) {
if(num == list.get(i)){
return false;
}
}
list.add(num);
if(judgeADJ){
if(isAdjacented()){
return false;
}
}
return true;
}
public static boolean setNum(int num,boolean condition){
//给定条件为false则返回false
if (!condition) return false;
for (int i = 0; i < list.size(); i++) {
if(num == list.get(i)){
return false;
}
}
list.add(num);
if(judgeADJ){
if(isAdjacented()){
return false;
}
}
return true;
}
public static void clearMemory(){
list.clear();
}
public static void addNonadjacentedJudge(int num1,int num2){
n1 = num1;
n2 = num2;
judgeADJ = true;
}
public static void removeNonadjacentedJudge(){
judgeADJ = false;
}
//判断集合中两个数是否相邻
private static boolean isAdjacented(){
int index1 = findIndexOfNum(n1);
int index2 = findIndexOfNum(n2);
if (index1>=0&&index2>=0) {
if(Math.abs(index1-index2)==1){
return true;
}
}
return false;
}
//找出两个数在集合中的位置
private static int findIndexOfNum(int num){
for (int i = 0; i < list.size(); i++) {
if(num == list.get(i)){
return i;
}
}
//没找到
return -1;
}
}
[Java] 纯文本查看 复制代码
public class Q1234ForObj {
public static void main(String[] args) {
// TODO Auto-generated method stub
//添加两个数不相邻的约束条件
MemoryBox.addNonadjacentedJudge(4, 3);
// MemoryBox.removeNonadjacentedJudge();//约束条件置空
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
for (int k = 1; k <= 4; k++) {
for (int l = 1; l <= 4; l++) {
//setNum数据加入记忆盒子,如果加入的数与盒子中的数重复则返回false
if (MemoryBox.setNum(i)&&MemoryBox.setNum(j)&&MemoryBox.setNum(k)&&MemoryBox.setNum(l)) {
int num = i*1000+j*100+k*10+l;
System.out.println(num);
}
//清空记忆,准备下次循环
MemoryBox.clearMemory();
}
}
}
}
}
}