Solutions to Self

advertisement
1
COMP 110 Self-help Exercises – Solutions
Answers are highlighted in blue color.
Self-help exercises for preparing for the finals. Sections are separated by a dashed line (and have similar
types/complexity of questions within each section). From each section, you can expect 1 or more questions
of that type on the final.
Evaluate each of the following Javascript expressions and show the value.
1.
“value is “ + 50
value is 50
2. “value is ” + “50”
value is 50
3. “value is “ + “\”50”
value is “50
4. “value is ” + “”50”
invalid expression (mismatched double-quotes)
5. 17 % 5
2
6. 5 % 17
5
7. 5/10
0.5
8. (Math.floor(x) == x)
true, if x is an integer, false otherwise
9. ( (x == Math.floor(y)) && ((2 > 3) || (3 > 4)) )
false
-----------------------------------------------------------------------------------------------Write javascript code to do the following.
10. Read two numbers and display (using alerts) their sum, product, quotient, average, and maximum.
var n1 = 1*prompt("Please enter a number.");
var n2 = 1*prompt("Please enter another number.");
alert("The sum of " + n1 + " and " + n2 + " is " + (n1+n2) );
alert("The product of " + n1 + " and " + n2 + " is " + n1*n2);
alert("The quotient of " + n1 + " and " + n2 + " is " + n1/n2);
alert("The average of " + n1 + " and " + n2 + " is " + (n1+n2)/2);
if (n1 > n2)
alert(“The max of “ + n1 + ” and “ + n2 + ” is “ + n1);
else
alert(“The max of “ + n1 + ” and “ + n2 + ” is “ + n2);
2
If you leave out multiplying the numbers by 1, n1 and n2 will store strings instead of numbers, and
you will get strange answers for the max. For example, while the number 100 is greater than the
number 99, the string "99" is greater than the string "100".
If you don’t add parenthesis around (n1+n2), they will be interpreted as strings and concatenated.
11. Keep prompting the user to enter integers in the range 0…100. Stop when the user enters something that is
not valid (not an integer, or not in range). Then display the average of all of the valid numbers entered by
the user.
Hint: the built in function isNaN(x) returns true if x is not a number. It returns false if x is a number. Sort
of backwards, but that's what's available.
var n = 1*prompt("Please enter an integer in the range 0…100");
var sum=0;
var count=0;
while (!isNaN(n) && (Math.floor(n) == n) && n>=0 && n<=100)
{
sum = sum + n;
count++;
n = 1*prompt("Please enter an integer in the range 0…100");
}
alert(“The average of the numbers entered is “, + (sum/count));
12. Prompt the user to enter an integer (keep prompting till the user enters a valid integer). Then prompt the
user to enter exactly those many numbers (need not be integers), then display the average of the numbers
entered. e.g., if the user enters 10 as an integer, the code should prompt the user to enter 10 numbers, and
then display the average of the 10 numbers. Assume that the user does enter 10 valid numbers.
// Get the count.
var count = 1*prompt ("Please enter an integer.");
while ( isNaN(count) || (Math.floor(count) != count) )
count = 1*prompt ("Please enter an integer.");
var sum = 0;
var n;
for (var i=0; i<count; i++)
{
3
n = 1*prompt ("Please enter a number.");
sum = sum + n; // Add n to the running sum.
}
alert("The average of the “ + count + “ numbers is " + (sum/count));
----------------------------------------------------------------------------------------------------------------------------------------------Write the following functions
13. Write a function multOf5(maxRange, minRange) that uses a loop to display (in a single alert window) the
numbers in the range maxRange…minRange that are multiples of 5. Note than maxRange >= minRange.
function multOf5(maxRange, minRange)
{
var s=””; // Create empty string.
for (var i=maxRange; i>=minRange; i--)
{
if (i%5==0)
// If number is a multiple of 5
s = s + i + “ “; // Concatenate number plus a space
}
alert(s);
}
14. Write a function minOf(n); prompts the user to enter n negative numbers (less than 0). It reprompts if any of the entries is not a valid number. It then displays the min of the n numbers entered.
function minOf(n)
{
var min=0;
var num;
var count = 0;
while (count < n)
{
num = 1*prompt(“Please enter a number.”);
if ( !isNaN(num) && (num < 0) )
4
{
if ( num < min )
min = num;
count++;
}
}
alert("The min of " + n + " numbers is " + min);
}
-----------------------------------------------------------------------------------------------------------------------------------------Code tracing:
15. Trace the following code by showing the values of the 3 variables in the table on the right, for each line of
code that is executed (after the line is executed):
function interchange(x, y)
{
var temp = x;
x = y;
y = temp;
}
…
x
y
z
5
Undefined
Undefined
var y = x/2;
5
2.5
Undefined
var z = 7;
5
2.5
7
x = (y+z)/2;
4.75
2.5
7
y = 8;
4.75
8
7
z = (x-y)/2;
8.5
4.75
8
0.25
-1.625
interchange(x,y);
4.75
8
-1.625
// Start of execution
var x = 5;
5
16. What is the output displayed by each of the following code fragments?
for (var i=9; i>0; i--)
{
alert(i);
}
9 alerts with the values 9…1.
for (var i=10; i<10; i++)
{
alert(i);
}
Nothing. The loop condition fails immediately.
for (var i=5; i>0; i--)
{
for (var j=0; j<9; j=j+3)
{
alert(i +" "+ j);
}
}
15 alerts with the following values.
5 0
5 3
5 6
4 0
4 3
4 6
3 0
3 3
3 6
2 0
6
2 3
2 6
1 0
1 3
1 6
Remember, when one loop is inside another, the inner loop runs to completion for every step of the outer
loop.
for (var i=0; i<5; i++)
{
for (var j=5; j>i; j--)
{
alert(i +" "+j);
}
}
15 alerts with the following values. Note that the inner loop ends at a different value each time.
0 5
0 4
0 3
0 2
0 1
1 5
1 4
1 3
1 2
2 5
2 4
2 3
3 5
3 4
4 5
7
17. Trace the following code by showing the text of the alert messages that are displayed when the function is
called originally as fb(4). There are no errors (assume n >= 0).
function fb(n)
{
var ret;
alert(“Entering function called with ” + n);
if (n == 0)
ret = 0;
else if (n == 1)
ret = 1;
else
ret = fb(n-1) + fb(n-2);
alert(“Exiting function called with ” + n );
return ret;
}
Entering function called with 4
Entering function called with 3
Entering function called with 2
Entering function called with 1
Exiting function called with 1
Entering function called with 0
Exiting function called with 0
Exiting function called with 2
Entering function called with 1
Exiting function called with 1
Exiting function called with 3
Entering function called with 2
Entering function called with 1
8
Exiting function called with 1
Entering function called with 0
Exiting function called with 0
Exiting function called with 2
Exiting function called with 4
----------------------------------------------------------------------------------------------------------------------------------------------18. Write a function that takes an array and an index as its parameters and returns the index of the smallest
element in the subarray starting at the specified index.
function minIndex(a,s)
{
// Return the index of the smallest element in
// the subarray a[s…a.length-1].
// Restriction: s must be an integer in the range
//
0…a.length-1.
var minIndexSoFar = s;
for (var i=s+1; i<a.length; i++)
{ if (a[i] < a[minIndexSoFar])
{ minIndexSoFar = i;} // New smaller value.
}
// minIndexSoFar contains the index of the minimum
// value in a[s…s.length-1].
return minIndexSoFar;
}
19. Write a function to swap two elements of an array. Parameters are the array and the indices of the two
elements to be swapped.
function swap(a, i, j)
{
// Swap the ith and jth element of the array a.
9
// Restrictions: a must be an array;
//
a.length-1
i & j must be integers in the range 0 …
var temp = a[i];
a[i] = a[j];
a[j] = temp;
}
20. Use the functions from the above two exercises (minIndex() and swap()) to implement a selection sort
function. The parameter will be the array to be sorted. In selection sort, array elements are considered oneby-one left to right, and for each element considered, it is swapped with the smallest element to its right.
e.g., if the original array is: 3, 2, 6, 1, 5, after each step it will successively look like:
Consider 3, swap it with 1 to get: 1, 2, 6, 3, 5
Consider 2 next, swap it with nothing (nothing on the right is smaller than it).
Consider 6 next, swap it with 3 to get: 1, 2, 3, 6, 5.
Consider 6 next, swap it with 5 to get: 1, 2, 3, 5, 6.
function sort(a)
{
// Sort the array a in ascending order by selection sort.
// Restriction: a contains numbers only.
for (var i=0;i<a.length-1;i++)
{
// Swap the smallest in a[i…a.length-1] with a[i].
{swap(a, i, minIndex(a, i)); }
}
}
21. Given that JavaScript uses call by value (i.e. gives the function a copy of the parameter, not the parameter
itself), why do your swap and sort functions work?
The array name is actually a reference to the array itself. JavaScript
passes a copy of the reference to the function, but the array referenced
by the original reference and by the copy are the same.
10
22. Write a function that returns the median of the values stored in an array. The parameter will be the array to
be sorted. (Hint: use the above sort() function.)
// Return the median of the values stored in an array
function medianVal(a)
{
// First copy the array to a temporary array
var temp = new Array;
for (var i=0; i< a.length; i++)
temp[i] = a[i];
// sort the temporary array
sort(temp);
if (a.length%2 == 0)
return ((temp[a.length/2] + temp[a.length/2 - 1])/2);
else
return temp[Math.floor(a.length/2)];
}
23. Write a function to search an array looking for key. Return the position of the first occurrence of key, or, if
key isn’t found, return -1.
// Search list.
Return the location of the first occurrence
// of key in list.
If key is not in the list, return -1.
function search(list, key)
{
for (var i=0;i<list.length;i++)
{
if (list[i] == key) // key found in position i
return i;
}
// If we survive to here, key wasn’t found.
11
return -1;
}
24. Write a function to search an array looking for key. Return an array containing all the locations where key
was found.
// Search list.
Return an array containing all locations
// in the array where key was found.
function searchAll(list, key)
{
var foundList = new Array;
// Contains locations where key was found
var foundCount=0;
// Count of the number of occurrences of
// key found so far.
for (var i=0; i<list.length; i++)
{
if (list[i] == key)
{
// Add to found location to found list.
foundList[foundCount] = i;
foundCount++;
}
}
// Return found array.
The array will be empty if no
// occurrences of key were found.
return foundList;
}
25. Write a function that takes two arrays, a and b, as parameters and returns true if every element of a is also
in b. Hint: use the search() function written above.
// Is every element of array a also in array b?
12
function subarray(a,b)
{
for (var i=0; i<a.length; i++)
{
if (search(b, a[i]) == -1)
// a[i] is not in b.
return false;
}
return true;
// Survived the loop.
}
-------------------------------------------------------------------------------------------------------------------------------------------26. Write an HTML form and the accompanying Javascript code to implement its functionality, that has the
following widgets:
a. A button called “Click Me”
b. A text box, initialized to 0
c. And an informational, read-only textarea
When the button is clicked, it should toggle the background color of the textarea between white and yellow,
toggle the font-size of the text box between 30 pt and 18 pt, and increment the number in the text box by 1.
When the mouse is over the button, the textarea should display an appropriate help message that describes
what will happen if the mouse is clicked. The message goes away when the mouse is removed from over the
button.
<html>
<head>
function buttonClick()
{
if (document.f.b.style.backgroundColor == “white”)
document.f.b.style.backgroundColor = “yellow”;
else
document.f.b.style.backgroundColor = “white”;
document.f.t.value = 1*document.f.t.value + 1;
if((1*document.f.t.value)%2 == 0)
document.f.t.style.fontSize=”30pt”;
else
13
document.f.t.style.fontSize=”18pt”;
}
function highlight(x)
{
if (x==0)
document.f.ta.value=””;
else
document.f.ta.value=”On clicking, button color will
toggle between white and yellow, counter above will increment, and font-size of
the counter will toggle between 30pt and 18pt.”;
}
</head>
<body>
<form name=”f” action=””>
<input type=”button” value=”Click Me” name=”b”
onmouseover=”highlight(1)” onmouseout=”highlight(0)” onclick=”buttonClick()”>
<input type=”text” value=”0” name=”t” style=”font-size:30pt”>
<textarea name=”ta” rows=”6” cols=”25”> </textarea>
</form>
</body>
</html>
--------------------------------------------------------------------------------------------------------------------------------------------27. Write a recursive function that checks if a string is a palindrome (returns true is the string is palindrome,
false otherwise). The parameter will be the string to check. A string is a palindrome if the reverse of the
string is the same as the string.
(Hints:
a. A string with only 0 or 1 characters is a palindrome, by definition.
b. The first and last characters are the same in a palindrome.
c. The substring containing all but the first and last characters of a palindrome, is also a palindrome.)
function isPalendrome(s)
{
14
if (s.length < 2)
return true;
if (s[0] != s[s.length-1])
return false;
else
return isPalendrome(s.substring(1,s.length-2));
}
Download