我正在开展一个项目,我需要使用递归,以及arraylists / vector来解决3-satisfiability实例。任务是选择整数子集,使得下面表示的每个集合包含子集的一个或多个元素。约束是一个数字,i&相反,-i,不能同时在子集中。
Vector<Vector<Integer>> matrix = new Vector<Vector<Integer>>();
for(int i=0;i<4;i++)
{
matrix.add(new Vector<Integer>());
}
然后用数字填充二维向量/ arraylist,例如:
1, -2, 3
-1, 2, 4
2, -3, 4
-1, -2, -3
if(startRec(matrix)
{
//solution is found
}
else
{
//no solution is possible
}
private boolean startRec(Vector<Vector<Integer>> matrix)
{ // I'm using trial and error to find a solution to the above problem. So in the below, matrix.get(0).get(i) is selected as part of a possibly correct set.
boolean success=false;
if(stagen(matrix.get(0).get(0), matrix))
{
success=true;
}
else if(stagen(matrix.get(0).get(1),matrix))
{
success=true;
}
else if(stagen(matrix.get(0).get(2),matrix))
{
success=true;
}
return success;
}
private boolean stagen(int input, Vector<Vector<Integer>> matrix)
{
removei(input, matrix) // this removes all Vector<Integer> that contain i. Those sets are considered satisfied, and no longer need to be addressed.
removenegative(input,matrix) // this removes all integers that are -input. Since i and -i cannot both be selected, I'm removing the -input.
//So if a set contained three ints, one of which was -input, it now contains 2.
boolean success=false;
if(stagen(matrix.get(0).get(0), matrix)) // since the original matrix.get(0) contained input, it was removed in removei(input,matrix), thus this is a one below the one called previously.
{
success=true;
}
else if(stagen(matrix.get(0).get(1),matrix))
{
success=true;
}
else if(stagen(matrix.get(0).get(2),matrix))
{
success=true;
}
return success;
}
我已删除超出范围的检查,以使其更具可读性。但我充满信心的过程就是:
1, -2, 3 //1 is selected in the second line of startRec
-1, 2, 4
2, -3, 4
-1, -2, -3
//1, -2, 3 line is removed from consideration by method removei() as 1 has been selected
2, 4 // -1 has been removed as both 1,-1 cannot be selected.
2, -3, 4
-2, -3 // -1 removed.
2, 4 now 2 is the first number, so 2 is selected.
-2, 3, 4
-2, -3
//2, 4 removed via removei method.
3, 4 //-2 is removed, because 2 has been selected.
-3 //-2removed.
3, 4 //Now 3 is selected.
-3
//3, 4 line removed as it has been satisfied.
_____ //There's now an empty set here as -3 was deleted
//false is returned by stagen.
程序返回到选择3的stagen,现在理想情况下现在选择4作为下一个字母。但我删除了整行。
有没有办法在不创建未知数量的向量的情况下执行此操作?
2,arraylists&amp; amp;引导?我一直在使用arraylists,但项目建议使用矢量。
答案 0 :(得分:0)
你问题的第一部分是不连贯的。但是,我将详细阐述Vector和Arraylist之间的区别:
请参阅this主题以获取详细说明。