Let's say there's 4 slots at the bottom.
[ ]
[ ] [ ]
[ ] [ ] [ ]
[s] [s] [s] [s]
|
[ ]
[ ] [ ]
[ ] [ ] [ ]
[s] [s] [s] [s]
|
We start always in the only slot available in the top. Let's call it position 0.
If we move left once, that's position 0 of the second row.
If we move left again, that's position 0 of the third row.
Finally, we move left again, that's position 0 of the fourth row.
Let's start at the top again, position 0.
Move right once, position 1.
Move right again, position 2.
Move right again, position 3.
So what we have is that, if you are moving "left", you keep your index the same.
If you are moving "right", you increase your position by one.
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
|
std::vector<int> histogram(slots, 0);
for (int j = 0; j<ballnum; j++){
cout << "Ball number " << j + 1 <<" : " ;
int position = 0;
for (int i = 0; i<slots-1; i++){
int r = rand()%2;
cout<<direction[r];
if (r == 1) {
position += 1;
}
}
histogram[position] += 1;
cout<<endl;
}
for (int i = 0; i < slots; i++)
{
for (int j = 0; j < histogram[i]; j++)
{
std::cout << '*';
}
std::cout << '\n';
}
| |
Edit with full example:
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
|
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
int main(){
int ballnum;
int slots;
int count = 1;
string direction[2] = {"L", "R"};
srand(time(0));
cout << "Enter number of balls to drop: ";
cin >> ballnum;
cout << "Enter number of slots in the bean machine: ";
cin >> slots;
std::vector<int> histogram(slots, 0);
for (int j = 0; j<ballnum; j++){
cout << "Ball number " << j + 1 <<" : " ;
int position = 0;
for (int i = 0; i<slots-1; i++){
int r = rand()%2;
cout<<direction[r];
if (r == 1) {
position += 1;
}
}
histogram[position] += 1;
cout<<endl;
}
for (int i = 0; i < slots; i++)
{
for (int j = 0; j < histogram[i]; j++)
{
std::cout << '*';
}
std::cout << '\n';
}
}
| |
Whoops sorry for tabs vs spaces formatting...