Write a javascript to simulate the rolling of two dice. The script should use Ma
ID: 3694981 • Letter: W
Question
Write a javascript to simulate the rolling of two dice. The script should use Math.random to roll the first die and again to roll the second die. The sum of the two values should then be calculated. Since each die can show an integer value from 1 to 6, the sum of the values will vary from 2 to 12, with 7 being the most frequent sum, and 2 and 12 the least frequent sums. Your program should roll the dice 36,000 times. Use a one-dimensional array to tally the number of times each possible sum appears. Display the results in an HTML5 table. Also determine whether the totals are reasonable (e.g., there are six ways to roll a 7, so approximately 1/6 of all the rolls should be 7).
Explanation / Answer
The javascript code for rolling of two dice
<html>
<head>
<title>ThrowDice</title>
<script type ="text/javascript">
var dice1;
var dice2;
var ans;
var num;
var Number;
var i;
function roll_dice()
{
var random_dice1=Math.floor(Math.random()*6);
return random_dice1+1;
}
function rolling()
{
var combination=new Array();
ans="";
var display;
display="";
num=window.prompt("Enter how many times you want to throw the dice");
for(i=0;i<12;i++)
{
combination[i]=0;
}
for(i=0;i<parseInt(num);i++)
{
dice1=roll_dice();
dice2=roll_dice();
ans=parseInt(dice1)+ parseInt(dice2);
combination[ans-2]+=1;
Number=i+1;
display += "Roll #"+ Number + ": " + dice1 + " " + dice2 + "<br>";
}
div1.innerHTML=display;
var ans1="";
for(i=0;i<11;i++)
{
Number=i+2;
ans1+="The Sum of "+ Number +" occurred :" + combination[i] +" Times<br>"
}
div2.innerHTML=ans1;
}
</script>
</head>
<body>
<h1> ThrowDice1</h1>
<hr />
<p>Press F5 or Refresh to load script again. This is a program for Rolling a Dice number of times as prompt by user</p>
<form name = "multiply" action = "">
<table>
<caption>Throw Dice Program1</caption>
<div id="div1">
</div>
<div id="div2"></div>
</table>
</form>
</body>
</html>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.