001package algs11;
002import stdlib.*;
003import java.util.Arrays;
004public class XArrayFunctions {
005
006        public static double average (double[] a) {
007                int N = a.length;
008                double sum = 0.0;
009                for (int i = 0; i < N; i++)
010                        sum += a[i];
011                double average = sum / N;
012                return average;
013        }
014
015        public static double[] copy (double[] a) {
016                int N = a.length;
017                double[] b = new double[N];
018                for (int i = 0; i < N; i++)
019                        b[i] = a[i];
020                return b;
021        }
022
023        public static void reverse (double[] a) {
024                int N = a.length;
025                for (int i = 0; i < N / 2; i++) {
026                        double temp = a[i];
027                        a[i] = a[N - 1 - i];
028                        a[N - i - 1] = temp;
029                }
030        }
031
032        public static double[][] multiply (double[][] a, double[][] b) {
033                int N = a.length;
034                double[][] c = new double[N][N];
035                for (int i = 0; i < N; i++)
036                        for (int j = 0; j < N; j++)
037                                // Compute dot product of row i and column j.
038                                for (int k = 0; k < N; k++)
039                                        c[i][j] += a[i][k] * b[k][j];
040                return c;
041        }
042
043        public static void main (String[] args) {
044                double[] a = new double[] { 10, 20, 30, 40, 50 };
045
046                StdOut.format ("average: %f\n", average (a));
047
048                double[] b = copy (a);
049                reverse (b);
050                StdOut.format ("reverse: %s\n", Arrays.toString (b));
051        }
052}