+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

jspspikeFinished PMerge73bc9bb

master
2.1 KiB62 linesraw
1import java.util.Arrays;
2import java.util.Random;
3
4public class MergeTest {
5
6    public static void main(String[] args) {
7        final int NUM_THREADS = 4; // Change this to however many threads you want to test with
8        testRandom(NUM_THREADS);
9        System.out.println("Congrats! Your implementation passes the randomly generated test cases!");
10    }
11
12    /**
13     * Generates and tests PMerge 10 times with random array inputs.
14     * @param numThreads number of threads to run PMerge with
15     */
16    public static void testRandom(int numThreads) {
17        Random rand = new Random();
18        for(int i = 0; i<10; ++i) {
19            int aSize = rand.nextInt(200);
20            int bSize = rand.nextInt(200);
21            int[] a = new int[aSize], b = new int[bSize];
22            for(int j = 0; j<a.length; ++j)
23                a[j] = rand.nextInt();
24            for(int j = 0; j<b.length; ++j)
25                b[j] = rand.nextInt();
26            int[] c = new  int[aSize + bSize];
27
28            Arrays.sort(a);
29            Arrays.sort(b);
30            PMerge.parallelMerge(a, b, c, numThreads);
31            verify(a, b, c);
32        }
33    }
34
35    public static void testSmall(int numThreads) {
36        int[] a = {1, 3, 4, 23, 32, 35, 234, 2345};
37        int[] b = {1, 9, 11, 14, 16, 17, 22, 24, 499, 5011, 6000};
38
39        int[] c = new int[a.length + b.length];
40        PMerge.parallelMerge(a, b, c, numThreads);
41    }
42
43    static void verify(int[] a, int[] b, int[] c) {
44        int[] expected = new int[a.length + b.length];
45        System.arraycopy(a, 0, expected, 0, a.length);
46        System.arraycopy(b, 0, expected, a.length, b.length);
47        Arrays.sort(expected);
48        reverse(expected);
49        if(!Arrays.equals(expected, c)) {
50            throw new AssertionError(String.format("\nExpected: %s\nReceived: %s\n", Arrays.toString(expected), Arrays.toString(c)));
51        }
52    }
53
54    static void reverse(int[] a) {
55        for(int i = 0; i<a.length/2; ++i) {
56            a[i] ^= a[a.length-1-i];
57            a[a.length-1-i] ^= a[i];
58            a[i] ^= a[a.length-1-i];
59        }
60    }
61
62}