Re: can this code be improved
....
Seems to me that topSix should now contain the top six picks but I
could be wrong..
I'm afraid you are wrong, and the apparent over-selection of the high
numbers is due to bugs in your top six selection.
I've written a simple test program comparing the two methods. Take a
look at it, and take it for a test drive:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class TopSixTest {
public static void main(String[] args) {
int[] data = new int[49];
// Fixed seed for reproducibility
Random rand = new Random(5);
for (int i = 0; i < data.length; i++) {
data[i] = 5;
}
System.out.println("data[i]==5");
test(data);
for (int i = 0; i < data.length; i++) {
data[i] = i + 1;
}
System.out.println("data[i]==i+1");
test(data);
for (int i = 0; i < data.length; i++) {
data[i] = 100 - i;
}
System.out.println("data[i]=100-i");
test(data);
testRandomData(rand);
testRandomData(rand);
testRandomData(rand);
}
/**
* Test random permutation of numbers from 1000 through 1048
*
* @param rand
*/
private static void testRandomData(Random rand) {
int[] data = new int[49];
List<Integer> dataList = new ArrayList<Integer>();
for (int i = 0; i < data.length; i++) {
dataList.add(new Integer(1000 + i));
}
Collections.shuffle(dataList, rand);
for (int i = 0; i < data.length; i++) {
data[i] = dataList.get(i).intValue();
}
System.out
.println("Random permutation of 1000 through 1048");
test(data);
System.out.println("Actual positions of largest 6 elements");
for (int i = 1048; i > 1042; i--) {
System.out.printf("%d %d", i, dataList
.indexOf(new Integer(i)));
System.out.println();
}
}
/**
* Print the results of both methods on the input data
*
* @param data
* "BigList" data, a 49 element frequency array.
*/
private static void test(int[] data) {
int[] printsTop = printsVersion(data.clone());
int[] patsTop = patsVersion(data.clone());
for (int i = 0; i < 6; i++) {
System.out.printf("%d Print's %d Pats's %d", i,
printsTop[i], patsTop[i]);
System.out.println();
}
}
private static int[] printsVersion(int[] BigList) {
int[] topSix = new int[6];
for (int count = 0; count <= topSix.length - 1; count++) {
int lIndex = 0;
int largest = BigList[0];
for (int x = 0; x <= BigList.length - 1; x++) {
for (int y = x + 1; y <= BigList.length - 2; y++)
if (BigList[y] > largest) {
largest = BigList[y];
BigList[y] = 0;
lIndex = y;
topSix[count] = lIndex;
}
}
}
return topSix;
}
private static int[] patsVersion(int[] BigList) {
int[] topSix = new int[6];
for (int count = 0; count < topSix.length; count++) {
int lIndex = 0;
int largest = BigList[0];
for (int x = 1; x < BigList.length; x++) {
if (BigList[x] > largest) {
largest = BigList[x];
lIndex = x;
}
}
topSix[count] = lIndex;
BigList[lIndex] = 0;
}
return topSix;
}
}