Java数组小工具
package algorithm.study.utils;
import java.util.Arrays;
/**
* A tool prepare for Array,it convenient to create a random array for sort and print them
*
* @author ygh 2017年2月27日
*/
public class ArraysTools {
/**
* Print a int[] into console
*
* @param arr The array need to print
*/
public static void toStringIntArray(int[] arr) {
System.out.println(Arrays.toString(arr));
}
/**
* Get a random array by size and max value
*
* @param size The size the new array you want to create
* @param maxValue The max value in the array;
* @return A random array
*/
public static int[] getRandomArray(int size, int maxValue) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = getIntRandomValue(maxValue);
}
return arr;
}
/**
* Get a random that less than max value
*
* @param maxValue The max value you get the random number
* @return A random number less than max value
*/
public static int getIntRandomValue(int maxValue) {
return (int) (Math.random() * maxValue);
}
/**
* Get a random value in a integer array
*
* @param arr A value come from this array
* @return A random value comes from this array
*/
public static int getRandomValue(int[] arr) {
int length = arr.length;
return (arr[getIntRandomValue(length)]);
}
/**
* Get the max value in a Array.
*
* @param arr[] The max value come from
* @return The max value in this array
*/
public static int getMaxValue(int arr[]) {
int max = arr[0];
for (int i = 1; i < arr.length - 1; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
return max;
}
/**
* Get average of an integer array
*
* @param arr The array provide data
* @return The average of this array
*/
public static double getArrayAverage(int[] arr) {
int length = arr.length;
int sum = 0;
for (int i = 0; i < length; i++) {
sum += arr[i];
}
return (sum / length);
}
/**
* Copy an array to new array
*
* @param arr The array needed to copy
* @return The copied array
*/
public static int[] copy(int arr[]) {
int length = arr.length;
int newArr[] = new int[length];
for (int i = 0; i < length; i++) {
newArr[i] = arr[i];
}
return newArr;
}
/**
* Reverse the elements within an array
*
* @param arr An array want to reverse all elements
*/
public static void reverse(int[] arr) {
int tmp;
int length = arr.length;
for (int i = 0; i < length / 2; i++) {
tmp = arr[i];
arr[i] = arr[length - 1 - i];
arr[length - 1 - i] = tmp;
}
}
/**
* multiple two matrix-matrix(square matrices)
* c[][]=a[][]*b[][]
* @return The result of two matrix multiple
*/
public static double[][] multiplation() {
int length = 5;
double[][] arr = new double[length][length];
double[][] multip = new double[length][length];
for (int i = 0; i < length; i++) {
for (int j = 0; i < length; i++) {
for (int k = 0; k < length; k++) {
multip[i][i] = arr[i][k] * arr[k][j];
}
}
}
return multip;
}
}