002—對數組的幾種基本操作
阿新 • • 發佈:2017-12-20
copy process ble reverse rand sin post body 矩陣
1 package oo2_array_code_processing; 2 3 import java.util.Arrays; 4 5 /** 6 * @author ALazy_cat 7 * 典型的數組代碼處理: 8 * 1. 找出數組中最大的元素 9 * 2. 計算數組元素的平均值 10 * 3. 復制數組 11 * 4. 顛倒數組元素的順序 12 * 5. 矩陣相乘 13 */ 14 public class ArrayCodeProcessin { 15 public static void main(String[] args) { 16int[] a = new int[8]; 17 for(int i=0; i<a.length; i++) { 18 a[i] = (int)(Math.random() * 100); 19 } 20 21 int[][] b = {{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}}; 22 int[][] c = {{1, 4}, {2, 5}, {3, 6}, {4, 7}}; 23 System.out.println("數組: " + Arrays.toString(a));24 System.out.println("數組中最大的數: " + getMax(a)); 25 System.out.println("數組中所有數的平均值: " + getAverage(a)); 26 System.out.println("復制數組: " + Arrays.toString(copyArray(a))); 27 System.out.println("顛倒數組順序: " + Arrays.toString(reverseArray(a))); 28 System.out.println("矩陣相乘:");29 //矩陣A與矩陣B相乘的條件是:A的列數 == B的行數 30 if(b[0].length == c.length) { 31 int[][] d = matrixMultiply(b, c); 32 for(int i=0; i<d.length; i++) { 33 for(int j=0; j<d[0].length; j++) { 34 System.out.print(d[i][j] + " "); 35 } 36 System.out.println(); 37 } 38 } else { 39 throw new IllegalArgumentException("這兩個矩陣不能相乘..."); 40 } 41 } 42 //找出數組中最大的元素 43 public static int getMax(int[] a) { 44 int max = Integer.MIN_VALUE; 45 for( int x : a) { 46 if(x > max) 47 max = x; 48 } 49 return max; 50 } 51 //計算數組元素的平均值 52 public static double getAverage(int[] a) { 53 int sum = 0; 54 double average = 0.0; 55 for(int x : a) { 56 sum += x; 57 } 58 average = sum/a.length; 59 return average; 60 } 61 //復制數組 62 public static int[] copyArray(int[] a) { 63 int[] b = new int[a.length]; 64 for(int i=0; i<a.length; i++) { 65 b[i] = a[i]; 66 } 67 return b; 68 } 69 //顛倒數組元素順序 70 public static int[] reverseArray(int[] a) { 71 int mid = a.length / 2; 72 int temp = 0; 73 for(int i=0; i<mid; i++) { 74 temp = a[i]; 75 a[i] = a[a.length-i-1]; 76 a[a.length-i-1] = temp; 77 } 78 return a; 79 } 80 //矩陣相乘 81 public static int[][] matrixMultiply(int[][] a, int[][] b) { 82 int[][] c = new int[a.length][b[0].length]; 83 for(int k=0; k<a.length; k++) { 84 for(int i=0; i<b[0].length; i++) { 85 for(int j=0; j<b.length; j++) 86 c[k][i] += a[k][j] * b[j][i]; 87 } 88 } 89 return c; 90 } 91 }
002—對數組的幾種基本操作