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...)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>

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.