Java coding problem

Post » Sat May 28, 2011 11:39 pm

Hello, I'm having some problems returning the 3 largest values from an array.

Basically, I've got a value1, value2 and value3, which need to be the 3 largest values from an array. A friend and I have literally tried for hours to make a working method to create this, resulting in things like this (we're getting the values from a HashMap and put it in an array):
setStrings = randomHashMap.keySet();
String[] tempArray = (String[])setStrings.toArray(new String[20]);
String tempString = tempArray[index];
Integer test = (Integer)randomHashMap.get(tempString);
int a = test.intValue();

for(int index=0; index Set setStrings1 = randomHashMap.keySet();
String[] tempArray1 = (String[])setStrings1.toArray(new String[20]);
String tempString1 = tempArray1[index1];
Integer test1 = (Integer)randomHashMap.get(tempString1);
int b = test1.intValue();
if(a >= B){
if(a>value1){
if(value1>value2){
value2=value1;
}
else{
value3=value1;
}
value1 = a;
if(b>value2) {
if(value2>value3){
value2 = b;
}
else{
value3=value2;
value2 = b;
}
}
else{
if(value1>value2){
value2=value1;
}
else{
value3=value1;

}
value1=b;
}


Now I know the above method doesn't work. I've tried dozens of variants on this type of solution (also making a second loop, but I thought it should be possible to get the highest values from a list using only 1 value from the list).
Can anybody help? Me and my buddy are getting very tired and our solutions aren't becoming better.
Any help would be very appreciated!
User avatar
Oyuki Manson Lavey
 
Posts: 3438
Joined: Mon Aug 28, 2006 2:47 am

Post » Sun May 29, 2011 1:30 am

Are you just trying to sort the 3 elements into highest to low?

You're making things more complex than they need to be if so. Just use a bubble sort, which I will give an example of below.
//assuming the presence of an int array with some values filled inint n = array.length;int pass = 0;for(pass = 1; pass < n ; pass++){     for(int i = 0; i < n-pass ; i++){           if(array[i] < array[i+1]);    //finish code to switch yourself      }}

User avatar
Lynne Hinton
 
Posts: 3388
Joined: Wed Nov 15, 2006 4:24 am

Post » Sat May 28, 2011 5:49 pm

Assumption: You have a container of n items and want to take the largest 3. (That is what I understood from the question).

Note: If you find yourself using numbered variables, you need to use some sort of container (an array probably).

The simplest way is to put the integers into a ordered container (hint: an array). Sort using Arrays.sort and take the last three values (which will be the largest). This is theoretically slower than the most effective algorithm but is neatest code wise.

Another way, possibly faster for large arrays but much more confusing (I don't have a clue if I got this correct):
//So lets say we have a array that holds the highest items (rather than using value1, value2 et al)int highest[] = new int[3];//So now we look through the container (HashMap/whatever)for ( int value : container ){    //So now we look down the list of highest values    //trying to find where value slots into it. the highest    //array is ordered highest first (at index 0)    for ( int i = 0; i < highest.length; i++ ){        //if the value is greater than the ith value of highest, we        //shift the other ith value and above up one to slot the        //new value in.        if ( value > highest[i] ){            for ( int j = i; j < highest.length - 1; i++ ){                hightest[j + 1] = highest[j];            }            hightest[i] = value;            break;        }    }}


Let me point out. If it isn't time critical, just sort it and take the top 3 items. Much simpler code wise.
User avatar
Ice Fire
 
Posts: 3394
Joined: Fri Nov 16, 2007 3:27 am

Post » Sat May 28, 2011 10:58 pm

import java.util.Arrays;

Arrays.sort(nameofarray);

Edit: stupid semicolons
User avatar
Sophie Payne
 
Posts: 3377
Joined: Thu Dec 07, 2006 6:49 am

Post » Sat May 28, 2011 9:44 pm

import java.util.Arrays;

Arrays.sort(nameofarray);

Edit: stupid semicolons

Bah, that's the easy way out :P

Always handy to learn how to write your own sorting algorithm.

Yacoby: that code looks like it could be more efficient in theory but it also looks monstrous (no offence :P ).
User avatar
T. tacks Rims
 
Posts: 3447
Joined: Wed Oct 10, 2007 10:35 am

Post » Sat May 28, 2011 7:48 pm

Always handy to learn how to write your own sorting algorithm.

Agreed on principle, but in reality I'll never do work done for me :P
User avatar
Eduardo Rosas
 
Posts: 3381
Joined: Thu Oct 18, 2007 3:15 pm

Post » Sat May 28, 2011 2:35 pm

Agreed on principle, but in reality I'll never do work done for me :P

But since you're working in java, it's fair to assume that any work done for you by the language itself is probably awful. Kind of like the entire language.
User avatar
gary lee
 
Posts: 3436
Joined: Tue Jul 03, 2007 7:49 pm

Post » Sat May 28, 2011 11:48 am

But since you're working in java, it's fair to assume that any work done for you by the language itself is probably awful. Kind of like the entire language.

Ouch :P

Though, in all honesty, if not for having done stuff with arrays recently in java (during which time I learned about Arrays.sort), I'd have probably done a bubble sort too. May not be fast, but it's simple.
User avatar
Tom
 
Posts: 3463
Joined: Sun Aug 05, 2007 7:39 pm

Post » Sun May 29, 2011 1:32 am

Yacoby: that code looks like it could be more efficient in theory but it also looks monstrous (no offence :P ).

Non taken. I hope I pointed that it is terrible in my post. It is also 2AM which is not helping my coding ability. If I used a list the code would be much more understandable as I could insert into it. But then I would have to remember an API.

Always handy to learn how to write your own sorting algorithm.
Of which bubble sort is a terrible terrible example. Insertion Sort is a more natural way of looking at a sort but you are going to write a decent algorithm for a very large list where you don't know its state implement timsort (a mergesort derivative). Basically what JDK7 uses.
User avatar
Kill Bill
 
Posts: 3355
Joined: Wed Aug 30, 2006 2:22 am

Post » Sun May 29, 2011 3:20 am

Non taken. I hope I pointed that out in my post.

Of which bubble sort is a terrible terrible example. Insertion Sort is a more natural way of looking at a sort if you are going to write a decent algorithm for a very large list where you don't know its state implement timsort (a mergesort derivative).

That's true, I just suggested bubble sort as it's generally the first sort taught to beginners (at least that's what I was taught first) and the OP seems to be just starting out. I would of course use something a lot better in my own code, but I find that the concept of bubble sort pretty easy to understand.

edit: Personally I favour Quicksort if I can use it, but I've been working on expanding my knowledge of sorting algorithms, one of the little side hobbies of mine when it comes to code. That and fractals, I love me some fractals.
User avatar
Iain Lamb
 
Posts: 3453
Joined: Sat May 19, 2007 4:47 am

Post » Sat May 28, 2011 1:06 pm

Of which bubble sort is a terrible terrible example. Insertion Sort is a more natural way of looking at a sort but you are going to write a decent algorithm for a very large list where you don't know its state implement timsort (a mergesort derivative). Basically what JDK7 uses.

Timsort is a pain in the ass to implement, though. If you really need to quickly implement an efficient sorting algorithm, combsort11 is the best choice. It's a relatively simple improvement of bubblesort, but very fast in practice even on large containers and with the average complexity of O(n*log(n)).
User avatar
Laura Shipley
 
Posts: 3564
Joined: Thu Oct 26, 2006 4:47 am

Post » Sat May 28, 2011 10:20 pm

edit: Personally I favour Quicksort if I can use it, but I've been working on expanding my knowledge of sorting algorithms, one of the little side hobbies of mine when it comes to code.

Quicksort has the issue of pivot choice, which if the wrong one is selected every time is running time is O(n2). Merge sort doesn't have this issue which is why it is used in many standard libraries.

Timsort is a pain in the ass to implement, though. If you really need to quickly implement an efficient sorting algorithm, combsort11 is the best choice. It's a relatively simple improvement of bubblesort, but very fast in practice even on large containers and with the average complexity of O(n*log(n)).

My comment was that if you were going to write something decent, that is what you would probably implement.

However IMHO you shouldn't really be implementing common algorithms unless you have a problem with the standard implementation. :shrug:
User avatar
Lilit Ager
 
Posts: 3444
Joined: Thu Nov 23, 2006 9:06 pm

Post » Sat May 28, 2011 2:41 pm

Thanks for all the suggestions! And sorry for the unclear language..

I eventually managed to ( a couple of hours back) to write a correct sorting algorithm (10 if's!) but if array has its own sorting algorithm I will gladly use that one. Thanks a lot!
User avatar
Jennifer Rose
 
Posts: 3432
Joined: Wed Jan 17, 2007 2:54 pm

Post » Sat May 28, 2011 1:36 pm

Sorry for the bump, but I got another question.


I need to get a key from a HashMap. The key has a unique value and vice versa, leading me to believe there must be a better way to store this key so I can easily retrieve it. However I'm only allowed to use standard classes contained in Java (everything on this list : http://download.oracle.com/javase/6/docs/api/index.html)

Does anybody have a good suggestion for another tool to use, or to get a key out of the HashMap that belongs to a specific value?
Note, that I can't switch the value and key positions due to the method.
User avatar
Sophh
 
Posts: 3381
Joined: Tue Aug 08, 2006 11:58 pm

Post » Sat May 28, 2011 6:08 pm

Sorry for the bump, but I got another question.


I need to get a key from a HashMap. The key has a unique value and vice versa, leading me to believe there must be a better way to store this key so I can easily retrieve it. However I'm only allowed to use standard classes contained in Java (everything on this list : http://download.oracle.com/javase/6/docs/api/index.html)

Does anybody have a good suggestion for another tool to use, or to get a key out of the HashMap that belongs to a specific value?
Note, that I can't switch the value and key positions due to the method.

You probably want to use a Bimap, not a HashMap, however as a quick and easy solution you can just iterate through a HashMap. It is however O(n) (Read: Horribly slow for large maps)
for (Map.Entry entry : map.entrySet()) {    if ( entry.getValue() == "MyVal" ){        return entry.getKey();    }}


The other way would be to maintain two HashMaps, one mapping Key->Val and the other Val->Key
User avatar
Riky Carrasco
 
Posts: 3429
Joined: Tue Nov 06, 2007 12:17 am


Return to Othor Games