Apologies if this does not seem related to code I have written but would want to understand what is going on in these Java code snippets(I do not understand Java to the extend I could decode this). I would like to implement these snippets in C(which I know fair bit). I see in snippet one there is some Hash Table search going on like elements of one array used as keys to search other array, but could not get it correctly.
1] Snippet 1.
The problem it is trying to solve is: Find first covering prefix of a array
For example, the first covering prefix of the following 5�?�element array A:
A[0] = 2 A[1] = 2 A[2] = 1
A[3] = 0 A[4] = 1
is 3, because sequence [ A[0], A[1], A[2], A[3] ] equal to [2, 2, 1, 0], contains all values that occur in array A.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
class FirstCovering {
int ps ( int[] A ) {
ArrayList<Integer> arrA = new ArrayList<Integer>(A.length);
for (int i = 0; i < A.length; i++) {
arrA.add(A[i]);
}
HashSet<Integer> hashSet = new HashSet<Integer>(arrA);
Iterator<Integer> iter = hashSet.iterator();
int index = 0, tempIndx=0;
while (iter.hasNext()) {
tempIndx = arrA.indexOf(iter.next());
if (tempIndx > index ) index = tempIndx;
}
return index;
}
}
2] Snippet 2
class ComplementaryPairs {
private static String palindrome;
public static void main(String[] args) {
int array[] = {4,5};
int a = complementary_pairs(6, array);
System.out.println(a);
int array2[] = {4,5};
int b = complementary_pairs(4, array2);
System.out.println("b = " + b);
}
static int complementary_pairs ( int k,int[] A ) {
// find count of complementary pairs from array A.
int count = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
if (A[j] + A[i] == k) {
count++;
}
}
}
return count;
}
}