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) {
16 int[] 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 }