|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +function runExperiment(sampleSize) { |
| 4 | + const valueCounts = [0, 0, 0, 0, 0, 0]; |
| 5 | + |
| 6 | + for (let i = 0; i < sampleSize; i++) { |
| 7 | + let num = Math.ceil(Math.random() * 6); |
| 8 | + valueCounts[num - 1]++; |
| 9 | + } |
| 10 | + console.log(valueCounts); |
| 11 | + // TODO |
| 12 | + // Write a for loop that iterates `sampleSize` times (sampleSize is a number). |
| 13 | + // In each loop iteration: |
| 14 | + // |
| 15 | + // 1. Generate a random integer between 1 and 6 (as if throwing a six-sided die). |
| 16 | + // 2. Add `1` to the element of the `valueCount` that corresponds to the random |
| 17 | + // value from the previous step. Use the first element of `valueCounts` |
| 18 | + // for keeping a count how many times the value 1 is thrown, the second |
| 19 | + // element for value 2, etc. |
| 20 | + |
| 21 | + const results = []; |
| 22 | + |
| 23 | + for (const value of valueCounts) { |
| 24 | + let numPercent = (value * 100) / sampleSize; |
| 25 | + results.push(numPercent.toFixed(2)); |
| 26 | + } |
| 27 | + // TODO |
| 28 | + // Write a for..of loop for the `valueCounts` array created in the previous |
| 29 | + // loop. In each loop iteration: |
| 30 | + // 1. For each possible value of the die (1-6), compute the percentage of how |
| 31 | + // many times that value was thrown. Remember that the first value of |
| 32 | + // `valueCounts` represent the die value of 1, etc. |
| 33 | + // 2. Convert the computed percentage to a number string with a precision of |
| 34 | + // two decimals, e.g. '14.60'. |
| 35 | + // 3. Then push that string onto the `results` array. |
| 36 | + console.log(results); |
| 37 | + return results; |
| 38 | +} |
| 39 | + |
| 40 | +runExperiment(100); |
| 41 | + |
| 42 | +function main() { |
| 43 | + const sampleSizes = [100, 1000, 1000000]; |
| 44 | + |
| 45 | + for (const i of sampleSizes) { |
| 46 | + let result = runExperiment(i); |
| 47 | + console.log(result); |
| 48 | + } |
| 49 | + // TODO |
| 50 | + // Write a for..of loop that calls the `runExperiment()` function for each |
| 51 | + // value of the `sampleSizes` array. |
| 52 | + // Log the results of each experiment as well as the experiment size to the |
| 53 | + // console. |
| 54 | + // The expected output could look like this: |
| 55 | + // |
| 56 | + // [ '26.00', '17.00', '10.00', '19.00', '16.00', '12.00' ] 100 |
| 57 | + // [ '14.60', '17.10', '19.30', '15.50', '16.70', '16.80' ] 1000 |
| 58 | + // [ '16.71', '16.68', '16.69', '16.66', '16.67', '16.59' ] 1000000 |
| 59 | +} |
| 60 | + |
| 61 | +main(); |
0 commit comments