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...
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 θ i...
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 i...
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...
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 comp...
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...
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. ...
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 satisfie...
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 ensur...
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 ...
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, ...
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 p...
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 +...
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,...
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 partic...
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...
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. Functi...
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...
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...
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...
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...
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() ...
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 ...
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...
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 ...
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...
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 sam...
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 nu...
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 a...
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 percent...
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 int...
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 jou...
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 t...
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 regu...
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 t...
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 ...
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...
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 bl...
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 except...
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 E...
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 sa...
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, the...
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-b...
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 refere...
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 fram...
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. Pr...
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 pro...
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. B...
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 t...
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...
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 t...
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 crea...
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...
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 ...
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 · ·...
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 ...
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 m...
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 chang...
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...
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 mor...
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 ...
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 let...
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 ex...
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 mem...
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 ...
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...
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 | | `--...
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 passe...
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...
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 HTM...
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 f...
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 e...
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 co...
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 ...
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-gr...
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...
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 respective...
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. ...
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 ex...
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 typ...
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 re...
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, ...
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...
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 recu...
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 ...
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 sta...
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 Fibo...
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 ...
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 alg...
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...
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 fi...
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...
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...
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 + ...
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 th...
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...
ComputerScienceOne_Page_252_Chunk1800