There is something wrong with my code.
My goal is to translate the pseudocode into java code
Yes my coding is an assignment, I don’t want any answer just to show me where the problem is
What I have to do is to compute the size of the intersection between two unsorted list of students containing no duplicates.
I will show the pseudocode and my java code corresponding to this pseudocode.
Pseudo code:
inter <-- 0
Array C[m+n]
for i <-- 0 to m-1 do C[i] <-- A[i]
for i <-- 0 to n-1 do C[i+m] <-- B[i]
C <-- sort(C, m+n);
pointer <-- 0
while (pointer < m+n-1) do{
if(C[pointer]=C[pointer+1]){
inter <-- inter+1
pointer <-- pointer+2
}
else pointer <-- pointer+1
}
return inter
Java Code:
public static int intersectionSizeMergeAndSort(studentList L1, studentList L2) {
/* Write your code for question 4 here */
int intersectionSize = 0;
int[] C = new int[L1.studentID.length+L2.studentID.length];
for(int i = 0; i<L1.studentID.length; i++){
C[i] = L1.studentID[i];
}
for(int i = 0; i<L2.studentID.length; i++){
C[i+L1.studentID.length] = L2.studentID[i];
}
Arrays.sort(C);
int pointer = 0;
while(pointer<((C.length-1))){
if(C[pointer] == C[pointer+1]){
intersectionSize = intersectionSize + 1;
pointer = pointer + 2;
}
else {
pointer = pointer + 1;
}
return intersectionSize;
}
return 0;
}
My main method:
public static void main(String args[]) throws Exception {
studentList firstList;
studentList secondList;
// This is how to read lists from files. Useful for debugging.
// firstList=new studentList("COMP250.txt", "COMP250 - Introduction to Computer Science");
// secondList=new studentList("MATH240.txt", "MATH240 - Discrete Mathematics");
// get the time before starting the intersections
long startTime = System.currentTimeMillis();
// repeat the process a certain number of times, to make more accurate average measurements.
for (int rep=0;rep<1000;rep++) {
// This is how to generate lists of random IDs.
// For firstList, we generate 16000 IDs
// For secondList, we generate 16000 IDs
firstList=new studentList(2 , "COMP250 - Introduction to Computer Science");
secondList=new studentList(2 , "MATH240 - Discrete Mathematics");
// run the intersection method
int intersection=studentList.intersectionSizeMergeAndSort(firstList,secondList);
System.out.println("The intersection size is: "+intersection);
}
// get the time after the intersection
long endTime = System.currentTimeMillis();
System.out.println("Running time: "+ (endTime-startTime) + " milliseconds");
}
}
Note: L1 and L2 have been declared previously
But I am not getting the results I am aiming for.
Can someone point out what is wrong ?
Thank you
Off the top of my head, it appears to me that your
return intersectionSize;statement occurs within your while loop, so that you loop never gets beyond the first iteration and does not properly compute the intersectionSize. I would delete that statement and replace yourreturn 0;withreturn intersectionSize;like so…