-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlab2copy.java
114 lines (92 loc) · 3.18 KB
/
lab2copy.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
/**
* lab2copy
*/
public class lab2copy {
public static void sort (int array[])
{
for (int i = 0; i < array.length -1; i++) {
if (array[i] > array[i+1]) {
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp; // OBS array[i] instead of temp
for (int j = i; j > 0; j--) {
if (array[j] < array[j-1]) { // OBS > instead of <
int temp2 = array[j];
array[j] = array[j-1];
array[j-1] = temp2;
}
else
{
break;
}
}
}
}
}
public static boolean binarySearch (int array[], int key){
int x = -1;
int l = 0; // OBS l = 1 instead of 0
int r = array.length-1;
do {
x = (l+r)/2;
if(key < array[x]){ // OBS > instead of <
r = x-1;
} else {
l = x+1;
}
} while (!(key == array[x]) && !(l > r)); // OBS || instead of && // OBS >= instead of >
if(key == array[x]){
return true;
} else {
return false;
}
}
public static boolean search (int array[], int key){
int temp[] = array.clone();
sort(temp);
return binarySearch(temp, key);
}
public static void runTests(String path, int numTests) throws IOException
{
File fp = new File(path);
FileReader fr = new FileReader(fp);
BufferedReader br = new BufferedReader(fr);
int counter_tests = 0;
for (int i = 0; i < numTests; i++) {
String line = br.readLine();
line = line.substring(1, line.length()-1);
int tmp[] = Arrays.stream(line.split(", ")).mapToInt(Integer::parseInt).toArray();
int key = Integer.parseInt(br.readLine());
boolean search = search(tmp, key);
boolean contains = false;
for (int j = 0; j < tmp.length; j++) {
if(tmp[j] == key){
contains = true;
break;
}
}
if (search == contains) {
counter_tests +=1;
} else {
System.out.println("Test # " + (i+1) + " failed. With key: " + key +" and array:" );
System.out.println(Arrays.toString(tmp));
System.out.println("Expected: " + contains + " but got: " + search +"\n");
}
}
fr.close();
System.out.println("Passed " + counter_tests + " of " + numTests);
}
public static void main(String[] args) throws IOException
{
System.out.println("Running pair-wise tests...");
runTests("pair_wise_test_cases.txt", 100);
System.out.println("\nRunning random tests...");
runTests("random_test_cases.txt", 100);
}
}