text
stringlengths
1
7.76k
source
stringlengths
17
81
4. Loops Write a program to approximate an integral using the rectangle method. For this particular exercise you will integrate the function f(x) = sin x x For reference, the function is depicted in Figure 4.3. Write a program that will read the end points a, b and the number of subintervals n and computes the integral of f using the rectangle method. It should then output the approximation. Figure 4.3.: Plot of f(x) = sin x x Exercise 4.13. Another way to compute an integral is to a technique called Monte Carlo Integration, a randomized numerical integration method. Given the interval [a, b], we enclose the function in a region of interest with a rectangle of a known area Ar. We then randomly select n points within the rectangle and count the number of random points that are within the function’s curve. If m of the n points are within the curve, we can estimate the integral to be Z b a f(x) dx ≈m n Ar Consider again the function f(x) = sin(x) x . Note that the global maximum and minimum of this function are 1 and ≈−0.2172 respectively. Therefore, we can also restrict the rectangle along the y-axis from −.25 to 1. That is, the lower left of the rectangle will be (a, −.25) and the upper right will be (b, 1) for a known area of Ar = |a −b| × 1.25 Figure 4.4 illustrates the rectangle for the interval [−5, 5]. Write a program that will takes as input interval values a, b, and an integer n and perform a Monte Carlo estimate of the integral of the function above. Realize that this is just an approximation and it is randomized so your answers may not match exactly and may be different on various executions of your program. Take care that you handle points within the curve but under the x-axis correctly. 116
ComputerScienceOne_Page_150_Chunk1701
4.8. Exercises Figure 4.4.: A rectangle for the interval [−5, 5]. Exercise 4.14. Consider a ball trapped in a 2-D box. Suppose that it has an initial position (x, y) within the box (the box’s dimensions are specified by its lower left (xℓ, yℓ) and an upper right (xr, yr) points) along with an initial angle of travel θ in the range [0, 2π). As the ball travels in this direction it will eventually collide with one of the sides of the box and bounce off. For this model, we will assume no loss of velocity (it keeps going) and its angle of reflection is perfect. Write a program that takes as input, x, y, θ, xℓ, yℓ, xr, yr, and an integer n and computes the first n −1 Euclidean points on the box’s perimeter that the ball bounces offof in its travel (include the initial point in your printout for a total of n points). You may assume that the input will always be “good” (the ball will always begin somewhere inside the box and the lower left and upper right points will not be reversed). As an example, consider the inputs: x = 1, y = 1, θ = .392699, xℓ= 0, yℓ= 0, xr = 4, yr = 3, n = 20 Starting at (1, 1), the ball travels up and to the right bouncing offthe right wall. Figure 4.5 illustrates this and the subsequent bounces back and forth. Your output should simply be the points and should look something like the following. (1.000000, 1.000000) (4.000000, 2.242640) (2.171572, 3.000000) (0.000000, 2.100506) (4.000000, 0.443652) (2.928929, 0.000000) (0.000000, 1.213202) (4.000000, 2.870056) (3.686287, 3.000000) (0.000000, 1.473090) 117
ComputerScienceOne_Page_151_Chunk1702
4. Loops y x (1, 1) (1.284, 3) Figure 4.5.: Follow the bouncing ball (3.556355, 0.000000) (4.000000, 0.183764) (0.000000, 1.840617) (2.798998, 3.000000) (4.000000, 2.502529) (0.000000, 0.845675) (2.041640, 0.000000) (4.000000, 0.811179) (0.000000, 2.468033) (1.284282, 3.000000) Exercise 4.15. An integer n ≥2 is prime if its only divisors are 1 and itself, n. For example, 2, 3, 5, 7, 11, . . . are primes. Write a program that outputs all prime numbers 2 up to m where m is read as input. Exercise 4.16. An integer n ≥2 is prime if the only integers that evenly divide it are 1 and n itself, otherwise it is composite. The prime factorization of an integer is a list of its prime divisors along with their multiplicities. For example, the prime decomposition of 188, 760 is: 188, 760 = 2 · 2 · 2 · 3 · 5 · 11 · 11 · 13 Write a program that takes an integer n as input and outputs the prime factorization of n. If n is invalid, an appropriate error message should be displayed instead. Your output should look something like the following. 118
ComputerScienceOne_Page_152_Chunk1703
4.8. Exercises 1001 = 7 * 11 * 13 Exercise 4.17. One way of estimating π is to randomly sample points within a 2 × 2 square centered at the origin. If the distance between the randomly chosen point (x, y) and the origin is less than or equal to 1, then the point lies inside the unit circle centered at the origin and we count it. If the point lies outside the circle then we can ignore it. If y x Figure 4.6.: Sampling points in a circle we sample n points and m of them lie within the circle, then π can be estimated as π ≈4m n Given a point (x, y), its distance from the origin is simply p x2 + y2 This idea is illustrated in Figure 4.6. Example code is given to randomly generate numbers within a bound. Write a program that takes an integer n as input and randomly samples n points within the 2 × 2 square and outputs an approximation of π. Of course, you’ll need a way to generate random numbers within the range [−1, 1]. Since you are using some randomization, the result is just an approximation and may not match exactly or even be the same between two different runs of your program. 119
ComputerScienceOne_Page_153_Chunk1704
4. Loops Figure 4.7.: Regular polygons Exercise 4.18. A regular polygon is a polygon that is equiangular. That is, it has n sides and n points whose angle from the center are all equal in measure. Examples for n = 3 through n = 8 can be found in Figure 4.7. Write a program that takes n and a radius r as inputs and computes the points of a regular n-sided polygon centered at the origin (0, 0). Each point should be distance r from the origin and the first point should lie on the positive x-axis. Each subsequent point should be at an angle θ equal to 2π n from the previous point. Recall that given the polar coordinates θ, r we can convert to cartesian coordinates (x, y) using the following. x = r · cos θ y = r · sin θ Your program should be robust enough to check for invalid inputs. If invalid, an error message should be printed and the program should exit. For example, running your program with n = 5, r = 6 should produce the points of a pentagon with “radius” 6. The output should look something like: Regular 5-sided polygon with radius 6.0: (6.0000, 0.0000) (1.8541, 5.7063) (-4.8541, 3.5267) (-4.8541, -3.5267) (1.8541, -5.7063) Exercise 4.19. Let p1 = (x1, y1) and p2 = (x2, y2) be two points in the cartesian plane which define a line segment. Suppose we travel along this line starting at p1 taking n steps that are an equal distance apart until we reach p2. We wish to know which points correspond to each of these steps and which step along this path is closest to anther point p3 = (x3, y3). Recall that the distance between two points can be computed using the Euclidean distance formula: δ = p (x1 −x2)2 + (y1 −y2)2 Write a program that takes three points and an integer n as inputs and outputs a sequence of points along the line defined by p1, p2 that are distance δ n apart from each other. It 120
ComputerScienceOne_Page_154_Chunk1705
4.8. Exercises should also indicate which of these computed points is the closest to the third point. For example, the execution of your program with inputs 0, 2, −5.5, 7.75, −2, 3, 10 should produce output that looks something like: (0.00, 2.00) to (-5.50, 7.75) distance: 7.9569 (0.00, 2.00) (-0.55, 2.58) (-1.10, 3.15) (-1.65, 3.72) <-- Closest point to (-2, 3) (-2.20, 4.30) (-2.75, 4.88) (-3.30, 5.45) (-3.85, 6.02) (-4.40, 6.60) (-4.95, 7.17) (-5.50, 7.75) Exercise 4.20. The natural log of a number x is usually computed using some numerical approximation method. One such method is to use the following Taylor series. ln x = (x −1) −(x −1)2 2 + (x −1)3 3 −(x −1)4 4 + · · · However, this only works for |x −1| ≤1 (except for x = 0) and diverges otherwise. For x such that |x| > 1, we can use the series ln y y −1 = 1 y + 1 2y2 + 1 3y3 + · · · where y = x x−1. Of course such an infinite computation cannot be performed by a computer. Instead, we approximate ln x by computing the series out to a finite number of terms, n. Your program should print an error message and exit for x ≤0; otherwise it should use the first series for 0 < x ≤1 and the second for x > 1. Another series that has better convergence properties and works for any range of x is as follows ln x = ln 1 + y 1 −y = 2y  1 + 1 3y2 + 1 5y4 + 1 7y6 · · ·  where y = (x−1) (x+1). You will write a program that approximates ln x using these two methods computed to n terms. You will also compute the error of each method by comparing the approximated value to the standard math library’s log function. 121
ComputerScienceOne_Page_155_Chunk1706
4. Loops Your program should accept x and n as inputs. It should be robust enough to reject any invalid inputs (ln x is not defined for x = 0 you may also print an error for any negative value; n must be at least one). It will then compute an approximation using both methods and print the relative error of each method. For example, the execution of your program with inputs 3.1415, 6 should produce output that looks something like: Taylor Series: ln(3.1415) ~= 1.11976 Error: 0.02494 Other Series: ln(3.1415) ~= 1.14466 Error: 0.00004 Exercise 4.21. There are many different numerical methods to compute the square root of a number. In this exercise, you will implement several of these methods. (a) The Exponential Identity Method involves the following identity: √x = e 1 2 ln (x) Which assumes the use of built-in (or math-library) functions for e and the natural log, ln. (b) The Babylonian Method involves iteratively computing the following recurrence: ai = 1 2  ai−1 + x ai−1  where a1 = 1.0. Computation is repeated until |ai −ai−1| ≤δ where δ is some small constant value. (c) A method developed for one of the first electronic computers (EDSAC [29]) involves the following iteration. Let a0 = x, c0 = x −1. Then compute ai+1 = ai −aici 2 ci+1 = c2 i (ci−3) 4 The iteration is performed for as many iterations as specified (n), or until the change in a is negligible. The resulting value for a is used as an approximation for √x ≈a. However, this method only works for values of x such that 0 < x < 3. We can easily overcome this by scaling x by some power of 4 so that the scaled value of x satisfies 1 2 ≤x < 2. After applying the method we can then scale back up by the appropriate value of 2 (since √ 4 = 2). Algorithm 4.17 describes how to scale x. 122
ComputerScienceOne_Page_156_Chunk1707
4.8. Exercises Write a program to compute the square root of an input number using these methods and compare your results. 1 power ←0 2 while x < 1 2 do //Scale up 3 x ←(x · 4) 4 power ←(power −1) 5 end 6 while x ≥2 do //Scale down 7 x ←x 4 8 power ←(power + 1) 9 end Algorithm 4.17: Scaling a value x so that it satisfies 1 2 ≤x < 2. After execution, power indicates what power of 2 the value x was scaled by. Exercise 4.22. There are many different numerical methods to compute the natural logarithm of a number, ln x. In this exercise, you will implement several of these methods. (a) A formula version approximates the natural logarithm as: ln(x) ≈ π 2M(1, 4/s) −m ln(2) Where M(a, b) is the arithmetic-geometric mean and s = x2m. In this formula, m is a parameter (a larger m provides more precision). (b) The standard Taylor Series for the natural logarithm is: ln(x) = ∞ X n=1 (−1)n+1 n (x −1)n As we cannot compute an infinite series, we will simply compute the series to the first m terms. Also note that this series is not convergent for values x > 1 (c) Borchardt’s algorithm is an iterative method that works as follows. Let a0 = 1 + x 2 b0 = √x Then repeat: ak+1 = ak+bk 2 bk+1 = p ak+1bk 123
ComputerScienceOne_Page_157_Chunk1708
4. Loops until the absolute difference between ak, bk is small; that is |ak −bk| < ϵ. Then the logarithm is approximated as ln(x) ≈2 x −1 ak + bk (d) Newton’s method works if x is sufficiently close to 1. It works by setting y0 = 1 and then computing yn+1 = yn + 2x −eyn x + eyn The iteration is performed m times. To ensure that some of the methods above work, you may need to scale the number x to be as close as possible to 1. One way to do this is to divide or multiply by e until x is close to 1. Suppose we divided by e k times; that is x = z · ek where z is close to 1. Then ln(x) = ln(z · ek) = ln(z) + ln(ek) = ln(z) + k Thus, we can apply the methods above to Newton’s method to z and add k to the result to get ln(x). A similar trick can be used to ensure that the Taylor Series method is convergent. Exercise 4.23. Write a program that takes a positive integer n as a command line argument and outputs a list of all pairs of integers x, y such that 1 ≤x, y ≤n whose sum, x + y is prime. For example, if n = 5, the output should look something like the following. 1 + 2 = 3 is prime 1 + 4 = 5 is prime 2 + 3 = 5 is prime 2 + 5 = 7 is prime 3 + 4 = 7 is prime Exercise 4.24. Consider the following variation on the classical “FizzBuzz” challenge. Write a program that will print out numbers 1 through n where n is provided as a command line argument. However, if the number is a perfect square (that is, the square of some integer; for example 1 = 12, 4 = 22, 9 = 32, etc.) print “Go Huskers” instead. If the number is a prime (2, 3, 5, 7, etc.) print “Go Cubs” instead. Exercise 4.25. Implement a program to solve the classic “Rainfall Problem” (which has been used in CS education studies to assess programming knowledge and skills). Write an interactive program that repeatedly prompts the user to enter an integer (which 124
ComputerScienceOne_Page_158_Chunk1709
4.8. Exercises represents the amount of rainfall on a particular day) until it reads the integer 99999. After 99999 is entered, it should print out the correct average. That is, it should not count the final 99999. Negative values should also be ignored. For example, if the user entered the sequence 4 0 -1 10 99999 the output should look something like the following. Average rainfall: 4.66 Exercise 4.26. Write a program that takes an integer n and a subsequent list of integers as command line arguments and determines which number(s) between 1 and n are missing from the list. For example, if the following numbers are given to the program: 10 5 2 3 9 2 8 8 your output should look something like: Missing numbers 1 thru 10: 1, 4, 6, 7, 10 Exercise 4.27. Write a program that takes a list of pairs of numbers representing latitudes/longitudes (on the scale [−180, 180] (negative values correspond to the southern and western hemispheres). Then, starting with the first pair, calculate the intermediate air distances between each location as well as a final total distance. To compute air distance from location A to a location B, use the Spherical Law of Cosines: d = arccos (sin(ϕ1) sin(ϕ2) + cos(ϕ1) cos(ϕ2) cos(∆)) · R where • ϕ1 is the latitude of location A, ϕ2 is the latitude of location B • ∆is the difference between location B’s longitude and location A’s longitude • R is the (average) radius of the earth, 6,371 kilometers Note: the formula above assumes that latitude and longitude are measured in radians r, −π ≤r ≤π. To convert from degrees deg (−180 ≤deg ≤180) to radians r, you can use the simple formula: r = deg 180π For example, if the command line arguments were 40.8206 -96.756 41.8806 -87.6742 41.9483 -87.6556 28.0222 -81.7329 125
ComputerScienceOne_Page_159_Chunk1710
4. Loops your output should look something like: (40.8206, -96.7560) to (41.8806, -87.6742): 766.8053km (41.8806, -87.6742) to (41.9483, -87.6556): 7.6836km (41.9483, -87.6556) to (28.0222, -81.7329): 1638.7151km Total Distance: 2413.2040 Exercise 4.28. A DNA sequence is made up of a sequence of four nucleotide bases, A, C, G, T (adenine, cytosine, guanine, thymine). One particularly interesting statistic of a DNA sequence is finding a CG island: a subsequence that contains the highest frequency of guanine and cytosine. For simplicity, we will be interested in subsequences of a particular length, n that will be provided as part of the input. Write a program that takes, as command line arguments, an integer n and a DNA sequence. The program should then find all subsequences of the given DNA string of length n with the maximal frequency of C and G in it. For example, if the DNA sequence is ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGC and the “window” size that we’re interested in is n = 5 then you would scan the sequence and find every subsequence with the maximum number of C or G bases. Your output should include all CG Islands (by indices) in the sequence similar to the following. n = 5 highest frequency: 5 / 5 = 100.00% CG Islands: 15 thru 20: CCCCC 16 thru 21: CCCCG 17 thru 22: CCCGG 18 thru 23: CCGGC 19 thru 24: CGGCC 42 thru 47: CCGGG 43 thru 48: CGGGG 44 thru 49: GGGGC 45 thru 50: GGGCC 126
ComputerScienceOne_Page_160_Chunk1711
4.8. Exercises Exercise 4.29. Write a program that will assist people in saving for retirement using a tax-deferred 401k program. Your program will read the following inputs as command line arguments. • An initial starting balance • A monthly contribution amount (we’ll assume its the same over the life of the savings plan) • An (average) annual rate of return (on the scale [0, 1]) • An (average) annual rate of inflation (on the scale [0, 1]) • A number of years until retirement Your program will then compute a monthly savings table detailing the (inflation-adjusted) interest earned each month, contribution, and new balance. The inflation-adjusted rate of return can be computed with the following formula. 1 + rate of return 1 + inflation rate −1 To get the monthly rate, simply divide by 12. Each month, interest is applied to the balance at this rate (prior to the monthly deposit) and the monthly contribution is added. Thus, the earnings compound month to month. Be sure that your program handles bad inputs as well as it can. It should also round to the nearest cent for every figure. Finally, as of 2014, annual 401k contributions cannot exceed $17,500. If the user’s proposed savings schedule violates this limit, display an error message instead of the savings table. For inputs 10000 500 0.09 0.012 10 your output should look something like the following: Month Interest Balance 1 $ 64.23 $ 10564.23 2 $ 67.85 $ 11132.08 3 $ 71.50 $ 11703.58 4 $ 75.17 $ 12278.75 5 $ 78.87 $ 12857.62 6 $ 82.58 $ 13440.20 7 $ 86.33 $ 14026.53 8 $ 90.09 $ 14616.62 9 $ 93.88 $ 15210.50 127
ComputerScienceOne_Page_161_Chunk1712
4. Loops ... 116 $ 678.19 $ 106767.24 117 $ 685.76 $ 107953.00 118 $ 693.37 $ 109146.37 119 $ 701.04 $ 110347.41 120 $ 708.75 $ 111556.16 Total Interest Earned: $ 41556.16 Total Nest Egg: $ 111556.16 Exercise 4.30. An affine cipher is an encryption scheme that encrypts messages using the following function: ek(x) = (ax + b) mod n Where n is some integer and 0 ≤a, b, x ≤n −1. That is, we fix n, which will be used to encode an alphabet as in Table 4.1. x character 0 (space) 1 A 2 B 3 C ... ... 25 Y 26 Z 27 . 28 ! Table 4.1.: Character Mapping for n = 29 Then we choose integers a, b to define the encryption function. Suppose a = 10, b = 13, then ek(x) = (10x + 13) mod 29 So to encrypt “HELLO!” we would encode it as 8, 5, 12, 12, 15, 27, then encrypt them, ek(8) = (10 · 8 + 13) mod 29 = 6 ek(5) = (10 · 5 + 13) mod 29 = 5 ek(12) = (10 · 12 + 13) mod 29 = 17 ek(12) = (10 · 12 + 13) mod 29 = 17 ek(15) = (10 · 15 + 13) mod 29 = 18 128
ComputerScienceOne_Page_162_Chunk1713
4.8. Exercises ek(28) = (10 · 28 + 13) mod 29 = 3 Which, when mapped back to characters using our encoding is “FEQQRC.” To decrypt a message we need to invert the decryption function, that is, dk(y) =
ComputerScienceOne_Page_163_Chunk1714
4. Loops (1, 1.5) (2, 3.6) (4.25, 2.1) (3.7, 1.5) (2.25, 0.25) (2.468, 1.902) Figure 4.8.: A polygon and its centroid. Whoo! A = 1 2 n−1 X i=0 (xi yi+1 −xi+1 yi) In these formulas, the vertices are assumed to be numbered in order of their occurrence along the polygon’s perimeter. Furthermore, the vertex (xn, yn) = (x0, y0). Write a program that takes n pairs of x-y coordinates as command line arguments that represent a polygon and computes its centroid. For example, the an input such as 1 1.5 2 3.6 4.25 2.1 3.7 1.5 2.25 0.25 would correspond to the polygon in Figure 4.8 with a centroid of (2.46, 1.90). The output should look something like the following. Centroid: (2.468405, 1.902874) Exercise 4.32. Suppose we are given a set of n points (x0, y0), (x1, y1), . . . , (xn1, yn−1) in the plane. Write a program that outputs instructions for someone to “walk” to each point in the order that they are given starting at the origin by only going in the cardinal directions (not “as the bird flies”). For example, if the following input is given, 3 5 2 7 9 5 Then the output should look like the following. Go north 5.00 units Go east 3.00 units Go north 2.00 units 130
ComputerScienceOne_Page_164_Chunk1715
4.8. Exercises Go west 1.00 units Go south 2.00 units Go east 7.00 units Exercise 4.33. A histogram is a graphical representation of the distribution of numerical data. Typically, a histogram is represented as a (vertical) bar graph. However, we’ll limit our attention to graphing a horizontal ASCII histogram. In particular, write a program that takes a sequence of numerical values representing grades (on a 0–100 scale; reject any invalid values). The program will then display a horizontal graph of the distribution of these values over 6 fixed ranges that looks something like the following. 0 - 49 (2, 11.11%) ****** 50 - 59 (1, 5.56%) *** 60 - 69 (1, 5.56%) *** 70 - 79 (5, 27.78%) ************** 80 - 89 (4, 22.22%) ************ 90 - 100 (5, 27.78%) ************** In the diagram, each star, * represents (at least) 2% Exercise 4.34. Shannon entropy is a measure of information in a piece of data; specifi- cally it is the expected value (average) of the information the data contains. A higher entropy value corresponds to more random data while 0 indicates highly structured data. Entropy is calculated using the following formula. H(X) = − n X i=1 p(xi) · log2 p(xi) where x1, x2, . . . , xn are the distinct symbols in the data sequence X and p(xi) is the probability of the xi-th symbol. If the length of X is n, then this is simply p(xi) = c(xi) n where c(xi) is a count of the number of times xi appears in X. For example, the string “Hello World” has 8 distinct symbols with the probability of “l” being .2727, “o” being .1818 and the remaining being .0909. Thus the entropy would be H(’Hello World’) = 2.845351 131
ComputerScienceOne_Page_165_Chunk1716
4. Loops Write a program that takes a string as command line input (which may contain spaces) and computes its entropy. 132
ComputerScienceOne_Page_166_Chunk1717
5. Functions In mathematics, a function is a mapping from a set of inputs to a set of outputs such that each input is mapped to exactly one output. For example, the function f(x) = x2 maps numeric values to their squares. The input is a variable x. When we assign an actual value to x and evaluate the function, then the function has a value, its output. For example, setting x = 2 as input, the output would be 22 = 4. Mathematical functions can have multiple inputs, f(x, y) = x2 + y2 f(x, y, z) = 2x + 3y −4z However, a function will only ever have a single output value. In programming languages, a function (sometimes called subroutine or procedure) can take multiple inputs and produce one output value. We’ve already seen some examples of these functions. For example, most languages provide a math library that you can use to evaluate the square root or sine of a value x. We’ve also seen some functions with multiple input values such as the “power” function that allows you to compute f(x, y) = xy. Finally, the main entry point to many programs is defined by a main function. More formally, a function is a sequence of instructions (code) that is packaged into a unit that can be reused. A function performs a specific task: given a number of inputs, it executes some sequence of operations (executes some code) and “returns” (outputs) a result. The output can be captured into a variable or used in an expression by whatever code invoked or “called” the function. Defining and using functions in programming has numerous advantages. The most obvious advantage is that it allows you a way to organize code. By separating a program it into distinct units of code it is more organized and it is clearer what each piece or segment of code does. This also facilitates top-down design: one way to approach a problem is to split it up into a series of subproblems until each subproblem is either trivial to deal with, or an existing, “off-the-shelf” solution already exists for it. Functions may serve as the logical unit for each subproblem. Another advantage is that by organizing code into functions, those functions can be reused in multiple places either in your program/project or even in other programs/projects. 133
ComputerScienceOne_Page_167_Chunk1718
5. Functions A prime example of this are the standard libraries available in most programming languages that provide functions to perform standard input/output or mathematical functions. These standard libraries provide functions that are used by thousands of different programs across multiple different platforms. Functions also form an isolated unit of code. This allows for better and easier testing. By isolating pieces of code, we can rigorously test those pieces of code by themselves without worrying about the larger program or contexts. Functions facilitates procedural abstraction. Placing code into functions allows you to abstract the details of how the function computes its answer. As an example: consider a standard math library’s square root function: it may use some interpolation method, a Taylor series, or some other method entirely to compute the square root of a given number. However, by putting this functionality into a function, we, as programmers, do not need to concern ourselves about these details. Instead, we simply use the function, allowing us to focus on the larger issues at hand in our program. 5.1. Defining & Using Functions Like variables, many programming languages may require that you declare a function before you can use it. A function declaration may simply include a description of the function’s input/output and name. A function declaration may require you to define the function’s body at the same time or separately. Functions can also have scope: some areas of the code may be able to “see” the function or know about it and be able to invoke the function while other areas of the code may not be able to see the function and therefore may not be able to invoke it. Some interpreted programming languages use function hoisting which allows you to use/invoke functions before you declare them. This works because the interpreter does an initial scan of the code and identifies all function declarations. Only after it has “hoisted” all functions into scope does it start to execute the program. Thus, a function declaration can appear after it has been used and it will still work. 5.1.1. Function Signatures A function is usually defined by its signature: every function can be identified by its name (also called an identifier), its list of input parameters, and its output. A function signature allows the programming language to uniquely identify each function so that 134
ComputerScienceOne_Page_168_Chunk1719
5.1. Defining & Using Functions when you invoke a function there is no ambiguity in which function you are calling. 1 Function sum(a, b) 2 x ←a + b 3 return x 4 end Algorithm 5.1: A function in pseudocode. In this case, the name (identifier) of the function is sum and it has two parameters, a and b. Its body is contained in lines 2–3. Its return value is indicated by the return statement on line 3. A function declaration in pseudocode is presented in Algorithm 5.1. In the pseudocode, explicit variable types are omitted, and thus the return type is inferred from the return statement. In Figure 5.1 we have provided an example of a function declaration in the C programming language with each element labeled. double getDistance(double x1, double y1, double x2, double y2); Parameters Return Type Identifier (name) Figure 5.1.: A function declaration (prototype) in the C programming language with the return type, identifier, and parameter list labeled. Some languages only allow you to use one identifier for one function (like variables) while other languages allow you to define multiple functions with the same identifier as long as the parameter list is different (see Section 5.3.2 below). In general, like variables, function names are case sensitive. Also similar to variables, modern lower camel casing is used with function names. When defining the parameters to a function (its input), you usually provide a comma delimited list of variable names. In the case of statically typed languages, the types of the variable parameters are also specified. The order is important as when you invoke the function, the number of inputs must match the number of parameters in the function declaration. The variable types may also need to match. In some dynamically typed languages, you may be able to call functions with different types or you may be able to omit some of the parameters (see Section 5.3.4 below). Similarly, the return type of the function may need to be specified in statically typed languages while with dynamic languages, functions may conditionally return different types. We generally refer to the “return value” or “return type” because when a function 135
ComputerScienceOne_Page_169_Chunk1720
5. Functions is done executing, it “returns” the control flow back to the line of code that invoked it, returning its computed value. You can also define functions that may not have any inputs or may not have any output. Some languages use the keyword void to indicate no return value and such functions are known as “void functions.” When a function doesn’t have any input values, its parameter list is usually empty. The function signature may be accompanied by the function body which contains the actual code that specifies what the function does. Typically the function body is demarcated with a code block using opening and closing curly brackets, { ... } . Within the function you can generally write any valid code including declaring variables. When you declare a variable inside a function, however, it is local to that function. That is, the variable’s scope is only defined within the function. A local variable cannot be accessed outside the function, indeed the local variable does not usually survive when the function ends its execution and returns control back to line of code that called it. Function parameters are essentially locally scoped variables as well and can usually be treated as such. 5.1.2. Calling Functions When a function has been defined and is in scope, you can invoke or “call” the function by coding the function name and providing the input parameters which can be either variables or literals. When provided as inputs, parameters are referred to as arguments to the function. The arguments are typically provided as a comma delimited list and placed inside parentheses. Invoking a function changes the usual flow of control. When invoked, control flow is transferred over to the function. When the function finishes executing the code in its body, control flow returns to the point in the code that invoked it. It is common for a program to be written so that a function calls another function and that function calls another. This can form a deep chain of function calls in which the flow of control is transferred multiple times. Upon the completion of each function, control is returned back to the function that called it, referred to as the calling function. If a function returns a value it can either be captured in a variable using an assignment 136
ComputerScienceOne_Page_170_Chunk1721
5.2. How Functions Work operator or by using it in an expression. 1 a ←10 2 b ←20 3 c ←sum(a, b) Algorithm 5.2: Using a function. We invoke a function by indicating its name (identifier) and passing it arguments. 5.1.3. Organizing Functions provide code organization, but functions themselves should also be organized. We’ve seen this with standard libraries. Functions that provide basic input/output are all grouped together into one library. Functions that involve math functions are grouped together into a separate math library. Some languages allow you to define and “import” individual libraries which organize similar functions together. Some languages do this by collecting functions into “utility” classes or modules. Only when you import these modules do the functions come into scope and can be used in your code. If you do not import these modules, then the functions are out of scope and cannot be used. In some languages once a function is imported it is part of the global scope and can be “seen” by any part of the code. This can cause conflicts: if you import modules from two different libraries each with different functions that have the same name or signature, then the two function definitions may be in conflict or it may make your code ambiguous as to which function you intend to invoke. This is sometimes referred to as “polluting the namespace.” There are several techniques that can avoid this situation. Some languages allow you to place functions into a namespace to keep functions with the same name in different “spaces.” Other languages allow you to place functions into different classes and then invoke them by explicitly specifying which class’s function you want to call. Yet other languages don’t have great support for function organization and it is the library designer’s responsibility to avoid naming conflicts, typically by adding a library-specific prefix to every function. 5.2. How Functions Work To understand how functions work in practice, it is necessary to understand how a program operates at a lower level. In particular, each program has a program stack (also called a call stack). A stack is a data structure that holds elements in a Last-In First-Out 137
ComputerScienceOne_Page_171_Chunk1722
5. Functions (LIFO) manner. Elements are added to the “top” of the stack in an operation called push and elements can be removed from the top of the stack in an operation called pop. In general, elements cannot be inserted or removed from the middle or “bottom” of the stack. In the context of a program, a call stack is used to keep track of the flow of control. Depending on the operating system, compiler and architecture, the details of how elements are stored in the program stack may vary. In general when a program begins, the operating system loads it into memory at the bottom of the call stack. Global variables (static data) are stored on top of the main program. Each time a function is called, a new stack frame is created and pushed on top of the stack. This frame contains enough space to hold values for the arguments passed to the function, local variables declared and used by the function, as well as a space for a return value and a return address. The return address is a memory location that the program should return to after the execution of the function. That way, when the function finishes its execution, the stack frame can be removed (popped) and the lower stack frame of the calling function is preserved. This is a very efficient way to keep track of the flow of control in a program. As each function calls another function, each stack frame is preserved by pushing a new one on top of the program stack. Each time a function terminates execution and returns, the removal of the stack frame means that all local variables go out of scope. Thus, variables that are local to a function are not accessible outside the function. To illustrate, consider the following snippet of C code. The main() function invokes the average() function which in turn invokes the sum() function. Each invocation creates a new stack frame on top of the last in the program stack which is depicted in Figure 5.2. 1 double sum(double a, double b) { 2 double x = a + b; 3 return x; 4 } 5 6 double average(double a, double b) { 7 double y = sum(a, b) / 2.0; 8 return y; 9 } 10 11 int main(int argc, char **argv) { 12 double n = 10.0; 13 double m = 16.0; 14 double ave = average(n, m); 15 printf("average = %f\n", ave); 16 return 0; 17 } 138
ComputerScienceOne_Page_172_Chunk1723
5.2. How Functions Work Bottom of the stack (high memory) Top of the stack (low memory) Unused stack space Program Code Global Variables Static Content arguments argc, argv return address, value ( 0 ) local variables n, m, ave main() stack frame arguments a, b return address, value ( 13.0 ) local variables y average() stack frame arguments a, b return address, value ( 26.0 ) local variables x sum() stack frame Figure 5.2.: Program Stack. At the bottom we have the program’s code, followed by static content such as global variables. Each function call has its own stack frame along with its own arguments and local variables. In particular, the variable arguments a and b in two different stack frames are completely different variables. Upon returning from the sum() function call, the top- most stack frame would be popped and removed, returning to the code for the average() function via the return address. The stack is depicted bottom-up with high memory at the bottom and low memory at the top, but this may differ depending on the architecture. 139
ComputerScienceOne_Page_173_Chunk1724
5. Functions 5.2.1. Call By Value When a function is invoked, arguments are passed to it. When you invoke a function you can pass it variables as arguments. However, the variables themselves are not passed to the function, but instead the values stored in the variables at the time that you call the function are passed to the function. This mechanism is known as call by value and the variable values are passed by value to the function. Recall that the arguments passed to a function are placed in a new stack frame for that function. Thus, in reality copies of the values of the variables are passed to the function. Any changes to the parameters inside the function have no effect on the original variables that were “passed” to the function when it was invoked. To illustrate, consider the following C code. We have a function sum that takes two integer parameters a and b which are passed by value. Inside sum , we create another variable x which is the sum of the two passed variables. We then change the value of the first variable, a to 10 . Elsewhere in the code we call sum on two variables, n , m with values 5 and 15 respectively. The invocation of the function sum means that the two values, 5 and 15, stored in the variables are copied into a new stack frame. Thus, changing the value to the first parameter changes the copy and has no effect on the variable n . At the end of this code snippet n retains its original value of 5. The program stack frames are depicted in Figure 5.3. 1 int sum(int a, int b) { 2 int x = a + b; 3 a = 10; 4 return x; 5 } 6 7 ... 8 9 int n = 5; 10 int m = 15; 11 int k = sum(n, m); 5.2.2. Call By Reference Some languages allow you to pass a parameter to a function by providing its memory address instead of the value stored in it. Since the memory address is being provided to the function, the function is able to access the original variable and manipulate the 140
ComputerScienceOne_Page_174_Chunk1725
5.2. How Functions Work 0x0010 n = 5 0x0014 m = 10 0x0018 k calling function stack frame 0x0080 a = 5 0x0084 b = 15 0x0088 x = 20 sum() stack frame ... (a) Upon invocation of the sum() function, a new stack frame is created which holds the parameters and local variable. The parameter variables a and b are distinct from the original argument variables n and m . 0x0010 n = 5 0x0014 m = 10 0x0018 k calling function stack frame 0x0080 a = 10 0x0084 b = 15 0x0088 x = 20 sum() stack frame ... (b) The change to the variable a in the sum() function changes the parameter variable, but the original variable n is unaffected. 0x0010 n = 5 0x0014 m = 10 0x0018 k calling function stack frame 0x0080 a = 10 0x0084 b = 15 0x0088 x = 20 sum() stack frame ... (c) When the sum() function finishes execution, its stack frame is removed and the variables a , b , and x are no longer valid. The return value 20 is stored in another return value location. 0x0010 n = 5 0x0014 m = 10 0x0018 k = 20 calling function stack frame 0x0080 a = 10 0x0084 b = 15 0x0088 x = 20 sum() stack frame ... (d) The returned value is stored in the variable k and the variable n retains its original value. Figure 5.3.: Demonstration of Pass By Value. Passing variables by value means that copies of the values stored in the variables are provided to the function. Changes to parameter variables do not affect the original variables. 141
ComputerScienceOne_Page_175_Chunk1726
5. Functions contents stored at that memory address. In particular, the function is now able to make changes to the original variable. This mechanism is known as call by reference and the variables are passed by reference. To illustrate, consider the following C code. Here, the variable a is passed by reference ( b is still passed by value, the *a and &n in the following code are dereferencing and referencing operators respectively. For details, see Section 18.2). Below when we invoke the sum() function, we pass not the value stored in n , but the memory address of the variable n . Thus, when we change the value of the variable a in the function, we are actually changing the value of n (since we have access to its memory location). At the conclusion of this snippet of code, the value stored in n has been changed to 10. The program stack frames are depicted in Figure 5.4. 1 int sum(int *a, int b) { 2 int x = *a + b; 3 *a = 10; 4 return x; 5 } 6 7 ... 8 9 int n = 5; 10 int m = 15; 11 int k = sum(&n, m); Whether or not a variable is passed by value or by reference depends on the language, type of variable, and the syntax used. 5.3. Other Issues 5.3.1. Functions as Entities In programming languages, any entity that can be stored in a variable or passed as an argument to a function or returned as a value from a function is referred to as a “first-class citizen.” Numerical values for example are usually first-class citizens as they can be stored in variables and passed to functions. Functional Programming is a programming language paradigm in which functions them- selves are first-class citizens. That is, functions can be assigned to variables, functions 142
ComputerScienceOne_Page_176_Chunk1727
5.3. Other Issues 0x0010 n = 5 0x0014 m = 10 0x0018 k calling function stack frame 0x0080 a = 0x0010 0x0084 b = 15 0x0088 x = 20 sum() stack frame ... (a) Upon invocation of the sum() function, a new stack frame is created which holds the parameters and local variable. The parameter variable a holds the memory location of the original variable n . 0x0010 n = 10 0x0014 m = 10 0x0018 k calling function stack frame 0x0080 a = 0x0010 0x0084 b = 15 0x0088 x = 20 sum() stack frame ... (b) The change to the variable a in the sum() function actually changes what the variable a references. That is, the original variable n . 0x0010 n = 10 0x0014 m = 10 0x0018 k calling function stack frame 0x0080 a = 0x0010 0x0084 b = 15 0x0088 x = 20 sum() stack frame ... (c) When the sum() function finishes execution, its stack frame is removed and the variables a , b , and x are no longer valid. The return value 20 is stored in another return value location. 0x0010 n = 10 0x0014 m = 10 0x0018 k = 20 calling function stack frame 0x0080 a = 0x0010 0x0084 b = 15 0x0088 x = 20 sum() stack frame ... (d) The returned value is stored in the variable k and the value in the variable n has now changed. Figure 5.4.: Demonstration of Pass By Reference. Passing variables by reference means that the memory address of the variables are provided to the function. The function is able to make changes to the original variable because it knows where it is stored. 143
ComputerScienceOne_Page_177_Chunk1728
5. Functions can be passed to other functions as arguments, and functions can even return functions as a result. This is done as a matter of course in functional programming languages such as Haskell and Clojure, but many programming languages contain some functional aspects. For example, some languages support the same concept by using function pointers which are essentially references to where the function is stored in memory. As a memory location is essentially a number, it can be passed around in functions and be stored in a variable. Purists would argue that this is not sufficient to call a function a “first-class citizen” in such a language. They may argue that a language must be able to create new functions at runtime for it to be considered a language in which functions are “true” first-class citizens. In any case, there are several advantages to being able to pass functions around as arguments or store them in variables. Passing a function to another function as an argument gives you the ability to provide a callback. A callback is simply a function that gets passed to another function as an argument. The idea is that the function that receives the callback will execute or “call back” the passed function at some point. Using callbacks enables us to program a “generic” function that provides some generalized functionality. Then more specific behavior can be be implemented in the callback function. For example, we could create a generic sort function that sorts elements in a collection. We could make the sort function generic so that it could sort any type of data: numbers, strings, objects, etc. A callback would provide more specific behavior on how to order individual elements in the sorted array. As another example, consider GUI Programming in which we want to design a user interface. In particular, we may be able to create a button element in our interface. We need to be able to specify what happens when the user clicks the button. This could be achieved by passing in a function as a callback to “register” it with the click “event.” A related issue is anonymous functions (also known as lambda expressions). Typically, we simply want to create a function so that we can pass it as a callback to another function. We may have no intention of actually calling this function directly as it may not be of much use other than passing it as a callback. Some languages allow you to define a function “inline” without an identifier so that it can be passed to another function. Since the function has no name and cannot be invoked by other sections of the code (other than the function we passed it to), it is known as an anonymous function. 5.3.2. Function Overloading Some languages do not allow you to define more than one function with the same name in the same scope. This is to prevent ambiguity in the code. When you write code to invoke a function and there are several functions with that name, which one are you 144
ComputerScienceOne_Page_178_Chunk1729
5.3. Other Issues actually calling? Some languages do allow you to define multiple functions with the same name as long as they differ in either the number (also called arity) or type of parameters. For example, you could define two absolute value, |x| functions with the same name, but one of them takes a floating point number while the other takes an integer as its parameter. This is known as function overloading because you are “overloading” the code by defining multiple functions with the same name. The ambiguity problem is solved by requiring that each function with the same name differs in their parameters. If you invoke the absolute value function and pass it a floating point number, clearly you meant to call the first version. If you passed it an integer, it is clear that you intended to invoke the second version. Depending on the type and number of arguments you pass to a function, the compiler or interpreter is able to determine which version you intend to call and is able to make the right function call. This process is known as static dispatch. In a language without function overloading, we would be forced to use different names for functions that perform the same operation but on different types. 5.3.3. Variable Argument Functions Many languages allow you to define special functions that take a variable number of parameters. Often they are referred to as “vararg” (short for variable argument) functions. The syntax for doing so varies as does how you can write a function to operate on a variable number of arguments (usually through some array or collection data structure). The standard printf (print formatted) function found in many languages is a good example of a vararg function. The printf function allows you to use one function to print any number of variables or values. Without a vararg function, you would have to implement a printf version for no arguments, 1 argument, 2 arguments, etc. Even then, you would only be able to support up to n arguments for as many functions as you defined. By using a vararg function, we can write a single function that operates on all of these possibilities. It is import to note, a vararg function is not an example of function overloading. There is still only one function defined, it just takes a variable number of arguments. 5.3.4. Optional Parameters & Default Values Suppose that you define a function which has, say, three parameters. Now suppose you invoke the function but only provide it 2 of the 3 arguments that it expects. Some languages would not allow this and it would be considered a syntax or runtime error. Yet 145
ComputerScienceOne_Page_179_Chunk1730
5. Functions other languages may have very complex rules about what happens when an argument is omitted. Some languages allow you to omit some arguments when calling functions as a feature of the language. That is, the parameters to a function are optional. When a language allows parameters to be optional, it usually also allows you to define default values to the parameters if the calling function does not provide them. If a user calls the function without specifying a parameter, it takes on the default value. Alternatively, the default could be a non-value like “null” or “undefined.” Inside the function you could implement logic that determined whether or not a parameter was passed to the function and alter the behavior of the function accordingly. 5.4. Exercises Exercise 5.1. Recall that the greatest common divisor (gcd) of two positive integers, a and b is the largest positive integer that divides both a and b. Adapt the solution from Exercise 4.6 into a function. If the language you use supports it, return the gcd via a pass by reference variable. Exercise 5.2. Write a function that scales an input x to to its scientific notation scale so that 1 ≤x < 10. If you language supports pass by reference, the amount that x is shifted should be stored in a pass-by-reference parameter. For example, a call to this function with x = 314.15 should return 3.1415 and the amount it is scaled by is n = −2. Exercise 5.3. Write a function that returns the most significant digit of a floating point number. The function should only return an integer in the range 1–9 (it should return zero only if x = 0). Exercise 5.4. Write a function that, given an integer x, sums the values of its digits. That is, for x = 29423 the sum 2 + 9 + 4 + 2 + 3 = 20. Exercise 5.5. Write a function to convert radians to degrees using the formula, deg = 180 · rad π Write another function to covert degrees to radians. Exercise 5.6. Write functions to compute the diameter, circumference and area of a circle given its radius. If your language supports pass by reference, compute all three of these with one function. Exercise 5.7. The arithmetic-geometric mean of two numbers x, y, denoted M(x, y) (or agm(x, y)) can be computed iteratively as follows. Initially, a1 = 1 2(x + y) and g1 = √xy (i.e. the normal arithmetic and geometric means). Then, compute an+1 = 1 2(an + gn) gn+1 = √angn 146
ComputerScienceOne_Page_180_Chunk1731
5.4. Exercises The two sequences will converge to the same number which is the arithmetic-geometric mean of x, y. Obviously we cannot compute an infinite sequence, so we compute until |an −gn| < ϵ for some small number ϵ. Exercise 5.8. Write a function to compute the annual percentage yield (APY) given an annual percentage rate (APR) using the formula APY = eAPR −1 Exercise 5.9. Write a function that will compute the air distance between two locations given their latitudes and longitudes. Use the formula as in Exercise 2.14. Exercise 5.10. Write a function to convert a color represented in the RGB (red-green- blue) color model (used in digital monitors) to a CMYK (cyan-magenta-yellow-key) used in printing. RGB values are integers in the range [0, 255] while CMYK are fractional numbers in the range [0, 1]. To convert to CMYK, you first need to scale each integer value to the range [0, 1] by simply computing r′ = r 255, g′ = g 255, b′ = b 255 and then using the following formulas: K = 1 −max{r′, g′, b′} C = (1 −r′ −k)/(1 −k) M = (1 −g′ −k)/(1 −k) Y = (1 −b′ −k)/(1 −k) Exercise 5.11. Write a function to convert from CMYK to RGB using the following formulas. r = 255 · (1 −C) · (1 −K) g = 255 · (1 −M) · (1 −K) b = 255 · (1 −Y ) · (1 −K) Exercise 5.12. Write some functions to convert an RGB color to a gray scale, “removing” the color values. An RGB color value is grayscale if all three components have the same value. To transform a color value to grayscale, there there are several possible techniques. The average method simply sets all three values to the average: r + g + b 3 The lightness method averages the most prominent and least prominent colors: max{r, g, b} + min{r, g, b} 2 147
ComputerScienceOne_Page_181_Chunk1732
5. Functions The luminosity technique uses a weighted average to account for a human perceptual preference toward green: 0.21r + 0.72g + 0.07b Exercise 5.13. Adapt the methods to compute a square root in Exercise 4.21 into functions. Exercise 5.14. Adapt the methods to compute the natural logarithm in Exercise 4.22 into functions. Exercise 5.15. Weight (mass in the presence of gravity) can be measured in several scales: kilogram force (kgf), pounds (lbs), ounces (oz), or Newtons (N). To convert between these scales, you can use the following facts: • 1 kgf is equal to 2.20462 pounds • There are 16 ounces in a pound • 1 kgf is equal to 9.80665 Newtons Write a collection of functions to convert between these scales. Exercise 5.16. Length can be measured by several different units. We will concern ourselves with the following scales: kilometer, mile, nautical mile, and furlong. A measure in each one of these scales can be converted to another using the following facts. • One mile is equivalent to 1.609347219 kilometers • One nautical mile is equivalent to 1.15078 miles • A furlong is 1 8-th of a mile Write a collection of functions to convert between these scales. Exercise 5.17. Temperature can be measured in several scales: Celsius, Kelvin, Fahren- heit, and Newton. To convert between these scales, you can use the following conversion table. From/To Celsius Kelvin Fahrenheit Newton Celsius – c + 273.15 c 9 5 + 32 c 33 100 Kelvin k −273.15 – 9 5k −459.67 .33k −90.1395 Fahrenheit (f −32)5 9 5 9f + 255.372 – 11 60f −88 15 Newton n100 33 100 33 n + 273.15 60 11n + 32 – Table 5.1.: Conversion Chart Write a collection of functions to convert between these scales. 148
ComputerScienceOne_Page_182_Chunk1733
5.4. Exercises Exercise 5.18. Energy can be measured in several different scales: calories (c), joules (J), ergs (erg) and foot-pound force (ft-lbf) among others. To convert between these scales, you can use the following facts: • 1 erg equals 1.0 × 10−7J • 1 ft-lbs equals 1.3558 joules • 1 calorie is equal to 4.184 joules Write a collection of functions to convert between these scales. Exercise 5.19. Pressure is a measure of force applied to the surface of an object per unit area. There are several units that can be used to measure pressure: • Pascal (Pa) which is one Newton per square meter • Pound-force Per Square Inch (psi) • Atmosphere (atm) or standard atmospheric pressure • The torr, an absolute scale for pressure To convert between these units, you can use the following formulas. • 1 psi is equal to 6,894.75729 Pascals, 1 psi is equal to 0.06804596 atmospheres • 1 atmosphere is equal to 101,325 Pascals • 1 torr is equal to 1 760 atmosphere and 101,325 760 Pascals Write a collection of functions to convert between these scales. 149
ComputerScienceOne_Page_183_Chunk1734
6. Error Handling Writing perfect code is difficult. The more complex a system or code base, the more likely it is to have bugs. That is, flaws or mistakes in a program that result in incorrect behavior or unintended consequences. The term “bug” has been used in engineering for quite a while. The term was popularized in the context of computer systems by Grace Hopper who, when working on the Naval Mark II computer in 1946, tracked a malfunction to a literal bug, a moth, trapped in a relay [2]. Some of the biggest modern engineering failures can be tracked to simple software bugs. For example, on September 26th, 1983 a newly installed Soviet early warning system gave indication that nuclear missiles had been launched on the Soviet Union by the United States. Stanislav Petrov, a lieutenant colonel in the Soviet Air Defense Forces and duty officer at the time, did not trust the new system and did not report the incident to superiors who may have ordered a counter strike. Petrov was correct as the false alarm was caused by sunlight reflections offof high altitude clouds as well as other bugs in the newly deployed system [28]. In September 1999 the Mars Climate Orbiter, a project intended to study the Martian climate and atmosphere was lost after it entered into the upper atmosphere of Mars and disintegrated. The error was due to a subsystem that measured the craft’s momentum in a non-standard pound force per second unit when all other systems expected the standard newton second unit [1]. The loss of the project was calculated at over $125 million. There are numerous other examples, some that have caused inconvenience to users (such as the Zune bug mentioned in Section 4.5.2) to bugs in medical devices that have cost dozens of lives to those resulting in the loss of millions of dollars [6]. In some sense, Software Engineering and programming is unique. If you build a bridge and forget one bolt its likely not going to cause the bridge to collapse. If you draw up plans for a development and the land survey is a few inches offoverall, its not a catastrophic problem. However, if you forget one character or are offby one number in a program, it can cause a complete system failure. There are a variety of reasons for why bugs make it into systems. Bugs could be the result of a fundamental misunderstanding of the problem or requirements. Poor management and the pressure of time constraints to deliver a project may make developers more careless. A lack of proper testing may mean many more bugs survive the development 151
ComputerScienceOne_Page_185_Chunk1735
6. Error Handling process than otherwise should have. Even expert programmers can overlook a simple mistake when writing thousands of lines of code. Given the potential for error, it is important to have good software development method- ologies that emphasize testing a system at all levels. Working in teams where regular code reviews are held so that colleagues can examine, critique, and catch potential bugs are essential for writing robust code. Modern coding tools and techniques can also help to improve the robustness of code. For example, debuggers are tools that help a developer debug (that is, find and fix the cause of an error) a program. Debuggers allow you to simulate the execution of a program statement-by-statement and view the current state of the program such as variable values. You can “step through” the execution line by line to find where an error occurs in order to localize and identify a bug. Other tools allow you to perform static analysis on source code to search for potential problems. That is, problems that are not syntax errors and are not necessarily bugs that are causing problems, but instead are anti-patterns or code smells. Anti-patterns are essentially common bad-habits that can be found in code. They are an attempted solution to a commonly encountered problem but which don’t actually solve the problem or introduces new problems. Code smells are “symptoms” in a source code that indicate a possible deeper design or implementation flaw. Failure to adhere to good programming principles such as properly initializing variables or failure to check for null values are examples of smells. Static analysis tools automatically examine the code base for potential issues like these. For example, a lint (or linter) is a tool that can examine source code suspicious or non-portable code or code that does not comply with generally accepted standards or ways of doing things. Even if code contains no bugs, it is still susceptible to errors. For example, a program could connect to a remote database to query and process data. However, if the network connection is temporarily unavailable, the program will not be able to execute properly. Because of the potential of such errors, it is important to write code that is not only bug free but is also robust and resilient. We must anticipate possible error conditions and write code to detect, prevent, or recover from such errors. Generally, this is referred to as error handling. Much of what we now consider Software Engineering was pioneered by people like Margaret Hamilton who was the lead Apollo flight software designer at NASA. During the Apollo 11 Moon landing (1969), an error in one system caused the lander’s computer to become overworked with data. However, because the system was designed with a robust architecture, it could detect and handle such situations by prioritizing more important tasks (those related to landing) over lower priority tasks. The resilience that was built into the system is credited with its success [11]. 152
ComputerScienceOne_Page_186_Chunk1736
6.1. Error Handling 6.1. Error Handling In general, errors are potential conditions or situations that can reasonably be anticipated by a developer. For example, if we write code to open and process a file, there are several things that could go wrong. The file may not exist, or we may not have permission on the system to read it, or the formatting in the file may be corrupted or not as expected. Still yet, everything could be fine with the file, but it may contain erroneous or invalid values. If an error can be anticipated, we may be able to write code that detects the particular error condition and handles it by executing code that may be able to recover from the error condition. In the case of a missing file for example, we may be able to prompt the user for an alternate file. We may be able to detect but not necessarily recover from certain errors. For example, if the file has been corrupted in example above, there may not be a way to properly “fix” it. If it contains invalid data, we may not even want the program to fix it as it may indicate a bug or other issue that needs to be addressed. Still yet, there may be some error conditions that we cannot recover from at all as they are completely unexpected. In such instances, we may want the error to result in the termination of the program in which case the error is considered fatal. 6.2. Error Handling Strategies There are several general strategies for performing error handling. We’ll look at two general methods here: defensive programming and exceptions. 6.2.1. Defensive Programming Defensive programming is a “look before you leap” strategy. Suppose we have a potentially “dangerous” section of code; that is, a line or block of code whose execution could encounter or result in an error condition. Before we execute the code, we perform a check to see if the error condition is present (usually using a conditional statement). If the error condition does not hold, then we proceed with the code as normal. However, if the error condition does hold, instead of executing the code, we execute alternative code that handles the error. Suppose we are about to divide by a number. To prevent a division by zero error, we can check if our denominator is zero or not. If it is, then we raise or handle the error instead of performing the division. What should be done in such a case? We could, as an alternative, use a predefined value as a result instead. Or we could notify the user and 153
ComputerScienceOne_Page_187_Chunk1737
6. Error Handling ask for an alternative. Or we could log the error and proceed as normal. Or we could decide that the error is so egregious that it should be fatal and terminate the execution of the program. Which is the right way to handle this error? It really depends on your design requirements really. This raises the question, though: “who” is responsible for making these decisions? Suppose we’re designing a function for a library that is not just for our project but others as well (as is the case with the standard library functions). Further, the function we’re designing could have multiple different error conditions that it checks for. In this scenario there are two entities that could handle the errors: the function itself and the code that invokes the function. Suppose that we decide to handle the errors inside the function. As designers of the function, we’ve made the decision to handle the errors for the user (the code that invokes our function). Regardless of how we decide to handle the errors, this design decision has essentially taken any decision making ability away from users. This is not very flexible for someone using our code. If they have different design considerations or requirements, they may need or want to handle the errors in a different way than we did. Now suppose that we decide not to handle the errors inside our function. Defensive programming may still be used to prevent the execution of code that results in an error. However, we now need a way to communicate the error condition to the calling function so that it can know what type of error happened and handle it appropriately. Error Codes One common pattern to communicate errors to a calling function is to use the return type as an error code. Usually this is an integer type. By convention 0 is used to indicate “no error” and various other non-zero values are used to indicate various types of errors. Depending on the system and standard used, error codes may have a predefined value or may be specific to an application or library. One problem with using the return type to indicate errors is that functions are no longer able to use the return type to return an actual computed value. If a language supports pass by reference, then this is not generally a problem. However, even with such languages there are situations where the return type must be used to return a value. In such cases, the function can still communicate a general error message by returning some flag value such as null. Alternatively, a language may support error codes by using a shared global variable that can be set by a function to indicate an error. The calling function can then examine the variable to see if an error occurred during the invocation of the function. 154
ComputerScienceOne_Page_188_Chunk1738
6.2. Error Handling Strategies Limitations Defensive programming has its limitations. Let’s return to the example of processing a file. To check for all four of the error conditions we identified, we would need a series of checks similar to the following. 1 if file does not exists then 2 return an error code 3 end 4 if we do not have permissions then 5 return an error code 6 end 7 if the file is corrupted then 8 return an error code 9 end 10 if the file contains invalid values then 11 return an error code 12 end 13 process file data A problem arises when an error condition is checked and does not hold. Then, later in the execution, circumstances change and the error condition does hold. However, since it was already checked for, the program remains under the assumption that the error condition does not hold. For example, suppose that another process or program deletes the file that we wish to process after its existence has been checked but before we start processing it. Because of the sequential nature of our program, this type of error checking is susceptible to these issues. 6.2.2. Exceptions An exception is an event or occurrence of an anomalous, erroneous or “exceptional” condition that requires special handling. Exceptions interrupt the normal flow of control in a program by handing the flow of control over to exception handlers. Languages usually support exception handling using a try-catch control structure such as the following. try { //potentially dangerous code here 155
ComputerScienceOne_Page_189_Chunk1739
6. Error Handling } catch(Exception e) { //exception handling code here } The try is used to encapsulate potentially dangerous code, or simply code that would fail if an error condition occurs. If an error occurs at some point within the try block, control flow is immediately transferred to the catch block. The catch block is where you specify how to handle the exception. If the code in the try block does not result in an exception, then control flow will skip over the catch statement and resume normally after. It is important to understand how exceptions interrupt the normal control flow. For example, consider the following pseudocode. try { statement1; statement2; statement3; } catch(Exception e) { //exception handling code here } Suppose statement1 executes with no error but that when statement2 executes, it results an exception. Control flow is then transferred to the catch block, skipping statement3 entirely. In general, there may not be a mechanism for your catch block to recover and execute statement3 . Therefore, it may be necessary to make your try-catch blocks fine-grained, perhaps having only a single statement within the try statement. Some languages only support a generic Exception and the type of error may need to be communicated through other means such as a string error message. Still other languages may support many different types of exceptions and you may be able to provide multiple catch statements to handle each one differently. In such languages, the order in which you place your catch statements may be important. Similar to an if-else-if statement, the first one that matches the exception will be the one that executes. Thus, it is best practice to order your catch blocks from the most specific to the most general. Some languages also support a third finally control statement as in the following example. 156
ComputerScienceOne_Page_190_Chunk1740
6.3. Exercises try { //potentially dangerous code here } catch(Exception e) { //exception handling code here } finally { //unconditionally executed code here } The try-catch block operates as previously described. However, the finally block will execute regardless of whether or not an exception was raised. If no exception was raised, then the try block will fully execute and the finally block will execute immediately after. If an exception was raised, control flow will be transferred to the catch block. After the catch block has executed, the finally block will execute. finally blocks are generally used to handle resources that need to be “cleaned up” whether or not an exception occurs. For example, opening a connection to a database to retrieve and process data. Whether or not an exception occurs during this process the connection will need to be properly closed as it represents a substantial amount of resources (a network connection, memory and processing time on both the server and client machines, etc.). Failure to properly close the connection may result in wasted resources. By placing the clean up code inside a finally statement, we can be assured that it will execute regardless of an error or exception. In addition to handling exceptions, a language may allow you to “throw” your own exceptions by using the keyword throw . In this way you can also practice defensive programming. You could write a conditional statement to check for an error condition and then throw an appropriate exception. 6.3. Exercises Exercise 6.1. Rewrite the function to compute the GCD in Exercise 5.1 to handle invalid inputs. Exercise 6.2. Rewrite the function to compute statistics of a circle in Exercise 5.6 to handle invalid input (negative radius). Exercise 6.3. Rewrite the function to compute the annual percentage yield in Exercise 5.8 to handle invalid input. Exercise 6.4. Rewrite the function to compute air distance in Exercise 5.9 to handle invalid input (latitude/longitude values outside the range [−180, 180]). 157
ComputerScienceOne_Page_191_Chunk1741
6. Error Handling Exercise 6.5. Rewrite the function to convert from RGB to CMYK in Exercise 5.10 to handle invalid inputs (values outside the range [0, 255]). Exercise 6.6. Rewrite the function to convert from CMYK to RGB in Exercise 5.11 to handle invalid inputs. Exercise 6.7. Rewrite the square root functions from Exercise 5.13 to handle invalid inputs. Exercise 6.8. Rewrite the natural logarithm functions from Exercise 5.14 to handle invalid inputs. Exercise 6.9. Rewrite the weight conversion functions from Exercise 5.15 to handle invalid inputs. Exercise 6.10. Rewrite the length conversion functions from Exercise 5.16 to handle invalid inputs. Exercise 6.11. Rewrite the temperature conversion functions from Exercise 5.17 to handle invalid inputs. Exercise 6.12. Rewrite the energy conversion functions from Exercise 5.18 to handle invalid inputs. Exercise 6.13. Rewrite the pressure conversion functions from Exercise 5.19 to handle invalid inputs. 158
ComputerScienceOne_Page_192_Chunk1742
7. Arrays, Collections & Dynamic Memory Rarely do we ever deal with a single piece of data in a program. Instead, most data is made up of a collection of similar elements. A program to compute grades would be designed to operate on an entire roster of students. Scientific data represents a collection of many different samples or measurements. A bank maintains and processes many different accounts, etc. Arrays are a way to collect similar pieces of data together in an ordered collection. The pieces of data stored in an array are referred to as elements and are stored in an ordered manner. That is, there is a “first” element, “second” element, etc. and a “last” element. Though the elements are ordered, they are not necessarily sorted in any particular manner. Instead, the order is usually determined by the order in which you place elements into the array. Some languages only allow you to store the same types of elements in an array. For example, an integer array would only be able to store integers, an array of floating-point numbers would only be able to store floating-point numbers. Other languages allow you to create arrays that can hold mixed elements. A mixed array would be able to hold elements of any type, so it could hold integers, floating-point numbers, strings, objects, or even other arrays. Some languages treat arrays as full-fledged object types that not only hold elements, but have methods that can be called to manipulate or transform the contents of the array. Other languages treat arrays as a primitive type, simply using arrays as storage data structures. Languages can vary greatly in how they implement and represent arrays of elements, but many have the same basic usage patterns allowing you to create arrays and manipulate their contents. 159
ComputerScienceOne_Page_193_Chunk1743
7. Arrays, Collections & Dynamic Memory index contents 2 0 3 1 5 2 7 3 11 4 13 5 17 6 19 7 23 8 29 9 Figure 7.1.: An integer array of size 10. Using zero-indexing, the first element is at index 0, the last at index 9. 7.1. Basic Usage Creating Arrays Though there can be great variation in how a language uses arrays, there are some commonalities. Languages may allow you to create static arrays or dynamically allocated arrays (see Section 7.2 below for a detailed discussion). Static arrays are generally created using the program stack space while dynamically allocated arrays are stored in the heap. In either case you generally declare an array by specifying its size. In statically typed languages, you must also declare the array’s type (integer, floating-point, etc.). Indexing Arrays Once an array has been created you can use it by assigning values to it or by retrieving values from it. Because there is more than one element, you must specify which element you are assigning or retrieving. This is generally done through indexing. An index is an integer that specifies an element in the array. The index is used in conjunction with (usually) square brackets and the array’s identifier. For example, if the array’s identifier is arr and the index is an integer value stored in the variable i , we would refer to the i-th element using the syntax arr[i] . An example is presented in Figure 7.1. For most programming languages, indices start at zero. This is known as zero-indexing.1 Thus, the first element is at arr[0] , the second at arr[1] etc. When an array is stored in memory, each element is usually stored one after the other in one contiguous space in memory. Further, each element is of a specific type which is represented using a fixed number of bytes in memory. Thus the index actually acts as an offset in memory from the beginning of the array. For example, if we have an array of integers which each take 4 bytes each, then the 5th element would be stored at index 4, which is an an offset equal to 4 × 4 = 16 bytes away from the beginning of the array. The first element, being at index 0 is 4 × 0 = 0 bytes from the beginning of the array (that is, the first element is at the beginning of the array). Once an element has been indexed, it can essentially be treated as a regular variable, 1Some languages do use 1-indexing but there are very strong arguments in favor of zero-indexing [13]. 160
ComputerScienceOne_Page_194_Chunk1744
7.1. Basic Usage assigning and retrieving values as you would regular variables. Care must be taken so that you do not make a reference to an element that does not exist. For example, using a negative index or an index i ≥n in an array of n elements. Depending on the language, indexing an array element that is out-of-bounds may result in undefined behavior, an exception being thrown, or a corruption of memory. Iteration Since we can simply index elements in an array, it is natural to iterate over elements in an array using a for loop. We can create a for loop using an index variable i which starts at 0, and increments by one on each iteration, accessing the i-th element using the syntax described above, arr[i] . One issue is that such a loop would need to know how large the array is in order to define a terminating condition. 1 n ←size of array arr 2 for (i ←0; i < (n −1); i ←(i + 1)) do 3 process element arr[i] 4 end Some languages build the size of the array into a property that can be accessed. Java, for example, has a arr.length property. Other languages provide functions that you can use to determine their size. Still other languages (such as C), place the burden of “bookkeeping” the size of an array on you, the programmer. Whenever you pass an array to a function you need to also pass a size parameter that informs the function of how many elements are in the array. Yet other functions may also require you to pass the size of each element in the array. Some languages also support a basic foreach loop (cf. Section 4.4). A foreach loop is syntactic sugar that allows you to iterate over the elements in an array (usually in order) without the need for boilerplate code that creates and increments an index variable. 1 foreach element a in arr do 2 process element a 3 end The actual syntax may vary if a language supports such a loop. 161
ComputerScienceOne_Page_195_Chunk1745
7. Arrays, Collections & Dynamic Memory Using Arrays in Functions Most programming languages allow you to use arrays as both function parameters and as return types. You can pass arrays to functions and functions can be defined that return arrays. Typically, when arrays are passed to functions, they are passed by reference so as to avoid making an entirely new copy of the array. As a consequence, if the function makes changes to the array elements, those changes may be realized in the calling function. Sometimes you may want this behavior. However, sometimes you may not want the function to make changes to the passed array. Some languages allow you to use various keywords to prevent any changes to the passed array. If a function is designed to return an array, care must be taken to ensure that the correct type of array is returned. Recall that static arrays are allocated on the call stack. It would be inappropriate to return static arrays from a function as the array is part of the stack frame that is destroyed when the function returns control back to the calling function (we discuss this in detail below). Instead, if a function returns an array, it should be an array that has been dynamically allocated (on the heap). 7.2. Static & Dynamic Memory Recall that arrays can be declared as static arrays, meaning that when you declare them, they are allocated and stored on the program’s call stack within the stack frame in which they are declared. For example, if a function foo() creates a static array of 5 integers, each requiring 4 bytes, then 20 contiguous bytes are allocated on the stack frame for foo() to store the static array. This can cause several potential problems. First, the typical stack space allocated for a program is relatively small. It can be as large as a couple of Megabytes (MBs) or on some older systems or those with limited resources, even on the order of a few hundred Kilobytes (KBs). When dealing with data of any substantial size, you could quickly run out of stack space, resulting in a stack overflow. Another problem arises if we want to return a static array from a function. Recall that when a function returns control to the calling function, its stack frame is popped offthe top and goes out-of-scope (see Section 5.2). Since the array is part of the stack frame of the function, it too goes out of scope. Depending on how the system works, the contents of the frame may be completely changed in the “bookkeeping” process of returning from the function. Even if the contents remain unchanged when the function returns, they will almost certainly be overwritten when another function call is made and a new stack frame overwrites the old one. For these reasons, static arrays are of very limited use. They must be kept small and cannot be returned from a function. 162
ComputerScienceOne_Page_196_Chunk1746
7.2. Static & Dynamic Memory Demonstration in C To make this concept a bit more clear, we’ll use a concrete example in the C programming language. Consider the program code in Figure 7.2. Here, we have a function foo() that creates a static integer array of size 5, int b[5]; . This memory is allocated on the stack frame and then assigned values. Printing them in the function will give the expected results, b[0] = 5 b[1] = 10 b[2] = 15 b[3] = 20 b[4] = 25 1 #include <stdlib.h> 2 #include <stdio.h> 3 4 int * foo(int n) { 5 int i; 6 int b[5]; 7 for(i=0; i<5; i++) { 8 b[i] = n*i; 9 printf("b[%d] = %d\n", i, b[i]); 10 } 11 return b; 12 } 13 14 int main(int argc, char **argv) { 15 int i, m = 5; 16 int *a = foo(m); 17 for(i=0; i<5; i++) { 18 printf("a[%d] = %d\n", i, a[i]); 19 } 20 return 0; 21 } Figure 7.2.: Example returning a static array 163
ComputerScienceOne_Page_197_Chunk1747
7. Arrays, Collections & Dynamic Memory However, when the function foo() ends execution and returns control back to the main() function, (sometimes called unwinding), the contents of foo() ’s stack frame are altered as part of the process. Some of the contents are the same, but elements have been completely altered. Printing the “returned” contents of the array gives us garbage: a[0] = 1564158624 a[1] = 32767 a[2] = 15 a[3] = 20 a[4] = -626679356 This is not an issue when returning primitive types as the return value is placed in a special memory location available to the calling function. Even in our example, the return value is properly communicated to the calling function: its just that the returned value is a pointer to the array’s location (which happens to be a memory address in the “stale” stack frame). The stack frames are depicted in Figure 7.3. 7.2.1. Dynamic Memory The solution to the problems presented by static arrays is to use dynamically allocated arrays. Such arrays are not allocated and stored in the program call stack, but instead are stored in another area called the heap. In fact, because of the shortcomings of static arrays, some languages only allow you to use dynamically allocated arrays even if it is done so implicitly. Recall that when a program is loaded into memory, its code is placed on the program call stack in memory. On top of that is any static data (global variables or data for example). Subsequent function calls place new stack frames on top of that. In addition, at the “other end” of the program’s memory space, the heap is allocated. The heap is a “pile” of memory like the stack is, but it is less structured. The stack is one contiguous piece of memory, but the heap may have “holes” in it as various chunks of it are allocated and deallocated for the program. In general, the heap is larger but allocation and deallocation is a more involved and more costly process while the stack is smaller and faster to allocate/deallocate stack frames from. Initially, a program is allocated a certain amount of memory for its heap. When a program attempts to dynamically allocate memory, say for a new array of integers, it makes a request to the operating system for a certain amount of memory (a certain number of bytes). The system responds by allocating a chunk of the heap memory which the program can then use to store elements in the array. Usually, the memory space is 164
ComputerScienceOne_Page_198_Chunk1748
7.2. Static & Dynamic Memory stored as a pointer or reference. The reference is stored in a variable in a stack frame, but the actual contents of the array are stored in the heap space. Depending on the language and system, if a program uses all of its heap space and runs out, the operating system may terminate the program or it may attempt to reserve even more memory for the program. Memory Management If a program no longer needs a dynamically allocated memory space, it should “clean up” after itself by deallocating or “freeing” the memory, releasing it back to the heap space so that it can be reused either by the program or some other program or process on the system. The process of allocating and deallocating memory is generally referred to as memory management. If a program does not free up memory, it may eventually run out and be forced to terminate. Even if it does not necessarily run out of available memory, its performance may degrade or it may impact system performance. If a program has poor memory management and fails to deallocate memory when it is no longer needed, the memory “leaks”: the available memory gradually runs out because it is not released back to the heap for reallocation. Programs which such poor memory management are said to have a memory leak. Sometimes this is a consequence of a dangling pointer: when a program dynamically allocates a chunk of memory but then due to carelessness, loses the reference to the memory chunk, making it impossible to free up. Some languages have automatic garbage collection that handle memory management for us. The language itself is able to monitor the dynamically allocated pieces of memory and determine if any variable in the program still references it. If the memory is no longer referenced, it is “garbage” and becomes eligible to be “collected.” The system itself then frees the memory and makes it available to the program or operating system. In such “memory managed” languages, we are responsible for allocating memory, but are not (necessarily) responsible for deallocating it. Even if a language offers automated memory management, it is still possible to have memory leaks and other memory allocation issues. Automated memory management does not solve all of our memory management problems. Moreover, it comes at a cost. The additional resources and overhead required to monitor memory can have a significant performance cost. However, with modern garbage collection systems and algorithms, the performance gap between garbage collected languages and user-managed memory languages has been shrinking. In any case, all program memory is reclaimed by the operating system when the program terminates. 165
ComputerScienceOne_Page_199_Chunk1749
7. Arrays, Collections & Dynamic Memory 7.2.2. Shallow vs. Deep Copies In most languages, an array variable is actually a reference to the array in memory. We could create an array referred to by a variable A and then create another reference variable B and set it “equal” to A. However, this is simply a shallow copy. Both the reference variables refer to the same data in memory. Consequently, if we change the value of an element in one, the change is realized in both. Often, we want a completely different copy, referred to as a deep copy. With a deep copy, A and B would refer to different memory blocks. Changes to one would not affect the other. This distinction is illustrated in Figure 7.5. 7.3. Multidimensional Arrays A normal array is usually one dimensional. One can think an array as a single “row” in a table that contains a certain number of entries. Most programming languages allow you to define multidimensional arrays. For example, two dimensional arrays would model having multiple rows in a full table. You can also view two dimensional arrays as matrices in mathematics. A matrix is a rectangular array of numbers that have a certain number of rows and a certain number of columns. As an example, consider the following 2 × 3 matrix (it has 2 rows and 3 columns):  1 9 −8 2.5 3 5  In mathematics, entries in a matrix are indexed via their row and column. For example, ai,j would refer to the element in the i-th row and j-th column. Referring to the row first and column second is referred to as row major ordering. If the number of rows and the number of columns are the same, the matrix is referred to as a square matrix. For example, the following is a square, 10 × 10 matrix.   2 68 9 44 80 79 77 59 27 2 3 86 22 42 58 24 45 39 7 47 5 7 17 12 29 56 68 14 65 3 7 35 64 69 79 56 52 77 82 85 11 55 36 5 25 6 22 25 72 37 13 20 37 74 3 53 87 70 3 78 17 72 68 26 11 6 63 70 29 16 19 59 6 26 87 18 82 27 75 19 23 73 30 80 51 14 34 67 59 58 29 48 2 39 18 21 33 28 40 34   166
ComputerScienceOne_Page_200_Chunk1750
7.4. Other Collections We can do something similar in most programming languages. First, languages may vary in how you can create multidimensional arrays, but you usually have to provide a size for each dimension when you create them. Once created, you can index them by providing multiple indices. For example, with a two dimensional array, we could provide two indices each in their own square brackets arr[i][j] referring to the i-th row and j-th column. Multidimensional arrays usually use the same 0-indexing scheme as single dimensional arrays. You can further generalize this and create 3-dimensional arrays, 4-dimensional arrays, etc. However, the use cases for arrays of dimension 3 and certainly for arrays of dimension 4 or greater are rare. If you need to store such data, it may be more appropriate to define a custom, user-defined structure or object (see Chapter 10) instead of a higher dimensional array. We usually think of 2-dimensional arrays as having the same number of elements in each “row”. In the example above, both of the matrix’s rows had 3 elements in it. Some languages allow you to create 2-dimensional arrays with a different number of elements in each row. Special care must be taken to ensure that you do not index an element that does not exist. 7.4. Other Collections Aside from basic arrays, many languages have rich libraries of other dynamic collections. Dynamic collections are not the same thing as dynamically allocated arrays. Once an array is created, its size is fixed and cannot, in general, be changed. However, dynamic collections can grow (and shrink) as needed when you add or remove elements from them. Lists are ordered collections that are essentially dynamic arrays. Lists are ordered and are usually zero-indexed just like arrays. Lists are generally objects and provide methods that can be used to add, remove, and retrieve elements from the list. If you add an element to a list, the list will automatically grow to accommodate it, so its size is not fixed when created. Two common implementations of lists are array-based lists and linked lists. Array-based lists indexarray-based list use an array to store elements. When the array fills up, the list allocates a new, larger array to hold more elements, copying the original contents over to the new array with a larger capacity. Linked lists hold elements in nodes that are linked together. Adding a new element simply involves creating a new node and linking it to the last element in the list. Some languages also define what are called sets. Sets allow you to store elements dynamically just like lists, but sets are generally unordered. There is no concept of a first, second, or last element in a set. Iterating over the elements in a set could result in a different enumeration of the elements each time. Elements in sets are also usually unique. For example, a set containing integers would only ever contain one instance of 167
ComputerScienceOne_Page_201_Chunk1751
7. Arrays, Collections & Dynamic Memory each integer. The value 10, for example, would only ever appear once. If you added 10 to a set that already contained it, the operation would have no effect on the set. Another type of dynamic array are associative arrays (sometimes called dictionaries). An associative array holds elements, but may not be restricted in how they are indexed. In particular, a language that supports associative arrays may allow you to use integers or strings as indices, or even any arbitrary object. Further, when using integers to index elements, indices need not be fully defined nor contiguous. In an associative array you could define an element at index 5 and then place the next element at index 10, skipping index 6 through 9 which would remain undefined. One way to look at associative arrays is as a map. A map is a data structure that stores elements as key-value pairs. Both they keys and values could be any arbitrary type (integers or strings) or object depending on the language. You could map account numbers (stored as strings) to account objects, or vice versa. Using a smart data structure like a map can make data manipulation a lot easier and more straightforward. 7.5. Exercises Exercise 7.1. Write a function to return the index of the maximum element in an array of numbers. Exercise 7.2. Write a function to return the index of the minimum element in an array of numbers. Exercise 7.3. Write a function to compute the mean (average) of an array of numbers. Exercise 7.4. Write a function to compute the standard deviation of an array of numbers, σ = v u u t 1 N N X i=1 (xi −µ)2 where µ is the mean of the array of numbers. Exercise 7.5. Write a function that takes two arrays of numbers that are sorted and merges them into one array (retuning a new array as a result). Exercise 7.6. Write a function that takes an integer n and produces a new array of size n filled with 1s. Exercise 7.7. Write a function that takes an array of numbers are computes returns the median element. The median is defined as follows: • If n is odd, the median is the n+1 2 -th largest element 168
ComputerScienceOne_Page_202_Chunk1752
7.5. Exercises • If n is even, the median is the average of the n 2 and the (n 2 + 1)-th largest elements Exercise 7.8. The dot product of two arrays (or vectors) of the same dimension is defined as the sum of the product of each of their entries. That is, n X i=1 ai × bi Write a function to compute the dot product of two arrays (you may assume that they are of the same dimension) Exercise 7.9. The norm of an n-dimensional vector, ⃗x = (x1, x2, . . . , xn) captures the notion of “distance” in a higher dimensional space and is defined as ∥⃗x∥= q x2 1 + · · · + x2 n Write a function that takes an array of numbers that represents an n-dimensional vector and computes its norm. Exercise 7.10. Write a function that takes two arrays A, B and creates and returns a new array that is the concatenation of the two. That is, the new array will contain all elements a followed by all elements in b. Exercise 7.11. Write a function that takes an array of numbers A and an element x and returns true/false if A contains x Exercise 7.12. Write a function that takes an array of numbers A, an element x and two indices i, j and returns true/false if A contains x somewhere between index i and j. Exercise 7.13. Write a function that takes an array of numbers A and an element x and returns the multiplicity of x; that is the number of times x appears in A. Exercise 7.14. Write a function to compute a sliding window mean. That is, it computes the average of the first m numbers in the array. The next value is the average of the values index from 1 to m, then 2 to m + 1, etc. The last window is the average of the last m elements. Obviously, m ≤n (for m = n, this is the usual mean). Since there is more than one value, your function will return a (new) array of means of size n −m + 1. Exercise 7.15. Write a function to compute the mode of an array of numbers. The mode is the most common value that appears in the array. For example, if the array contained the elements 2, 9, 3, 4, 2, 1, 8, 9, 2, the mode would be 2 as it appears more than any other element. The mode may not be unique; multiple elements could appear the same, maximal number of times. Your function should simply return a mode. Exercise 7.16. Write a function to find all modes of an array. That is, it should find all modes in an array and return a new array containing all the mode values. 169
ComputerScienceOne_Page_203_Chunk1753
7. Arrays, Collections & Dynamic Memory Exercise 7.17. Write a function to filter out certain elements from an array. Specifically, the function will create a new array containing only elements that are greater than or equal to a certain threshold δ. Exercise 7.18. Write a function that takes an array of numbers and creates a new “deep” copy of the array. In addition, the function should take a new “size” parameter which will be the size of the copy. If the new size is less than the original, then the new array will be a truncated copy. If the new size is greater then the copy will be padded with zero values at the end. Exercise 7.19. Write a function that takes an array A and two indices i, j and returns a new array that is a subarray of A consisting of elements i through j. Exercise 7.20. Write a function that takes two arrays A, B and creates and returns a new array that represents the unique intersection of A and B. That is, an array that contains elements that are in both A and B. However, elements should not be included more than once. Exercise 7.21. Write a function that takes two arrays A, B and creates and returns a new array that represents the unique union of A and B. That is, an array that contains elements that are either in A or B (or both). However, elements should not be included more than once. Exercise 7.22. Write a function that takes an array of numbers and returns the sum of its elements. Exercise 7.23. Write a function that takes an array of numbers and two indices i, j and computes the sum of its elements between i and j inclusive. Exercise 7.24. Write a function that takes two arrays of numbers and determines if they are equal: that is, each index contains the same element. Exercise 7.25. Write a function that takes two arrays of numbers and determines if they both contain the same elements (though are not necessarily equal) regardless of their multiplicity. That is, the function should return true even if the arrays’ elements appear a different number of times or in a different order. For example [2, 2, 3] would be equal to an array containing [3, 2, 3, 3, 3, 2, 2, 2]. Exercise 7.26. A suffix array is a lexicographically sorted array of all suffixes of a string. Suffix arrays have many applications in text indexing, data compression algorithms and in bioinformatics. Write a program that takes a string and produces its suffix array. For example, the suffixes of science are science , cience , ience , ence , nce , ce , and e . The suffix array (sorted) would look something like the following. 170
ComputerScienceOne_Page_204_Chunk1754
7.5. Exercises ce cience e ence ience nce science Exercise 7.27. An array of size n represents a permutation if it contains all integers 0, 1, 2, . . . , (n−1) exactly once. Write a function to determine if an array is a permutation or not. Exercise 7.28. The k-th order statistic of an array is the k-th largest element. For our purposes, k starts at 0, thus the minimum element is the 0-th order statistic and the largest element is the n −1-th order statistic. Another way to view it is: suppose we were to sort the array, then the k-th order statistic would be the element at index k in the sorted array. Write a function to find the k-th order statistic. Exercise 7.29. Write a function that takes two n × n square matrices A, B and returns a new n × n matrix C which is the product, A × B. The product of two matrices of dimension n × n is defined as follows: cij = n X k=1 aikbkj Where 1 ≤i, j ≤n and cij is the (i, j)-th entry of the matrix C. Exercise 7.30. We can multiply a matrix by a single scalar value x by simply multiplying each entry in the matrix by x. Write a function that takes a matrix of numbers and an element x and performs scalar multiplication. Exercise 7.31. Write a function that takes two matrices and determines if they are equal (all of their elements are the same). Exercise 7.32. Write a function that takes a matrix and an index i and returns a new array that contains the elements in the i-th row of the matrix. Exercise 7.33. Write a function that takes a matrix and an index j and returns a new array that contains the elements in the j-th column of the matrix. Exercise 7.34. Iterated Matrix Multiplication is where you take a square matrix, A and multiply it by itself k times, Ak = A × A × · · · × A | {z } k times Write a function to compute the k-th power of a matrix A. 171
ComputerScienceOne_Page_205_Chunk1755
7. Arrays, Collections & Dynamic Memory Exercise 7.35. The transpose of a square matrix is an operation that “flips” the matrix along the diagonal from the upper left to the lower right. In particular the values mi,j and mj,i are swapped. Write a function to transpose a given matrix Exercise 7.36. Write a function that takes a matrix, a row index i, and a number x and adds x to each value in the i-th row. Exercise 7.37. Write a function that takes a matrix, a row index i, and a number x and multiples each value in the i-th row with x. Exercise 7.38. Write a function that takes a matrix, and two row indices i, j and swaps each value in row i with the value in row j Exercise 7.39. A special matrix that is often used is the identity matrix. The identity matrix is an n × n matrix with 1s on its diagonal and zeros everywhere else. Write a function that, given n, creates a new n × n identity matrix. Exercise 7.40. Write a function to convert a matrix of integers to floating point numbers. Exercise 7.41. Write a function to determine if a given matrix is a permutation matrix. A permutation matrix is a matrix that represents a permutation of the rows of an identity matrix. That is, A is a permutation matrix if every row and every column has exactly one 1 and the rest are zeros. Exercise 7.42. Write a function to determine if a given square matrix is symmetric. A matrix is symmetric if mi,j = mj,i for all i, j. Exercise 7.43. Write a function to compute the trace of a matrix. The trace of a matrix is the sum of its elements along its diagonal. Exercise 7.44. Write a function that returns a “resized” copy of a matrix. The function takes a matrix of size n × m (not necessarily square) and creates a copy that is p × q (p, q are part of the input to the function). If p < n and/or q < m, the values are “cut off”. If p > n and/or q > m, the matrix is padded (to the right and to the bottom) with zeros. Exercise 7.45. A submatrix is a matrix formed by selecting certain rows and columns from a larger matrix. Write a function that constructs a submatrix from a larger matrix. To do so, the function will take a matrix as well as two row indices i, j and two column indices k, ℓand it will return a new matrix which consists of entries from the i-th row through the j-th row and k-th column through the ℓ-th column. For example, if A is A =   8 2 4 1 10 4 2 3 12 42 1 0  . then a call to this function with i = 1, j = 2, k = 2, ℓ= 3) should result in A = 2 3 1 0  . 172
ComputerScienceOne_Page_206_Chunk1756
7.5. Exercises Exercise 7.46. The Kronecker product (http://en.wikipedia.org/wiki/Kronecker_ product) is a matrix operation on two matrices that produces a larger block matrix. Specifically, if A is an m × n matrix and B is a p × q matrix, then the Kronecker product A ⊗B is the mp × nq block matrix: A ⊗B =   a11B · · · a1nB ... ... ... am1B · · · amnB   more explicitly: A ⊗B =   a11b11 a11b12 · · · a11b1q · · · · · · a1nb11 a1nb12 · · · a1nb1q a11b21 a11b22 · · · a11b2q · · · · · · a1nb21 a1nb22 · · · a1nb2q ... ... ... ... ... ... ... ... a11bp1 a11bp2 · · · a11bpq · · · · · · a1nbp1 a1nbp2 · · · a1nbpq ... ... ... ... ... ... ... ... ... ... ... ... ... ... am1b11 am1b12 · · · am1b1q · · · · · · amnb11 amnb12 · · · amnb1q am1b21 am1b22 · · · am1b2q · · · · · · amnb21 amnb22 · · · amnb2q ... ... ... ... ... ... ... ... am1bp1 am1bp2 · · · am1bpq · · · · · · amnbp1 amnbp2 · · · amnbpq   . Write a function that computes the Kronecker product. Exercise 7.47. The Hadamard product is an entry-wise product of two matrices of equal size. Let A, B be two n × m matrices, then the Hadamard product is defined as follows. A◦B =      a11 a12 · · · a1m a21 a22 · · · a2m ... ... ... ... an1 an2 · · · anm     ◦      b11 b12 · · · b1m b21 b22 · · · b2m ... ... ... ... bn1 bn2 · · · bnm     =      a11b11 a12b12 · · · a1mb1m a21b21 a22b22 · · · a2mb2m ... ... ... ... an1bn1 an2bn2 · · · anmbnm      Write a function to compute the Hadamard product of two n × m matrices. 173
ComputerScienceOne_Page_207_Chunk1757
7. Arrays, Collections & Dynamic Memory Stack Frame Variable Address Content ... ... b[4] 0x5c44cb76 25 b[3] 0x5c44cb72 20 b[2] 0x5c44cb68 15 b[1] 0x5c44cb64 10 b[0] 0x5c44cb60 5 i 0x5c44cb56 5 foo n 0x5c44cb52 5 ... ... a 0x5c44cb34 NULL m 0x5c44cb30 5 main i 0x5c44cb26 0 (a) Program stack at the end of the execution of foo() prior to returning control back to main() . Stack Frame Variable Address Content ... ... b[4] 0x5c44cb76 -626679356 b[3] 0x5c44cb72 20 b[2] 0x5c44cb68 15 b[1] 0x5c44cb64 32767 b[0] 0x5c44cb60 1564158624 i 0x5c44cb56 5 foo n 0x5c44cb52 5 ... ... a 0x5c44cb34 0x5c44cb60 m 0x5c44cb30 5 main i 0x5c44cb26 0 (b) Upon returning, the stack frame is no longer valid; the pointer variable a points to a stack memory address but the frame and its local variables are no longer valid. Some have been overwritten with other values. Subsequent usage or access of the values in a are undefined behavior. Figure 7.3.: Illustration of the pitfalls of returning a static array in C. Static arrays are locally scoped and exist only within the function/block in which they are declared. The program stack frame in which the variables are stored is invalid when the function returns control back to the calling function. Depending on how the system/compiler/language handles this unwinding process, values may be changed, unavailable, etc. 174
ComputerScienceOne_Page_208_Chunk1758
7.5. Exercises Program Code Static Content Allocated Stack Available Stack Available Heap Allocated Heap Stack Growth Heap Growth Figure 7.4.: Depiction of Application Memory. The details of how application memory is allocated and how the stack/heap “grow” may vary depending on the architecture. The figure shows stack memory growing “upward” while heap allocation grows “downward.” Allocation and deallocation may fragment the heap space though. 175
ComputerScienceOne_Page_209_Chunk1759
7. Arrays, Collections & Dynamic Memory A B 2 0 3 1 5 2 7 3 11 4 13 5 17 6 19 7 23 8 29 9 (a) A shallow copy. B refers to A which refers to the array. Thus, B implicitly refers to the same array. A B 2 0 3 1 5 2 7 3 11 4 13 5 -1 6 19 7 23 8 29 9 (b) When an element in a shallow copy is changed, A[6] = -1; , it is changed from the perspective of both A and B. A B 2 0 3 1 5 2 7 3 11 4 13 5 17 6 19 7 23 8 29 9 2 0 3 1 5 2 7 3 11 4 13 5 17 6 19 7 23 8 29 9 (c) A deep copy. B refers to its own copy of the array distinct from A. Both are stored in separate memory locations. A B 2 0 3 1 5 2 7 3 11 4 13 5 -1 6 19 7 23 8 29 9 2 0 3 1 5 2 7 3 11 4 13 5 17 6 19 7 23 8 29 9 (d) When an element in a deep copy is changed, A[6] = -1; , it is changed only in the array A. The element in B is unaffected. Figure 7.5.: Shallow copies are when two references refer to the same data in memory (a) and (b). Changes to one affect the other. Deep copies (c) and (d) are distinct data in memory, changes to one do not affect the other. 176
ComputerScienceOne_Page_210_Chunk1760
8. Strings A string is an ordered sequence of characters. We’ve previously seen string data types as literals. Most languages allow you to define and use static string literals using the double quote syntax. We used strings to specify output formatting using printf() -style functions for example. When reading input from a user, we read it as a string and converted the input to numbers. We also described some basic operations on strings including concatenation. We now examine strings in more depth. Programming languages vary greatly in how they represent string data types. Some languages have string types built-in to the language and others require that you use arrays and yet others treat strings as a special type of object. One issue with string representations is determining where and how the string ends. Some languages use a length prefix string representation. The length (the number characters in the string) is stored in a special location at the beginning of a string. Then the string characters are stored as an array. Other Object-Oriented Programming (OOP) languages use a special character, the null-terminating character to denote the end of a string. Still other languages store strings as arrays or dynamic arrays and the “bookkeeping” is done internally as part of an object representation. Other details vary as well. Most languages support the basic ASCII characters, others have full Unicode support or support Unicode through a library. Most languages also provide large libraries of functions and operations that make working with strings easier. 8.1. Basic Operations Depending on how a language supports strings, it may support various basic operations to create strings and assign them to variables. Usually languages allow you to create and use string literals using the double quote syntax. Modifying a string or copying one string into another may be supported by the built-in assignment operator or it may require the use of a copy function. When copying strings, similar issues come into play as with arrays. The “copy” could be a shallow copy or a deep copy (see Section 7.2.2). Other basic operations may include accessing and/or modifying individual characters in a string. In order to do so, we may also need to know a string’s length (so that we do not access invalid characters). A language could provide this as part of the string 177
ComputerScienceOne_Page_211_Chunk1761
8. Strings itself (usually called a property of the string) or through a function call. We can further use such functionality to iterate over the individual characters in a string using an index-controlled for-loop. More advanced operations on strings include concatenation which is the operation of combining one or more strings to create a new string. Concatenation simply appends one string to the end of another string. Another common operation is to extract a substring from a string, that is create a new string from a portion of another string. Commonly, this is done via some standard function that may operate by specifying indices and/or the length of the desired substring. Finally, it is also common to deal with collections of strings. Some languages allow you to create arrays of strings or dynamic collections (lists or sets) of strings. for languages in which strings are arrays of characters, an array of strings might be implemented with a 2-dimensional array of characters. 8.2. Comparisons When processing strings there are several other standard operations. In particular, we often have need to make comparisons between two string variables or between a string variable and a literal. Some languages allow you to use the same operators such as == or even < to make comparisons between strings. The implied behavior would compare strings for equality (case sensitive) or for lexicographic order. For example “Apple” < “Banana” might evaluate to true because “Apple” precedes “Banana” in alphabetic order. Many languages, however, require that you make string comparisons using a function. Using the equality operator == may be correct syntactically, but is usually making a pointer or reference comparison which evaluates to true if and only if the two variables represent the same memory address. Even if two string variables have the same content, the equality operator may evaluate to false if they are distinct (deep) copies of the same string. Likewise, the inequality operators <, ≤, etc. may only be comparing memory addresses which is meaningless for comparing strings. The solution that many languages provide is the use of a comparator, which is either a function or an object that facilitates the comparison of strings (and more generally, any object). Generally, a comparator function takes two arguments, a, b and compares them, not just for equality, but for their relative order: does a “come before” b or does b “come before” a, or are they equal. To distinguish between these three cases, a comparator returns an integer value with the following general contract: it returns • Something negative if a < b • Zero if a = b • Something positive if a > b 178
ComputerScienceOne_Page_212_Chunk1762
8.3. Tokenizing Using this contract we can determine the relative ordering of any two strings. In general we cannot make any assumptions about the actual value that a comparator returns, only that it returns something negative or positive. The actual magnitude of the returned value need not be −1 or +1, and it may not even have any predefined meaning. 8.3. Tokenizing It is common to store different pieces of data as a string such that each individual piece of data is demarcated by some delimiter. For example, Comma Separated Values (CSV) or Tab Separated Values (TSV) data use commas and tabs to delimit data. For example, the string Smith,Joe,12345678,1985-09-08 is a CSV string holding data about a particular person (last name, first name, ID, date of birth). Often we need to process such strings to extract each individual piece of data. Processing such strings is usually referred to as parsing. In particular, a string is “split” into a collection of individual strings called tokens (thus the process is also sometimes referred to as tokenizing). In the example above, the string would be processed into 4 individual strings, Smith , Joe , 12345678 , and 1985-09-08 . Each string could further be tokenized if needed, such as parsing the date of birth to extract the year, month, and date. Most languages provide a function to facilitate tokenization. Some do so by directly returning an array or collection of the resulting tokens (usually with the delimiter removed). Others have a more manual process that requires a loop structure to iterate over each token. 8.4. Exercises Exercise 8.1. Write functions to reverse a string. If appropriate, write versions to do so by manipulating a given string and returning a new string that is a reversed copy. Exercise 8.2. Write a function to replace all spaces in a string with two spaces. Exercise 8.3. Write a program to take a phrase (International Business Machines) and “acronymize” it by producing a string that is an upper-cased string of the first letter of each word in the phrase (IBM). Exercise 8.4. Write a function that takes a string containing a word and returns a pluralized version according to the following rules. 179
ComputerScienceOne_Page_213_Chunk1763
8. Strings 1. If the noun ends in “y,” remove the “y” and add “ies” 2. If the noun ends in “s,” “ch,” or “sh,” add “es” 3. In all other cases, just add “s” Exercise 8.5. Write a function that takes a string and determines if it is a palindrome or not. A palindrome is a word that is spelled exactly the same when the letters are reversed. Exercise 8.6. Write a function to compute the longest common prefix of two strings. For example, the longest common prefix of “global” and “glossary” is “glo”. If two strings have no common prefix, then the longest common prefix is the empty string. Exercise 8.7. Write a function to remove any whitespace from a given string. For exam- ple, if the string passed to the function contains "Hello World How are you? " then it should result in the string "HelloWorldHowareyou?" Exercise 8.8. Write a function that takes a string and flips the case of each alphabetic character in it. For example, if the input string is "GNU Image Processing Tool-Kit" then it should output "gnu iMAGE pROCESSING tOOL-kIT" Exercise 8.9. Write a function to validate a variable name according to the rules that it must begin with an alphabetic character, a–z or A–Z but may contain any alphanumeric character a–z, A–Z, 0–9, or underscores _ . Your function should take a string with a possible variable name and return true or false depending on whether or not it is valid. Exercise 8.10. Write a function to convert a string that represents a variable name using under_score_casing to lowerCamelCasing . That is, it should remove all underscores, and replace the first letter of each word with an uppercase (except the first word). Exercise 8.11. Write a function that takes a string and another character c and counts the number of times that c appears in the string. Exercise 8.12. Write a function that takes a string and another character c and removes all instances of c from the string. For example, a call to this function on the string "Hello World" with c being equal to 'o' would result in the string "Hell Wrld" . Exercise 8.13. Write a function that takes a string and two characters, c and d and replaces all instances of c with d. Exercise 8.14. Write a function to determine if a given string s contains a substring t. The function should return true if t appears anywhere inside s and false otherwise. Exercise 8.15. Write a function that takes a string s and returns a new string that contains the first character of each word in s capitalized. You may assume that words are separated by a single space. For example, if we call this function with the string "International Business Machines" it should return "IBM" . If we call it with the string "Flint Lockwood Diatonic Super Mutating Dynamic Food Replicator" it should return "FLDSMDFR" 180
ComputerScienceOne_Page_214_Chunk1764
8.4. Exercises Exercise 8.16. Write a function that trims leading and trailing white space from a string. Inner whitespace should not be modified. Exercise 8.17. Write a function that splits a string containing a unix path/file into its three components: the directory path, the file base name and the file extension. For example, if the input string is /usr/home/message.txt then the three components would be /usr/home/ , message and txt respectively. For the purposes of this function, you may assume that the path ends with the last forward slash (or is empty if none) and that the extension is always after the last period. That is, you should be able to handle inputs such as ../foo/bar/baz.old.txt . Exercise 8.18. Write a function that (re)formats a string representing a telephone number. Phone numbers can be written using a variety of formats, for example 1-402-555-1234 or +4025551234 or 402 555-1234 , etc. Assume that you will only deal with 10 digit US phone numbers. Create a new string that uses the “standard” format of (402) 555-1234 . Exercise 8.19. Write a function that takes a string and splits it up to an array of strings. The split will be length-based: the function will also take an integer n and will split the given string up into strings of length n. It is possible that the last string will not be of length n. For example, if we pass "Hello World, how are you?" with n = 3 then it should return an array of size 9 containing the strings "Hel" , "lo " , "Wor" , "ld," , " ho" , "w a" , "re " , "you" , "?" Exercise 8.20. HyperText Markup Language (HTML) (Hypertext Markup Language) is the primary document description language for the World Wide Web (WWW). Certain characters are not rendered in browsers as they are special characters used in HTML; in particular tags which begin and end with the < and > . To display such characters correctly they need to be escaped (similar to how you need to escape tabs \t and endline \n characters). Properly escaping these characters is not only important for proper rendering, but there are also security issues involved (Cross-Site Scripting Attacks). Write a function that takes a string and escapes the HTML characters in Table 8.1. Replace the following with this & &amp; < &lt; > &gt; " &quot; Table 8.1.: Replacement HTML Characters 181
ComputerScienceOne_Page_215_Chunk1765
9. File Input/Output A file is a block of data used for storing information. Normally, we think of a file as something that is stored on a hard drive (or memory stick or other physical media), but the concept of a file is much more general. For example, when a file is loaded (“read”) by a program it then exists in main memory. An executable program itself is a file (containing instructions to be executed), both stored on the hard drive and run in memory. In a typical unix-based system, everything is a file. Directories are files, executables are files, devices are files, etc. Even the familiar standard input and standard output are buffers that are treated as files that can be read from or written to. Data files may be stored as binary data or as plaintext files. Plaintext files are still stored as binary data, but are stored in an encoding using the ASCII text values. Binary files will also have structure, but it depends on the application that produced the file to give meaning to the data. For example, an image file in a Joint Photographic Experts Group (JPEG) format is essentially just binary data but it has a very specific format that an image viewer would be able to process, but, say, a text editor would not. Further, if the binary format is corrupted, the image viewer might not be able to display the image correctly Typical programs are short lived, anywhere from a few milliseconds to maybe a user “session.” We often want data to be saved across multiple runs of a program. We need to save it or persist it in some durable storage medium (disk). Files provide a way to achieve data persistence. 9.1. Processing Files In general, processing data in a file involves three basic steps: 1. Open (or create) the file 2. Read from (or write to) the file 3. Close the file 183
ComputerScienceOne_Page_217_Chunk1766
9. File Input/Output Depending on the language, the act of opening a file may determine if it will be read from or written to. When read from, the file is referred to as an input file while a file that is written to is an output file. Languages may also have different a different API or functions to read/write or append to a file. A file may be read line by line until the end of the end of the file has been reached. Languages usually support this by using a special End Of File (EOF) flag or value to indicate the end of a file has been reached. A file is a resource just like memory and we need to properly manage it. We need to make sure that we close a file once we are finished processing it. Depending on the language and other factors such as the operating system, failure to close a file may result in corrupted data. Though a file may be closed automatically for us when the program terminates, its still best practice to properly close it. 9.1.1. Paths When opening a file on a file system, it is necessary to specify which file you want to open. This is typically done by specifying at least the name of the file. Often files will have “extensions” which indicate the type of file it is such as .txt for text files or .html for HTML files. However, file extensions are only for organizational purposes and have no real bearing on what data is stored in the file. More important is the path of the file. Usually, if no path is specified, then implicitly we are opening the file in the Current Working Directory (CWD). For example, if we open the file data.txt then we are opening the file in the same directory in which our program is executing. When specifying a path we can either specify an absolute path or a relative path. An absolute path specifies each and every subdirectory in the file system from the root to the directory that the file is located in. The root directory is the top-most directory in the file system. Each subdirectory is separated by some delimiter. Windows systems use a backslash as a directory delimiter while the root directory is specified using a “volume” name such as C:\ . For example, an absolute path on a Windows system may look something like: C:\applications\users\data\data.txt On a Unix-based system, a forward slash is used as a directory delimiter and the root directory is simply a single forward slash. The same directory structure in a Unix-based system would look like the following. /applications/users/data/data.txt A path may also be relative to the current working directory. In most systems (Windows and Unix-based) the current directory is denoted using a single period, . . You can use 184
ComputerScienceOne_Page_218_Chunk1767
9.1. Processing Files this to specify directories deeper in the directory tree from the current directory. For example (in Unix), ./app/data/data.txt would refer to the directory app in the current working directory, the directory data within that, and finally the file data.txt within that directory. We can also refer to files further up the directory tree using the “parent” directory symbol which is two periods, .. . For example, ../../system/data.txt would refer to a file two levels up in the subdirectory system . 9.1.2. Error Handling When dealing with files there are many potential error conditions that may be anticipated and may need to be dealt with. Some types of errors that can occur include the following. • Permission errors – Your program may not have the proper permissions to read or write to a particular directory or file. For example, user-level processes typically do not have permissions to read system-level files (such as password files) nor can they write to them lest they corrupt critical system data. • File Not Found errors – Your program may attempt to open a file that does not exist. Sometimes, particularly when writing, the file will be created if it does not exist. However, for reading, this may be a serious error. • I/O Errors – We may be able to successfully find and open a file, but while processing it something might go wrong with the file system that results in a general input/output error. • Formatting errors – As previously mentioned, the format of a file is highly dependent on the application that created it (though there are universal data formats such as XML or JavaScript Object Notation (JSON)). If the format is not as expected the file may be corrupted and the program may not be able to successfully read data from it. Depending on the language, these errors may be fatal or may result in error codes or error values that can be dealt with. Or they may result in exceptions that can be caught and handled. 185
ComputerScienceOne_Page_219_Chunk1768
9. File Input/Output /proc/self/ |-- attr |-- cwd -> /proc |-- fd | `-- 3 -> /proc/15589/fd |-- fdinfo |-- net | |-- dev_snmp6 | |-- netfilter | |-- rpc | | |-- auth.rpcsec.context | | |-- auth.rpcsec.init | | |-- auth.unix.gid | | |-- auth.unix.ip | | |-- nfs4.idtoname | | |-- nfs4.nametoid | | |-- nfsd.export | | `-- nfsd.fh | `-- stat |-- root -> / `-- task `-- 15589 |-- attr |-- cwd -> /proc |-- fd | `-- 3 -> /proc/15589/task/15589/fd |-- fdinfo `-- root -> / Figure 9.1.: The Linux file system (like most file systems), defines a tree directory structure. Each file and directory is contained in subdirectories all contained within the root directory, / . This diagram was generated by the Tree command, http://mama.indstate.edu/users/ice/tree/. 186
ComputerScienceOne_Page_220_Chunk1769
9.1. Processing Files 9.1.3. Buffered and Unbuffered When processing files the input/output may be either buffered or unbuffered. A buffered input or output “stream” is one in which data that is read/written is actually stored in memory in a “buffer” until such a time as the buffer is “flushed” and the accumulated data is passed to/from the actual file. For example, in a buffered output file, our program could write several kilobytes of data to the output file, but it might not actually be written to the file right away. Instead, those kilobytes of data are stored in memory until the buffer fills up or some other event takes place to cause the buffer to be flushed. At that point, the data stored in the buffer is emptied and written to the file. Buffered input/output is used because I/O operations are expensive in terms of system resources and can slow the system down. Because of this, it is better to keep I/O operations as infrequent as possible. Buffers help to reduce the number of I/O operations performed by a program by making them less frequent. There are some instances in which we want unbuffered I/O. When error messages are written to the standard error output for example, we would prefer to know about errors as soon as possible rather than waiting for error messages to accumulate in a buffer. Using an unbuffered output means that data is written to the standard error (which is a file) immediately. However, because errors are (hopefully) infrequent and (likely) fatal, this is not a performance issue. 9.1.4. Binary vs Text Files As previously mentioned, files can be stored as pure binary data or as plaintext (ASCII). Depending on our application and the nature of the data being written to files, the choice of which to use may be clear. If we want the data in our files to be human-readable, then we need to store them as plaintext. However, in general, we should prefer storing data in a binary format. The reason for this is that binary generally requires less space and is more efficient to process. Consider as an example, storing a collection of integers in a file. Each integer requires 4 bytes when represented in binary. However, when represented as a string, it requires as many bytes as there are digits in the number. For example, the maximum representable value of such an integer would be 231 −1 = 2, 147, 483, 647, requiring 10 ASCII characters and thus 10 bytes to represent, two and a half times as much memory as with the binary representation. Further, if a lot of numbers are stored, each number (as a string) would need to be delimited by yet another character. With a binary representation, no delimiter would be necessary as we would know that each 4 byte block represents a single number. This disparity can be even more stark with other types such as floating-point numbers. 187
ComputerScienceOne_Page_221_Chunk1770
9. File Input/Output There are additional performance issues when reading/writing the data and converting binary numbers to their string representations. With binary data no such parsing is necessary. As long as the data does not need to be human-readable, binary formats should be preferred. 9.2. Exercises Exercise 9.1. Write a function that takes a string representing a file name and opens and processes the file, returning all of its contents as a single string. Exercise 9.2. Consider an irregular, 2-D simple polygon with n points, (x1, y1), (x2, y2), . . . , (xn, yn) The area A of the polygon can be computed as A = 1 2 n−1 X i=0 (xiyi+1 −xi+1yi) Note, that the initial and end point will be the same, (x0, y0) = (xn, yn). An example polygon for n = 5 can be found in Figure 9.2. Figure 9.2.: An example polygon for n = 5 Write a program to open and process a text file containing n coordinates. In particular, the first line is a single integer n that indicates how many points should be read in. Each line after that has the x, y coordinates of each point separated by a single space. 4 1.0 0.0 13.2 1.25 20.5 18.4 16.37 24.54 188
ComputerScienceOne_Page_222_Chunk1771
9.2. Exercises After reading the file in, it will compute the area of the polygon according to the formula above and output it to the user. For example, the output for the above file may be something like Area of the polygon: 197.9135 Exercise 9.3. Write a program that processes an input text file and scrubs it of any HTML characters that need to be escaped (see Exercise 8.20 for details). It should produce a new output file with all special characters escaped. Exercise 9.4. Write a program that spell checks a plain text file. The program will open a text file and process each word separately, checking for proper spelling against a standard dictionary. You may assume that each word is separated by some whitespace (you may assume that there are no multi-line hyphenated words). However, you should ignore all punctuation (periods, question marks, etc.). Use a standard American dictionary provided on your unix system which stores words one per line. Your output should include all misspelled or unrecognized words (words not contained in the dictionary file). Exercise 9.5. A standard word search consists of an n × n grid in which there are a number of words hidden, some intersecting, with dummy letters filling in the blanks. An example is provided in Figure 9.3. Figure 9.3.: A Word Search Write a program to solve a word search. Your program will read in an input file with the following format: the first line will contain a single integer n which is followed by n lines with n characters (not including the end line character) corresponding to the word search. Once you read in the word search, you will iterate through all possible words running down, right, or diagonally down-right. You will attempt to match each possibility against a standard English dictionary. If the word matches a word in the dictionary, output it to the standard output, otherwise ignore it. To simplify, you may restrict your attention to words that have a length between 3 and 8 (inclusive). 189
ComputerScienceOne_Page_223_Chunk1772
9. File Input/Output Exercise 9.6. Write a crossword puzzle cheater. The program will take, as input, a “partial” word in a crossword puzzle. That is, some of the letters are known (from other solved clues) while some of the letters are not known. For the purposes of this exercise, we’ll use a hyphen as a placeholder for missing letters. Your program will match the partial word against words in a standard English dictionary and list all possible matches. For example, if the user provided foo- as input it might match food , fool , and foot . Exercise 9.7. Bridge is a four player (2 team) game played with a standard 52-card deck. Prior to play, a round of bidding is performed to determine which team is playing for or against the contract, the trump suit, and at what level. Understanding the rules of the game or the bidding conventions involved are not necessary for this exercise. Instead, write a program to assist players in how they should bid based on the following point system. A standard 52-card deck is dealt evenly to 4 different hands (Players 1 thru 4, 13 cards each). Each player’s hand is worth a number of points based on the following rules: • Each Ace in the hand is worth 4 points • Each King is worth 3 • Each Queen is worth 2 • Each Jack is worth 1 • For each suit (Diamond, Spade, Club, Heart) such that the hand has only 2 cards (a “doubleton”) an additional point is added • For each suit that the hand has only 1 card in (a “singleton”) two additional points are added • For each suit that the hand has no cards (a “void”) 3 additional points are added. Write a program that reads in a text file containing a deal. The formatting is as follows: the input file will have 4 lines, one for each player. Each line contains the cards dealt to that player delimited by a single space. The cards are indicated by the rank (A, K, Q, J, 10, 9, . . . , 2) and the suit (D, S, C, H). An example: 3C 3D 7S QD KC AS 6S AC JS 4S JD 7H 6D 5D 8C 7D AH 3H QC 8D JH 5H 9D 7C 9C 4D 2H 10D 8H KS QH 4C 10S 9S 6H 8S KD AD QS 2D 10C 6C 2C 10H 4H 2S 3S 5C 9H KH JC 5S 190
ComputerScienceOne_Page_224_Chunk1773
9.2. Exercises Your program should process the file and output the total number of points each hand represents. You should not make any assumptions about the ordering of the input. Hand 1 Points: 17 Hand 2 Points: 10 Hand 3 Points: 16 Hand 4 Points: 6 Exercise 9.8. The game of Sudoku is played on a 9 × 9 grid in which entries consist of the numbers 1 thru 9. Initially, the board is presented with some values filled in and others blank. The player has to fill in the remaining values until all grid boxes are filled and the following constraints are satisfied. • In each of the 9 rows, each number, 1–9 must appear exactly once • In each of the 9 columns, each number 1–9 must appear exactly once • In each of the 3 × 3 sub-grids, each number 1–9 must appear exactly once A full example is presented in Figure 9.4. Figure 9.4.: A solved Sudoku puzzle Write a program that processes a text file containing a possible sudoku solution and determine if it is a valid or invalid solution. The file will have the following format: it will contain 9 lines with 9 numbers on each line delimited by a single space. If the input represents a valid solution, output ”Valid Solution”, otherwise output at least one reason why the input is not a valid solution. Exercise 9.9. Write a program that parses and processes a data file containing Comma Separated Values (CSV) and produce an equivalent JSON (JavaScript Object Notation) output file containing the same data. 191
ComputerScienceOne_Page_225_Chunk1774
9. File Input/Output The input file will have the following format. The first line is a CSV list of column names. Each subsequent line is an individual record with values for each column. The number of columns and rows may vary from file to file. The following is an example containing data about students, which has four columns and 3 records. lastName,firstName,NUID,GPA Castro,Starlin,11223344,3.48 Rizzo,Anthony,55667788,3.95 Bryant,Chris,01234567,2.7 The output file will be formatted in JSON where each “object” (record) is denoted with opening and closing curly brackets, each record is separated by a comma, and all records are enclosed in square brackets (putting them in an array). For each record, each value is denoted with a key (the column name) and a value. For this exercise, treat all values as strings even if they are numbers. For example, the input file above would be formatted as follows. 1 [ 2 { 3 "lastName": "Castro", 4 "firstName": "Starlin", 5 "NUID": "11223344", 6 "GPA": "3.48" 7 }, 8 { 9 "lastName": "Rizzo", 10 "firstName": "Anthony", 11 "NUID": "55667788", 12 "GPA": "3.95" 13 }, 14 { 15 "lastName": "Bryant", 16 "firstName": "Chris", 17 "NUID": "01234567", 18 "GPA": "2.7" 19 } 20 ] Exercise 9.10. Ranked voting elections are elections where each voter ranks each candidate rather than just voting for a single candidate. If there are n candidates, then 192
ComputerScienceOne_Page_226_Chunk1775
9.2. Exercises each voter will rank them 1 (best) through n (worst). Usually, the winner of such an election is determined by a Condorcet method (the candidate that would win in by a majority in all head-to-head contests). However, we’ll use an alternative method, a Borda count. In a Borda count, points are awarded to each candidate for each ballot. For every number 1 ranking, a candidate receives n points, for every 2 ranking, a candidate gets n −1 points, and so on. For a rank of n, the candidate only receives 1 point. The candidates are then ordered by their total points and the one with the highest point count wins the election. Such a system usually leads to a “consensus” candidate rather than one preferred by a majority. Implement a Borda-count based ranked voting program. Your program will read in a file in the following format. The first line will contain an ordered list of candidates delimited by commas. Each line after that will represent a single ballot’s ranking of the candidates and will contain comma delimited integers 1 through n. The order of the rankings will correspond to the order of the candidates on the first line. Your program will take an input file name as a command line argument, open the file and process it. It will then report the results including the point total for each candidate (in order) as well as the overall winner. It will also report the total number of ballots. You may assume each ballot is valid and all rankings are provided. An example input: Alice,Bob,Charlie,Deb 2,1,4,3 3,4,2,1 4,2,3,1 3,2,1,4 3,1,4,2 An example output: Election Results Number of ballots: 5 Candidate Points Bob 15 Deb 14 Charlie 11 Alice 10 193
ComputerScienceOne_Page_227_Chunk1776
9. File Input/Output Winner is Bob Exercise 9.11. A DNA sequence is a sequence of some combination of the characters A (adenine), C (cytosine), G (guanine), and T (thymine) which correspond to the four nucleobases that make up DNA. Given a long DNA sequence, its often useful to compute the frequency of n-grams. An n-gram is a DNA subsequence of length n. Since there are four bases, there are 4n possible n-grams. Write a program that processes a DNA sequence from a plaintext file and, given n, computes the relative frequency of each n-gram as it appears in the sequence. As an example, consider the sequence in Figure 9.5. GGAAGTAGCAGGCCGCATGCTTGGAGGTAAAGTTCATGGTTCCCTGGCCC Figure 9.5.: A DNA Sequence To compute the frequency of all n = 2 n-grams, we would consider all 16 combinations of length-two DNA sequences. We would then go through the sequence and count up the number of times each 2-gram appears. We then compute the relative frequency (note: if a sequence is length L, then the total number of n-grams in it is L −(n −1)). The relative frequency of each such 2-gram is calculated below. AA 6.1224% AC 0.0000% AG 10.2041% AT 4.0816% CA 6.1224% CC 10.2041% CG 2.0408% CT 4.0816% GA 4.0816% GC 10.2041% GG 12.2449% GT 8.1633% TA 4.0816% TC 4.0816% TG 8.1633% TT 6.1224% Exercise 9.12. Given a long DNA sequence, it is often useful to compute the number of instances of a certain subsequence. As an example, if we were to search for the 194
ComputerScienceOne_Page_228_Chunk1777
9.2. Exercises subsequence GTA in the DNA sequence in Figure 9.5, it appears twice. As another example, in the sequence CCCC , the subsequence CC appears three times. Write a program that processes a text file containing a DNA sequence and, given a subequence s, searches the DNA sequence and counts the number of times s appears. Exercise 9.13. Protein sequencing in an organism consists of a two step process. First the DNA is translated into RNA by replacing each thymine (T) nucleotide with uracil (U). Then, the RNA sequence is translated into a protein according to the following rules. The RNA sequence is processed 3 bases at a time. Each trigram is translated into a single amino acid according to known encoding rules. There are 20 such amino acids, each represented by a single letter in (A, C, D, E, F, G, H, I, K, L, M, N, P, Q, R, S, T, V, W, Y ). The rules for translating trigrams are presented in Figure 9.6. Each triple defines a protein, but we’re only interested in the first letter of each protein. Moreover, the trigrams UAA, UAG, and UGA are special markers that indicate a (premature) end to the protein sequencing (there may be additional nucleotides left in the RNA sequence, but they are ignored and the translation ends). Figure 9.6.: Codon Table for RNA to Protein Translation As an example, suppose we start with the DNA sequence AAATTCCGCGTACCC; it would be encoded into RNA as AAAUUCCGCGUACCC; and into an amino acid sequence KFRV P. Write a program that processes a file containing a DNA sequence and outputs the translated proteins (only the first letter of each protein) to an output file. 195
ComputerScienceOne_Page_229_Chunk1778
9. File Input/Output Exercise 9.14. Recently, researchers have successfully inserted two new artificial nucle- ases into simple bacteria that successfully reproduced the artificial bases through several generations. The artificial bases d5SICS and dNaM, (X and Y for short) mimic the natural G, and C nucleobases respectively. Write a program that takes a normal DNA sequence and replace some of its G, C pairs with X, Y respectively. DNA is translated into RNA which is then translated into 20 different amino acids. Each amino acid produced depends on a 3 nucleobase codon. For this exercise, we will change G, C pairs with X, Y pairs but only in codons that represent the amino acids Threonine (an essential amino acid) and Alanine (a non-essential amino acid). Table 9.1 contains the codons corresponding to these amino acids and the codons you should translate each one to. All other codons should not be modified. Your program should open and process a DNA sequence contained in a file and modify the DNA sequence as described above and output the artificial DNA sequence to a new output file. Amino Acid Codon Artificial Codon Threonine ACT AYT ACC AYY ACA AYA ACG AYX Alanine GCT XYT GCC XYY GCA XYA GCG XYX Table 9.1.: Amino Acid Codons 196
ComputerScienceOne_Page_230_Chunk1779
10. Encapsulation & Objects One reason we prefer to write programs in high-level programming languages is that we can use syntax that is closer to plain English. Though programming language syntax is a far cry from “natural” language, it is far closer than lower level languages such as assembly or binary machine code. However, from what we’ve seen so far, when writing programs we are still forced to utilize the primitive variable types built-in to the language we’re using, which is still quite limiting. As a motivating example, suppose we were to write a program that involved organizing the enrollment of students into courses. To model a particular student, we would need a collection of variables, say a first name, last name, GPA, and a unique identification number (likely a lot more, but let’s keep it simple). Each of these pieces of data could be modeled by strings, a floating-point number and perhaps an integer.1 Each of these pieces of data are stored in separate, unrelated variables even though they represent a single entity. Even worse, suppose that we needed to keep track of a collection of students. Each piece of data would need to be stored in a separate array. If we wanted to rearrange the data (say, sort it), we would need to do a lot of manual bookkeeping to make sure that the separate pieces of data that represented a single entity were all aligned at the same index in each of the arrays. If we wanted to pass the data around to functions, we’d be forced to pass multiple arrays to each function. This becomes all the more complex when we attempt to model entities with more pieces of data. The solution is to encapsulate the pieces of data into one logical entity, sometimes referred to as an object. More formally, encapsulation is a mechanism by which pieces of data can be grouped together along with the functions that operate on that data. Encapsulation may also provides a means to protect that data by controlling the visibility of that data from code outside the object. Contrast this with an array which is also a collection of data. However, an array usually contains pieces of similar data (all elements are integers or all elements are floating point numbers) while an object may collect pieces of dissimilar data that make up a larger entity. It is like the difference between rows and columns in a table. Consider the student data in Table 10.1. Each row represents a record while each column represents a 1Depending on the identification number, it may be more appropriately modeled with a string. Social Security Numbers for example are not purely numeric; they include dashes and may begin with zeros. 197
ComputerScienceOne_Page_231_Chunk1780
10. Encapsulation & Objects First Name Last Name ID GPA Tom Baker 74 3.75 Christopher Eccleston 5 3.5 David Tennant 10 4.0 Matt Smith 29 3.2 Peter Capaldi 13 2.9 Table 10.1.: Student Data collection of data from each record. A single column is comparable to an array while each row is comparable to an object. In this example, each object has four pieces of data encapsulated in it, a first name, last name, an ID, and a GPA. To represent this data in code without objects we would need at least 4 separate arrays, more if we wanted to model more data for a student. Moreover, data in separate arrays or collections have no real logical relationship to each other. The solution that most programming languages provide is allowing you to define an object or structure that collects pieces of data into one logical unit, allowing you to name the object (say “Student”) so that you can deal with the data in a more abstract way. With objects, we can treat each row in the table as a single, distinct entity allowing us to collect Student objects into a single array or collection rather than many separate ones. 10.1. Objects Though languages differ in how they support objects, they all have some commonalities. A language needs to provide ways to define objects, create instances of objects, and to use them in code. 10.1.1. Defining Most object oriented programming languages such as C++ and Java are class-based languages. Meaning that they allow you to define objects by declaring and defining a “class.” A class is essentially a blueprint for what the object is and how it is defined. Generally, a class declaration allows you to specify member variables and member methods which are part of the class. Further, full encapsulation is achieved by using visibility keywords such as public or private to either allow or restrict access to variables and methods from code outside the object. Non-object-oriented languages may not support full encapsulation. Instead they may allow you to define structures which support the grouping of data, but make it difficult 198
ComputerScienceOne_Page_232_Chunk1781
10.1. Objects or impossible to achieve the other two aspects of encapsulation (the grouping of methods that act on that data and the protection of data). In either case, a language allows you to define the member variables and to name the class or structure so that instances can be referred to by that type. Built-in types such as numbers or strings already have a type name defined by the language. However, an object is a user-defined type that is not built-in to the language. Once defined, however, the class or structure can be referred to just like any built-in variable type. It is not unusual to create objects that are made of other objects. For example, a student object may be defined by using two strings for its first and last name. In the language, a string may also be an object. As a more complex example, suppose that we wanted an additional member variable to model a student’s date of birth. A date may itself be an object as it consists of several pieces of information (a year, month, and date at least). When an object “owns” an instance of another object it is referred to as composition as the object is composed of other objects. Further, an object may consist of a collection of other objects (suppose that a student object owned an array of course objects representing their schedule). This is a form of composition known as aggregation (multiple objects have been aggregated by the object). 10.1.2. Creating Once a blueprint for an object (or structure) has been declared and defined, we need a way to create instances of the object. The concept of an “object” is general and abstract. It is more like the idea of a student. Only once we have created an entity that exists in memory do we have an actual instance of the class. Creating instances of an object is usually referred to as instantiation. Languages may be able to automatically create instances of your object with default values. After all, your object is likely composed of built-in types. The student example above for example could be modeled with two strings, an integer, and a floating point number. The language/compiler/interpreter “knows” how to deal with these built-in types, so it can extend that knowledge to create instances of your object which are essentially just collections of types that it already knows how to deal with. Object-oriented languages usually provide a special method for you to be able to specify the details of how to create an instance. These are called constructor methods. Sometimes you can define multiple constructors methods that take different number(s) of arguments and/or have different behavior. Constructor methods typically have special syntax or have the same name as the class. In other languages that do not fully support object-oriented programming, you must define utility functions that can be used to create instances of your object. Sometimes these are referred to as factory functions as they are responsible for “manufacturing” 199
ComputerScienceOne_Page_233_Chunk1782
10. Encapsulation & Objects instances of your object. 10.1.3. Using Objects After defining and creating an object, you can usually use it like any regular variable. In a strongly typed language you would declare a variable whose type matches the declared class or structure. The variable type can usually be passed and returned from functions, assigned to other variables, etc. A language also provides ways to access the member variables or methods that are visible to the outside world. Languages usually allow you to do this through the “dot operator” or the “arrow operator.” Suppose we have an instance of a student object stored in a variable s . To access the first name of this instance, we may be able to use either s.firstName or s->firstName . We can access and invoke visible methods likewise. The dot/arrow operators are how code outside the object interacts with the object. Outside code is able to do this because it holds a reference, s to the object. However, inside the object, we may not have a reference (the variable s was ostensibly declared and used outside the object and so is not in scope inside the object). However, we still have need to reference member variables or methods from inside the object. Many languages use open recursion , a mechanism by which we can write code so that an instance is able to refer to itself. Languages use keywords such as this or self or something similar. The keyword is essentially a self-reference to the object itself so that you can refer to “this” object from within the object. 10.2. Design Principles & Best Practices Using objects in your code follows more of a bottom-up design rather than a top-down design approach. In a top-down design, a program is designed by breaking a program or problem down into smaller and smaller components. Bottom-up design approaches a problem differently. First, real-world entities involved with the problem are modeled by defining objects. Then objects are used as building blocks that can be combined and made to interact to solve a problem. Object design is usually a straightforward process. Typically an object is modeling a real-world entity, so it is simple enough to decompose the entity into its constituent components. We do this until the component can either be modeled by a built-in type such as a string or number or by an existing object. In general, you want to keep things as simple as possible. Any time you need to associate pieces of data together into one logical unit, it is appropriate to encapsulate them into an object. A good design principle is to utilize composition as much as possible. If you have multiple 200
ComputerScienceOne_Page_234_Chunk1783
10.3. Exercises pieces of data that define a logical entity or unit, it is good design to create another object. For example, suppose a student object needs to model a mailing address; think about what an address is: it is a street address, city, state, zip, etc. Rather than having these as member fields to your object, it is probably more appropriate to define an “address” object, especially if such an object would be useful elsewhere in a program. 10.3. Exercises Exercise 10.1. A complex number consists of two real numbers: a real component a and an imaginary component bi where b is a real number and i = √−1. Define an object or structure to model a complex number. Write functions to: • Create a complex number • Print a complex number • Perform basic arithmetic operations on two complex numbers including addition, subtraction and multiplication as defined by: c1 + c2 = (a1 + b1i) + (a2 + b1i) = (a1 + a2) + (b1 + b2)i c1 −c2 = (a1 + b1i) −(a2 + b1i) = (a1 −a2) + (b1 −b2)i c1 · c2 = (a1 + b1i) · (a2 + b1i) = (a1a1 −b1b2) + (a1b2 + b1a1)i Exercise 10.2. Design an object (or structure) that models an album. Include at least the album title, artist (or band) and release year. Include any other data that you think is relevant and write functions to support your object. Exercise 10.3. Design an object (or structure) that models a bank savings account. Include at least the balance, APR, an account “number” and customer information (which may be another object or structure). Include any other data that you think is relevant and write functions to support your object. Exercise 10.4. Design an object (or structure) that models a sports stadium. Include at least the stadium name, the team that plays there, its city, state, and year built. Include both latitude and longitude data. Include any other data that you think is relevant and write functions to support your object. Write a parser to process a flat file data of all stadiums (in your chosen sport) and build instances of all of them. Exercise 10.5. Design an object (or structure) that models a network-connected elec- tronic device. Include at least a unique ID, a human-readable name for the device, a Media Access Control (MAC) address and Internet Protocol (IP) address as well as the device’s bandwidth in megabits per second. Include any other data that you think is relevant and write functions to support your object. 201
ComputerScienceOne_Page_235_Chunk1784
10. Encapsulation & Objects Exercise 10.6. Design an object (or structure) that models an airport. Include at least the name, FAA designation, its city, state, and latitude/longitude data. Include any other data that you think is relevant and write functions to support your object. 202
ComputerScienceOne_Page_236_Chunk1785
11. Recursion Suppose we wanted to write a simple program that performed a countdown, printing 10, 9, 8, . . . , 2, 1 and when it reached zero it printed a “Happy New Year” message. Likely our first instinct would be to write a very simple for loop using an increment variable. But suppose we lived in a world without the usual loop control structures that we are now familiar with. How might we write such a program? After thinking about it for a while, we might think: well, we don’t have loops, but we still have functions. In particular what if we had a function that took the “current” value of our counter variable and decremented it, passing it to another function, which did the same thing. For example, we could pass 10 to such a function, which would then subtract 1, passing 9 to another function and so on. A check could be made to see if the value was zero, in which case we print our special message and no longer call any more functions. In fact, we would not need to define 10 different functions to do so. Instead, we could define one function that called itself. It might look something like Algorithm 11.1. Input : An integer n ≥0 Output : A countdown of integers n, . . . 0 1 if n = 0 then 2 output “Happy New Year!!!” 3 else 4 output n 5 CountDown(n −1) 6 end Algorithm 11.1: Recursive CountDown(n) Function The function in this case is called CountDown(). In Line 5 the function calls itself on a decremented value. When a function calls itself, it is a recursive function. When a language allows functions to call themselves they support recursion. This is not that odd of a concept. We’ve seen many examples where functions invoke (call) other functions. Each function call simply creates a new stack frame on the program stack. There is nothing particularly special about which functions call which other functions, so there is little difference when a function calls itself. 203
ComputerScienceOne_Page_237_Chunk1786
11. Recursion This was not just a toy example. There are many programming languages in which recursion is used as a matter of course. Functional programming languages tend to avoid control structures like loops and even (mutable) variables. Instead, control flow is defined by evaluating a series of functions, making recursion a fundamental technique. Recursion is extensively used in mathematics. Recurrence relations or recursive functions are common. The Fibonacci sequence is a common, if not overused1 example. It has a simple definition: the next value in the sequence is simply the sum of the two previous values. The sequence starts with the initial values of 1. The first few terms in the sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, . . . The more formal mathematical definition can be stated as follows. Fn =    1 if n = 0 1 if n = 1 Fn−1 + Fn−2 otherwise The Fibonacci sequence is the cliche example for recursion. We can define an algorithmic function to compute the n-th Fibonacci number as follows. Input : An integer n ≥0 Output : The n-th Fibonacci number, Fn 1 if n ≤1 then 2 output 1 3 else 4 output Fibonacci(n −1) + Fibonacci(n −2) 5 end Algorithm 11.2: Recursive Fibonacci(n) Function Though hackneyed, it does provide a good example for how recursive functions work. We’ll also utilize it as an example of why you should avoid recursion in practice. We use it to illustrate how the problems with recursion can be mitigated or avoided altogether. 11.1. Writing Recursive Functions When writing a recursive function, there are several key elements that we need to take care of to ensure that it executes correctly. In particular, every recursive function requires 1The Fibonacci sequence is nothing special; its simply a second order linear homogenous recurrence relation with coefficients of 1. The near reverence that so many people attribute to it borders on mysticism. 204
ComputerScienceOne_Page_238_Chunk1787
11.1. Writing Recursive Functions at least one base case or base condition which serves as a terminating condition for the recursion. A base case is a condition which, instead of making a recursive call, processes and returns a value. Without a base case, the recursion would continue unbounded: the function would call itself over and over again, creating new stack frame after stack frame until we run out of stack space. If a program makes too many function calls and runs out of stack memory, it may lead to a stack overflow and the termination of the program. Even if we don’t have unbounded recursion, it is still possible to run out of stack space even with simple recursion. The other key element that we need is to ensure that every recursive call makes progress toward one of the terminating conditions. If no progress is made, then again we may have an unbounded recursion. In the Fibonacci example in Algorithm 11.2, the base case can be found in the first if-statement: when n reaches 1 or less, no recursive calls are made. In the else-statement, we make two recursive calls, but both of them make progress toward this base case. The first decrements n by 1 and the second by 2, eventually reaching n = 1. 11.1.1. Tail Recursion Making many function calls can be costly in terms of stack space. One optimization that can be made is to use tail recursion. The last operation that a function executes is referred to as the tail operation. If a function invokes another function as its tail operation, its a tail call. For example, consider the following snippet of code: 1 int foo(int x) { 2 ... 3 return bar(x-1) + 1; 4 } Here, foo() calls bar() but it is not the last operation before it returns. Instead, it invokes bar() , takes the result and adds one then returns to the calling function. Note that decrementing x is performed before the invocation of bar() . In contrast, consider the following modified code: 1 int foo(int x) { 2 ... 3 return bar(x-1); 4 } 205
ComputerScienceOne_Page_239_Chunk1788
11. Recursion Here, the invocation of bar() is the last operation performed by foo() . Thus, this is a tail call. Tail calls have the advantage that a language or compiler can generally optimize the function call with respect to the stack frame. Since the function foo() is essentially done with its computation, its stack frame is no longer needed. The system, therefore, can reuse the stack frame. Tail recursion is such an important optimization, some languages require it or “guarantee” it in other ways. 11.2. Avoiding Recursion Recursion is not essential; some languages do not even support recursion. In fact, any recursive function can be rewritten to not use recursion. Usually, you can write an equivalent loop structure or use an in-memory stack data structure to replace the recursion. So why use it? Proponents would argue that recursion allows you to write simple code that more closely matches mathematical functions and expressions. Recursion is also a natural way to think about certain problem solving techniques such as divide- and-conquer (see Chapter 12). It is also a natural way to code in functional programming languages. These arguments, however, are subjective. One person’s “cleaner” or “more understand- able” code is another person’s spaghetti code hack. What is “natural” for one person may be “weird” and “odd” for another. However, there are many other arguments against recursion, many of which are objective reasons: that recursion is more expensive and can easily lead to inefficient, exponential algorithms. In general, recursion requires lots of function calls which requires creating and removing lots of stack frames. This usually results in a lot of overhead and resources being used to perform the computation. Unless you are using a language in which recursion is optimized and made to be more efficient (such as functional programming languages), this is a lot more expensive than using simple loops and iteration. Another reason to avoid recursion is that it can lead to a lot of extraneous re-computations. The cliched example of the Fibonacci recursion is a prime example of this.2 Consider the computation of Fibonacci(5). This results in two recursive calls, each of those calls results in 2 recursive calls and so on as depicted in Figure 11.1. As depicted in the figure, several function calls are repeated: Fibonacci(3) is called twice, Fibonacci(2) is called 3 times, etc. 15 total function calls are made to compute 2Its overuse as an example of recursion is even less explicable as it solves a problem that no one cares about. 206
ComputerScienceOne_Page_240_Chunk1789
11.2. Avoiding Recursion Fibonacci(5) Fibonacci(4) Fibonacci(3) Fibonacci(2) Fibonacci(1) Fibonacci(0) Fibonacci(1) Fibonacci(2) Fibonacci(1) Fibonacci(0) Fibonacci(3) Fibonacci(2) Fibonacci(1) Fibonacci(0) Fibonacci(1) Figure 11.1.: Recursive Fibonacci Computation Tree Fibonacci(5). In general, the computation of Fibonacci(n) will result in an exponential number of function calls. The number of function calls to compute Fn with this recursive solution will be equal to Fn−2 + n−1 X i=0 Fi That is more than the first n −1 Fibonacci numbers combined! It should come as no surprise that the Fibonacci sequence grows exponentially and thus so would the number of operations with this recursive solution. To put this in perspective, consider computing F45 = 1, 836, 311, 903 (n = 45), the maximum representable value for a 32-bit signed two’s complement integer. Executing a C implementation of this recursive algorithm took about 8 seconds3 and required 3,672,623,805 function calls! What if we wanted to compute F100 = 573, 147, 844, 013, 817, 084, 101 (573 quintillion) it would result in 1,146,295,688,027,634,168,201 (1.146 sextillion) function calls. Using the same hardware, at 4.59 × 108 (459 million) function calls per second, it would take 2.497 × 1012 seconds to compute. That would be more than 79,191 years! Even if we performed these (useless) calculations on hardware that was 1 million times faster than my laptop, it would still take over 4 weeks! 3On a 2.7GHz Intel Core i7. 207
ComputerScienceOne_Page_241_Chunk1790
11. Recursion 11.2.1. Memoization The inefficiency in the example above comes from the fact that we make the same function calls on the same values over and over. One way to avoid recomputing the same values is to store them into a table (or tableau if you prefer being fancy). Then, when you need to compute a value, you look at the table to see if it has already been computed. If it has, we reuse the value stored in the table, otherwise we compute it by making the appropriate recursive calls. Once computed, we place the value into the table so that it can be looked up on subsequent function calls. This approach is usually referred to as memoization. The “table” in this scenario is very general: it can be achieved using a number of different data structures including simple arrays, or even maps (mapping input value(s) to output values). The table is essentially serving as a cache for the previously computed values. An illustration of how this might work can be found in Algorithm 11.3. Here, the recursion only occurs if the value Fn is not yet defined. Input : An integer n ≥0, a global map M that maps n values to Fn Output : The n-th Fibonacci number, Fn 1 if Fn is defined in M then 2 output M(n) 3 else 4 a ←Fibonacci(n −1) 5 b ←Fibonacci(n −2) 6 Define M(n) = a + b 7 output (a + b) 8 end Algorithm 11.3: Recursive Fibonacci(n) Function With Memoization In many functional programming languages, memoization is implicit and provided by the language itself to ensure that we do not have the same problems with recomputing values as we observed above. In languages such as C and Java, memoization becomes our responsibility and is not an optimization provided by the language itself. However, if we are filling in a table of values anyway, we really don’t need to make recursive calls at all. We simply need to figure out in what order to fill out the values in the table. This is actually the basis of a powerful programming technique known as dynamic programming which is a “bottom-up” approach to solving problems by combining solutions to smaller ones. 208
ComputerScienceOne_Page_242_Chunk1791
11.3. Exercises 11.3. Exercises Exercise 11.1. The binomial coefficients, C(n, k) or
ComputerScienceOne_Page_243_Chunk1792
12. Searching & Sorting Searching and sorting are two fundamental operations when dealing with collections of data. Both operations are not only important in and of themselves, but they also form the basis of many algorithms and other more complex operations. These operations are so essential that a wide variety of algorithms and techniques have been developed to solve them, each with their own advantages and disadvantages. This variety provides a good framework from which to study the relative efficiency and complexity of algorithms through algorithm analysis. 12.1. Searching Searching is a very basic operation. Given a collection of data, we wish to find a particular element or elements that match a certain criteria. More formally, we have the following. Problem 1 (Searching). Given: a collection of elements, A = {a1, a2, . . . , an} and a key element ek Output: The element ai in A such that ai = ek The “equality” in this problem statement is not explicitly specified. In fact, this is a very general, abstract statement of the basic search problem. We didn’t specify that the “collection” was an array, a list, a set, or any other particular data structure. Nor did we specify what type of elements were in the collection. They could be numbers, they could be strings, they could be objects. There are many variations of this general search problem that we could consider. For example, we could generalize it to find the “first” or “last” such element if our collection is ordered. We could find all elements that match our criteria. Some basic operations that we’ve already considered such as finding the minimum or maximum (extremal elements), or median element are also variations on this search problem. When designing a solution to any of these variations additional considerations must be made. We may wish our search to be index-based (that is, output the index i rather than the element ai). We may need to think about how to handle unsuccessful searches (return null ? A special flag value? Throw an exception?, etc.). 211
ComputerScienceOne_Page_245_Chunk1793
12. Searching & Sorting index contents 42 0 4 1 9 2 4 3 102 4 34 5 12 6 2 7 0 8 Figure 12.1.: Array of Integers When implementing a solution in a programming language, we of course will need to be more specific about the type of collection being searched and the type of elements in the collection. However, we will still want to keep our solution as general as possible. As we’ll see, most programming languages facilitate some sort of generic programming so that we do not need to reimplement the solution for each type of collection or for each type of variable. Instead, we can write one solution, then configure it to allow for comparisons of any type of variable (numeric, string, object, etc.). 12.1.1. Linear Search The first solution that we’ll look at is the linear search algorithm (also known as sequential search). This is a basic, straightforward solution to the search problem that works by simply iterating through each element ai, testing for equality, and outputting the first element that matches the criteria. The pseudocode is presented as Algorithm 12.1. Input : A collection of elements A = {a1, . . . , an} and a key ek Output : An element a in A such that a = ek according to some criteria; φ if no such element exists 1 foreach ai in the collection A do 2 if ai = ek then 3 output ai 4 end 5 end 6 output φ Algorithm 12.1: Linear Search To illustrate, consider the following example searches. Suppose we wish to search the 0-indexed array of integers in Figure 12.1. A search for the key ek = 102 would start at the first element. 42 ̸= 102 so the search would continue; it would compare it against 4, then 9, then 5, and finally find 102 at index i = 4, making a total of 5 comparisons (including the final comparison to the matched element). 212
ComputerScienceOne_Page_246_Chunk1794
12.1. Searching a1 · · · a n 2 −1 a n 2 a n 2 +1 · · · an m < m > m Figure 12.2.: When an array is sorted, all elements in the left half are less than the middle element m, all elements in the right half are greater than m. A search for the key ek = 42 would get lucky. It would find it after only one comparison as the first element is a match. A search for the element 20 would result in an unsuccessful search with a total of 10 comparisons being made. Finally a search for ek = 4 would only require two comparisons as we find 4 at the second index. There is a duplicate element at index 3, but the way we’ve defined linear search is to find the “first” such element. Again, we could design any number of variations on this solution. We give a more detailed analysis of this algorithm below. 12.1.2. Binary Search An alternative search algorithm is binary search. This is a clever algorithm that requires that the array being searched is sorted in ascending order. Though it works on any type of data, let’s again use an integer array as an example. Suppose we’re searching for the key element ek. We start by looking at the element in the middle of the array, call it m. Since the array is sorted, everything in the left-half of the array is < m and everything in the right-half of the array is > m.1 We will now make one comparison between ek and m. There are three cases to consider. 1. If ek = m, then we’ve found an element that matches our key and search criteria and we are done. We can output m and stop the algorithm. 2. If ek < m then we know that if a matching element exists, it must lie in the left-half of the list. This is because all elements in the right-half are > m. 3. If ek > m then we know that if a matching element exists, it must lie in the right-half of the list. This is because all elements in the left-half are < m. In either of the second two cases, we have essentially cut the array in half, halving the number of elements we need to consider. Suppose that the second case applies. Then we can consider elements indexed from 1 to n 2 −1 (we need not consider a n 2 as the first case would have applied if we found a match). We can then do the same trick: check the middle element among the remaining elements and determine which half to cutout and 1If duplicate elements are in the array, then elements in the left/right half could be less than or equal to and greater than or equal to m, but this will not affect how our algorithm works. 213
ComputerScienceOne_Page_247_Chunk1795
12. Searching & Sorting which half to consider. We repeat this process until we’ve either found the element we are looking for or the range in which we are searching becomes “empty” indicating an unsuccessful search. This description suggests a recursive solution. Given two indices l, r, we can compute the index of the middle element, m = l+r 2 and make one of two recursive calls depending on the cases identified above. Of course, we will need to make sure that our base case is taken care of: if the two indices are invalid, that is if the left is greater than the right, l > r, then we know that the search was unsuccessful. Input : A sorted collection of elements A = {a1, . . . , an}, bounds 1 ≤l, r ≤n, and a key ek Output : An element a in A such that a = ek according to some criteria; φ if no such element exists 1 if l > r then 2 output φ 3 end 4 m ←⌊l+r 2 ⌋ 5 if am = ek then 6 output am 7 else if am < ek then 8 BinarySearch(A, m + 1, r, ek) 9 else 10 BinarySearch(A, l, m −1, ek) 11 end Algorithm 12.2: Recursive Binary Search Algorithm, BinarySearch(A, l, r, ek) As discussed in Chapter 11, non-recursive solutions are generally better than recursive ones. We can design a straightforward iterative version of binary search using a while loop. We initialize two index variables, l, r and update them on each iteration depending on the three cases above. The loop stops when we’ve found our element or l > r resulting in an unsuccessful search. The iterative version is presented in Algorithm 12.3, an example 214
ComputerScienceOne_Page_248_Chunk1796
12.1. Searching run of the algorithm is shown in Figure 12.3. Input : A sorted collection of elements A = {a1, . . . , an} and a key ek Output : An element a ∈A such that a = ek according to some criteria; φ if no such element exists 1 l ←1 2 r ←n 3 while l ≤r do 4 m ←⌊l+r 2 ⌋ 5 if am = ek then 6 output am 7 else if am < ek then 8 l ←(m + 1) 9 else 10 r ←(m −1) 11 end 12 end 13 output φ Algorithm 12.3: Iterative Binary Search Algorithm, BinarySearch(A, ek) 12.1.3. Analysis When algorithms are implemented and run on a computer, they require a certain amount of resources. In general, we could consider a lot of different resources such as computation time and memory. Algorithm analysis involves quantifying how many resource(s) an algorithm requires to execute with respect to the size of the input it is run on. When analyzing algorithms, we want to keep the analysis as abstract and general as possible, independent of any particular language, framework or hardware. We could always update the hardware on which we run our implementation, but that does not necessarily make the algorithm faster. The algorithm would still execute the same number of operations. Faster machines just mean that more steps can be performed in less time. In fact, the concept of an algorithm itself is a mathematical concept that predates modern computers by thousands of years. One of the oldest algorithms, for example, Euler’s GCD (greatest common divisor) algorithm dates to 300 BCE. Whether or not you’re “running” it on a piece of papyrus 2,300 years ago or on a modern supercomputer, the same number of divisions and subtractions are performed. To keep things abstract, we analyze an algorithm by identifying an elementary operation. 215
ComputerScienceOne_Page_249_Chunk1797
12. Searching & Sorting index contents -3 0 2 1 4 2 4 3 9 4 12 5 34 6 42 7 102 8 157 9 180 10 (a) Initially, l = 0, r = 10 and so we examine the middle element at index m = 5 which is 12. index contents -3 0 2 1 4 2 4 3 9 4 12 5 34 6 42 7 102 8 157 9 180 10 (b) Since 64 > 12, we update our left index variable l to m + 1, thus l = 6 and we’ve eliminated the left half of the list from consideration. index contents -3 0 2 1 4 2 4 3 9 4 12 5 34 6 42 7 102 8 157 9 180 10 (c) Our new middle index is m = l+r 2 = 6+10 2 = 8, corresponding to the element 102. index contents -3 0 2 1 4 2 4 3 9 4 12 5 34 6 42 7 102 8 157 9 180 10 (d) Since 64 < 102, we update the right index variable r to m −1 = 7, eliminating the right half of the subarray. index contents -3 0 2 1 4 2 4 3 9 4 12 5 34 6 42 7 102 8 157 9 180 10 (e) Here, l = 6, r = 7, and so our new middle index is m = ⌊6+7 2 ⌋= 6. Since 64 > 34, we update our left index variable l to m + 1 = 7 index contents -3 0 2 1 4 2 4 3 9 4 12 5 34 6 42 7 102 8 157 9 180 10 (f) Since 64 > 42 we again update our left index variable l to m + 1 = 8. index contents -3 0 2 1 4 2 4 3 9 4 12 5 34 6 42 7 102 8 157 9 180 10 (g) Since l = 8 and r = 7, l > r and the loop terminates, resulting in an unsuccessful search. Figure 12.3.: The worst case scenario for binary search, resulting in an unsuccessful search for ek = 64. This example is run on a 0-indexed array with an array of integers of size 11. 216
ComputerScienceOne_Page_250_Chunk1798
12.1. Searching This is generally the most common or most “expensive” operation that the algorithm performs. Sometimes there may be more than one reasonable choice for an elementary operation which may give different results in our analysis. However, we generally do not consider basic operations that are necessary to the control flow of an algorithm. For example, variable assignments or the iteration of index variables. Once we have identified an elementary operation, we can quantify the complexity of an algorithm by analyzing the number of times the elementary operation is executed with respect to the input size. For a collection, the input size is generally the number of elements in the collection, n. We can then characterize the number of elementary operations and thus the complexity of the algorithm itself as a function of the input size. We illustrate this process by analyzing and comparing the two search algorithms. Linear Search Analysis When considering the linear search algorithm, the input size is clearly the number of elements in the collection, n. The best candidate for the elementary operation is the comparison (Line 2, Algorithm 12.1). To analyze this algorithm, we need to determine how many comparisons are made with respect to the size of the collection, n. As we saw in the examples, the number of comparisons made by linear search can vary depending on the element we’re searching and the configuration of the collection being searched. Because of this variability, we can analyze the algorithm in one of three ways: by looking at the best case scenario, worst case scenario, and average case scenario. The best case scenario is when the number of operations is minimized. For linear search, the best case scenario happens when we get lucky and the first element that we examine matches our criteria, requiring only a single comparison operation. In general, it is not reasonable to assume that the best case scenario will be commonly encountered. The worst case scenario is when the number of operations is maximized. This happens when we get “unlucky” and have to search the entire collection finding a match at the last element or not finding a match at all. In either case, we make n comparisons to search the collection. A formal average case analysis is not difficult, but is a bit beyond the scope of the present analysis. However, informally, we could expect to make about n 2 comparisons for successful searches if we assume that all elements have a uniform probability of being searched for. Both the worst-case and average-case are reasonable scenarios from which to analyze the linear search algorithm. In the end, however, the only difference between the two analyses is a constant factor. Both analyses result in two linear functions, f1(n) = n f2(n) = 1 2n 217
ComputerScienceOne_Page_251_Chunk1799
12. Searching & Sorting The only difference being the constant factor 1 2. In fact, this is why the algorithm is called linear search. The number of comparison operations performed by the algorithm grows linearly with respect to the input size. For example, if we were to double the input size from n to 2n, then we would expect the number of comparisons to search the collection would also double (this applies in either the worst-case and average-case scenarios). This is what is most important in algorithm analysis: quantifying the complexity of an algorithm by the rate of growth of the operations (and thus resources) required to execute the algorithm as the input size n grows.2 Binary Search Analysis Like linear search, the input size is the size of the collection n and the elementary operation is the comparison. As presented in the pseudocode, binary search would seem to perform two comparisons (Lines 5 and 7 in Algorithm 12.3). However, to make the analysis simpler, we will instead count one comparison operation per iteration of the while loop. This is a reasonable simplification; in practice the comparison operation would likely involve a single function call, after which distinguishing between the three cases is a simple matter of control flow. Further, even if we were to consider both comparisons, it would only contribute a constant factor of 2 to the final analysis. Since we perform one comparison for each iteration of the while loop, we need to determine how many times the while loop executes. In the worst case, the number of iterations is maximized when we fail to find an element that does not match our criteria. However each iteration essentially cuts the array in half each time. That is, if we start with an array of size n, then after the first iteration, it is of size n 2. After the second iteration we have cut it in half again, so it is of size n 4, after the third iteration it is of size n 8 and so on. More generally, after k iterations, the size of the array is n 2k The loop terminates one iteration after the the index variables are equal, l = r. Equiv- alently, when l = r, the size of the subarray under consideration is 1. That is, the algorithm stops when the array size has been cut down to 1: n 2k = 1 Solving for k gives us the number of iterations: k = log2 (n) Adding one additional comparison for the final iteration gives us a total of k = log2 (n) 2This is the basis of Big-O analysis, something that we will not discuss in detail here, but is of prime importance when analyzing algorithms. 218
ComputerScienceOne_Page_252_Chunk1800