### Vectors and arrays

There are 20 boxes and each box has a size of 0.2 cm. It is something like this:

 -2.0,-1.8,.....-0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6,.....,1.8, 2.0

I generate (float) random numbers between -2.0 and 2.0, and would like to put each number into the corresponding box. If a box is occupied by a number then it's filled, otherwise it's empty.

At the end, I would like to know how many of the boxes are empty.

For example, if the number is -0.61, then it should go into the 7th box. if the number is 1.85, then it goes into the 19th box.

What is the way to do this in C++ ?

thanks
new thread same topic ;)
Just had too much spare time. Try this... (I didn't check so there might be errors...)

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374`` ``````#include #include #include #include class boxes{ private: bool *boxValue; int numberOfBoxes; float spacing; //requires all boxes to be evenly sized and distributed! no space in between them! float offset; public: boxes( int _numberOfBoxes, float _offset, float _spacing ); ~boxes(); int getFull(); bool isFull( int _number ); void place( float _value ); void clear(); }; boxes::boxes( int _numberOfBoxes, float _offset, float _spacing ){ spacing = _spacing; offset = _offset; numberOfBoxes = _numberOfBoxes; boxValue = new bool[numberOfBoxes]; clear(); }; boxes::~boxes( ){ delete[] boxValue; }; void boxes::clear(){ for( int i = 0; i < numberOfBoxes; i++ ) boxValue[i] = false; }; void boxes::place( float _value ){ int address = (int) floor(( _value - offset ) / spacing ); assert( address >= 0 and address < numberOfBoxes ); boxValue[address] = true; }; int boxes::getFull(){ int number = 0; for( int i = 0; i < numberOfBoxes; i++ ) if( boxValue[i] == true ) number++; return number; }; bool boxes::isFull( int _number ){ assert( _number >= 0 and _number < numberOfBoxes ); return boxValue[_number]; }; int main( void ){ float maxValue = 2.0; float minValue = -2.0; boxes myBoxes( 20, -2.0, 0.2 ); srand( 1 ); //better use time but I dont know what you want to do... //place 10 numbers: for( int i = 0; i < 10; i++ ) myBoxes.place( ((double) rand() / (double) RAND_MAX) * (maxValue - minValue) + minValue ); printf( "Full boxes: %i\n\n", myBoxes.getFull() ); for( int i = 0; i < 10; i++ ){ printf( "Box %i: ", i ); if( myBoxes.isFull( i )) printf( "full\n" ); else printf( "empty\n" ); }; return 1; };``````
Topic archived. No new replies allowed.