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]){
min[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.
Related
I'm studying sorting algorithms, including selection sort, so i decided to write a method and it works fine, but when i checked the book it had 2 variables so i checked it and found that it's using a variable to store the current index and the other as temporary to swap
while mine had only the temporary variable that also stored the initial value in the index as the lowest, then compared it to the other values in the array and swapped if a larger value was found.
Here's my code:
public static void selectionSort(int[] arr){
int lowest;
for(int i = 0; i < arr.length - 1; i++){
lowest = arr[i];
for(int j = i+1; j<arr.length; j++){
if(arr[j]<lowest){
lowest = arr[j];
arr[j] = arr[i];
arr[i] = lowest;
}
}
}
}
and Here's the book's
public static void selectionSort(int[] list){
int min;
int temp;
for(int i = 0; i < list.length - 1; i++) {
min = i;
for(int j = i + 1; j < list.length; j++)
if( list[j] < list[min] )
min = j;
temp = list[i];
list[i] = list[min];
list[min] = temp;
}
}
so I looked on the web and all of them follow the same way as the book, so is my code bad or slower, or it is not considered Selection sort ?
sorry for any english mistakes :P
So, the original code works like this:
Start with the first element of the array
Find the smallest number in the array
Swap the two numbers
Repeat the process Until You reach the end of the list
While Yours does this:
Start with the first element of the array
For each element smaller than the current Swap the two numbers
Replace the lowest number with the swapped
Repeat the process
The result should be the same, but probably You are swapping more numbers than the first one. This probably will make it a little bit slower than the original.
Actually it kinda looks like the insertion sort now, so basically You are swapping the elements with all that are bigger than the one You have.
It looks like you're doing a lot more swaps in the nested for loop.
What happens if you do a sort of [4,3,2,1]? I think you'll have more swap operations than the actual selectionSort.
I'm not sure if your code is bad or slower.
SelectionSort is known to be correct, but it isn't fast either.
I want to find the frequency of occurence for large value, like in the array largest value is 98, I want to find how many times it is repeating. Help me guys
public static void main(String[] args) {
int numbers[] = new int[]{32,43,53,25,98,54,32,65,63,98,43,23,25,98};
int largest = numbers[0];
for (int i=1; i< numbers.length; i++) {
if(numbers[i] > largest)
largest = numbers[i];
}
System.out.println("Largest Number is : " + largest);
}
Not sure if this is a homework question, so I'll try to help by giving you a design in pseudocode rather than Java.
Suppose you're looking at an element. There are three cases:
It's smaller than the previous max. Ignore it.
It's bigger than the previous max (or it's the first item). Make it the new max. As of now, its count must be 1.
It's equal to the previous max. Increment the max's count by 1.
You need to add a count variable. Reset this variable to one whenever you find a new largest value, and increment it whenever the value at your current index is equal to the largest number that you found so far.
Use a counter that you increment each time you see the largest value and reset each time you find a new larger value:
int largest = numbers[0];
int counter = 1;
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > largest) {
largest = numbers[i];
counter = 1;
} elseif (numbers[i] == largest) {
counter++;
}
}
A conventional way to go about such a problem is to use a hash table. The first time you see an element, put it into the hash table with count = 1. Each time you see the same element after that, increase its count by 1. At the end, loop through the keys of the hash table and find the key which is the greatest, then output that key and its associated value (i.e. its count).
There may be solutions which are more efficient in some sense, but I'm guessing they are also more complicated. You can say whether you need to consider that.
I'm currently working on a Bank Account program that takes user input and enters it into an array. It performs actions like deposit, withdraw, search, etc. I'm currently stuck utilizing a selection sort based on the balance amounts in each account. The program should sort the accounts based on balance from highest to lowest and print the results to the screen.
This is my first time using selection sort and one of my first few times using arrays. I understand the concept of selection sort and how to do it with primitive values, but translating that to object values is stumping me. Below is the code I have for the selection sort.
if (out.equals("Sort")) {
int i, j, maxIndex;
double maxValue;
//getNumberOfAccounts is a static counter incremented each time
//a new bank account is created
for (i = 0; i < BankAccount.getNumberOfAccounts(); i++) {
//Sets first value as largest
maxValue = BankAccounts[i].getBalance();
maxIndex = i; //Index of first value
for (j = i; j == BankAccount.getNumberOfAccounts(); j++) {
//Compares subsequent values to initial max value
if (BankAccounts[j].getBalance() > maxValue) {
maxValue = BankAccounts[j].getBalance();
maxIndex = j;
}
}
//Attempts to swap values
BankAccount temp = BankAccounts[i];
BankAccounts[i] = BankAccounts[maxIndex];
BankAccounts[maxIndex] = temp;
//Outputs Bank Account data in descending order based on balance
BankAccounts[maxIndex].printReport();
}
}
Notes:
-This is a portion of the full program so if I'm missing a bracket it's just because I didn't copy the whole thing.
-It seems that when I run the program it does not store the maxValue; the output of maxValue instead outputs whichever value of the loop iteration is next.
-When I run the program it simply prints the bank accounts in the exact order I enter them.
Thank you in advance and if there's any more information I can provide I gladly will.
When you're doing BankAccounts[maxIndex].printReport();, you've already swap the values. So you're printing the value in position maxIndex, and there is already item that was at position i at the beginning of current step.
So, you need to do BankAccounts[maxIndex].printReport(); before swap, or print the value from the right position — BankAccounts[i].printReport();
About maxValue — it's updates each step, so if you need this after cycle ends, you can just get it as BankAccounts[0].getBalance() after sort routine ends.
Moreover, if you need only to sort items, but you're not tied to use selection sort, I'd like to recommend Java built-in methods for sort, so your code should look like this:
Arrays.sort(BankAccounts, 0, BankAccount.getNumberOfAccounts(), new Comparator<BankAccount>() {
#Override
public int compare(BankAccount o1, BankAccount o2) {
if (o1.getBalance() > o2.getBalance()) return -1;
if (o1.getBalance() < o2.getBalance()) return 1;
return 0;
}
}
);
After this sort operation, array BankAccounts is sorted in descending order of balances, and you can print reports just in a simple loop:
for (i = 0; i < BankAccount.getNumberOfAccounts(); i++) {
BankAccounts[i].printReport;
}
First you need to change this line
for (j = i; j == BankAccount.getNumberOfAccounts(); j++) {
to
for (j = i; j < BankAccount.getNumberOfAccounts(); j++) {
The way you have it now you're saying "loop until j is equal to BankAccount.getNumberOfAccounts()" and that’s never gonna happen in this code.
Another performance issue that you have.
BankAccount temp = BankAccounts[i];
BankAccounts[i] = BankAccounts[maxIndex];
BankAccounts[maxIndex] = temp;
Imagen that the current index is already in the right spot. You will make an unnecessary "switch".
For example: current intex ( i == 5 ) biggest balance position ( maxIndex == 5 ).
You will have:
BankAccount temp = BankAccounts[5];
BankAccounts[5] = BankAccounts[5];
BankAccounts[5] = temp;
So you can change this part to this:
if(i != maxIndex) {
//Attempts to swap values
BankAccount temp = BankAccounts[i];
BankAccounts[i] = BankAccounts[maxIndex];
BankAccounts[maxIndex] = temp;
}
After following a couple of old related threads I stumbled upon a thread that perfectly answered my question. While the Array.sort method mentioned above worked perfectly, I was uncomfortable using it simply because I have not yet learned about it.
if (out.equals("Sort")){
for (int i = 0; i < BankAccount.getNumberOfAccounts(); i++){
for(int j = i+1; j < BankAccount.getNumberOfAccounts(); j++){
if(BankAccounts[j].getBalance() > BankAccounts[i].getBalance()){
BankAccount [] temp = new BankAccount [BankAccounts.length];
temp [j] = BankAccounts [j];
BankAccounts [j] = BankAccounts [i];
BankAccounts [i] = temp [j];
}
}
}
for (int i = 0; i < BankAccount.getNumberOfAccounts(); i++){
BankAccounts[i].printReport();
System.out.println();
}
Here's the code that printed the results I've been looking for. I realized my comparison in the inner loop was off and I wasn't creating a new array for the swap, only new objects. Thanks for all the help!
I'm trying to populuate an array with random numbers to be sorted and used in a binary search. All of my code seems to work fine except the generating part. The numbers need be between 1-32767 and I continue to get 0.
for(int i = 0; i < SIZE-1; i++){
array[i] = (gen.nextInt(32767 - 1) + 1);
}
// Print out five entries
for(int i = 0; i < 5; i++){
System.out.println(array[i]);
}
// Sort array
Arrays.sort(array);
// Print out first five sorted entries
for(int i = 0; i < 5; i++){
System.out.println(array[i]);
}
After they're sorted and printed, the first entry is always 0. Perhaps this has to do with the array sorting, and I'm not realizing it. Any suggestions?
You're never setting the last element of the array -- use i < SIZE, not i < SIZE-1.
I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.