I am trying to implement an algorithm that does the following:
If the number stored in the variable compHandexists, its index will be stored in indexArray, and this index will be added to the method banIndex(), so this index will never be considered for further work.
OR
if the summation of any two numbers in the list is equal compHand, the indices of that number will be stored in indexArrayand added to banIndex(), so that they will never be considered for any further work.
Actually, the algorithm works fine, but always, if the last valuehashMap is 10, then it 10will be displayed twice? it should be displayed only once. for example: the result of this algorithm according to populateHash()will be: 5,6,7,7 and it should be: 5,6,7
Any idea why this is happening?
the code
public class Test {
static HashMap<Integer, Integer> h1 = new HashMap<Integer, Integer>();
public static void main(String[] args) {
int compHand = 10;
populateHash(Test.h1);
int iter = -1;
int [] indexArray = new int[(Test.h1.size())];
HashMap<Integer, Integer> bannedIndexHash = new HashMap<Integer, Integer>();
for (int i=1; i<=Test.h1.size(); i++) {
if (! isBannedIndex(bannedIndexHash, i)) {
if (i == Test.h1.size()) {
if (compHand == Test.h1.get(i)) {
indexArray[++iter] = i;
banIndex(bannedIndexHash, i);
}
}else {
if (compHand == Test.h1.get(i)) {
indexArray[++iter] = i;
banIndex(bannedIndexHash, i);
}
else {
for (int j=i+1; j<=Test.h1.size(); j++) {
if ( (! isBannedIndex(bannedIndexHash, i)) &&
(! isBannedIndex(bannedIndexHash, j)) ) {
if ( (compHand == (Test.h1.get(i)+Test.h1.get(j))) || (compHand == Test.h1.get(j)) ) {
if (compHand == (Test.h1.get(i)+Test.h1.get(j))) {
indexArray[++iter] = i;
indexArray[++iter] = j;
banIndex(bannedIndexHash, i);
banIndex(bannedIndexHash, j);
break;
}
else {
if (compHand == Test.h1.get(j)) {
indexArray[++iter] = j;
banIndex(bannedIndexHash, j);
}
}
}
}
}
}
}
}
}
if (iter > -1) {
System.out.println("iter > -1");
for (int i=0; i<indexArray.length; i++) {
System.out.println(indexArray[i]);
}
}
}
private static boolean isBannedIndex(HashMap<Integer, Integer> _bannedIndexHash, int index) {
if (!_bannedIndexHash.isEmpty()) {
for (int i=1; i<_bannedIndexHash.size(); i++)
if (index == _bannedIndexHash.get(i))
return true;
return false;
}else
return false;
}
private static void banIndex(HashMap<Integer, Integer> _bannedIndexHash, int index) {
if (_bannedIndexHash != null)
_bannedIndexHash.put(_bannedIndexHash.size()+1, index);
}
private static void populateHash(HashMap<Integer, Integer> hash) {
hash.put(1, 1);
hash.put(2, 3);
hash.put(3, 1);
hash.put(4, 1);
hash.put(5, 10);
hash.put(6, 10);
hash.put(7, 10);
}
}