Read sections 6.1-6.6 in chapter 6 of the textbook Explorations in Computing.
def print_sum(matrix) sum = 0 for row in 0..matrix.length-1 do for col in 0..matrix[row].length-1 do sum = sum + matrix[row][col] end end print sum, "\n" end
Using this function as a guide write a function print_col_sum(matrix) to print the sum of each column of the two-dimensional array. You should think about how to nest the for loops and where to put the print statement so that you can print as many numbers as there are columns.
rpn = [23, 3, "-", 4, 6, "+", "/"]
Recall the algorithm to compute the value of a RPN expression using a stack:
1. Set i equal to 0. 2. Set s equal to an empty stack. 3. While i is not equal to the length of the rpn array, do the following: a. Set x equal to rpn[i]. b. If x is a number, then push x on stack s. c. If x is a string (i.e. operator), then do the following: i. Pop stack s and store number in b. ii. Pop stack s and store number in a. iii. If operator is "+", push a+b on stack s. iv. If operator is "-", push a-b on stack s. v. If operator is "*", push a*b on stack s. vi. If operator is "/", push a/b on stack s. d. Add 1 to i and continue looping. 4. Pop stack s and return this number.
Trace how this algorithm computes the value of the following RPN expression stored as an array:
rpn = [8, 2, "+", 4, 2, "/", "*", 10, 2, "/", 5, "*", "+"]
(Draw a new stack whenever a number is pushed or popped, to show how the stack progresses throughout the computation. You can find an example in the lecture slides.)
Suppose we represent a queue using an array named q such that the first element in the array (at index 0) is the front of the queue and the last element in the array (at index q.length-1) is the rear of the queue.
def h(string, table_size) k = ((string[0].ord)*26) + string[1].ord return k % table_size end
In the function above, string[i] returns the ASCII code of the i^{th} character of string and the ord method gives its order in the alphabet. For lowercase letters, ord(x) is x-97. Here are the ASCII codes for the lowercase letters:
a b c d e f g h i j k l m 97 98 99 100 101 102 103 104 105 106 107 108 109 n o p q r s t u v w x y z 110 111 112 113 114 115 116 117 118 119 120 121 122
vertices = ["New York", "Pittsburgh", "Los Angeles", "Dallas", "Atlanta"] edges = [ [∞, 5, 2, 6, 1], [5, ∞, 8, ∞, 3], [2, 8, ∞, 7, 4], [6, ∞, 7, ∞, 9], [1, 3, 4, 9, ∞] ]