对数器的好处
1 当没有oj时,也可以验证算法是否正确
2 小样本测试通过,大样本测试出错了,可以使用对数器迅速看出错在哪
3 验证贪心策略是否正确
对数器的概念与使用
随机样本产生器
笔试前要准备好各类随机样本产生器,如数组随机样本产生器、二叉树随机样本产生器等。
代码举例
1 import java.util.Arrays; 2 3 public class Code_01_InsertionSort { 4 5 public static void insertionSort(int[] arr) { 6 if (arr == null || arr.length < 2) { 7 return; 8 } 9 for (int i = 1; i < arr.length; i++) { 10 for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) { 11 swap(arr, j, j + 1); 12 } 13 } 14 } 15 16 public static void swap(int[] arr, int i, int j) { 17 arr[i] = arr[i] ^ arr[j]; 18 arr[j] = arr[i] ^ arr[j]; 19 arr[i] = arr[i] ^ arr[j]; 20 } 21 22 // for test 23 public static void comparator(int[] arr) { 24 Arrays.sort(arr); 25 } 26 27 // for test 28 public static int[] generateRandomArray(int maxSize, int maxValue) { 29 int[] arr = new int[(int) ((maxSize + 1) * Math.random())]; 30 for (int i = 0; i < arr.length; i++) { 31 arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random()); 32 } 33 return arr; 34 } 35 36 // for test 37 public static int[] copyArray(int[] arr) { 38 if (arr == null) { 39 return null; 40 } 41 int[] res = new int[arr.length]; 42 for (int i = 0; i < arr.length; i++) { 43 res[i] = arr[i]; 44 } 45 return res; 46 } 47 48 // for test 49 public static boolean isEqual(int[] arr1, int[] arr2) { 50 if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) { 51 return false; 52 } 53 if (arr1 == null && arr2 == null) { 54 return true; 55 } 56 if (arr1.length != arr2.length) { 57 return false; 58 } 59 for (int i = 0; i < arr1.length; i++) { 60 if (arr1[i] != arr2[i]) { 61 return false; 62 } 63 } 64 return true; 65 } 66 67 // for test 68 public static void printArray(int[] arr) { 69 if (arr == null) { 70 return; 71 } 72 for (int i = 0; i < arr.length; i++) { 73 System.out.print(arr[i] + " "); 74 } 75 System.out.println(); 76 } 77 78 // for test 79 public static void main(String[] args) { 80 int testTime = 500000; 81 int maxSize = 100; 82 int maxValue = 100; 83 boolean succeed = true; 84 for (int i = 0; i < testTime; i++) { 85 int[] arr1 = generateRandomArray(maxSize, maxValue); 86 int[] arr2 = copyArray(arr1); 87 insertionSort(arr1); 88 comparator(arr2); 89 if (!isEqual(arr1, arr2)) { 90 succeed = false; 91 break; 92 } 93 } 94 System.out.println(succeed ? "Nice!" : "Fucking fucked!"); 95 96 int[] arr = generateRandomArray(maxSize, maxValue); 97 printArray(arr); 98 insertionSort(arr); 99 printArray(arr); 100 } 101 102 }