views:

109

answers:

2

Woohoo, I've come to arrays now, thank god.

Now, I've got 2 arrays!

int colorvalues[][]  = {{34,255,255,56},{127,204,11,34},{123,98,127,34},{34,34,127,17}};

Imagine it as a 4x4 pixel picture

Now, I want to create a histogram, the distribution of colorvalues from 0 to 255. For example here I've 2*255, 2*127, 5*34 and so on.

So I've created an int histogram[] = new int [255];

To test if my colorvalues are correct I wrote:

 for(int i=0; i < colorvalues.length; i++){
  for (int j = 0; j < colorvalues.length; j++){
   System.out.println("Colorvalue in Array " + i + "." + j + " is" + colorvalues[i][j]);
  }
 }

So far, so good. Now, how do I write a procedure that goes in histogram[255] from 0 to 255, and compares it to the value of colorvalues[][], and if, for example, histogram[34] compares to colorvalues[][] it adds 5 to histogram[34]. Because there's 5 times 34 in colorvalues[][].

Maybe my thinking is wrong and I was supposed to have histogram[255][], 255 for colorvalues from 0 to 255 and the other for the counter. Even then, how do I realize it?

+3  A: 
Joey
And you may want to range check the colorvalues[i][j] since it can be considerably larger than histogram's size if colorvalues gets filled with bogus values. That is, if you want to handle that care gracefully.
PSpeed
@PSpeed: Pardon, what?
NoCanDo
NoCanDo: Elaborated on that point a bit.
Joey
Okay, this works, but I'm still not clear why I had to increase it to "int histogram[] = new int [256];" 256 not 255. I thought Arrays started at 0?
NoCanDo
NoCanDo: Sorry, overlooked that one. See edit.
Joey
Cheers, I'm stupid. I was thinking in terms of 0-255 when creating, which 0-255 = 256 ;). Thanks!
NoCanDo
A: 

I'd be tempted to add the histogram values into a TreeMap where the map key is the colour value and the map value is the count.

The map will increase in size automatically, no problems with index out of bounds etc. it will be sorted automatically into size order.

Fortyrunner
Thanks, but one step at a time ;). Still learning Java.
NoCanDo
No problem.Another tip would be to write a unit test for your class. This will save you a lot of pain and its a fairly simple technique.
Fortyrunner