I am trying to keep track of the the scores of the lowest numbers and if I find the lowest scores of those players I don't want them to play again in the next round. I have gotten to the point of storing those low player value into the array but I only want them to be stored ONCE.
for(int i =0; i < player.length; i++){
for(int j =1; j < player.length; j++){
if(player[j] < player[i]){
mi开发者_JAVA百科n[i] =j;
System.out.println(min[i]+" "+round+" "+playerList.get(j));
}
}
}
One way is to have a sorted array, but it might be an overhead as far as insertion into the array is concerned.
The other method is to encapsulate the array in a data structure which internally keeps track of the index of the lowest value in the array. This data structure will have special methods for insertion and deletion which would always check while inserting and deleting to update the private member if the new number to be inserted is lower than the current lowest number.
This data structure should also expose a method to return the index of the lowest number in the array, which is already stored in a member variable.
Do 2 separate loops instead. One to find lowest number, second to collect indexes.
int minValue = 1000000; //
for(int i =0; i< player.length; i++){
if(player[i] < minValue){
minValue = player[i];
}
}
int j =0;
for(int i =0; i< player.length; i++){
if(player[i]==minValue){
min[j]=i;
j++;
}
}
One way to sort lowest numbers in array
// let array be of size x
int arr[]=new int[x];
// Now,assign some values to array
int smallest=arr[0]; // assign any value to smallest
// logic
for( int i=0; i < arr.length; i++ ) {
if( smallest > arr[i] ) {
smallest = arr[i];
}
}
System.out.println(smallest); // gets the smallest number out on output stream
Unless this is homework, you should just have an Object for each player and score. You can add them to a PriorityQueue to always get the lowest or add them to a Collection/array[] and call sort().
You may want to keep just one copy, but that makes more work for yourself and only saves the computer a milli-second at most.
Your time is worth more than the computers most of the time.
精彩评论