1. 程式人生 > 其它 >Fiddler筆記(13)弱網測試

Fiddler筆記(13)弱網測試

import java.util.Arrays;

public class Solution {

    private static boolean isRight(int[] a, int[] b) {
        if (a == null) {
            return b == null;
        } else {

        }
        if (b == null) {
            return false;
        }
        if (a.length != b.length) {
            return false;
        }
        for (int i = 0; i < a.length; ++i) {
            if (a[i] != b[i]) {
                return false;
            }
        }
        return true;
    }

    private static void merge(int[] arr, int M, int L, int R) {

        if (M < L || M >= R) {
            return;
        }

        int[] helper = new int[R - L + 1];

        int count = 0;
        int p1 = L, p2 = M + 1;
        while (p1 <= M && p2 <= R) {
            helper[count++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
        }

        while (p1 <= M) {
            helper[count++] = arr[p1++];
        }

        while (p2 <= R) {
            helper[count++] = arr[p2++];
        }

        for (int i = L; i <= R; ++i) {
            arr[i] = helper[i - L];
        }
    }

    private static void sort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }

        int n = arr.length;
        int mergeSize = 1;
        while (mergeSize < n) {
            int l = 0;
            while (l < n) {
                int m = l + mergeSize - 1;
                int r = Math.min(m + mergeSize, n - 1);
                merge(arr, m, l, r);
                l = r + 1;
            }

            if (n / 2 < mergeSize) {
                return;
            }
            mergeSize <<= 1;
        }
    }

    public static int[] generateRandomArray(int len, int maxValue) {
        int[] res = new int[len];
        for (int i = 0; i != res.length; i++) {
            res[i] = (int) (Math.random() * maxValue);
        }
        return res;
    }

    public static int generateRandomLen(int limit) {
        return (int) (Math.random() * limit + 1);
    }

    public static void main(String[] args) {
        System.out.println("test begin");
        int maxValue = 1000;
        for (int i = 0; i < 100000; i++) {
            int len = generateRandomLen(100);
            int[] arr = generateRandomArray(len, maxValue);
            int[] copy = Arrays.copyOf(arr, arr.length);
            sort(arr);
            Arrays.sort(copy);
            if (!isRight(arr, copy)) {
                System.out.println("失敗了");
            }
        }
        System.out.println("test finish");
    }
}
心之所向,素履以往 生如逆旅,一葦以航