0

I am trying to simulate 2000 dice rolls of an 11 sided die (number 2 through 12 on the sides). I have to store the data in an array.

here's my loop where the die is rolled:

for($counter = 0; $counter <=2000; $counter++)
{
$die = rand(2, 12);
$int[$counter] = $die;
echo " $die ,";
}

^ that seems to work okay as I have 2000 random numbers output.

The next part is where I have trouble. I have to output some of the results. Just to make it simple, let's say I have to output the number of fives that were rolled with an echo statement like:

"__ fives were rolled."

I can't seem to get it to work. For this assignment I HAVE to use a for loop. I tried making a new one with an if statement, and including an if statement in the loop up above. No luck with either. How can I make this work?

1

2 Answers 2

1

There is a native function array_count_values() that returns an array using the values of the input array as keys and their frequency in input as values.

You could use that on $int, and then use a for loop to go through each of your die options.

If that is not an option, you can copy that functions process by using a for loop to create a new array using the values of your $int array as keys, and then increase the value of each key by 1.

Since this is an assignment I don't want to post the actual code I would use. But if you post what you have tried so far I would be willing to look it over and provide corrections/edits to get your code to work.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help, I've made some progress - it seems to be working.
0

I think this one will solve your problem..

 $array = array();
 for($counter = 0; $counter <=2000; $counter++)
 {
     $die = rand(2, 12);
     $array[]= $die;
 }

for($c=2;$c<=12;$c++){
    foreach($array as $r){
        if($c==$r)
        {
            $arr[$c]+=1;
        }
    }
}

foreach($arr as $key=>$value)
{

    echo $value." [".$key."] were rolled<br>";
}

1 Comment

Your welcome... Please upvote or choose it as best answer if that help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.