I'm likely to stick with my original code |
If you intend doing that, you should still simplify it.
Take this block of code for 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
|
i=rand()%10;
if (i>=0 && i<1)
{bin[0]++;}
else if (i>=1 && i<2)
{bin[1]++;}
else if (i>=2 && i<3)
{bin[2]++;}
else if (i>=3 && i<4)
{bin[3]++;}
else if (i>=4 && i<5)
{bin[4]++;}
else if (i>=5 && i<6)
{bin[5]++;}
else if (i>=6 && i<7)
{bin[6]++;}
else if (i>=7 && i<8)
{bin[7]++;}
else if (i>=8 && i<9)
{bin[8]++;}
else if (i>=9 && i<=10)
{bin[9]++;}
|
Just taking one of those if statements as an example,
9 10
|
else if (i>=2 && i<3)
{bin[2]++;}
|
Let's see how many possible values of
i
match that condition. Which integers are greater than or equal to 2 and also less than 3? I can think of just one, the integer 2.
So the code would change to
9 10
|
else if (i ==2)
{bin[2]++;}
|
So, if we rewrite that block of code using just the == condition each time, and tidy it up a bit, we get this:
1 2 3 4 5 6 7 8 9 10 11 12
|
i = rand()%10;
if (i==0) bin[0]++;
else if (i==1) bin[1]++;
else if (i==2) bin[2]++;
else if (i==3) bin[3]++;
else if (i==4) bin[4]++;
else if (i==5) bin[5]++;
else if (i==6) bin[6]++;
else if (i==7) bin[7]++;
else if (i==8) bin[8]++;
else if (i==9) bin[9]++;
|
That's exactly the same as your original code, but just reformatted a little bit.
Now there's a very clear pattern emerging. Whenever
i
has a particular value, say
7
, then the array element to be incremented has the same number, say
bin[7]++
So if the element being incremented is always the same as the value of i. then why not just use i directly?
Hence that same block of code becomes just
1 2 3
|
i = rand()%10;
bin[i]++;
|
Well, we don't even need
i
, it merely saves the random number which will be used in just one place, on the very next line, so get rid of
i
as well and simply write