In: Computer Science
Code programs using ReadlineSync for prompts.
Note: For all programs, create and call a main function, and if required additional functions called by the main. Also please use the ES6 style of keywords => instead of the older function and for local scope variables use the keyword let, not var
Name: coinflip.js
For this program you will have two functions, one called main and the second called flip. This program is also required the use of a loop construct.
Write a program that simulates tossing a coin. Prompt the user for how many times to toss the coin. Code a function called flip with no parameters that randomly ( use the math library random ) returns either the String "heads"or the string "tails". Call this function in main as many times as requested using a loop and report the results. See Example outputs below.
Example Outputs
How many times should I toss the coin? 1000
Results of 1000 tosses.
Heads: 483, tails: 517
How many times should I toss the coin? 1000000
Results of 1000000 tosses.
Heads: 500074, tails: 499926
Recheck the requirements before you submit.
//import the readline library for standard input from console
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
//flip function that returns 'heads' or 'tails'
let flip = () => {
//if the result is 0 return heads
if (Math.floor(Math.random() * 2) == 0) {
return "heads";
}
//else return tails
else {
return "tails";
}
};
//main function
let main = () => {
let mapper = { heads: 0, tails: 0 };
// prompt the user for number of flips
readline.question("How many times should I toss the coin?", n => {
//Iterate for the number opf times
for (let i = 0; i < n; i++) {
//call flip() to get the result
result = flip();
// increase the count of the mapper
mapper[result]++;
}
// log the output
console.log(`Result of ${n} tosses.`);
console.log(`Heads: ${mapper["heads"]}, Tails: ${mapper["tails"]}`);
//close the stream
readline.close();
});
};
//call the main function
main();