演演算法 Algorithms (第四版)書中,第1章:基礎程式設計模型第15題:
public static int[] histogram(int[] a, int m) { int[] nm = new int[m]; int sum = 0; for (int i = 0; i < m; i++) { nm[i] = countValueTimes(a, i); //計算第i個元素的值為整數i在引數陣列中出現的次數 sum += nm[i]; //計算新陣列中所有元素之和 } //判斷陣列中所有元素之和應該和a.length相等 if (sum == a.length) { System.out.println(" == == Match result is: " + outputArraytoString(nm)); return nm; } else return nm; }
public static int countValueTimes(int[] a, int x) { if (a.length <= 0) return 0; int count = 0; for (int i = 0; i < a.length; i++) { if (a[i] == x) count++; } return count; }
public static String outputArraytoString(int[] a) { String result = ""; for (int i = 0; i < a.length; i++) { result += a[i] + " "; if (i > 0 && i % 10 == 0) result += "\n"; } return result; }
// 開始執行 histogram 函數,執行90次,看有多少次結果匹配1,2兩個條件 public static void startRun() { for (int i = 10; i < 100; i++) { System.out.println("Start for length " + i); int[] originala = initArrayInt(i); System.out.println("the original array is: " + outputArraytoString(originala)); int[] newintarray = histogram(originala, i); System.out.println("new array int is: " + outputArraytoString(newintarray)); } } public static int[] initArrayInt(int m) { // 隨機生成一個整型陣列,大小為M int[] a = new int[m]; Random r = new Random(); for (int i = 0; i < m; i++) { a[i] = r.nextInt(m - 1); } return a; }
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == Start for a[] length is 99 The original array is: 97 47 78 18 23 5 84 94 78 57 22 36 52 78 59 65 27 80 46 65 37 80 0 42 66 39 60 75 62 56 13 38 25 79 80 97 21 72 69 54 5 66 85 58 29 5 27 39 49 38 80 51 61 80 78 74 80 80 1 82 84 55 83 51 26 85 63 5 63 82 72 10 7 8 36 41 75 18 57 42 97 88 95 55 62 52 4 87 59 6 75 23 80 64 34 9 32 60 22 ==== New array Match Condition ==== 1 1 0 0 1 4 1 1 1 1 1 0 0 1 0 0 0 0 2 0 0 1 2 2 0 1 1 2 0 1 0 0 1 0 1 0 2 1 2 2 0 1 2 0 0 0 1 1 0 1 0 2 2 0 1 2 1 2 1 2 2 1 2 2 1 2 2 0 0 1 0 0 2 0 1 3 0 0 4 1 8 0 2 1 2 2 0 1 1 0 0 0 0 0 1 1 0 3 0
[END]
當在複雜的環境中面臨問題,格物之道需:濁而靜之徐清,安以動之徐生。 雲中,恰是如此!