1- "use strict" ;
1+ 'use strict' ;
2+ // new function is created for code reusable.
3+ // This function will give you random number from 1 to 6
4+ function rollDice ( min , max ) {
5+ return Math . floor ( Math . random ( ) * ( max - min + 1 ) ) + 1 ;
6+ }
7+
8+ function percent ( diceRolled , totalDiceRoll ) {
9+ return ( diceRolled / totalDiceRoll ) * 100 ;
10+ }
211
312function runExperiment ( sampleSize ) {
413 const valueCounts = [ 0 , 0 , 0 , 0 , 0 , 0 ] ;
5-
14+ for ( let index = sampleSize ; index > 0 ; -- index ) {
15+ let result = rollDice ( 1 , 6 ) ;
16+ valueCounts [ result - 1 ] += 1 ;
17+ }
618 // TODO
719 // Write a for loop that iterates `sampleSize` times (sampleSize is a number).
820 // In each loop iteration:
@@ -14,7 +26,14 @@ function runExperiment(sampleSize) {
1426 // element for value 2, etc.
1527
1628 const results = [ ] ;
17-
29+ valueCounts . forEach ( ( rolledDiceCount ) => {
30+ // console.log(percent(rolledDiceCount, sampleSize));
31+ results . push (
32+ ` '${ parseFloat ( percent ( rolledDiceCount , sampleSize ) )
33+ . toFixed ( 2 )
34+ . toString ( ) } '`
35+ ) ;
36+ } ) ;
1837 // TODO
1938 // Write a for..of loop for the `valueCounts` array created in the previous
2039 // loop. In each loop iteration:
@@ -31,13 +50,24 @@ function runExperiment(sampleSize) {
3150function main ( ) {
3251 const sampleSizes = [ 100 , 1000 , 1000000 ] ;
3352
53+ for ( let index = 0 ; index < sampleSizes . length ; index ++ ) {
54+ console . log (
55+ `[ ${ runExperiment ( sampleSizes [ index ] ) } ] ${ sampleSizes [ index ] } `
56+ ) ;
57+
58+ // This just extra to print the result on the webpage
59+ document . getElementById (
60+ ( index + 1 ) . toString ( )
61+ ) . innerHTML = `[ ${ runExperiment ( sampleSizes [ index ] ) } ] ${
62+ sampleSizes [ index ]
63+ } `;
64+ }
3465 // TODO
35- // Write a for..of loop that calls the `runExperiment()` function for each
36- // value of the `sampleSizes` array.
37- // Log the results of each experiment as well as the experiment size to the
38- // console.
66+ // Write a for..of loop
67+ // that calls the `runExperiment()` function for each value of the `sampleSizes` array.
68+ // Log the results of each experiment as well as the experiment size to the console.
3969 // The expected output could look like this:
40- //
70+
4171 // [ '26.00', '17.00', '10.00', '19.00', '16.00', '12.00' ] 100
4272 // [ '14.60', '17.10', '19.30', '15.50', '16.70', '16.80' ] 1000
4373 // [ '16.71', '16.68', '16.69', '16.66', '16.67', '16.59' ] 1000000
0 commit comments