Untitled
By: a guest | Feb 9th, 2010 | Syntax:
Java | Size: 2.46 KB | Hits: 7 | Expires: Never
package lab2;
import java.util.Random;
/**
*
* @author James Valente
*/
public class Randmax {
/*Because every java app needs main()*/
/**
*
* @param args
*/
public static void main
(String[] args
) {
long startTime, endTime;
int[] dummyArray;
int maximum;
double bigO;
int sizes[] = {10, 100, 500, 1000, 5000, 10000, 50000, 100000, 1000000, 2000000, 5000000, 10000000};
/*Time for output*/
System.
out.
printf("%-10s %-8s %-8s %-8s\n",
"Size",
"Max",
"Runtime (ns)",
"Big-O"); //Header part 1
System.
out.
printf("%-10s %-8s %-8s %-8s\n",
"--------",
"--------",
"-----------",
"--------"); //Header part 2
String specify
= "%-10s %-8d %-8d ns %-8f\n"; //Output format specifer.
/*Now begins the point at which I must output each max and its runtime.*/
for (int i = 0; i < sizes.length; i++) {
dummyArray = populate(sizes[i]);
startTime
= System.
nanoTime();
maximum = findMax(dummyArray);
endTime
= System.
nanoTime() - startTime
;
bigO = (double)endTime/(double)sizes[i];
System.
out.
printf(specify, sizes
[i
], maximum, endTime, bigO
);
}
}
/*Some method that most likely exists as a java builtin.*/
/**
*
* @param arr Array to find max
* @return Max value of array
*/
public static int findMax(int[] arr) {
int max = arr[0]; /*Value was zero
* Negatives could cause issues
* Here's my fix for that
*/
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i]; //Highlander style: there can be only one.
}
}
return max;
}
/*With 9+ arrays being populated, creating a function is much more efficient*/
/**
*
* @param n Size of Array
* @return Randomly populated array of size n
*/
public static int[] populate(int n) {
int array[] = new int[n];
int seed = 10000000; //uh sure
for (int i = 0; i < array.length; i++) {
int phobos = randGen.nextInt(seed); //Okay make a random
int deimos = randGen.nextInt(seed / 2); //You too, pick a random.
array[i] = deimos - phobos; //Do mathy things to be SUPER RANDOM
}
return array;
}
}