In: Computer Science
JavaScript Programming Assignment
PLEASE NOTE: You must create and call a main function, and if instructed include additional functions called by the main. Make sure to use ES6 style of keywords => instead of the older function and for local scope variables use the keyword let and not a keyword var. Make sure to follow the requirements and recheck before submitting.
PROJECT GOAL:
Create a program that simulates tossing a coin. This program should be titled flippingacoin.js and will require you to include two functions, one of them is called main and the other flip. The use of a loop is required for this program. Make sure the program includes a user prompt asking how many times to toss the coin. Program a function called flip which does not include parameters and randomly (using math library random) returns either a String called heads or one called tails. Call onto this function in main as many times as requested by using a loop. Make sure to report the results.
Example output:
How many times should I toss the coin? 4000
Results of 4000 tosses.
Heads: # 2635, Tails: 1365
NOTE: End users should be able to enter a higher number of tosses such as 300500020 and receive accurate results.
Thank you for your help with this project.
// Javascript program that simulates tossing a coin.
let readline = require('readline-sync'); // module for taking input
// flip function that returns "heads" is random() returns a
value <0.5 else "tails"
// simulates the flipping of a fair coin where probability of heads
and tails are equal
var flip = () =>{
if(Math.random() < 0.5)
return "heads";
else
return "tails";
}
// main function that includes a user prompt asking how many
times to toss the coin.
// and records the number of heads and tails for that number of
coin toss
var main = () =>{
//input of number of coin toss
let num_toss = parseInt(readline.question("How many
times should I toss the coin?"));
let i;
let num_heads = 0, num_tails = 0; // counter to store
the number of heads and tails
// loop to simulate the coin flip
for(i=0;i<num_toss;i++)
{
let result = flip(); // get the
result of one flip
// if we get heads increment the
number of heads
if(result === "heads")
num_heads++;
else // increment the number of
tails
num_tails++;
}
// output the result
console.log("Results of "+num_toss+" tosses.");
console.log("Heads: # "+num_heads+", Tails:
"+num_tails);
}
// call the main function
main()
//end of program
Output: