Professional Documents
Culture Documents
Exam
Exam
JavaScript:
Arrays
With sobs and tears he sorted
out
Those of the largest size . . .
Lewis Carroll
OBJECTIVES
Robert Herrick
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Chapter 10
JavaScript: Arrays
Self-Review Exercises
10.1
10.2
State whether each of the following is true or false. If false, explain why.
a) An array can store many different types of values.
ANS: True.
b) An array subscript should normally be a floating-point value.
ANS: False. An array subscript must be an integer or an integer expression.
c) An individual array element that is passed to a function and modified in it will contain
the modified value when the called function completes execution.
ANS: False. Individual primitive-data-type elements are passed by value. If a reference to
an array is passed, then modifications to the elements of the array are reflected in the
original element of the array. Also, an individual element of an object type passed to
a function is passed by reference, and changes to the object will be reflected in the
original array element.
10.3 Write JavaScript statements (regarding array fractions) to accomplish each of the following tasks:
a) Declare an array with 10 elements, and initialize the elements of the array to 0.
ANS: var fractions = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
ANS: fractions[ 3 ]
f) Sum all the elements of the array, using a forin statement. Define variable x as a control variable for the loop.
ANS: var total = 0;
10.4
tasks:
table)
a) Declare and create the array with three rows and three columns.
ANS: var table = new Array( new Array( 3 ), new Array( 3 ),
new Array( 3 ) );
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Self-Review Exercises
c) Use a forin statement to initialize each element of the array to the sum of its subscripts. Assume that the variables x and y are declared as control variables.
10.5
Find the error(s) in each of the following program segments, and correct them.
a) var b = new Array( 10 );
for ( var i = 0; i <= b.length; ++i )
b[ i ] = 1;
ANS: Error: Referencing an array element outside the bounds of the array (b[10]). [Note:
b)
var a = [ [ 1, 2 ], [ 3, 4 ] ];
a[ 1, 1 ] = 5;
ANS: Error: The array subscripting is done incorrectly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
1 ][ 1 ] = 5;.
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Chapter 10
JavaScript: Arrays
Exercises
10.6
10.7
State whether each of the following is true or false. If false, explain why.
a) To refer to a particular location or element in an array, we specify the name of the array
and the value of the element.
ANS: False, we specify the name of the array and the indexed location to refer to a specific
element.
b) A variable declaration reserves space for an array.
ANS: False. Space is not allocated until operator new is used to instantiate the array.
c) To indicate that 100 locations should be reserved for integer array p, the programmer
should write the declaration
p[ 100 ];
d) A JavaScript program that initializes the elements of a 15-element array to zero must
contain at least one for statement.
ANS: False. Arrays can be initialized upon declaration.
e) A JavaScript program that totals the elements of a two-dimensional array must contain
nested for statements.
ANS: False. It must contain any nested repetition statement (such as while), not necessarily
a for statement, though using for is usually the most efficient way to total the elements.
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
10.8
ANS: document.write( f[ 6 ] );
total += parseInt( c[ i ] );
d) Copy 11-element array a into the first portion of array b, which contains 34 elements.
ANS: for ( var i = 0; i < a.length; i++ )
b[ i ] = a[ i ];
e) Determine and print the smallest and largest values contained in 99-element floatingpoint array w.
ANS: var highestNumber = w[ 0 ];
var lowestNumber = w[ 0 ];
for ( var i = 1; i < 99; i++ )
{
if ( w[ i ] > highestNumber )
highestNumber = w[ i ];
if ( w[ i ] < lowestNumber )
lowestNumber = w[ i ];
}
document.writeln( highestNumber + " " + lowestNumber );
10.9
b)
t[ 0 ] = newArray( 3 );
t[ 1 ] = new Array( 3 );
How many rows does t have?
ANS: 2.
g) Write a single statement that sets the elements of t in row 1 and column 2 to zero.
ANS: t[ 1 ][ 2 ] = 0;
h) Write a series of statements that initializes each element of t to zero. Do not use a repetition structure.
ANS: t[ 0 ][ 0 ] = 0;
t[
t[
t[
t[
t[
0
0
1
1
1
][
][
][
][
][
1
2
0
1
2
]
]
]
]
]
i) Write a nested
= 0;
= 0;
= 0;
= 0;
= 0;
for statement
or
t[ j ][ k ] = 0;
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Chapter 10
JavaScript: Arrays
ANS:
for ( var j in t )
for ( var k in t[ j ] )
t[ j ][ k ] = 0;
j) Write a series of statements that determines and prints the smallest value in array t.
ANS: // assume small is declared and initialized
for ( var x = 0; x < t.length; x++ )
for ( var y = 0; y < t[ x ].length; y++ )
if (t[ x ][ y ] < small )
small = t[ x ][ y ];
document.writeln( "Smallest is " + small);
m) Write a series of statements that prints the array t in neat, tabular format. List the column subscripts as headings across the top, and list the row subscripts at the left of each
row.
document.writeln(
"<colgroup><col span = 4 align = center width = 100>" +
"</colgroup>" );
document.writeln(
"<tr><td> </td><th>0</th><th>1</th><th>2</th></tr>" );
for ( var i in t )
{
document.writeln( "<tr><th>" + i + "</th>" );
for ( var j in t[ i ] )
document.write( "<td>" + t[ i ][ j ] + "</td>" );
document.writeln( "</tr>" );
}
document.writeln( "</table>" );
10.10 Use a one-dimensional array to solve the following problem: A company pays its salespeople
on a commission basis. The salespeople receive $200 per week plus 9 percent of their gross sales for
that week. For example, a salesperson who grosses $5000 in sales in a week receives $200 plus 9 percent of $5000, or a total of $650. Write a script (using an array of counters) that obtains the gross
sales for each employee through an XHTML form and determines how many of the salespeople
earned salaries in each of the following ranges (assume that each salespersons salary is truncated to
an integer amount):
a) $200299
b) $300399
c) $400499
d) $500599
e) $600699
f) $700799
g) $800899
h) $900999
i) $1000 and over
1
2
3
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
0 )
end the function immediately
9 )
put in highest salary range
++total[ x - 2 ]
outputArray();
} // end function addEntry
function outputArray()
{
var sales = document.getElementById( "sales" );
sales.output.value =
"Number of people who earned salaries " +
"in the following ranges:\n" +
"$200-$299 \t " + total[ 0 ] + "\n" +
"$300-$399 \t " + total[ 1 ] + "\n" +
"$400-$499 \t " + total[ 2 ] + "\n" +
"$500-$599 \t " + total[ 3 ] + "\n" +
"$600-$699 \t " + total[ 4 ] + "\n" +
"$700-$799 \t " + total[ 5 ] + "\n" +
"$800-$899 \t " + total[ 6 ] + "\n" +
"$900-$999 \t " + total[ 7 ] + "\n" +
"$1000 and over \t " + total[ 8 ];
} // end function outputArray
// -->
</script>
</head>
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
8
57
58
59
60
61
62
63
64
65
66
67
Chapter 10
JavaScript: Arrays
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
10
Chapter 10
JavaScript: Arrays
10.11 Write statements that perform the following operations for a one-dimensional array:
a) Set the 10 elements of array counts to zeros.
ANS: for ( var i = 0; i < 10; i++ )
counts[ i ] = 0;
10.12 Use a one-dimensional array to solve the following problem: Read in 20 numbers, each of
which is between 10 and 100. As each number is read, print it only if it is not a duplicate of a number that has already been read. Provide for the worst case, in which all 20 numbers are different.
Use the smallest possible array to solve this problem.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
function start()
{
var input;
var form = document.getElementById( "numTest" );
for ( count = 0; count < 20; count++ )
{
input = parseInt(
window.prompt( "Enter number:" ) )
// validate the input
if ( input < 10 || input > 100 )
{
form.output.value = "Invalid Entry!!!";
continue;
} // end if
//
//
//
//
//
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
11
12
75
Chapter 10
JavaScript: Arrays
</html>
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
13
14
Chapter 10
JavaScript: Arrays
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
10.13 Label the elements of three-by-five two-dimensional array
which they are set to zero by the following program segment:
sales
15
ANS: The array contents are traversed from left to right in the following order:
00 01 02 03 04
10 11 12 13 14
20 21 22 23 24
10.14 Write a script to simulate the rolling of two dice. The script should use Math.random to roll
the first die and again to roll the second die. The sum of the two values should then be calculated.
[Note: Since each die can show an integer value from 1 to 6, the sum of the values will vary from 2
to 12, with 7 being the most frequent sum, and 2 and 12 the least frequent sums. Figure 10.15
shows the 36 possible combinations of the two dice. Your program should roll the dice 36,000
times. Use a one-dimensional array to tally the numbers of times each possible sum appears. Display
the results in an XHTML table. Also determine whether the totals are reasonable (e.g., there are six
ways to roll a 7, so approximately 1/6 of all the rolls should be 7).]
1
9 10
9 10 11
9 10 11 12
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
16
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Chapter 10
JavaScript: Arrays
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
17
10.15 Write a script that runs 1000 games of craps and answers the following questions:
a) How many games are won on the first roll, second roll, , twentieth roll and after the
twentieth roll?
b) How many games are lost on the first roll, second roll, , twentieth roll and after the
twentieth roll?
c) What are the chances of winning at craps? [Note: You should discover that craps is one
of the fairest casino games. What do you suppose this means?]
d) What is the average length of a game of craps?
e) Do the chances of winning improve with the length of the game?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
18
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
Chapter 10
JavaScript: Arrays
default:
gameStatus = CONTINUE;
myPoint = sum;
break;
} // end switch
{
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
19
98
99
function rollDice()
100
{
101
var die1;
102
var die2,
103
var workSum;
104
105
die1 = Math.floor( 1 + Math.random() * 6 );
106
die2 = Math.floor( 1 + Math.random() * 6 );
107
workSum = die1 + die2;
108
109
return workSum;
110
}
111
// -->
112
</script>
113
</head><body></body>
114 </html>
10.16 (Airline Reservations System) A small airline has just purchased a computer for its new automated reservations system. You have been asked to program the new system. You are to write a program to assign seats on each flight of the airlines only plane (capacity: 10 seats).Your program
should display the following menu of alternatives: Please type 1 for "First Class" and Please type
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
20
Chapter 10
JavaScript: Arrays
2 for "Economy". If the person types 1, your program should assign a seat in the first-class section
(seats 15). If the person types 2, your program should assign a seat in the economy section (seats
610). Your program should print a boarding pass indicating the persons seat number and whether
it is in the first-class or economy section of the plane.
Use a one-dimensional array to represent the seating chart of the plane. Initialize all the elements of the array to 0 to indicate that all the seats are empty. As each seat is assigned, set the corresponding elements of the array to 1 to indicate that the seat is no longer available.
Your program should, of course, never assign a seat that has already been assigned. When the
first-class section is full, your program should ask the person if it is acceptable to be placed in the
economy section (and vice versa). If yes, then make the appropriate seat assignment. If no, then
print the message "Next flight leaves in 3 hours."
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
if ( conf )
{
window.alert( "Your seat assignment is "
+ economy );
seats[ economy ] = 1;
++people;
++economy;
} // end if
else
window.alert( "Next flight leaves in "
+ "3 hours." );
} // end else if
else
window.alert( "Next flight leaves in 3 "
+ "hours." );
} // end if
else if ( section == 2 )
{
if ( economy <= 10 && seats[ economy ] == 0 )
{
window.alert( "Economy. Seat #" +
economy );
seats[ economy ] = 1;
++people;
++economy;
} // end if
else if ( economy > 10 && firstclass <= 5 )
{
var conf = window.confirm(
"Economy is full. Would you like to "
+ "sit in first class?\n" +
"Click Cancel to wait for the next "
+ "flight." ) ;
if ( conf )
{
window.alert( "Your seat assignment is "
+ firstclass );
seats[ firstclass ] = 1;
++people;
++firstclass;
} // end if
else
window.alert( "Next flight leaves in 3 "
+ "hours." );
} // end else if
else
window.alert( "Next flight leaves in 3 "
+ "hours." );
} // end else if
else
window.alert( "Invalid input." );
} // end if
} // end function processReservation
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
21
22
Chapter 10
JavaScript: Arrays
98
// -->
99
</script>
100
</head>
101
<body>
102
<form id = "myForm" action = "">
103
<table border = "0">
104
<tr><td>Please type 1 for "First Class"<br />
105
Please type 2 for "Economy":</td>
106
<td><input name = "section" type = "text"
107
size = "30" /></td>
108
<td><input type = "button" value =
109
"Make Reservation" onclick =
110
"processReservation()" />
111
</td>
112
</tr>
113
</table>
114
</form>
115
</body>
116 </html>
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
23
24
Chapter 10
JavaScript: Arrays
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
25
26
Chapter 10
JavaScript: Arrays
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
27
10.17 Use a two-dimensional array to solve the following problem: A company has four salespeople (1 to 4) who sell five different products (1 to 5). Once a day, each salesperson passes in a slip for
each different type of product actually sold. Each slip contains
a) the salesperson number,
b) the product number, and
c) the total dollar value of the product sold that day.
Thus, each salesperson passes in between zero and five sales slips per day. Assume that the information from all of the slips for last month is available. Write a script that will read all this information
for last months sales and summarize the total sales by salesperson by product. All totals should be
stored in the two-dimensional array sales. After processing all the information for last month, display the results in an XHTML table format, with each of the columns representing a different
salesperson and each of the rows representing a different product. Cross-total each row to get the
total sales of each product for last month; cross-total each column to get the total sales by salesperson for last month. Your tabular printout should include these cross-totals to the right of the
totaled rows and to the bottom of the totaled columns.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
28
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
Chapter 10
JavaScript: Arrays
function addToTotals()
{
var form = document.getElementById( "myForm" );
var s = parseFloat( form.sales.value );
person = parseInt(
form.salesPerson.value );
product = parseInt( form.product.value );
if ( person >= 1 && person < 5 && product >= 1 && product < 6)
{
if ( numForms[person] == 5 )
window.alert( "Salesperson " + person +
" has already submitted the maximum number of forms." )
else
{
++numForms[ person ];
sales[ person - 1 ][ product - 1 ] += s;
} // end else
} // end if
else
window.alert( "Invalid input!" );
summary();
} // end function addToTotals
function summary()
{
var form = document.getElementById( "myForm" );
var total = 0.0;
for ( var j = 0; j < totalProducts.length; ++j )
totalProducts[ j ] = 0;
var result = "Product\t\t1\t2\t3\t4\t5\tTotal";
for ( var row = 0; row < sales.length; ++row )
{
result += "\nSalesperson " + ( row + 1 );
total = 0.0;
for ( var col = 0; col <
sales[ row ].length; ++col )
{
total += sales[ row ][ col ];
result += "\t" + sales[ row ][ col ];
totalProducts[ col ] += sales[ row ][ col ];
} // end for
result += "\t" + total;
} // end for
result += "\nTotal\t";
for ( var k = 0; k < totalProducts.length; ++k )
result += "\t" + totalProducts[ k ];
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
71
72
form.output.value = result;
73
} // end function summary
74
// -->
75
</script>
76
</head>
77
<body>
78
<form id = "myForm" action = "">
79
<table border = "0">
80
<colgroup>
81
<col align = "right" />
82
</colgroup>
83
84
<tr><td>Enter salesperson number: </td>
85
<td><input name = "salesPerson"
86
type = "text" /></td>
87
</tr>
88
<tr><td>Enter product number:</td>
89
<td><input name = "product"
90
type = "text" /></td>
91
</tr>
92
<tr><td>Enter sales amount:</td>
93
<td><input name = "sales"
94
type = "text" /></td>
95
</tr>
96
<tr><td><input type = "button"
97
value = "Enter Sales Figure"
98
onclick= "addToTotals()" /></td></tr>
99
100
<tr><td colspan = "2">
101
<textarea name = "output" rows = "7"
102
cols = "70"></textarea>
103
</td>
104
</tr>
105
</table>
106
</form>
107
</body>
108 </html>
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
29
30
Chapter 10
JavaScript: Arrays
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
31
32
Chapter 10
JavaScript: Arrays
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
33
10.18 (Turtle Graphics) The Logo language, which is popular among young computer users, made
the concept of turtle graphics famous. Imagine a mechanical turtle that walks around the room under the control of a JavaScript program. The turtle holds a pen in one of two positions, up or down.
When the pen is down, the turtle traces out shapes as it moves; when the pen is up, the turtle moves
about freely without writing anything. In this problem, you will simulate the operation of the turtle
and create a computerized sketchpad as well.
Use a 20-by-20 array floor that is initialized to zeros. Read commands from an array that
contains them. Keep track of the current position of the turtle at all times and of whether the pen
is currently up or down. Assume that the turtle always starts at position (0, 0) of the floor, with its
pen up. The set of turtle commands your script must process are as in Fig. 10.16.
Suppose that the turtle is somewhere near the center of the floor. The following program
would draw and print a 12-by-12 square, then leave the pen in the up position:
2
5,12
3
5,12
3
5,12
3
5,12
1
6
9
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
34
Chapter 10
JavaScript: Arrays
Command
Meaning
Pen up
Pen down
Turn right
Turn left
5,10
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
35
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
36
Chapter 10
JavaScript: Arrays
84
// skip next command, since it (the number of spaces
85
// to move) was already processed
86
i++;
87
break;
88
case 6:
89
// print the floor array
90
document.writeln( "<pre>" );
91
92
for ( var row = 0; row < floorSize; row++ )
93
{
94
for ( var column = 0; column < floorSize; column++ )
95
{
96
if ( floor[ row ][ column ] == 1 )
97
document.write ( " * " );
98
else
99
document.write ( "
" );
100
} // end for
101
document.writeln ( "<br />" );
102
} // end for
103
document.writeln( "</pre>" );
104
break;
105
case 9:
106
document.writeln( "<p>End of data.</p>" );
107
break;
108
} // end switch
109
} // end for
110
// -->
111
</script>
112
</head>
113
<body></body>
114 </html>
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
37
10.19 (The Sieve of Eratosthenes) A prime integer is an integer greater than 1 that is evenly divisible
only by itself and 1. The Sieve of Eratosthenes is an algorithm for finding prime numbers. It operates as follows:
a) Create an array with all elements initialized to 1 (true). Array elements with prime subscripts will remain as 1. All other array elements will eventually be set to zero.
b) Set the first two elements to zero, since 0 and 1 are not prime. Starting with array subscript 2, every time an array element is found whose value is 1, loop through the remainder of the array and set to zero every element whose subscript is a multiple of the
subscript for the element with value 1. For array subscript 2, all elements beyond 2 in
the array that are multiples of 2 will be set to zero (subscripts 4, 6, 8, 10, etc.); for array
subscript 3, all elements beyond 3 in the array that are multiples of 3 will be set to zero
(subscripts 6, 9, 12, 15, etc.); and so on.
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
38
Chapter 10
JavaScript: Arrays
When this process is complete, the array elements that are still set to 1 indicate that the subscript is
a prime number. These subscripts can then be printed. Write a script that uses an array of 1000 elements to determine and print the prime numbers between 1 and 999. Ignore element 0 of the
array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
48
49
50
51
52
53
54
55
56
57
58
39
10.20 (Simulation: The Tortoise and the Hare) In this problem, you will re-create one of the truly
great moments in history, namely the classic race of the tortoise and the hare. You will use random
number generation to develop a simulation of this memorable event.
Our contenders begin the race at square 1 of 70 squares. Each square represents a possible
position along the race course. The finish line is at square 70. The first contender to reach or pass
square 70 is rewarded with a pail of fresh carrots and lettuce. The course weaves its way up the side
of a slippery mountain, so occasionally the contenders lose ground.
There is a clock that ticks once per second. With each tick of the clock, your script should
adjust the position of the animals according to the rules in Fig. 10.17.
Use variables to keep track of the positions of the animals (i.e., position numbers are 170).
Start each animal at position 1 (i.e., the starting gate). If an animal slips left before square 1,
move the animal back to square 1.
Generate the percentages in Fig. 10.17 by producing a random integer i in the range 1 i 10.
For the tortoise, perform a fast plod when 1 i 5, a slip when 6 i 7 and a slow plod when
8 i 10. Use a similar technique to move the hare.
Begin the race by printing
(
BANG !!!!!
AND THEY'RE OFF !!!!!
Then, for each tick of the clock (i.e., each repetition of a loop), print a 70-position line showing the letter T in the position of the tortoise and the letter H in the position of the hare. Occa 2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
40
Chapter 10
JavaScript: Arrays
Animal
Move type
Actual move
Tortoise
Fast plod
50%
Slip
20%
Slow plod
30%
Sleep
20%
No move at all
Big hop
20%
Big slip
10%
Small hop
30%
Small slip
20%
Hare
Fig. 10.17 | Rules for adjusting the position of the tortoise and the hare.
sionally, the contenders will land on the same square. In this case, the tortoise bites the hare, and
your script should print OUCH!!! beginning at that position. All print positions other than the T,
the H or the OUCH!!! (in case of a tie) should be blank.
After each line is printed, test whether either animal has reached or passed square 70. If so,
print the winner, and terminate the simulation. If the tortoise wins, print TORTOISE WINS!!! YAY!!!
If the hare wins, print Hare wins. Yuck! If both animals win on the same tick of the clock, you may
want to favor the turtle (the underdog), or you may want to print It's a tie. If neither animal
wins, perform the loop again to simulate the next tick of the clock. When you are ready to run
your script, assemble a group of fans to watch the race. Youll be amazed at how involved your
audience gets!
Later in the book, we introduce a number of Dynamic HTML capabilities, such as graphics,
images, animation and sound. As you study those features, you might enjoy enhancing your tortoise-and-hare contest simulation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
document.write( "<pre>" );
document.writeln( "ON YOUR MARK, GET SET" );
document.writeln( "BANG
!!!!" );
document.writeln( "AND THEY'RE OFF
!!!!" );
while ( tortoise != RACE_END && hare != RACE_END )
{
moveHare();
moveTortoise();
printCurrentPositions();
++timer;
} // end while
if ( tortoise >= hare )
document.writeln( "\nTORTOISE WINS!!! YAY!!!" );
else
document.writeln( "Hare wins. Yuch!" );
document.writeln( "TIME ELAPSED = " + timer +
" seconds" );
document.write( "</pre>" );
} // end function start
function moveTortoise()
{
var x = parseInt( 1 + Math.random() * 10 );
var tortoiseMoves = [ 3, 6 ];
if ( x >= 1 &&
tortoise +=
else if ( x ==
tortoise -=
else
++tortoise;
if ( tortoise < 1 )
tortoise = 1;
else if ( tortoise > RACE_END )
tortoise = RACE_END;
} // end function moveTortoise
function moveHare()
{
var y = parseInt( 1 + Math.random() * 10 );
var hareMoves = [ 9, 12, 2 ];
if ( y == 3 || y == 4 ) // big hop
hare += parseInt( hareMoves[ 0 ] );
else if ( y == 5 ) // big slip
hare -= parseInt( hareMoves[ 1 ] );
else if ( y >= 6 && y <= 8 ) // small hop
++hare;
else if ( y > 8 ) // small slip
hare -= parseInt( hareMoves[ 2 ] );
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
41
42
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
Chapter 10
JavaScript: Arrays
if ( hare < 1 )
hare = 1;
else if ( hare > RACE_END )
hare = RACE_END;
} // end function moveHare
function printCurrentPositions()
{
for ( var count = 1; count <= RACE_END; count++ )
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
Exercises
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
43
44
Chapter 10
JavaScript: Arrays
2008 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.