logic question, -array, struct-


There are 99 boxes and each box is separated by 2 cm. so the order is something like this:

-99, -97, -95, ...... -1, 1, 3, 5, .... 95, 97, 99


I generate (float) random numbers between -99 and 99, and would like to put each number into the corresponding box. For example, if the number is -96., then it should go into the second box. if the number is 4.9, then it goes into the 52. box.

What is the best way to do this ? Can I do it with a simple array, struct,.... ?



It'll depend on what you want to do with the program and whether it should be portable or just to try something or what?!

In your special case above and if I understood it correctly you want to count the matches in each "box" or what. After your example your boxes two and 52 would show 1 and the rest zero?! Is this correct? Or do you want to store actual numbers?
Right, I forgot the write this detail.


After your example your boxes two and 52 would show 1 and the rest zero?! Is this correct?


That's right.

Or do you want to store actual numbers?


No. I only want to know if a box is filled or not.

no matter how many numbers go into a box. if a box is occupied by a number, then it's filled otherwise it's empty.

so, after filling the boxes, I will ask that how many boxes are filled ( TRUE ) and how many of them are empty ( FALSE ) ? that's it.
Last edited on
Ok next question: do all those boxes have always the same spacing and same size or does it vary?

If you can answer yes I would do some mystic math:
number -= offset (offset = lower border = -99 -> therefore making smallest number possible 0)
number /= spacing (=2 -> calculating for boxes of size 1)
now all you need is floor which is a function of math.h (cutting off all decimal digits)

what it does so far:
1
2
3
4
5
6
7
bool boxes[100] = false;

float number = -98.1; 
number -= -99; //-> number = 0.9 now 
number /= 2; //-> number = 0.45 now
floor( number ); //-> number = 0; (should go to box zero! , which would be your box one but if you use arrays zero is the first index)
boxes[(int)number] = true; //set our box *number* to true 


an even cooler way doing would be using "vector" class with boolean types -> it uses less memory and has some cool functions...it comes with vector.h

ZED

Last edited on
Oh if your answer would be "no" then you need to store lower and upper bounds of each box as well and cycle through all of them each step till you find the matching one e.g.

if( box[i].lowerbound <= number and box[i].upperbound > number ) box[i].value = true;
Topic archived. No new replies allowed.