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