//COMS 161.02 //A REVIEW -- MORE ARRAY PROBLEMS //#1) Report which names in an array have length 5. names = new Array("Morgan", "Westerhoff", "Lilley", "Duling", "Welch", "Adair", "Perkins", "Reed", "James"); i=0; while (i < names.length) { if (names[i].length == 5) alert(names[i] + " has length 5"); i++; } //#2) Instead report HOW MANY have length 5. i=0; fives=0; while (i < names.length) { if (names[i].length == 5) fives++; i++; } alert(fives + " names had length 5"); //#3) Instead report the average length of all the names. i=0; sum=0; while (i < names.length) { sum += names[i].length; i++; } average = sum / names.length; alert("Average length is " + average); //#4) IS IT FAIR ... ?? //How do I tell if the die is a "fair die"? //Here's an idea -- simulate lots of rolls of the die. //Count how many 1's, 2's, ... , 6's occur. //If the die is fair, they should occur with about the //same frequency ones = 0; twos = 0; threes = 0; fours = 0; fives = 0; sixes = 0; count = 0; while (count < 10000) { die = 1 + Math.floor( 6 * Math.random() ); if (die == 1) ones++; else if (die == 2) twos++; else if (die == 3) threes++; else if (die == 4) fours++; else if (die == 5) fives++; else sixes++; //THERE OUGHT TO BE A BETTER WAY TO DO THIS... count++; //advance towards 10000 } //NOW REPORT THE RESULTS alert(ones + " ones " + twos + " twos " + threes + " threes " + fours + " fours " + fives + " fives " + sixes + " sixes "); //#5) A better way to solve the problem of (#4): freq = new Array(0, 0, 0, 0, 0, 0); //6 counts, all initially 0. count = 0; while (count < 10000) { die = 1 + Math.floor( 6 * Math.random() ); freq[die-1]++; //increment appropriate frequency!! count++; //advance towards 10000 } alert(freq); //#6) IF YOU ROLL A PAIR OF DICE REPEATEDLY, //HOW DO YOU COUNT THE NUMBER OF 2's, 3's, ... , 12's?? freq = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); //11 counts, all initially 0. count = 0; while (count < 10000) { die1 = 1 + Math.floor( 6 * Math.random() ); die2 = 1 + Math.floor( 6 * Math.random() ); roll = die1 + die2; freq[roll-2]++; //increment appropriate frequency!! count++; //advance towards 10000 } alert(freq);