ForumsProgramming Forum**Java** Finding Mode in a random set of integers in an Array

23 14988
Graham
offline
Graham
8,051 posts
Nomad

AAAGH! i always get an out of bounds exception error and when i put on a stopping mechanism i get mode = 0. Help?

size = size of list

public void computeMode()
{
while(found = false)
{
for(modeLookUp = 1; modeLookUp < size; modeLookUp++)
for(modeLookUp2 = 0; modeLookUp2 < size; modeLookUp2++)
{
if(list[modeLookUp] == list[modeLookUp2]);
{
mode = list[modeLookUp];
found = true;
}
if(list[modeLookUp] != list[modeLookUp2])
found = false;
}

  • 23 Replies
Graham
offline
Graham
8,051 posts
Nomad

not work. :l

http://i271.photobucket.com/albums/jj146/grahaam/failure.jpg

Hectichermit
offline
Hectichermit
1,828 posts
Bard

I should download Java...so I can work on this...I think most of the syntax is not different from C++ B)

Graham
offline
Graham
8,051 posts
Nomad

noone in my class has it working :P

Here's the files Hectic

you can just google JCreator LE and it's free

Hectichermit
offline
Hectichermit
1,828 posts
Bard

Yea I was wondering what the Expo class was....

Hectichermit
offline
Hectichermit
1,828 posts
Bard

hahaha that was funny I knew the problem was with your nested loops, I was thinking Why do i need an nested look with an array because they are basically a linear set, normally you can use nested loops to work with Matrices but I figure that removing one of the loops would work so heres the right way...

public void computeMode()
{
for (modeLookUp1 = 0; modeLookUp1 < size; modeLookUp1++)
{
incidences = 0;
for (modeLookUp2 = 0; modeLookUp2 < size; modeLookUp2++)
{
if (list[modeLookUp2] == list[modeLookUp1])
incidences++;
}
if (incidences > maxIncidences)
{
maxIncidences = incidences;
mode = list[modeLookUp1];
}
}
}

No need for a nested Loop

Parsat
offline
Parsat
2,180 posts
Blacksmith

I didn't remove the found loop because it was already in the class that he created (didn't want to mess with that). I assumed you were using it for another method, but the while loop is entirely unneeded. Unless you were to physically write the for-loops as while-loops, you don't need the found boolean. From what I can see the innards have remained unchanged?

Graham
offline
Graham
8,051 posts
Nomad

yay, works without the while and boolean

Hectichermit
offline
Hectichermit
1,828 posts
Bard

Ya parsat didnt change the code besides removine the extra loop...

Showing 16-23 of 23