Programming Problems and Exercises
DR
AF
T
by E. Dembskey Draft Version: 2014-01-01
DR
AF
T
This work is dedicated to Rudolf Dembskey
Contents Contents
3
List of Tables
5
List of Figures
6
1 Introduction
7 11 13 13
3 Algorithm Complexity 3.1 Introduction . . . . . . . . . 3.2 Big-O Notation . . . . . . . 3.3 Constant Time: 0(1) . . . . 3.4 Linear Time: 0(N ) . . . . . 3.5 Quadratic Time: 0(N 2 ) . . 3.6 Cubic Time: 0(N 3 ) . . . . . 3.7 Logarithmic Time: O(logN ) 3.8 Exponential Time: O(2n ) . 3.9 Factorial Time: O(N !) . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . and O(N logN ) . . . . . . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
15 15 16 17 17 18 18 18 18 19
4 Languages 4.1 Introduction . . . . . . . 4.2 Programming Paradigm 4.3 Degree of Abstraction . 4.4 Method of Execution . . 4.5 Generations . . . . . . . 4.6 Conclusion . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
21 21 22 27 27 28 29
DR
AF
T
2 Problem Solving 2.1 A note on plagiarism . . . . . . . . . . . . . . . . . . . . . . . . 2.2 A note on working in the industry . . . . . . . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
5 Problem Set 01
31
6 Problem Set 02
41
7 Problem Set 03
49 3
4
CONTENTS 57
9 Problem Set 05
63
10 Problem Set 06
81
11 Problem Set 07
89
12 Problem Set 08
93
13 Problem Set 09
99
14 Problem Set 10
101
15 Problem Set 11
103
16 Problem Set 12
109
17 Problem Set 13
113
18 Problem Set 14
121
19 Problem Set 15
127
21 Problem Set 17
AF DR
20 Problem Set 16
T
8 Problem Set 04
129 135
22 Problem Set 18
141
23 Problem Set 19
143
24 Problem Set 20
147
Bibliography
151
Index
153
List of Tables 3.1
Comparison of Rates of Growth . . . . . . . . . . . . . . . . . . . .
20
9.1
Calendar
71
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
20.1 Half-Lives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
DR
AF
T
21.1 Morse Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 21.2 HTTP Responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
5
List of Figures List . . . . . . . . . . . Singly Linked List . . . Doubly Linked List . . . Queue . . . . . . . . . . Queue after ENQUEUE Queue after DEQUEUE Stack . . . . . . . . . . Stack after PUSH . . . Stack after POP . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
12.1 12.2 12.3 12.4
Tic Tac Toe . . Checkers Board Chess Board . Go Board . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
AF
. . . .
DR
. . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
T
10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9
. . . .
6
. . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
82 83 83 84 85 85 87 87 87
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
94 94 96 97
Chapter
1
Introduction
DR
AF
T
A beginning is the time for taking the most delicate care that the balances are correct. - PRINCESS IRULAN, in Dune (1965)
Experience has shown that students’ programming ability and confidence improves after extensive programming practice and problem solving. These graded1 exercises and problems are intended to provide practice opportunities for programming students in a structured manner. This document is not intended as a stand-alone textbook, but rather as a supplement to an existing textbook or course material. It is also common to be given short programming problems to solve when applying for a programming job. This document can help prepare for this kind of interview, though this is not it’s primary purpose. For more help in preparing for interviews, refer to [16]. It can also be used to prepare for programming competitions, though a better book for this purpose would be [25]. This document now includes more than 150 exercises and problems, a chapter on programming paradigms and approaches, a chapter on algorithm complexity and advice on problem solving strategies for the student. Proper problem solving skills are absolutely necessary, as programming problems are solved with the mind, not the fingers. There is now also advice on proper programming practices and program structure. 1 Grading
problems is a problem itself, and open to interpretation.
7
8
CHAPTER 1. INTRODUCTION
This document follows the convention outlined by Paul Zeitz [30]. According to Zeitz, an exercise is a question that you know how to resolve immediately. Whether or not the exercise is completed correctly depends on how well specific techniques are applied, but which techniques are to be used is not a mystery. In contrast, a problem demands much thought and resourcefulness before the correct approach is found. Though this document is titled Programming Problems, the majority of the problems are in fact exercises, meant to keep pace with the student’s development. As a pedagogical principle, students should follow an understand, design, code, review cycle. First study the problem and ensure you understand it. Then design a solution. Some solutions warrant only mental designs, but some will require the use of some methodology, even if only pen and paper. Then code the solution. After a working solution is obtained, review the solution. Try to improve the solution by looking for improvements that reduce time and space complexity. Output is usually not prescribed. For all programs, unless otherwise specified, print the output to the screen, a text file, or a Windows or Web Form.
DR
AF
T
Many of these problems have been extensively tested. Some of them were originally presented in International School for Scientific Computing (ISSC) courses around the world 2 . Many are are used for lab practice for the subjects ITN20BT, AIT401T, DPC401T and IIS401T at The Tshwane University of Technology in South Africa. A subset has been presented to DSO401T and DEV401T students at UNISA. Some problems, such as those aimed specifically at prolog, can be found in their own section. The problems are not necessarily categorically unique. For example, the effort, techniques and approach for some problems may be the same as other problems. The effort required to write a program that determines BMI is not all that different from the effort required to write a program to determine interest. Thus, from some points of view, nothing new will be learnt by solving both problems. However, from a lecturer’s point of view, having a variety of problems staves off boredom. Also, practice is off itself a good thing. Many of the problems can be solved quickly using, for example, the STL, the .NET Framework and CPAN. However, this defeats the object of these exercises and problems. Every student should solve these problems themselves as part of their computer science or ICT education. New to this version is a difficulty rating for the problems. The easiest problems, which can be solved in less than a minute, are rated as Difficulty: 1. Problems which can be solved in less than 10 minutes are rated Difficulty: 2. Problems that should take less than an hour and a half or so (100 minutes) are Difficulty: 3. Those that would 2 See
http://issc.uj.ac.za for more information on ISSC courses
9 require two full working-days (1000 minutes) are Difficulty: 4.Difficulty: 5 is a full working month (10000 minutes). Difficulty: 6 will take no longer than two thirds of a year, and is the highest rating at this point in time. Of course, these are estimates only, and your mileage will vary. A particular programmer may suffer under a problem that another solves in minutes, but the roles may very well be reversed with a different problem. Skill, ability to concentrate and motivation vary sharply, so the difficulty rating should be used as an guide only. Some problems throw light on subjects as diverse as astronomy, physics, biology, computer science, economics and finance, gaming and chemistry. This is in the spirit of broadening one’s horizons. This document is a work in progress. Suggestions, criticisms and errata are always welcome. Please send them to
[email protected]. A small PayPal donation to
[email protected] will be appreciated.
Legal matters
AF
T
E. Dembskey Michigan, January 2014
DR
c This book is copyright by its author, Evan Dembskey. Redistributing or selling this book in printed or in electronic form is prohibited. This book must not be mirrored on the Internet. Using this book as promotional material is prohibited. While the author has taken every reasonable measure to attribute problems to authors, it is possible that one slipped through. If you feel this is the case, but make the author aware so that he can properly attribute your contribution.
AF
DR T
Chapter
2
Problem Solving
DR
AF
T
We can face our problem. We can arrange such facts we have with order and method. - HERCULE POIROT, in Murder on the Orient Express (1934)
To succeed, planning alone is insufficient. One must improvise as well. - SALVOR HARDIN, in Foundation (1951)
Not only must a programmer learn the syntax of his or her chosen language, the nuances of their development and deployment environments, but he or she must become accomplished problem-solvers. This aspect is clearly the most difficult, and it is still argued whether programmers are born or made, the question hinging off the matter of whether or not problem-solving is a talent or a skill. Paul Zeitz provides a useful analogy. You are standing at the base of a tall mountain, hoping to climb to the summit. First, you need to develop a strategy. This may include several small trips to scope out the terrain. Next, you may try a more focused strategy, like trying to climb the mountain along a particular route. Now you begin to think about the tactics of the situation, or how to achieve the strategy. Suppose you intend to climb the mountain along the north ridge, but there is a wide river and a deep canyon to cross. Specific tactics for negotiating these obstacles must be developed. The final task is to move on to the specific tools that will be required. These are specific techniques to accomplish very narrow, specific tasks. For example, when crossing the canyon, 11
12
CHAPTER 2. PROBLEM SOLVING
specific ropes and knots are chosen to create a bridge [30]. This analogy is highly pertinent to software development, as it demonstrates that tools are just implements for achieving a goal, and are not appropriate to all tasks. There are typically six steps to follow when faced with the task of solving a problem. Some form of this process is used no matter the complexity of the problem. It is not a linear process; often new conditions arise, or existing conditions become better understood, necessitating a new approach to a problem and the loss of completed work. Returning to an earlier step is a common occurrence, and should be accepted as a natural part of the work. The six steps are: 1. Identify the problem: The first step towards solving a problem is to identify the problem. Strange as it may sound, this is an often neglected step in the problem solving process. In the classroom or lab, problems have mostly been identified for the student. However, sometimes the problem is not obvious, and much effort is wasted on what initially appears to be the problem, leaving the real problem lurking undiscovered in the background.
DR
AF
T
2. Understand the problem: The second step is to come to an understanding of what is involved in the problem. Ask yourself if it is a single problem, or if there are more than one problem to solve. You must also think about what you know, and decide whether any research is required to fully understand the problem. 3. Identify alternate ways to solve the problem: Develop and apply multiple strategies. The first solution that comes to mind may not be the best solution. Solutions can have unintended consequences. Formulate a number of solutions and determine to the best of your ability the consequences of each of these solutions. 4. Select the best way to solve the problem from the list of alternative solutions: Refine your strategy and develop specific tactics. Think about the process and results; is your method working or should you go back a step or two? 5. List instructions that enable the problem to be solved: Choose the correct tools to use and use them. Some research might be required before deciding which tool is best. 6. Evaluate the solution: Is the solution a good one? What have you learnt from both the programming and the process that you can apply to your next project? Don’t underestimate the importance of this step. Often a problem is solved under pressure from a deadline, leading to a less than optimal solution. The consequences of the solution now become apparent. In time, a better solution may be found.
2.1. A NOTE ON PLAGIARISM
13
There are many variations on this theme. The important lesson to take away is that some problem solving method is required; some method is usually better than no method. However, some methods are better than others, and some methods suit particular circumstances and people better than others. Rigidity limits success. One of the most powerful techniques is to break problems down into smaller pieces which are more easily solved. This permits us to see details which are hidden when looking at the big picture. Often the true nature of the problem is revealed in this process.
2.1
A note on plagiarism
T
It is relatively easy to find code online that solves most of the problems in this book, and even most of the problems a programmer encounters in the course of a day’s work. The temptation to take this route is particularly acute when one is under pressure to solve a problem by some particular point in time.
AF
Avoid the temptation to use code off the Internet!
DR
The biggest problem with using code that you do not understand is that there will be unexpected consequences. The code may appear to work initially, but may fail at a critical time. Even worse, the code may introduce a security problem. Without a good understanding of the code, you will be back at the beginning of the journey, but perhaps with a bigger problem. By all means, join Web forums and mailing lists related to your job and ask questions. If you don’t understand the answer, even if it works, make the effort to understand it. Some day you, or someone else, will have to maintain that code. It’s likely if you did not understand it, that you did not document it properly. It is sometimes easier to re-write code than to understand written code. Don’t be the cause of problems in the future to save a few moments of time now.
2.2
A note on working in the industry
The goals of professors and managers often differ. Computer Science graduates are taught to be computer scientists, not programmers. Industry needs programmers and hires computer scientists for this purpose. While not a recipe for total disaster, this disconnect is the source of much frustration.
14
CHAPTER 2. PROBLEM SOLVING
The Computer Science graduate may have achieved a distinction writing programs no larger than a thousand lines, while in industry he or she is expected to work on programs orders of magnitude larger. With larger programs comes a concomitant increase in complexity. The skill of analysing and understanding large and complex programs must be learnt. One may argue that there is as much of the study of human nature in this task as of the study of programs and programming.
DR
AF
T
A word of advice for the graduate; if you plan on making a career of programming, in your own time, study the broader view. This includes project management, systematic testing, documentation, working with other people’s code, having other people work on your code, code quality and systems architecture. If you have not had the opportunity to apply the knowledge you have gained in a synthesised manner, take the time to think about it. Problem solving while learning typically involves solving problems that are limited in scope, while the working programmer must call on all his or her knowledge in new and creative ways.
Chapter
3
Algorithm Complexity
Introduction
DR
3.1
AF
T
Form ever follows function. - LOUIS HENRI SULLIVAN (Lippincott’s Magazine (March 1896))
An algorithm is a code-recipe that is used to solve a problem; it produces correct output given some input. The question arises: how do programmers measure the work that algorithms perform, with a view to comparing two algorithms to determine the most efficient? We usually consider two dimensions; computational space (memory) and computational time (how many operations). When comparing two algorithms for efficiency, the first solution is to code the algorithms and then compare the execution time and space of the algorithms. Common sense suggests that the algorithm with the shortest execution time and smallest space is the most efficient algorithm. However, this may not be entirely accurate. All we have determined is that a particular algorithm is more efficient than another particular algorithm on a specific computer at a specific time. For most cases, computational space is less used as a measure than computational time, because space is reusable while time is not. An example of this can be seen in the case of adding two arrays of integers. In the first example a third array is used, thus making the space complexity 3N.
for(int i = 0;i
16
CHAPTER 3. ALGORITHM COMPLEXITY
The name algorithm honours { the Arabic mathematician Abu C[i] = A[i] + B[i]; Ja’far Muhammad ibn Musa } al-Khwarizmi. He lived in present-day Iraq, at around 800 AD. In this second example, only two arrays are used, thus making the space com-
plexity 2N.
for(int i = 0;i
A better method is count the number of instructions executed. There are two issues with this method. Firstly, it is language dependent. Secondly, it varies with programming style.
DR
AF
T
Another method is to isolate an operation that is fundamental to the algorithm, and count the number of times that this operation is performed. In fact, in many algorithms we can do just this, relegating all but one operation to the ”noise” level [2]. Complexity is looked at from a number of viewpoints. We typically are interested in worst-case complexity, because it gives a guaranteed upper bound for how much resource a algorithm will use. Using best-case complexity is not that useful, except as a contrast to worst-case complexity. It also gives us a lower bound for resources used. Average-case complexity is useful, but can be very difficult to determine. We can generally conclude that a problem is efficiently solved when a polynomialtime algorithm has been found for it (O(LogN ), O(N ), O(N 2 ), O(N 3 ) and so on).
3.2
Big-O Notation
The complexity of an algorithm is usually defined in terms of the order of magnitude of the number of operations required to perform a function. This is denoted by a capital O, followed by an expression representing some growth relative to the size of the problem (N) [8] [2]. When calculating the values for Table 3.1Comparison of Rates of Growthtable.3.1, a Sharp scientific calculator, model EL-506W, sufficed for all calculations up
3.3. CONSTANT TIME: 0(1)
17
to 64!. The number 128! exceeded the calculator’s capacity. For 128! we thus turned to SciLab, which yielded a result1 . For 256! even SciLab failed. For this we turned to Maple 10, which yielded a (staggering) result2 .
3.3
Constant Time: 0(1)
In O(1) an algorithm takes constant time to run. It is also called bounded time [2]. Performance is not affected by the size of the problem. This does not guarantee a fast algorithm, only that it will always take the same amount of time to run. Finding an algorithm that runs in constant time is very difficult [8]. Assigning a value to the nth element of an array of N elements is O(1), because all elements in an array can be directly accessed through its index [2].
T
Linear Time: 0(N )
AF
3.4
DR
In O(N) an algorithm performs a number of operations directly proportional to the number of items being processed. That is to say, its running time is at most a constant factor times the size of the input. Algorithms that run in O(N) are usually quite acceptable [8]. An example of an O(N) algorithm is a program that writes all the elements of a list into a file. If N is the number of elements in the list, we can determine the time taken to execute the algorithm as follows:
time − to − open − f ile + (N × time − to − write − one − element) + time − to − close − f ile The algorithm is O(N) because the only important operation we need to measure is (N × time − to − write − one − element). Time increases in a linear fashion as N increases [2]. One way to get a algorithm that runs in linear time is to process the input in a single pass, spending a constant amount of time on each input item. Other algorithms achieve it for more subtle reasons. For example, an algorithm running on a high-speed switch on the Internet can only perform a constant amount of computational work on each packet. [12]. 1 http://www.scilab.org 2 http://www.maplesoft.com
18
3.5
CHAPTER 3. ALGORITHM COMPLEXITY
Quadratic Time: 0(N 2 )
Algorithms that run in quadratic time may be a programmer’s worst nightmare. They are only usable on the smallest problems, on which they work reasonably quickly. However, as N increases, the situation rapidly gets out of hand.
The example of a group of people meeting for the first time and needing to shake each other’s hands is often provided [8]. If three people meet, there are 3 + 2 + 1 = 6 handshakes that need to occur. If ten people, then 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 55 handshakes need to occur.
Cubic Time: 0(N 3 )
DR
AF
3.6
T
Most simple sorting algorithms are O(N 2 ) [2].
A few moments contemplation of Table 3.1Comparison of Rates of Growthtable.3.1 reveals everything you want to know about the efficiency of a O(N 3 ) algorithm. An example is a routine that increments every element in a three-dimensional table of integers [2]
3.7
Logarithmic Time: O(logN ) and O(N logN )
Logarithmic time is better than O(N), but not as good as O(1). The running time of a logarithmic algorithm increases with the log of the size of the problem. Thus if the size of the input data set increases by a factor of one million, the run time will increase only by a factor of 20 [8]. Finding a value in list of sorted elements using the binary search algorithm is O(log2 N ) [2]. The better sort algorithms such as Quicksort, Heapsort and Mergesort are O(N log2 N ) [2].
3.8. EXPONENTIAL TIME: O(2n )
3.8
19
Exponential Time: O(2n )
Algorithms with complexities which cannot be bounded by polynomial functions are called exponential time algorithms. This order of algorithms is very costly. Execution time increases dramatically as N increases. Some problems of this order require computation times exceeding the age of the universe [2].
3.9
Factorial Time: O(N !)
DR
AF
T
An algorithm that performs in factorial time is a poor algorithm [8]. By referring to Table 3.1Comparison of Rates of Growthtable.3.1 we see that for even relatively small values of N the situation is untenable.
O(N ) 1 2 4 8 16 32 64 128 256
O(LogN ) 0 1 2 3 4 5 6 7 8
O(N logN ) 1 2 8 24 64 160 384 896 2048
N2 1 4 16 64 256 1024 4096 16384 65536
T
N 1 2 4 8 16 32 64 128 256
N3 1 8 64 512 4096 32768 262144 2097152 16777216
the universe itself is only approximately 4.323 × 1017 seconds old! [22] [10]
2N 2 4 16 256 65536 4294967296 1.845 × 1019a 3.403 × 1038 1.158 × 1077 Table 3.1: Comparison of Rates of Growth
AF
a Consider
DR
CHAPTER 3. ALGORITHM COMPLEXITY 20
O(N !) 1 2 24 40320 2.092 × 1013 2.631 × 1035 1.269 × 1089 3.856 × 10215 8.578 × 10506
Chapter
4
Languages
DR
AF
T
Language shapes the way we think, and determines what we can think about. - BENJAMIN LEE WHORF
Thought is the blossom; language the bud; action the fruit behind it. - RALPH WALDO EMERSON
4.1
Introduction
The next question is may be that of which programming language to use. There are many thousands of languages in existence, which makes it difficult for a beginner to choose an appropriate language. As in all things, an organising principle1 is required. Modern programming languages can be classified according to a number of criteria [9]. The most important of these criteria are
• Programming paradigm • Degree of abstraction • Method of execution 1 Sometimes
that principle goes under the name of ”teacher” or ”professor”.
21
22
CHAPTER 4. LANGUAGES
4.2
Programming Paradigm
A programming paradigm is the approach taken to create a particular program. Particular paradigms are better at solving certain types of problems than other paradigms. Programming paradigms function as an organising principle, an approach to programming. A given language is not limited to a single paradigm. Java can be categorised as both a procedural and as an object-oriented language. It can also be used in an event-driven manner. Programming paradigms will continue to change and grow, as computing capabilities increase.
Procedural Programming Languages Procedural programming specifies a list of operations that the program must complete to reach the desired state. Each program has a starting state, a list of operations to complete, and an ending state.
DR
AF
T
A procedure is effectively a list of computations to be carried out. Procedures, also known as functions, subroutines or methods, are seperate sections of code that perform specific tasks. When combined, a software solution is produced. By splitting a program into small pieces, procedural programming allows a section of code to be re-used in the program without making multiple copies of the code. It also makes it easier for programmers to understand and maintain complex program structure. Two of the most popular procedural programming languages are Ada, C, C++. Pascal, Modula-2, COBOL, FORTRAN and BASIC. Most procedural languages are designed explicitly for compilation. The following procedural code example, in C, shows how to determine a bank charge according to bank balance.
if(account_balance < 300) { service_charge = 10; } else { service_charge = 5; }
4.2. PROGRAMMING PARADIGM
23
Structured Programming Languages Structured programming is a special type of procedural programming. Additional tools are provided to manage the complexity of larger programs. Programmers break program structure into small pieces of code variously called methods, subroutines, procedures, functions or routines. These are easily understood and combined to produce a final software solution. Structured programming is often associated with a ”top-down” architectural approach. The top-down approach begins with an initial overview of the system that contains minimal details about the different parts. Subsequent design iterations then add increasing detail to the components until the design is complete. In many langauges pre-written routines are supplied, like the string routines strcopy and strlen in C. The most popular structured programming languages include C and Pascal.
T
The following code converts a number into a letter denoting a day of the week.
DR
AF
char funcDayConv (int number) { char selection[] = {’M’,’T’,’W’,’T’,’F’,’S’,’S’}; return selection[number]; }
Object-Oriented Programming Languages Object-orientated programming is not just a programming style, but also a design method for designing systems ( [1]). In object-oriented programs, the designer specifies both the data structures and the types of operations that can be applied to those data structures. The combination of data and operations is coded as a class and instantiated (executed) as an object. A program is a collection of cooperating objects. Objects can store state information and interact with other objects, but generally each object should have a a welldefined and distinct role. There are several key concepts in object-oriented programming
• A class is a code template or prototype from which objects are created. A class thus describes a collection of variables and methods. These methods have different levels of accessibility.
24
CHAPTER 4. LANGUAGES • A distinguishing feature of object-orientated programming is that new classes can be derived from a parent class. These derived classes inherit the attributes and behaviour of the parent, but they can also be extended with new data structures and methods. • The list of available methods of an object represents all the possible interactions it can have with external objects, which means that it is a concise specification of what the object does. New classes can be added to a system that uses the interfaces of the existing classes. • Encapsulation is an essential characteristic of OOP. It refers to how the implementation details of a particular class are hidden from all objects outside of the class. Programmers specify what information in an object can be shared with other objects.
T
• Objects of different types can receive the same message and respond in different ways. This is called polymorphism. The different objects need to have only the same interface while the calling object does not need to know exactly what type of object it is calling, only that is has a method of a specific name with defined arguments.
DR
AF
Object-orientated languages often feature constructors. The constructor is a function that is automatically called when an instance of a class is created.The constructor is used to initialize class member variables, allocate memory or do any other necessary startup tasks. The destructor is a function that is automatically called just before the object is destroyed. The destructor could be thought of as the opposite of a constructor. It is usually used to free any memory allocated by the class and any other cleanup chores. The most popular object-oriented programming languages include Java, Visual Basic, C#, C++, and Python. In the following example, in C++, a class called Fract is shown. The implementation of the method is procedural. class fract{ long numerator; long denominator; public: fract(long value); void addition(long value); };
// // // // //
Attribute Attribute Access rights Constructor Method
4.2. PROGRAMMING PARADIGM
25
Concurrent programming Concurrent programming provides for multiple computations running at once. This often means support for multiple threads of program execution. For example, one thread might monitor the mouse and keyboard for user input, while another thread performs database operations. Popular concurrent languages include Ada and Java.
Functional Programming Functional programming has its roots in lambda-calculus and are designed as a higher-level, more abstract notation than most other language paradigms. They define subroutines and programs as mathematical functions. pure functional languages use no value assignments. These languages are most frequently used in various types of mathematical problem solving.
DR
AF
T
Most programming languages use a state that is repeatedly modified. Language statements are typically executed for their side-effects on the state. In functional languages this is not allowed; functions cannot have side-effects on the state of a program. The exception is when the state is carried around in the arguments of the functions [1]. This is known as referential transparency. Popular functional languages include LISP, F# and Mathematica. XSLT is one of the newest examples of a functional language. In the following example, in LISP, a function called adiff returns the absolute difference between two numbers.
(defun adiff (num1 num2) (if (> num1 num2) (princ (- num1 num2))) (if (< num1 num2) (princ (- num2 num1))) ) ; end adiff
Logic Programming Like Functional Programming, Logic Programming is concerned with letting the programmer specify what the problem is, rather than how to solve it. A logic program consists of facts and properties about a problem; it’s the job of the system to find a solution to the problem.
26
CHAPTER 4. LANGUAGES
The success of logic programming is due to a formalism known as Horn Logic. Horn Logic can specify problems and also be executed automatically. Horn Logic is the basis for the most important logic programming language - Prolog. In the Prolog example below, relationships are created between family members.
father(fenton,joe). father(fenton,frank). father(angus,david). sibling(fenton,angus). sibling(angus,fenton). male(joe). male(frank). uncle(X,Y):- male(X), sibling(X,Z),father(Z,X).
AF
T
1. 2. 3. 4. 5. 6. 7. 8.
DR
Event-driven programming
Event-driven programming is a paradigm where the program flow is determined by user actions. This is in contrast to batch programming, where flow is determined when the program is written. Event-driven programming is used for interactive programs, such as word processors and spreadsheets. The program usually has an event loop, which repeatedly checks for interesting events, such as a keypress or mouse movement. Events cause the execution of trigger functions, which process the events. VB.NET is a popular event-driven language. The following example, in VB.NET, shows a typical event. In this case, the code that will be executed when a button is clicked.
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click ’ Event executes this code End Sub
4.3. DEGREE OF ABSTRACTION
4.3
27
Degree of Abstraction
The degree of abstraction defines how far the semantics of a language are from the basic commands used by a microprocessor. The lowest degree of abstraction is Machine Code. Machine Code is directly understood by a processor. The next level of abstraction is assembler. Higher-level languages vary in their level of abstraction.
4.4
Method of Execution
Compiled languages
AF
T
Compiled languages use a program called a compiler to translate source code into machine instructions, which is saved to a separate executable file. The use of a precompiler allows for optimisation and high execution speeds. A compiler is also capable of finding errors in the source code with great accuracy.
Interpreted languages
DR
Examples of compiled languages are C and C++.
Interpreted languages are programs that can be executed directly from source code by a program called an interpreter. This distinction refers to the implementation, rather than the language design itself. Most software is compiled, and in fact, any language can be compiled. Examples of interpreted languages are PERL and TCL.
Mixed A mixed language compiles a program into an intermediate form. The intermediate form is called bytecode in Java and Common Intermediate Language in C#. At runtime, the intermediate form is compiled into an executable. Usually the final step involves a virtual machine. This has the benefit of making the code portable across platforms. Examples of mixed languages are Java and C#.
28
4.5
CHAPTER 4. LANGUAGES
Generations
Another language classification in general use is that of generations. There are six recognised generations. To some degree the six generations overlap with the degree of abstraction of the programming language. The six generations are as follows (See [1] for more information).
1st generation These are machine languages, and are the oldest programming languages. This type of program was typically entered via routing wires or flipping switches on a front panel. Thus they talk directly to specific hardware, and are not portable.
2nd generation
DR
AF
T
These are assembly languages. Assembly is considerably easier to learn than machine code, but is still considered difficult by the average programmer. An assembler converts the assembler language statements into machine language. Below is an example of such a program.
; Hello World for Intel Assembler mov mov mov mov int xor int
ax,cs ds,ax ah,9 dx, offset Hello 21h ax,ax 21h
Hello: db "Hello, World!",13,10,"\$"
3rd generation These are procedural languages. They are often called high-level languages, and are an attempt to make programming languages more friendly. Early examples are Cobol and Fortran, but C and other modern languages are also
4.6. CONCLUSION
29
classified as 3rd generation languages. A compiler converts the statements of a 3rd generation programming language into machine language.
4th generation These are application languages. It is typical of application languages to exhibit strong data support. Data are self-describing and persistent. Most 4th generation languages incorporate information about the problem domain and of user interfaces [1]. Fourth generation languages are designed to reduce programming effort and development time and cost, be portable and OS-independent, and be usable by non-programmers.
5th generation
6th generation
DR
AF
T
These are inference languages, and include AI techniques. This, instead of the programmer explicitly designing algorithms, problems are solve using constraints. They are intended to allow non-specialists to apply AI techniques; the problem is specified and the computer solves the problem. Prolog is an example of a simple 5th generation language.
There are still differing opinions as to what constitutes the 6th generation of programming languages. Perhaps a defining characteristic is that this generation exhibits learning behaviour. An example may be a neural net, though in the opinion of many, this is an example of a 5th generation language.
4.6
Conclusion
Having said that, the choice of language may likely be market-driven. Lovely as prolog is, one is more likely to find gainful employment with a thorough knowledge of Java, or C#.
AF
DR T
Chapter
5
Problem Set 01
DR
AF
T
Practice yourself, for heaven’s sake, in little things; and thence proceed to greater. - EPICTETUS (Discourses IV.I)
Exercise is the beste instrument in learnyng. - ROBERT RECORDE (The Whetstone of Witte)
This chapter is the first that contains the actual exercises and problems. Each set is designed to be a more-or-less self-contained unit. A student will typically work on a single set before moving onto the next one. Of course, this is merely a suggestion and the student can pick and choose problems as they wish. Perhaps a warning is in order; not all of the problems have solutions! However, the act of attempting to solve them will bear fruit1 . The student will improve his or her programming skills and ”feel” for which problems are tractable or not. Output is given as an example only (when possible), and is not be indicative of the results of all possible inputs. This section contains warm-up exercises for the beginning programmer. Each problem should take no more than a few minutes to solve and requires only rudimentary knowledge of the language. These exercises will typically be as1 There
are considerable rewards for solving some of the problems!
31
32
CHAPTER 5. PROBLEM SET 01
signed after an hour or two of instruction. No input processing is required, as all variables will be hard-coded.
PROBLEM 1.
Difficulty: 1
The venerable Hello World program is traditionally used to give a first taste of a particular programming language. The program simply prints the string ”Hello World” to the output device of choice. Write a program that outputs ”Hello World” to your device. Input None. Output
Difficulty: 1
AF
PROBLEM 2.
T
Hello World
Input
DR
Write a program that outputs ”Hello World” on one line, and ”I’m doing okay!” on a second line. Use separate print/write statements to achieve this.
None. Output Hello World I’m doing okay!
PROBLEM 3.
Difficulty: 1
Write a program that outputs ”Hello World” on one line, and ”I’m doing okay!” on a second line. Use a single print/write statement to achieve this. Input None. Output
33 Hello World I’m doing okay!
The exercises listed as Problems 1 and 2 should clearly demonstrate the first basic control structure, sequence. When the program is PROBLEM 4. Difficulty: 1 required to print a second line, the code to do so is placed Write a program using a for loop that prints ”*” 10 times on the screen, all on after the code that prints the one line. first line. If this was not the case, programming would Input either be impossible or very, very complex.
None Output **********
PROBLEM 5.
Difficulty: 1
DR
Input
AF
T
In which type of variable would you store the following values? This will depend on the language you have chosen.
• A person’s name • A person’s age to the nearest year • A person’s weight in kilograms • A person’s annual salary • The radius of a circle • The cost of an item • A test grade out of 100 • Temperature in Celsius • A person’s net worth • The distance to a star in kilometres • The distance to a star in lightyears Output
34
CHAPTER 5. PROBLEM SET 01 • string
The exercises following Problem 4Problem Set 01pcount.4 clearly show the second basic control structure, repetition.
• int • etc...
PROBLEM 6.
Difficulty: 1
Write a program using a for loop that prints ”*” 10 times on the screen, one asterisk per line for ten lines.
Input None
PROBLEM 7.
AF DR
* * * * * * * * * *
T
Output
Difficulty: 1
Write a program using a loop of your choice that sums all the numbers from 1 to 10 and prints the result. Input None Output 55
PROBLEM 8.
Difficulty: 1
35 Write a program using a loop of your choice that multiplies all the numbers between 1 and 15 together (1 × 2 × 3 × ... × 15 or 15!). Input None Output 1.307674368 × 1012
PROBLEM 9.
Difficulty: 2
Write a program using two for loops to produce the following pattern of asterisks. Print only a single asterisk to the screen at a time. Input
AF
T
None
DR
Output
***** ***** ***** ***** *****
PROBLEM 10.
Difficulty: 1
Write a program that checks the contents of a integer variable containing a number between 0 and 9. Print the number as a word corresponding to the number in the variable. For this exercise, the number in the variable can be hardcoded; no interaction is required. Run the application a few times to test it, but remember to change the number in the variable before you recompile or interpret. Input 0 5
36 Output Zero Five
PROBLEM 11.
Difficulty: 2
Expand your solution to exercise 10Problem Set 01pcount.10 to include values from 0 to 999. Can you approach solving this problem like you did for exercise 10Problem Set 01pcount.10, or is there a more efficient way? Input 0 5 15 89
PROBLEM 12.
AF
Zero Five Fifteen Eighty-nine
T
Output
DR
Problem 10Problem Set 01pcount.10 demonstrates the use of the third basic control structure, selection. These are also known as conditionals. An example is the if ... then... statement, which typically takes the form if test is true, then perform some action; end if
CHAPTER 5. PROBLEM SET 01
Difficulty: 2
Write a program with two string variables. Initialize the first string (strOne) to ”World” and the second (strTwo) to ”Hello”. Print strOne followed by strTwo to the screen, then write the code to swap the values of strOne and strTwo and print them again. Note that you must change the values of the string variables, not just print them in a different order! Input None Output
37 World Hello
Hello World
PROBLEM 13.
Difficulty: 2
Write a program to determine a students’ average mark if they write four tests, and each test carries a weight of 25%. Print the result to the screen. Input None Output An example of a student with {50, 70, 46, 59} would be:
Difficulty: 2
AF
PROBLEM 14.
T
56%
DR
The surface area of a square or rectangle can be determined by multiplying the length by the breadth. Write a program to determine the surface area of a given square or rectangle. Assume the measurements will be in metres. Input None
Output Given a rectangle with length 20 metres and breadth 15 metres, the output would be: 300 square metres
PROBLEM 15.
Difficulty: 2
The volume of a sphere can be determined by the following formula:
38
CHAPTER 5. PROBLEM SET 01
V =
4 2 πr 3
(5.1)
Write a program to determine the volume of a sphere with a given radius. Input None
Output Given a sphere with r = 2metres, the output would be: 16.76 cubic metres PROBLEM 16.
Difficulty: 2
DR
AF
T
A common business calculation is to determine the percentage that the price of some product or service has increased [31]. The formula used is:
IncreaseAmount × 100 BaseAmount
(5.2)
Write a program to determine the increase for some set of figures. Note that in the example, the unit of currency is the South African Rand (R). Input None
Output If some product cost R200,000 in year 1 and R250,000 in year 2, then: 50000 200000
× 100 = 0.25 = 25%
PROBLEM 17.
Difficulty: 2
Produce a table of Celsius and the equivalent Fahrenheit temperatures from 0C to 100C. Fahrenheit can be converted from Celsius by multiplying by 9,
39 dividing by 5 and adding 32. Input None
Output
AF
T
Fahrenheit 32 33.8 35.6 ... 212
DR
Celsius 0 1 2 ... 100
AF
DR T
Chapter
6
Problem Set 02
DR
AF
T
This section contains a selection of trickier problems, and should perhaps be tackled after 3-4 hours of instruction. Some problems will be the work of a few minutes to solve. Others may take longer and require the student to think a little deeper.
PROBLEM 18.
Difficulty: 2
Write a program using two for loops to produce the following pattern of asterisks. Print only a single asterisk to the screen at a time. Input None.
Output
* ** *** **** ***** ****** ******* 41
42
CHAPTER 6. PROBLEM SET 02
******** ********* **********
PROBLEM 19.
Difficulty: 2
Write a program using one for loop to produce the following pattern of asterisks. Print only a single asterisk to the screen at a time. Input None.
PROBLEM 20.
AF DR
* ** *** **** ***** ****** ******* ******** ********* **********
T
Output
Difficulty: 2
Write a program that allows users to type letters on the keyboard. If the letter is a vowel, echo the letter on the screen. If the letter is a consonant, print an error message. Note that while it is fun to use insulting or sarcastic error messages while developing programs for yourself, never do it for programs that you write for your company, school or university.
Input A B D E
43 Output A Error! Error! E
PROBLEM 21.
Difficulty: 2
Write a method/function that receives two numbers as arguments and returns the value of their product.
Input 5 6
30
PROBLEM 22.
Difficulty: 2
DR
AF
T
Output
Write a recursive method/function to take the value 3 to the power of some other number.
Input 4
Output 81
PROBLEM 23.
Difficulty: 2
Write a program which calculates the sum
44
CHAPTER 6. PROBLEM SET 02
1+
1 1 1 + + ... + 2 3 n
(6.1)
for any given positive integer n. The program must contain two methods which can do the job. The first is public static void sum1(ref double sum,int n)) and the second is public static double sum2(int n) Thus for the method sum1() we pass sum by reference. Input None
DR
In the case n = 15, then:
3.318229 3.318229
PROBLEM 24.
AF
T
Output
Difficulty: 2
Write a program that prints determines the larger of 2 numbers and the larger of 3 numbers. Each section must use its own method. Method overloading must be used for this exercise.
Method for 2 numbers
public static double max(double p, double q)
Method for 3 numbers
public static double max(double p, double q, double r)
45
Input 59 9 10 3
Output 9 10
PROBLEM 25.
Difficulty: 3
Write a program that takes the system time, convert it into words, and print the result.
T
Input
DR
AF
5:00 5:10 5:15 5:30 5:45 5:47
Output Five o’clock Ten minutes past five Quarter past five Half past five Quarter to six Thirteen minutes to six PROBLEM 26.
Difficulty: 4
Write a program using for loops to produce the following pattern of asterisks. Print only a single asterisk to the screen at a time. Input
46
CHAPTER 6. PROBLEM SET 02
None.
Output
* *** ***** ******* *********
PROBLEM 27.
Difficulty: 4
Write a program using for loops to produce the following pattern of asterisks. Print only a single asterisk to the screen at a time. Input
AF
T
None.
DR
Output
* * *** *** ***** ***** ******* ******* ****************** ******* ******* ***** ***** *** *** * *
PROBLEM 28.
Difficulty: 3
Write a program that prints your initials on the screen. Compose each initial with six lines of small initials, as in the following example. Note that in the example it is assumed the initials will be hardcoded; an improvement to the program will be to input the initials. Input
47 None.
Output
eeeeee e eeeeee e eeeeee
jjjjjj j j j jjjj
PROBLEM 29.
ddddd d d d d d d ddddd
Difficulty: 3
Write a program that takes a string which contains a number of words. Split the string into its component parts. Store each word in its own string. To display the result, print the strings in random, reverse, or some other order.
T
Input
Output
DR
AF
He who does wrong does wrong against himself. He who acts unjustly acts unjustly to himself, because he makes himself bad.
Himself against wrong does wrong does who he. Who he acts unjustly acts to unjustly himself, he because himself makes bad.
AF
DR T
Chapter
7
Problem Set 03
Difficulty: 2
AF
PROBLEM 30.
T
This set contains problems that reinforce I/O concepts. A number of them will require file manipulation.
DR
Write a program that inputs a string of keyboard characters and outputs the characters in reverse order.
Input Joy to the world
Output dlrow eht ot yoJ
PROBLEM 31.
Difficulty: 2
Write a program that reads three floating point numbers from the keyboard. Then add the three numbers and calculate the arithmetic mean (average).
Input
49
50
CHAPTER 7. PROBLEM SET 03
1.2 5.8 15.15
Output 7.38
PROBLEM 32.
Difficulty: 3
Write a program that takes 5 input values and displays these values in a histogram form using asterisks. Write the program using loops, and then again without loops.
Input
Output 1: * 4: **** 9: ********* 15: *************** 12: ************
PROBLEM 33.
DR
AF
T
For example, if the input is 1 4 9 15 12 then your output would look like:
Difficulty: 3
The Trabb Pardo-Knuth algorithm is a program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of computer programming languages. The algorithm reads eleven numbers from an input device, stores them in an array and then processes them in reverse order, applying a userdefined function to each value and reporting either the value of the function or a message to the effect that the value has exceeded some threshold.
Implement the Trabb Pardo-Knuth algorithm. The user-defined function could, for example, square the number. The threshold may be some arbitrary number, for example, 100.
51 Input None.
Output PROBLEM 34.
Difficulty: 3
Write a program that accepts as input the user’s birthday. Then display the number of days between the user’s birthday and the following 1st of January.
Input Month? 12 Day? 01
T
Output
Difficulty: 3
DR
PROBLEM 35.
AF
31
Write a program that opens a file, sorts the contents, and saves the sorted file under a different name. Use as input a file containing a list of integer numbers, one per line. Any of the sort algorithms can be used for sorting the file (see section 15Problem Set 11chapter.15).
Input 8 9 2 18 141 54 ... 4
Output
52
CHAPTER 7. PROBLEM SET 03
2 4 8 9 18 54 141 ...
PROBLEM 36.
Difficulty: 3
Write a program which asks for the name of a file and then counts the number of words in the file. A word is defined as any sequence of symbols separated by any combination of space characters and/or line breaks.
Input
DR
AF
T
I WILL here give a brief sketch of the progress of opinion on the Origin of Species. Until recently the great majority of naturalists believed that species were immutable productions, and had been separately created. This view has been ably maintained by many authors. Some few naturalists, on the other hand, have believed that species undergo modification, and that the existing forms of life are the descendants by true generation of pre-existing forms. passing over allusions to the subject in the classical writers, the first author who in modern times has treated it in a scientific spirit was Buffon. But as his opinions fluctuated greatly at different periods, and as he does not enter on the causes or means of the transformation of species, I need not here enter on details.
Output 131 words
PROBLEM 37.
Difficulty: 2
Write a program that prompts the user for a filename. The program then outputs whether or not a file of that name exists, what the access rights on the file are, when last the file was accessed and the size of the file.
Input
53 Enter filename: testlog.txt
Output Exists Rights: Read, Write, Delete Access date: 2002-07-21 Filesize: 19681114 bytes
PROBLEM 38.
Difficulty: 3
AF
T
Write a program that accepts input from the user in the form of text data of arbitrary length. When the user has entered their data, allow the user to save their data to a text file. Upon saving the file, perform a spell check. To accomplish this each word in the user’s text file must be compared against a list of words in another file. If a word in the user’s file is close, but exactly the same as a word in the spell check file, show the user that their might be a spelling error, and include a line number for them.
DR
The spell check file should contain as many words as possible, but for the sake of this exercise, perhaps 50-100 of the most common words will suffice.
The problem arises of what kind of metric to use to decide if a word is misspelt or not. This is a problem for the programmer. One suggestion is to compare the two words, and if the word lengths are the same or 1 character shorter or longer, and the words differ at most2 characters, then suggest an alternative spelling. In words of the same length, a one or two character difference might indicate an error.
To substantially improve the utility of this program, allow users to select a word and replace the misspelt word in their file with that selected word.
Input ENTER DATA: It was in July, 1805, and the speaker was the well-known Anna Pavlovna Scherer, maid of honour and favourite of the Empress Marya Fedorovna. With these words she greetd Prince Vasili Kuragin, a man of high rank and importance, who was the first to arrive at her reception. Anna Pavlovna had had a coff for some days. She was, as she said, suffering from la
54
CHAPTER 7. PROBLEM SET 03
grippe; grippe being then a new word in St. Petersburg, used only by the elite.
Output Possible error line 2: greetd = greeted? Possible error line 3: coff = cough, coffin? Possible error line 4: teh = the?
PROBLEM 39.
Difficulty: 3
Write a program to list all the files in the current directory/folder. Show some relevant data about the file, for example, the date it was last modified. Include a line of output showing the number of files found.
Input
AF
T
lst
17/07/2009 22/03/2006 12/09/2007
DR
Output 22:11 12:10 21:39 3 File(s)
PROBLEM 40.
0 dir.txt 1,501 ITN20BT_ST_20061.txt 3,006,590 vs2005.tif 3,008,091 bytes
Difficulty: 4
Create a modified version of the above directory listing program that shows a thumbnail to indicate the type of file. If the file is an image file, it may be a good idea to show a thumbnail image of the file instead.
Input lst
Output 12/09/2001
11:39
3,006,590 Knossos.bmp
55
AF
T
3,008,091 bytes
DR
1 File(s)
AF
DR T
Chapter
8
Problem Set 04
DR
AF
T
Many computational problems find their solution in arrays. Arrays are used for holding sets of items that are of the same kind, and allows a general way to access all of them. For example, an array is useful for holding a set of examination marks, and performing some operation on them. This problem set provides practice with arrays. The value of the elements may be hardcoded or input at runtime PROBLEM 41. Difficulty: 2 Write a program to find the sum of the elements of an array. Input 64591
Output Sum = 25
PROBLEM 42.
Difficulty: 2
Write a program to find the largest of the elements of an array.
Input 57
58
CHAPTER 8. PROBLEM SET 04
64591
Output Largest = 9
PROBLEM 43.
Difficulty: 2
Write a program to find the smallest of the elements of an array. Input 64591
Output
Difficulty: 2
DR
PROBLEM 44.
AF
T
Smallest = 1
Write a program to find the range of the elements of an array. Input 64591
Output Range = 1 to 9
PROBLEM 45.
Difficulty: 2
Write a program to find the mean of the elements of an array.
Input 64591
59 Output Mean = 12.5
PROBLEM 46.
Difficulty: 2
Write a program to find the geometric mean of the elements of an array.
Input .
Output GM =
T
Difficulty: 2
AF
PROBLEM 47.
DR
Write a program to find the median of the elements of an array. Input 64591
Output Median = 5
PROBLEM 48.
Difficulty: 2
Write a program to find the mode of the elements of an array. Input 64591595
Output
60
CHAPTER 8. PROBLEM SET 04
Mode = 5
PROBLEM 49.
Difficulty: 2
Write a program to rotate the elements of an array. Move the value of the first element into the second element, the value of the second into the third and so on. Move the value of the last element into the first. Input 19830121
Output 11983012
Difficulty: 3
T
PROBLEM 50.
DR
Inputasdgfhfh
AF
Write a program to determine if an array is in alphabetical order.
OutputNot in order
PROBLEM 51.
Difficulty: 3
Write a program that reads in 55 integers. Output them in reverse order in the form of a triangle. One integer should appear on the first line, two on the second, three on the third, and so on. Input Output PROBLEM 52.
Difficulty: 3
Write a program to add corresponding elements of 2 two-dimensional arrays to give a 3rd two-dimensional array. The arrays should be at least 5 rows by 5 columns. Display only the 3rd array i.e. the sum array.
61 Consider the space complexity problem. How much space can be saved by using only two arrays? Can you devise an experiment to show the benefit of using two versus three arrays? Is there a benefit? Input First array:
1 2 3 4 1
1 2 3 4 2
1 2 3 4 3
1 2 3 4 4
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
AF
1 2 3 4 5
DR
1 2 3 4 5
T
Second array:
Output 2 4 6 8 6
2 4 6 8 7
2 4 6 8 8
2 4 6 8 9
2 4 6 8 10
PROBLEM 53. Difficulty: 3 Write a program that increments every element in a three-dimensional array of integers. Write the program in such a way that the dimensions of the array can be chosen at runtime. For larger arrays, it would be better to then assign all elements a random value. Input Enter dimension? 3
62
CHAPTER 8. PROBLEM SET 04
Output 27 elements populated Elements are: 1 2 1 3 2 1 2 3 1 2 3 1 2 3 4 3 2 4 3 2 1 2 3 2 1 2 3 Incremented elements are: 2 3 2 4 3 2 3 4 2 3 4 2 3 4 5 4 3 5 4 3 2 3 4 3 2 3 4
PROBLEM 54.
Difficulty: 3
Write a program to display a mileage table. Show the range of litres at fillup from 10 to 50 litres in increments of 5 litres. Show the range of distances travelled in increments of 10 kilometres. Input Output PROBLEM 55.
Difficulty: 3
Output PROBLEM 56.
DR
Input
AF
T
Write a program that takes as its input either a character or string. Examine an array for any occurrence of this character or string, and remove it. Shift the subsequent elements of the array to fill the gap.
Difficulty: 3
Write a program which sorts the contents of a two-dimensional array, row by row, so that they are in ascending order when read left to right. Leave the elements in their respective rows. Can this be achieved without using additional arrays for storage? Input Output
Chapter
9
Problem Set 05
AF
T
This section contains exercises and problems that involve number manipulation and maths. PROBLEM 57. Difficulty: 3
DR
This problem may have been originally designed by Jeff Atwood on the Coding Horror blog. Write a program that prints the numbers from 1 to 100. But for multiples of three print ”Coca” instead of the number and for the multiples of five print ”Cola”. For numbers which are multiples of both three and five print ”Coca Cola”1 . Input None.
Output 1 2 Coca 4 Cola Coca 1 Coca Cola is a trademarked name. It’s use here does not constitute a challenge to that trademark.
63
64
CHAPTER 9. PROBLEM SET 05
7 8 Coca Cola 11 Coca 13 14 Coca Cola ...
PROBLEM 58.
Difficulty: 2
The two’s complement is a method of storing signed integers. It is used in most present day CPUs [7]. Write a program that shows how to obtain the negative of a number, and how to add and subtract, using two’s complement.
AF
PROBLEM 59.
Difficulty: 2
DR
Output
T
Input
Write a program which reads an integer N and returns its absolute value. If N is positive, we merely produce N. If N is negative, we remove the sign. Input 5 -10
Output 5 10
PROBLEM 60.
Difficulty: 2
Produce a sequence of six random numbers between 1 and 49. These can then be used to play the National lottery. The odds on getting the right numbers are 13,983,816 to 1.
65
Input None.
Output 3 6 12 17 24 40 10 11 19 27 36 41
PROBLEM 61.
Difficulty: 3
The highest common factor (HCF) of two positive integers x and y is the largest integer that divides each of x and y exactly. For example, the HCF of 45 and 30 is 15.
DR
AF
T
Here is a form of Euclid’s algorithm for finding the HCF of two integers. Let’s say we want to find the HCF of 36 and 90.
Write down the numbers: 36 90 Then write down their difference: 36 90 54 Form a ”number chain” by repeatedly writing down the difference between the last two numbers, stopping when you get to zero. The last non-zero number is the HCF: 36 90 54 36 18 18 0 The HCF of 36 and 90 is 18
Write a program that inputs two positive integers and outputs their HCF.
Input First Number: 36 Second Number: 90
Output Answer: 18
66
CHAPTER 9. PROBLEM SET 05
PROBLEM 62.
Difficulty: 3
The Collatz conjecture is an unsolved conjecture in mathematics, named after Lothar Collatz, who proposed it in 1937. The conjecture is also known as the 3n + 1 conjecture, as the Ulam conjecture and the Syracuse problem. par When taking an arbitrary integer, perform the following operations on it: • If the integer is even, divide by 2. • If the integer is odd, triple it and add 1. The conjecture states that the number will eventually equal 1. For example, if we start with 6 we get: 6, 3, 10, 5, 16, 8, 4, 2, 1. If we use 10: 10, 5, 16, 8, 4, 2, 1.
DR
AF
T
Write a program that accepts a integer and displays the entire sequence. As a variation, you can write a program that uses a brute force method to determine if the Collatz conjecture is true, and runs the algorithm against a large set of numbers, say 1 to 100,000,000 (or higher). In this case, only cases that disprove the conjecture will be displayed. Input 15 224
Output 15: 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1 224: 112 56 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
PROBLEM 63.
Difficulty: 3
Referring to Problem 62Problem Set 05pcount.62, write a program that accepts two arbitrary integers. Then print the lowest and highest cycle lengths for every number between, and including, the two input integers. The cycle length is the number of numbers generated to generate the 1 (including the 1). Input
67 24 1 10
Output 17 1 20
PROBLEM 64.
Difficulty: 3
Fibonacci numbers are a sequence of numbers named after the Italian mathematician Leonardo of Pisa (c.1175-c.1250), whose book Liber Abaci, published in 1202, introduced the sequence [4]. Leonardo is better known as Fibonacci, which means ”son of Bonaccio”.
T
A Fibonacci number is computed by adding the preceding two numbers together. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. Write a program that uses iteration to print the first 25 Fibonacci numbers.
AF
Input
DR
None.
Output 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...
PROBLEM 65.
Difficulty: 3
A Fermat number, named after the French mathematician Pierre de Fermat n (1601-65) who first studied them, is a positive integer of the form F n = 22 +1. The first 3 Fermat numbers are 3, 5, 17 [4].
Write a program to display the first 6 Fermat numbers.
Input None.
68
CHAPTER 9. PROBLEM SET 05
Output 3, 5, 17...
PROBLEM 66.
Difficulty: 3
Take any 3-digit number and arrange its digits in descending order and in ascending order and subtract. Repeat with the result, remembering to arrange the numbers digits in the correct order. Eventually, all 3 digit numbers (except when all digits are the same, like 333) will end up as 495. This is called Kaprekar’s Constant, after the famous Indian mathematician. Having never received any formal postgraduate training, for his entire career (1930-1962) he was a schoolteacher in the small town of Devlali in Maharashtra, India [20].
Write a program that will return the number of steps it takes to get to 495, and show each step clearly.
AF
213 - 123 - 189 - 279 - 369 - 459
= = = = =
198 792 693 594 495
DR
Input: 1: 321 2: 981 3: 972 4: 963 5: 954
T
Here is an example series:
Note the following invalidates the number:
1. it is zero or negative 2. it is not a 3-digit number 3. it is a positive 3-digit number but all the digits are equal (e.g. 444)
Does this apply for a 4- or 5-digit number?
Input Output
69 PROBLEM 67.
Difficulty: 3
Body Mass Index (BMI) gives an accurate measure of obesity. In order to determine BMI, determine height in metres and weight in kilograms, and use the formula below [26].
BM I =
weight(kg) height(m)2
(9.1)
Write a program that determines BMI. If the BMI is less than 18, then the user is underweight, if between 19 and 25 their weight is normal, if 26-30 they are overweight. If BMI is over 30, they are obese.
Input
AF
T
Weight in kilograms? 75 Height in metres? 1.7
DR
Output Your weight is NORMAL.
PROBLEM 68.
Difficulty: 3
The formulae used for the compound increase or decrease of money, populations and variety of articles whose value change on a regular basis are as follows, where A is the accumulated amount after a given time period, P is the present value of a sum before an increase or decrease, n is the number of increases or decreases that have been taken over a given time and r is the rate of interest for the time period between each increase.
Compound Increase
A = P (1 + ( Compound Decrease
r n ) 100
(9.2)
70
CHAPTER 9. PROBLEM SET 05
A = P (1 − (
r n ) 100
(9.3)
Write a program to determine A, given the appropriate input.
Input Output PROBLEM 69.
Difficulty: 3
The escape velocity is the speed required to escape from the surface of an astronomical body. The following formula can be used when considering escape velocities from planets:
r
2GM r
(9.4)
DR
AF
T
Ve =
Here G is the gravitational constant 6.67 × 10−11 m3 /s2 kg, M is the mass of the astronomical body in kilograms and r is its radius in meters.
Write a program to calculate escape velocity. You can use the following: Planet Earth Jupiter
M 5.98 × 1024 1.899 × 1027
r 6.38 × 106 7.145 × 107
Input Output PROBLEM 70.
Difficulty: 3
Write a program that prints a calendar for a given year. Your calendar must include all 12 months, and the days of the week must fall on the correct dates. It is your decision whether to start a week on a Sunday or Monday, and whether to print the week days vertically to the left of the month or horizontally above.
71 Input Welcome to Print-a-Calendar! For which year would you like a calendar? 2009
Output One example month is shown. For this exercise, show all 12 months.
FEBRUARY
T
W
T
F
S
2 9 16 23
3 10 17 24
4 11 18 25
5 12 19 26
6 13 20 27
7 14 21 28
S 1 8 15 22
Table 9.1: Calendar Difficulty: 3
T
PROBLEM 71.
M
DR
AF
The Julian Day is a continuous count of days and fractions of days from the beginning of the year 4712BC. Almost 2.5 million days have passed since then. By tradition the Julian Day begins at Greenwich mean noon. [15]. The Julian Day was originally conceived in 1582 by the French Chronologist Joseph Justus Scalinger (1540-1609). Scalinger used the name ”Julian” to honour is father, Julius Caesar Scalinger. It is not to be confused with the Julian Calendar, devised by Julius Caesar (100 BC-44 BC) [19]. For example, the Julian day for the 1st of January, 2008 at 00:00:00.0 UT is JD 2454466.50000. The formulae are below, where Y is the year, M the month number (1 for January, 2 for February and so on), D is the day of the month (with decimals as needed). Note that the INT in the formulae below means that integer division is applied; remainders are discarded.
• If M > 2 leave Y and M unchanged • If M = 1 or M = 2 replace Y by Y-1 and M by M+12. • Express D as the day and time, with the time as a decimal between .0 and .99. For example the 5th of the month at 12:00 will be 5.5, and the 20th of the month at 15:30 will be 20.65. In other words, if the date is in January or February, it is considered to be in the 13th or 14th month of the preceding year. Now determine the following:
72
CHAPTER 9. PROBLEM SET 05
A = IN T (
Y ) 100
(9.5)
A B = 2 − A + IN T ( ) 4 If the date is before October the 4th, 1582, then B = 0.
(9.6) 2
The require Julian Day is then:
JD = IN T (365.25(Y + 4716)) + IN T (30.6001(M + 1)) +D + B − 1524.5
(9.7)
Input
DR
AF
T
Write a program to calculate the Julian Day for a given time and date. For example, October 4th 1957 at 19:26, the launch of Sputnik 1 (the first artificial satellite, made in the USSR), or August 25th 2012, the day that Neil Armstrong died.
Year: 1957 Month: 10 Day: 4 Hour: 19 Minute: 26
Output JD: 2,436,116.31
Note that depending on how your machine represents numbers, the answer for the example may differ slightly
PROBLEM 72.
Difficulty: 3
2 It was on this date that the Julian Calendar was discarded in favour of the Gregorian Calendar, which corrected for the accumulated error in the former.
73 Write a program that, given the coordinates of two aeroplanes in flight, and their headings, that determines whether or not they will collide with one another. Input Output PROBLEM 73.
Difficulty: 3
Roche’s Limit is the approximate point where a satellite will be torn apart by tidal forces. It assumes the satellite is only held together by it’s own gravity, so the Roche Limit is not used for artificial satellites like the International Space Station. For a satellite of density ρP orbiting a planet of radius r and density ρP the formula is:
p 3
ρP /ρS
(9.8)
T
L = 2.44r
DR
AF
Write a program that determine’s Roche’s Limit for a given planet and its satellite. For test data you can use the Earth-Moon system, where r = 6378, ρP = 5.497 and ρS = 3.36.
Input r : 6378 ρP : 5.497 ρS : 3.36
Output Roche Limit = 18337.34662
PROBLEM 74.
Difficulty: 3
An irrational number is a number that cannot be written as a rational number [11]. Some examples are: √
2,
√
3, π, e, φ
74
CHAPTER 9. PROBLEM SET 05
Write a program to generate the first 1,000,000 numbers of each of these irrational numbers. Save the results in a file for later use. This problem is perhaps more difficult that it appears on the surface, as you may have to create a way to store very large numbers.
Input π
Output 3.1415...
PROBLEM 75.
Difficulty: 3
Input Draw8thCircle(int r);
DR
AF
T
Write a function that draws the upper eighth of a circle. Centre the circle at (0,0), with a given radius r. The upper eighth is defined as the position starting at 12 ’o clock on a clock face [16].
Output PROBLEM 76.
Difficulty: 3
Oleksandr Mikolaivich Sharkovsky is a Ukrainian mathematician. Sarkovskii’s theorem describes an ordering of natural numbers according to which periodicities imply other periodicities for continuous maps in R. The ordering is:
3 . 5 . 7 . 9 . ... . 2 · 3 . 2 · 5 . 2 . 7 . ... . 22 · 3 . 22 · 5 . 22 · 7 . ... . 23 . 22 . 2 . 1
That is to say, all odd numbers excluding 1 come first, followed by the same sequence multiplied by 2, then by 22 and so on. Lastly, the powers of 2 in decreasing order [28].
75 Write a program that accepts as input two integers. Determine whether for those integers x and y whether x . y or y . x.
Input Output PROBLEM 77. Eratosthenes of Cyrene (c.275-194 BC) was a Greek mathematician and astronomer . Among his many accomplishments was the determination of the circumference of the Earth [4].
The Sieve of Eratosthenes is a simple algorithm for finding all prime numbers up to a specified integer. The algorithm is as follows:
AF
T
1. Write a list of numbers from 2 to the largest number you want to test for primality. Call this List A.
DR
2. Write the number 2, the first prime number, in another list for primes found. Call this List B. 3. Strike off 2 and all multiples of 2 from List A. 4. The first remaining number in the list is a prime number. Write this number into List B. 5. Strike off this number and all multiples of this number from List A. The crossing-off of multiples can be started at the square of the number, as lower multiples have already been crossed out in previous steps. 6. Repeat steps 4 and 5 until no more numbers are left in List A. Note that, once you reach a number greater than the square root of the highest number in List A, all the numbers remaining in List A are prime. Using Eratosthenes’ sieve, write a program that can produce all the prime numbers greater than zero and less than or equal to some largest number Max. Input Max? 10
Output
76
CHAPTER 9. PROBLEM SET 05
12357
PROBLEM 78. A number P is said to be perfect if P is equal to the sum of all its factor excluding itself. Example, 6 is perfect, so is 28. Write a program to determine perfect numbers [11].
Input None.
Output 6, 28, 496...
AF
T
PROBLEM 79.
DR
Christian Goldbach (1690-1764) was a German mathematician. Goldbach’s Conjecture is that any even number is the sum of two primes. Write a program to test Goldbach’s Conjecture over a range of numbers. What can you deduce from the results.
Input Output PROBLEM 80. A palindrome is a number that reads the same forwards and backwards, like 12321. Write a program that tests input integers for the palindrome property.
This is a similar problem to one of the previous problems (Problem 135Problem Set 13pcount.135).
Input 12321
77 246642 23442
Output Palindrome Palindrome Not palindrome
PROBLEM 81. Write a program that accepts as input an arbitrary integer. Take the reverse of the integer and add that value to the integer. Repeat the process with the sum. If a palindrome is produced, display this fact, the palindrome, and the number of iterations it took to reach the palindrome. To prevent an infinite loop, limit the program to some upper bound of iterations (100, 1,000,000, 100,000,000?).
AF DR
3 196 265
T
Input
Output Palindrome: 9339 in 4 iterations No Palindrome Palindrome: 6666 in 3 iterations
PROBLEM 82. The Hungarian mathematician Paul Erd¨os is one of the most famous and prolific mathematicians of all time. It is considered an honour to have co-authored a paper with him. Not everybody got a chance to do so, so the best they could do was publish with someone who co-authored a paper with Erd¨os. This gave rise to the so-called Erd¨ os number. An author who has published with Erd¨os gets an Erd¨ os number of 1. If someone publishes with someone with an Erd¨os number of 1, then his or her Erd¨os number is 2. And so on. If there is no connection then the Erd¨ os number is infinity [25]. Write a program that accepts two string parameters. The first string will represent the primary author, the one whom his or her own Erd¨os number
78
CHAPTER 9. PROBLEM SET 05
will be applied. The second string will contain another author. Then take as input a file containing a list of papers, some of them by the authors entered in the strings. The program will calculate a number for the second author that relates him or her to the first author in the same manner as Erd¨os numbers relate authors to Paul Erd¨os. Input File? nonlinear.txt First Author? WH Steeb Second Author? Y Hardy
Output Number: 1
PROBLEM 83.
Difficulty: 4
10 16
DR
Input
AF
T
Given a number N, express it as a product of its prime factors.
Output 2*5 2*2*2*2
PROBLEM 84.
Difficulty: 4
Given a number N, determine whether it is a prime. Do not use Eratosthenes Sieve. Input 13 15
79 Output
Benoit Mandelbrot (1924 2010) was a Polish-born French and American mathematician. His most famous contributions were in the field of fractals, the term which he coined.
Prime Not a Prime
PROBLEM 85.
Difficulty: 4
A Mandelbrot set is a set of mathematical points that forms a two-dimensional fractal shape. Generate and draw the Mandelbrot set. Input
DR
AF
T
Output
AF
DR T
Chapter
10
Problem Set 06
DR
AF
T
An abstract data type is a collection of well-defined operations that can be performed on a particular structure [24]. Containers are abstract data types that permit storage and retrieval of data items independently of content. The most commonly encountered containers are stacks, queues and tables. These can implemented using arrays or linked lists. Other containers are dictionaries, binary search trees and priority queues. This section contains exercises and problems about data structures like lists, queues and stacks. In some cases, depending on the approach taken, they also provide practice with arrays. PROBLEM 86. Difficulty: 3 A list is an ordered collection of elements supporting random access to each element, like an array. Lists preserve insertion order and makes no attempt to preserve the uniqueness of values. Lists are dynamic. Write a program that creates a list of objects and allows the following operations on the list:
• insert: Allows insertion into a specified position in the list • delete: Deletes the value at a specified position in the list • get: Obtains the value at a specified position in the list • size: Obtains the number of elements in a list
PROBLEM 87.
Difficulty: 3 81
82
CHAPTER 10. PROBLEM SET 06
1
2
3
4
5
Figure 10.1: List
Create the following operations for the previous list program.
• set: Sets the value at a specified position in the list • add: Adds a value to the end of the list • deletefirst: Deletes the first occurrence of a value in a list • contains: Determines if a specified value is contained in the list • indexOf : Obtains the position of the first occurrence of a value • isEmpty: Determines if the list is empty or not
T
• iterator: Creates an iterator for all elements of the list
Input
DR
AF
• clear: Deletes all elements from a list
Output PROBLEM 88.
Difficulty: 3
A singly linked list is a data structure holding a series of elements which contain both a data item and a pointer to the next element in the list.
Implement a singly linked list. One possibility is to use two parallel arrays (one for the data item and one for the link to the (logically) next item). Input Output PROBLEM 89.
Difficulty: 3
A doubly linked list is a data structure holding a series of elements which contain both a data item, a pointer to the next element in the list and a pointer to the previous element.
83
1
2
3
4
5
Figure 10.2: Singly Linked List
Implement a doubly linked list. One possibility is to use three parallel arrays (one for the data item and one for the link to the (logically) next item). Input Output
2
3
4
5
AF
T
1
PROBLEM 90.
Difficulty: 3
DR
Figure 10.3: Doubly Linked List
A linked list can be cyclic or cyclic. The difference between the two appears at their ends. A cyclic linked list has an end node that points back to one of the earlier nodes. An acyclic linked list is NULL terminated. Write a program that determines if a linked list is cyclic or acyclic. Do not modify the list in any way.
Input Output PROBLEM 91.
Difficulty: 3
A queue is a data structure holding data items that are processed on a firstin-first-out (FIFO) basis. That means that the first value to go in is the first value to come out. There are two main operations that can be performed on a queue, a node can be added to the end of a queue and a node can be removed from the head of a queue.
Implement a queue using an array that can perform the following operations.
84
CHAPTER 10. PROBLEM SET 06
• enqueue: Stores a value in a queue • dequeue: Retrieves and deletes the next value in the queue • clear: Deletes all elements in a queue • size: Obtains the number of elements in a queue • isEmpty: Determines if the queue is empty
Input
DR
Output
AF
T
Figure 10.4Queuefigure.10.4 shows a queue with 5 elements in it, which were ENQUEUED in order, 1, 2, 3, 4 and then 5. If we perform the operation of ENQUEUE on it, or add an element, then figure 10.5Queue after ENQUEUEfigure.10.5 will result; we have added element number 6. Then if we were to perform an DEQUEUE operation, the first element that was ENQUEUED is returned and deleted, giving us figure 10.6Queue after DEQUEUEfigure.10.6.
Refer to figures 10.5Queue after ENQUEUEfigure.10.5 and 10.6Queue after DEQUEUEfigure.10.6.
1 2 3 4 5
PROBLEM 92.
Figure 10.4: Queue Difficulty: 3
A priority queue is a type of queue that provides access to the largest element within it [8]. Using an unsorted queue, create a modified dequeue operation
85
1 2 3 4 5 6 Figure 10.5: Queue after ENQUEUE
2
DR
5
AF
4
T
3
6 Figure 10.6: Queue after DEQUEUE
that retrieves the element in a queue with the highest value.
Input Output PROBLEM 93.
Difficulty: 3
Modify your priority queue program to allow for sorted queues. Do not perform a sort, but modify the enqueue operation to automatically insert new values in a sorted order. Then the dequeue operation will automatically remove the largest item at the end of the queue.
86
CHAPTER 10. PROBLEM SET 06
Input Output PROBLEM 94.
Difficulty: 3
A stack is a data structure holding data items which are processed in a lastin-first-out (LIFO) basis. The operations performed on stack data structures are pop (removing the top element) and push (adding a new element). A frequently used metaphor is the idea of a stack of plates in a spring loaded cafeteria stack. Only the top plate is visible and accessible to the user, all other plates remain hidden. As new plates are added, each new plate becomes the top of the stack, hiding each plate below, pushing the stack of plates down. As the top plate is removed from the stack the plates pop back up, and the second plate becomes the top of the stack. See [8] and [2] for more information.
T
Implement a stack using an array that can perform the following operations:
AF
• push: Adds a value to the top of the stack.
DR
• pop: Deletes and returns the value at the top of a stack. • peek: Returns but does not delete the value at the top of a stack. • size: Obtains the number of elements in a stack. In figure 10.7Stackfigure.10.7, size will return 3. • isEmpty: Determines whether or not a stack is empty. In figure 10.7Stackfigure.10.7, isEmpty will return false. • clear: Deletes all elements from a stack. In figure 10.7Stackfigure.10.7, clear will delete elements 1 to 3. Input Figure 10.7Stackfigure.10.7 shows a representation of a stack with three elements in it. The elements were PUSHed in order, 1, 2, then 3. Thus if we PEEK, we will get a return value of 3. If we PUSH, then the stack will look like figure 10.8Stack after PUSHfigure.10.8 and a PEEK will return a value of 4. If we perform a POP, then a value of 4 will be returned, the element 4 will be deleted and the stack will look like figure 10.9Stack after POPfigure.10.9.
Output
87 Refer to figures 10.8Stack after PUSHfigure.10.8 and 10.9Stack after POPfigure.10.9.
3 2 1 Figure 10.7: Stack
4 3
T
2
AF
1
DR
Figure 10.8: Stack after PUSH
3 2 1 Figure 10.9: Stack after POP PROBLEM 95.
Difficulty: 3
A tree is made up of nodes with zero or more child pointers to other nodes. Each node has only one other node pointing to it. A Binary Search Tree (BSD) is a tree in which each node’s left child is less than or equal to it’s value, and its right child is greater or equal to its value [16].
Write a program that implements both a tree and a BSD.
Input
88
CHAPTER 10. PROBLEM SET 06
DR
AF
T
Output
Chapter
11
Problem Set 07
AF
T
This section contains a series of cryptographic problems that range from the simple to the fairly complex. PROBLEM 96. Difficulty: 3
DR
In cryptography, a substitution cipher is a method of encryption by which units of plaintext are substituted with ciphertext according to a regular system; the ”units” may be single letters, pairs of letters, triplets of letters or some combination of the above. The receiver deciphers the text by performing an inverse substitution. Substitution over a single letter can be demonstrated by writing out the alphabet in some order to represent the substitution. This is termed a substitution alphabet. The cipher alphabet may be shifted or reversed or scrambled in a more complex fashion, in which case it is called a mixed alphabet or deranged alphabet. A common example of this is the ”Caesar Cipher”, described by Julius Caesar in his book The Gallic Wars. In this method each letter in the alphabet is replaced by the letter three places after it in the alphabet. So A = D, B = E, C = F... Z = C [18]. Write a program to implement a substitution cipher. Input Output PROBLEM 97.
Difficulty: 3
It is possible to break or decipher a substitution cipher using a brute force method. This is a method that merely checks each possible answer until a 89
90
CHAPTER 11. PROBLEM SET 07
decipherment is achieved. Write a program to decipher ciphertext created by the above substitution cipher program, using the brute force method. PROBLEM 98.
Difficulty: 3
In classical cryptography, a transposition cipher changes one character from the plaintext to another (to decrypt the reverse is done). That is, the order of the characters is changed. The simplest form of this method is the Monoalphabetic Cipher, in which we write the alphabet in a randomly chosen order beneath the alphabet written in alphabetic order. The key is then the order in which the random letters are written [18]. Write a program to implement a transposition cipher. PROBLEM 99.
Difficulty: 3
Determine the number of possible keys for the above Monoalphabetic Cipher. PROBLEM 100.
Difficulty: 3
DR
AF
T
Write a program that takes as its input a text file and produces a histogram of the relative frequencies of all the letters in the textfile. What do you notice about the distribution of the letters? How can we use this knowledge to decipher ciphertext? If we use as input a file containing ciphertext, have we made any progress in deciphering it? Input The Time Traveler (for so it will be convenient to speak of him) was expounding a recondite matter to us. Output A: 3 B: C: D: E: 12 F: G: H: 2 I: 6 J: K: L: M: 3
91
DR
AF
T
N: O: P: Q: R: 3 S: T: 7 U: V: 2 W: X: Y: Z:
AF
DR T
Chapter
12
Problem Set 08
DR
AF
T
This set of problems covers board games. They are arranged from the simple to the extremely difficult to program, but most are still turn-based two-player games. The intention is to develop a game in which a player plays against the computer. However, it makes sense to first develop a two player game, then update the program to include the computer player. PROBLEM 101. Difficulty: 3 Write a program to play the game of Tic-Tac-Toe, also known as Noughts and Crosses. This game is played on a three-by-three grid. Players alternate by placing either a ”X” or a ”0” in one of the squares of the grid. The winner is the first person to have a horizontal, vertical or diagonal line. Input Output PROBLEM 102.
Difficulty: 4
Checkers is a popular board game played on an eight-by-eight grid. Write a program to play the game of checkers. Input Output PROBLEM 103.
Difficulty: 4
93
94
CHAPTER 12. PROBLEM SET 08
DR
AF
T
Figure 12.1: Tic Tac Toe
Figure 12.2: Checkers Board
Write a program to play the game of Backgammon.
Input Output PROBLEM 104.
Difficulty: 4
Chess is one of the oldest and most popular board games. It is played on an eight-by-eight grid. Each player has 16 separate pieces; 8 pawns, 2 rooks, 2 knights, 2 bishops, 1 king and 1 queen. Write a program that reads a chessboard and determines if a king is under attack or not.
95 Input Output PROBLEM 105.
Difficulty: 4
Write a program that allows two players to play the the game of chess. Input Output PROBLEM 106.
Difficulty: 4
Write a program to play chess over email. Use a server to manage the process.
Input
Difficulty: 4
DR
PROBLEM 107.
AF
T
Output
Write a program to play chess over email. Do not use a server to manage the process; players must email each other directly.
Input Output PROBLEM 108. Write a program that allows one player to play the the game of chess against a computer opponent. The computer opponent must be able to play against weak and strong players. That is to say, the program must have an option to set the level of the computer opponent.
Input Output PROBLEM 109.
96
CHAPTER 12. PROBLEM SET 08
Figure 12.3: Chess Board
Output
DR
Input
AF
T
Go is a popular Japanese board game. Write a program to play the game of Go.
DR
AF
T
97
Figure 12.4: Go Board
AF
DR T
Chapter
13
Problem Set 09
DR
AF
T
This set of problems covers card games. They are arranged from the simple to the extremely difficult to program, but most are still turn-based two-player games. The intention is to develop a game in which a player plays against the computer. However, it makes sense to first develop a two player game, then update the program to include the computer player. There are many excellent books and websites that will describe the rules of the various games. PROBLEM 110. Write a program to play the game of Beggar My Neighbour. Input Output PROBLEM 111. Write a program to play the game of Canasta. Input Output PROBLEM 112. Write a program to play the game of Poker. 99
100
CHAPTER 13. PROBLEM SET 09
Input Output PROBLEM 113.
Difficulty: 4
Write a program to play poker over email. Use a server to manage the process.
Input Output PROBLEM 114.
Difficulty: 4
Write a program to play poker over email. Do not use a server to manage the process; players must email each other directly.
AF DR
Output
T
Input
Chapter
14
Problem Set 10
Difficulty: 4
AF
PROBLEM 115.
T
This section contains problem about the creation of miscellaneous games. Some of them may require graphics programming.
DR
Lunar Lander is an vector graphics arcade game released by Atari in 1979. The object of the game is to pilot a lunar landing module to a safe landing on the moon. Players can move left or right, and must use thrusters to control the lander’s descent.
The terrain of the moon is very jagged and has only a few flat areas appropriate for landing. These areas are highlighted with a flashing bonus multiplier, which is higher for smaller areas. If the player successfully lands the module, he or she is awarded points based on how good the landing was and the difficulty of the landing site. If he or she crashes, no points are awarded, but instead the player receives a fuel penalty. In either case, the game starts another round with a different set of terrain and the player’s remaining fuel. The game is over when the player has run out of fuel and crashes on the moon’s surface.
To pilot the lander, the player must counteract gravity by using the lander’s aft thrusters to slow its descent. The player uses a proportional throttle to adjust the strength of the thrusters. Three buttons provide the ability to rotate the craft clockwise and counter-clockwise, and to ”abort” an approach by firing the thrusters at full strength for a short time. Each action uses up the craft’s limited fuel, and when fuel has run out, the lander stops responding to the 101
102
CHAPTER 14. PROBLEM SET 10
player’s actions.
Write a program that implements Lunar Lander, using vector graphics.
Input Output PROBLEM 116.
Difficulty: 4
Write a program to implement an Asteroids clone.
Input Output Difficulty: 4
T
PROBLEM 117.
DR
AF
Space Invaders, originally released in 1978, was designed by Tomohiro Nishikado for the Japanese company Taito. It is a two-dimensional fixed shooter game. Nishikado credits the Atari game Breakout as his inspiration. Space Invaders in turn inspired the creation of many games and revolutionised the video game industry. Write a program to implement a Space Invaders clone.
Input Output PROBLEM 118.
Difficulty: 4
Write a program to create a crossword puzzle. The program must print out a blank crossword with clues, and a separate solution sheet on another page.
Input Output
Chapter
15
Problem Set 11
DR
AF
T
This set of problems is about implementing common sort algorithms. Sorting is the basic building block around which many other algorithms are built. We obtain an amazing amount of programming power applicable to a number of problems when we understand sorting [24]. Searching, finding the closest pair given a set of n numbers, testing for element uniqueness, determining frequency distribution, selection and convex hulls are all examples of applications in which sorting provides good solutions [24]. All sorting algorithms are based on two fundamental operations [8]:
• Comparing items to determine if they are in order or not • Move out of order items into order
The advantages and disadvantages of each algorithm is based on how many times each of these two fundamental operations have to be performed and how computationally expensive they are. For the task of sorting N elements, the best algorithms require on the order of several times N Log2 N operations. The algorithm inventor tries to reduce the constant N to as small a value as possible [29]. PROBLEM 119. 103
104
CHAPTER 15. PROBLEM SET 11
A bubble sort algorithm compares pairs of adjacent1 items in an array and swaps them if they are out of order, and repeats the process until the array is sorted. At the end of the first past the largest element in the array will have bubbled to the end of the array. Subsequent passes will repeat the process until the array is ordered smallest to largest element. As the bubblesort is inefficient (O(N 2 )), it is not recommended for serious use [29]. Donald Knuth stated that ”the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems”. [13] For example, we will take the array of numbers (5,4,3,2,1) and show the first pass. In each step, elements written in bold are being compared. Clearly, the number 5 is ”bubbled” from it’s position in the array 0 to position 4.
) ) ) )
( ( ( (
45321 43521 43251 43215
) ) ) )
T
First Pass: (54321 (45321 (43521 (43251
DR
AF
Write a program to sort an array using a bubble sort algorithm. Ensure that the algorithm makes as many passes of the array as necessary to completely sort the array. Input 53421 acbed
Output 12345 abcde
PROBLEM 120. An insertion sort algorithm scans an array until an out of order element is found. The scan is then temporarily halted while a backward scan is made to find the correct position to insert the out of order element. Elements that are bypassed during the backward scan are moved up one position to make room to insert the out of order element. 1 Nearest
in space or position; immediately adjoining without intervening space
105 Write a program to sort an array using an insertion sort algorithm. Input 53421 acbed
Output 12345 abcde
PROBLEM 121.
T
A selection sort algorithm finds the smallest element in an array and moves it to the first position in the array by swapping it with the element currently in first position. Each subsequent pass places one more element in place.
53421 acbed
DR
Input
AF
Write a program to sort an array using a selection sort algorithm.
Output 12345 abcde
PROBLEM 122. Shellsort breaks a large list of items into many smaller sublists. These are sorted independently using an insertion sort. The trick lies in repeating the process a number of times with careful creation of larger and larger sublists, until the whole list is sorted. Implement the shellsort algorithm. Input
106
CHAPTER 15. PROBLEM SET 11
53421 acbed
Output 12345 abcde
PROBLEM 123. The quicksort algorithm uses a divide-and-conquer approach. Smaller and smaller parts of the list are processed until sorting is complete. Typically a recursive approach is used. During each iteration, the following happens: • One item is placed in the final sorted position • All smaller items are placed on the left of the sorted item
AF
T
• All greater items are placed on the right of the sorted item
DR
Thus the list is divided into two parts that are sorted independently. Implement the quicksort algorithm. Input 53421 acbed
Output 12345 abcde
PROBLEM 124. Mergesort takes a list of unsorted items, divides it in two and recursively divides the sublists, merges each sublist with the next higher sublist until the list is sorted. Implement the mergesort algorithm.
107 Input 53421 acbed
Output
DR
AF
T
12345 abcde
AF
DR T
Chapter
16
Problem Set 12
12345 21344 2rf42 ewggt f45ff
DR
AF
T
This set includes search and graph traversal exercises and problems . These programs will search through data to find some specific datum. For some of the search problems we can use two specially prepared files that contains (for example) 100,000 five character alphanumeric strings. One file will be sorted, the other unsorted. For example:
A graph consists of a set of vertices and a set of vertice edges. They can be used to represent essentially any relationship. For example, they can model a network of roads with cities as vertices and roads between cities as edges. Indeed, the key to understanding many algorithmic problems is to think of them in terms of graphs. However, designing novel graph algorithms is a difficult task [24]. PROBLEM 125. Difficulty: 3 Write a program that searches for a specific five character alphanumeric string in the file discussed above. Search by checking each string in order, from the first string until the desired string is found. This is known as a sequential search. For this exercise, the unsorted file can be used. Input 109
110
CHAPTER 16. PROBLEM SET 12
uihhe
Output Found at line 47,987.
PROBLEM 126.
Difficulty: 3
Write a program to run the sequential search at least 1000 times, using a randomly selected string for each search. Store the line number each string is found in, in another file. Determine how much of the list has to be searched, on average, before the sequential search succeeds in findings its string. Input Output Difficulty: 3
T
PROBLEM 127.
DR
AF
A binary search algorithm is a more efficient method of searching. Sorted data is searched by repeatedly dividing the search interval in half, beginning with a search interval equals to the total data. If the value of the search key is less than the item in the middle of the interval, the interval is narrowed to the first half of the data. If the value is higher, then the search interval is narrowed it to the upper half. This is repeated until the value is found or the interval is empty. Write a program to search the sorted file for a given string using a binary search algorithm. Input uihhe
Output Found at line 95,456.
PROBLEM 128.
Difficulty: 3
Write a program to run the binary search at least 1000 times, using a randomly
111 selected string for each search. Store the line number each string is found in, in another file. Determine how much of the list has to be searched, on average, before the binary search succeeds in findings its string. Compare the result to the result obtained from Problem 126Problem Set 12pcount.126. Input Output PROBLEM 129.
Difficulty: 3
By storing the vertices in a FIFO queue, we can explore the oldest unexplored vertices of a graph first. This is known as breadth-first search. As you can see, the search is conducted horizontally, the exploration of the graph radiating slowly from the starting vertex. Create an application to demonstrate the breadth-first search. One possibility is to implement a search on the tree in Problem 95Problem Set 06pcount.95.
PROBLEM 130.
Difficulty: 3
DR
Output
AF
T
Input
By storing the vertices in a LIFO stack, we explore the graph by following a vertical path. We only back up and follow the next path when there are no more undiscovered vertices in the current path. Create an application to demonstrate the depth-first search. One possibility is to implement a search on the tree in Problem 95Problem Set 06pcount.95. Input Output
AF
DR T
Chapter
17
Problem Set 13
AF
T
This set is about implementing some interesting algorithms. They may be of particular use in job interviews. PROBLEM 131. Difficulty: 4
DR
The Wolves and Chickens problem is stated as follows. Three chickens and three wolves are on one side of a river, along with a boat that can hold one or two people or animals. Find a way to get everyone to the other side, without ever leaving a group of chickens in one place outnumbered by wolves in that same place [21, pg. 90]. Solve the problem by implementing a program that searches for a solution. Choose an appropriate search algorithm, such as breadth-first, depth-first, A* and so forth. Input Output PROBLEM 132.
Difficulty: 4
The International Society of Mad Hatters meets for a tea party once a year. At these occasions each hatter arrives, wearing a hat of course, and hangs his or her hat on an individually numbered peg. Unfortunately, the hatters get very excited during the course of the party and by the end none of them can remember their peg number. As a result each hatter simply takes a hat at random and heads for home. If there are n hatters, the probability that each hatter picks the correct hat is:
113
114
CHAPTER 17. PROBLEM SET 13
1%/nx1/(n − 1)x1/(n − 2)x...x1/3x1/2x1/1 This is usually written as 1/n! where n! is usually called ”n factorial”. However, in this case we are interested in the probability that no hatter picks the correct hat. Write a program that estimates this probability when the number of hatters is large. Input Output PROBLEM 133.
Difficulty: 3
DR
AF
T
Prefix notation is a non-conventional notation for writing arithmetic expressions. The standard way of writing arithmetic expressions, also known as infix notation, positions a binary operator between the operands, e.g., 3 + 4, while in prefix notation the operator is positioned before the operands, e.g., +3 4. Similarly, the prefix notation for 5 - 2 is -5 2. A nice property of prefix expressions with binary operators is that parentheses are not required since there is no ambiguity about the order of operations. For example, the prefix representation of 5 - (4 - 2) is -5 - 4 2, while the prefix representation of (5 - 4) - 2 is - - 5 4 2. The prefix notation is also known as Polish notation, due to Jan Lukasiewicz, a Polish logician, who invented it around 1920. Similarly, in postfix notation, or reverse Polish notation, the operator is positioned after the operands. For example, postfix representation of the infix expression (5 - 4) - 2 is 5 4 - 2-. Write a program that translates a prefix arithmetic expression into a postfix arithmetic expression and vice versa. This is good practice for your Lisp compiler, which is one of the last problems in this book. Lisp uses prefix notation. Input Output PROBLEM 134.
Difficulty: 3
An anagram is a word or a phrase formed by rearranging the letters of another phrase such as ”item” and ”time”. Anagrams may be several words long such as ”Dormitory” and ”A Dirty Room”. Note that two phrases may be anagrams of each other even if each phrase has a different number of words [3]. Write a
115 program to determine if two phrases are anagrams of each other. The program should prompt the user for two phrases, each entered on a separate line. The program should not be case-sensitive. Input Goodness me Dormitory
Output Not an anagram Anagram
PROBLEM 135.
Difficulty: 3
AF
T
A palindrome is a word or phrase that reads the same in the reverse direction as in the forward. For example, ”level”, ”redder” and ”Live not on evil” [3]. Write a program to determine if a phrase is a palindrome or not. The phrase can be hard-coded or entered by the user.
DR
Input Live not on evil Roses are red
Output Palindrome Not palindrome
PROBLEM 136.
Difficulty: 3
It is possible to change one word into another by changing one letter at a time, while having at each intermediate step a real word [3]. Write a program that accepts as input two words of equal length, and converts the first word into the second word by changing only one letter at a time. Each intermediate step must be a real word in the same language as the first and second words. Out put each intermediate step. Is it even possible to write such a program? If so, what order of complexity is
116
CHAPTER 17. PROBLEM SET 13
it? Input For example, to change SETTLE to BANKER:
Output SETTLE settee setter better batter banter BANKER
PROBLEM 137.
Difficulty: 3
Input
DR
AF
T
Modify the above problem to accept words of different length. Then allow for deletion of letters and addition of letters in each round. Each intermediate word must still be a real word in the same language as the original two words.
Output PROBLEM 138.
Difficulty: 5
Given a collection of cities and the cost of travel between each pair of them, the travelling salesman problem (TSP) is to find the cheapest way of visiting all of the cities and returning to your starting point. In the standard version we study, the travel costs are symmetric in the sense that travelling from city X to city Y costs just as much as travelling from Y to X. The simplicity of the statement of the problem is deceptive, the TSP is one of the most intensely studied problems in computational mathematics and yet no effective solution method is known for the general case. The TSP belongs to a class of problems known as NP-complete [12]. Indeed, the resolution of the TSP would settle the P versus NP problem and fetch a $1,000,000 prize from the Clay Mathematics Institute. Although the complexity of the TSP is still unknown, for over 50 years its study has led the way to improved solution methods in many areas of mathematical
117 optimization [27]. Formally, this algorithm is defined as: Find a path through a weighted graph which starts and ends at the same vertex, includes every other vertex exactly once, and minimizes the total cost of edges [17]. Write a program to implement the TPS. Start with a low number of cities, and increase by one per execution of the program. What does this teach you about this class of problems? Input Output PROBLEM 139.
Difficulty: 5
A hiker is planning a trip. He can carry at most 20 kilograms in his knapsack. He wishes to maximise the value of the items he carries, so he assigns a value to each possible item he can take [7]. This is known as a Knapsack Problem.
AF
T
Write a program that selects the highest value of items without exceeding the maximum weight.
DR
Input Output PROBLEM 140.
Difficulty: 5
Imagine a circular table with five philosophers seated about it. These worthy gentlemen spend their time thinking, eating and drinking. While eating, they are not thinking, and while thinking, they are not eating. In the middle of the table is a bowl of spaghetti. A fork is placed in between each philosopher. Thus each philosopher has one fork to his or her left and one fork to his or her right. As spaghetti is difficult to serve and eat with a single fork each philosopher must eat with two forks. The philosopher can only use the fork on his or her immediate left or right. The philosophers never speak to each other, which creates a dangerous possibility of deadlock when every philosopher holds a left fork and waits perpetually for a right fork (or vice versa). This system can reach deadlock when there is a ’cycle of unwarranted requests’. In this case philosopher P1 waits for the fork grabbed by philosopher P2 who
118
CHAPTER 17. PROBLEM SET 13
is waiting for the fork of philosopher P3 and so forth, making a circular chain. Starvation might also occur independently of deadlock if a philosopher is unable to acquire both forks due to a timing issue. For example there might be a rule that the philosophers put down a fork after waiting five minutes for the other fork to become available and wait a further five minutes before making their next attempt. This scheme eliminates the possibility of deadlock (the system can always advance to a different state) but still suffers from the problem of livelock. If all five philosophers appear in the dining room at exactly the same time and each picks up their left fork at the same time the philosophers will wait five minutes until they all put their forks down and then wait a further five minutes before they all pick them up again.
AF
T
The lack of available forks is an analogy to the locking of shared resources in real computer programming, a situation known as concurrency. Locking a resource is a common technique to ensure the resource is accessed by only one program or chunk of code at a time. When the resource a program is interested in is already locked by another one, the program waits until it is unlocked. When several programs are involved in locking resources, deadlock might happen, depending on the circumstances. For example, one program needs two files to process. When two such programs lock one file each, both programs wait for the other one to unlock the other file, which will never happen.
DR
Write a program to simulate the dining philosophers problem. Then look for solutions to the problem, and incorporate them into your solution. There are three well known solutions to the problem. They are: • Waiter Solution : A waiter is introduced to the table. Philosophers must ask his permission before taking up any forks. Because the waiter is aware of which forks are in use, he is able to arbitrate and prevent deadlock. When four of the forks are in use, the next philosopher to request one has to wait for the waiter’s permission, which is not given until a fork has been released. The logic is kept simple by specifying that philosophers always seek to pick up their left hand fork before their right hand fork (or vice versa). • Resource hierarchy solution: Another simple solution is achieved by assigning a partial order, or hierarchy, to the resources (the forks, in this case), and establishing the convention that all resources will be requested in order, and released in reverse order, and that no two resources unrelated by order will ever be used by a single unit of work at the same time. Here, the resources (forks) will be numbered 1 through 5, in some order, and each unit of work (philosopher) will always pick up the lowernumbered fork first, and then the higher-numbered fork, from among the two forks he plans to use. Then, he will always put down the higher numbered fork first, followed by the lower numbered fork. In this case, if
119 four of the five philosophers simultaneously pick up their lower-numbered fork, only the highest numbered fork will remain on the table, so the fifth philosopher will not be able to pick up any fork. Moreover, only one philosopher will have access to that highest-numbered fork, so he will be able to eat using two forks. When he finishes using the forks, he will put down the highest-numbered fork first, followed by the lower-numbered fork, freeing another philosopher to grab the latter and begin eating. This is often the most practical solution for real world Computer Science problems; by assigning a constant hierarchy of locks, and by enforcing the ordering of obtaining the locks this problem can be avoided.
DR
AF
T
• Chandy / Misra Solution: In 1984, K. Mani Chandy and J. Misra proposed a different solution to the Dining Philosophers problem to allow for arbitrary agents (numbered P1, ..., Pn) to contend for an arbitrary number of resources (numbered R1, ..., Rm). Unlike in Dijkstra’s solution, these labellings can be arbitrary. For every pair of philosophers contending for a resource, create a fork and give it to the philosopher with the lower ID. Each fork can either be dirty or clean. Initially, all forks are dirty. When a philosopher wants to use a set of resources (i.e. eat), he must obtain the forks from his contending neighbours. For all such forks he does not have, he sends a request message. When a philosopher with a fork receives a request message, he keeps the fork if it is clean, but gives it up when it is dirty. If he sends the fork over, he cleans the fork before doing so. After a philosopher is done eating, all his forks become dirty. If another philosopher had previously requested one of the forks, he cleans the fork and sends it.
The dining philosopher problem is an abstraction of resource allocation problems. Learning about resource allocation problems and their solutions will help in the development of robust and complex software, such as operating systems and databases. It will be time well spent. See [5] for more information. Input Output PROBLEM 141. A clothes maker has N orders from customers that he must satisfy. He can only work on one job per day, and a job may take a day or longer to complete. Each order has a deadline, after which the clothes maker pays a fine for every day the work is late. Write a program to sort the orders in such a way that it minimises the fines he must pay. For each order assign a random duration of 1 to 5 days, and a deadline between 1 and 50 days from the starting day. Ensure that the total duration to complete the orders is 50.
120
CHAPTER 17. PROBLEM SET 13
Input
DR
AF
T
Output
Chapter
18
Problem Set 14
AF
T
This set contains a number of object-orientated programming (OOP) exercises and problems. See 4.2Object-Oriented Programming Languagessubsection*.6 for more information on OOP. PROBLEM 142. Difficulty: 1
DR
Write a class that when instantiated, prints ’Hello, World’ to the screen. Input None
Output Hello, World
PROBLEM 143.
Difficulty: 2
Write a class that takes a person’s height in inches and returns the height in centimetres. One inch is 2.54 centimetres. Input 60
121
122 A femtometre is a unit of Output length equivalent to 10−15 metres. It is named after the 152.4 Italian-American physicist Enrico Fermi (1901-54). It is used to measure the size of the PROBLEM 144. nuclei of atoms.
CHAPTER 18. PROBLEM SET 14
Difficulty: 2
Derive a class from the class in Problem 143Problem Set 14pcount.143 that
An angstrom is a unit of length equivalent to 10−10 . It was first also returns the height in femtometres and angstroms. used by the Swedish physicist Anders Jonas Angstr¨ om Input (1814-74) to enable him to describe the solar spectrum. It Output is largely obsolete.
PROBLEM 145.
Difficulty: 2
Assume a bank account begins with a balance of R100 and earns interest at an annual rate of 5%. The interest is computed at the end of each year using the following formula:
AF
T
newBalance = previousBalance + previousBalance * (1 + interestRate).
Input None. Output Starting balance: 100 Year 1: 105 Year 2: 100.25 Year 3: 115.76 Year 4: 121.55 Year 5: 127.62 Year 6: 134.00 Year 7: 140.71 Year 8: 147.74 Year 9: 155.13 Year 10: 162.88
PROBLEM 146.
DR
Write a class named ComputeInterest to determine and display the account balance at the end of each year for a ten-year period. Do not use loops.
123 Write a program that adds two complex numbers together. Create a complex number class and use operator overloading so that the + can be used for addition. Operator overloading allows the use of common operators in new contexts. This is a powerful tool, and should be thoroughly mastered. Input Output PROBLEM 147. Write a class called vehicle that prints a vehicle? weight, speed and cost. Write an application that uses this class. Then write an application called car.cs that inherits from the vehicle class, and prints numcylinders, horsepower and displacement.
PROBLEM 148.
DR
Output
AF
T
Input
Design and write your own class called mammal. Create three more animal classes. Two must inherit directly from mammal and the other from one of the animal classes. Input Output PROBLEM 149. Write a class with a method that accepts two military times (e.g. 15:00 and 19:22). The class must return the number of minutes between the two times. Input 15:00 16:30
Output
124
CHAPTER 18. PROBLEM SET 14
90 minutes
PROBLEM 150.
Difficulty: 2
Write a class that accepts a decimal argument called amount. The class must return the best spread of 1, 2, 5, 10, 20 and 50 cent coins that make up the amount. Input Amount? R1.29
PROBLEM 151.
AF DR
50 = 2 20 = 1 10 = 0 5=0 2=2 1=0
T
Output
Difficulty: 3
Using the code from Money Changer above (150Problem Set 14pcount.150) write a cash register program. The program must accept a running total of products, provide a total, add tax, accept money from the customer and provide appropriate change. It should also manage the cash float; initialise the register to contain a certain amount of money, in certain denominations, and then track that as customers pay with notes and coins of differing denominations. In the example below, 20N means cash note of value 20, and 5C a coin of value 5. Use the example as a rough guide only. It would be better to use a GUI for this exercise. Input 9.99 4.99 7.99 total tax 20N
125 5C 1C done
Output
DR
AF
T
9.99 14.98 22.97 22.97 25.27 Change = .50C, .20C, .2C, .1C Float now: 2 * 20 N, 5C, 1C, 20 * .2C
AF
DR T
Chapter
19
Problem Set 15
DR
AF
T
This set contains exercises and problems that (on the whole) will be solved using recursion. Note that while exercises are given to write programs to compute Fibonacci numbers and factorials, recursion is not a good solution to these in general [14]. However, they do provide good exercises. PROBLEM 152. Write a program using iteration to determine n!. This is ”n factorial”, which is the product of all integers between n and 1. For example, 5! = 5×4×3×2×1 = 120. Input 4
Output 24
PROBLEM 153.
Difficulty: 3
Write a program using recursion to determine n!. Compare the efficiency of your algorithm with the solution to the previous problem. Which appears to be the better approach, iteration or recursion? Using recursion to determine n! is the classic example [2]. Steve McConnell states this is not a good approach to the problem (beyond using it as an exercise) [14]. 127
128
CHAPTER 19. PROBLEM SET 15
Input 4
Output 24
PROBLEM 154. The Towers of Hanoi is a classic game in which disks on a peg must be moved from peg A to peg C. The rules of the game can be summarised as follows. • Only one disk may be moved at a time
T
• Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod
DR
AF
• No disk may be placed on top of a smaller disk
Write a program to implement this game. The user should be allowed to choose the number of disks, say between 7 and 15. Allow a user to play the game, or the computer to automatically solve it. Input Output PROBLEM 155. A chessboard is an 8 by 8 grid. The 8-queens problem requires us to place 8 queens on the chessboard so that no queen is attacking another. A queen attacks another if it is in the same row, column or diagonal to another queen [7]. Write a recursive program to solve this problem. Input Output
Chapter
20
Problem Set 16
DR
AF
T
This set contains more advanced problems. Some of the problems presented are steps toward implementing real-world applications. Others are simply fun ways to spend an afternoon programming in your favourite language. Some may require graphics programming. PROBLEM 156. Write a function Timer() that accepts as its parameter any other function. Timer() must determine how much time it takes for a function to execute. Input Timer(funcInt(17,1100,12));
Output 1500 ms
PROBLEM 157.
Difficulty: 3
The rate of decay of a radioactive substance is often expressed in terms of the half-life of the substance in question. The half-life is the period of time that it takes for the substance to decay to half its original amount [23]. Write a program that accepts as input the half-life of a substance and outputs the quantity present over time until none of the original substance is left. Use Table 20.1Half-Livestable.20.1 for input. 129
130
CHAPTER 20. PROBLEM SET 16
Input Some stuff
Output Quantity present:
Substance Carbon-14 Rhodium-106 Strontium-90 Uranium-222 Uranium-235
Table 20.1: Half-Lives Difficulty: 3
T
PROBLEM 158.
Half-Life 5715 years 29.9 seconds 29.1 years 1 microsecond 704 million years
DR
AF
Secure passwords are part of the foundation of good security. Some guidelines for constructing good passwords are:
• Passwords must consist of a mixture of lowercase and uppercase letters, numerical digits and possibly non-alphanumeric characters, with at least one of each. • Passwords must be between 6 and 20 characters in length. • Passwords must not contain any sequence of characters immediately followed by the same sequence.
Write a program that inputs a password and then prints REJECTED if the password is rejected, or ACCEPTED if it adheres to the above criteria. Input Password: sappword Password: heY!2 Password: Fido123!
Output
131 REJECTED REJECTED ACCEPTED
PROBLEM 159. A password is not stored as plaintext in a database. If they were, then anyone with access to the database could read passwords at will. To solve the problem we save passwords as hashes. That is, we run the password through a one-way function, and store the result. When a user enters their password, the same function is run on their plaintext password, and the resulting hash is compared with the hash stored in the database. Input Output PROBLEM 160.
DR
AF
T
Credit cards usually have a so-called check digit. This is a single digit that is assigned when the account number is developed and has a special property. One particularly simple mechanism is to assign the last digit of the sum of all the other digits. For example, suppose we have a nine-digit account number (including the check digit). The check digit would be the sum of the eight digits. This digit could be placed anywhere in the sequence, say the fifth digit. As a full example, suppose the eight numbers are 12345678. Their sum is 36. Thus 6 is the check digit, ignoring the 3. The account number is therefore 123465678. Write a program to read in a nine digit integer from the keyboard and check it for these rules. Write ”okay” or ”not okay” for the results of the test. Input 12345678 12645725
Output 123465678 126425725
132
CHAPTER 20. PROBLEM SET 16
PROBLEM 161. You plan to start a lawn-mowing business in Pretoria to fund your studies. You have determined that you will have to earn R15 per hour to make a profit. Write a program to determine how much you should charge to mow a lawn. You program must determine the area of the yard that needs to be moved by subtracting the area of all of the buildings on the land from the total area of the land. You can assume it will take two seconds to mow one square metre. Input Output PROBLEM 162.
PROBLEM 163.
AF
Output
DR
Input
T
Modify problem 161Problem Set 16pcount.161 to graphically show a plot of all the buildings on the land and the lawn. The scale of the display should be adjustable between 1 cm to 1 m and 5 cm to 1m. Colour the lawn green and the buildings brown.
Difficulty: 4
The Game of Life is a cellular automaton devised by the British mathematician John Conway in 1970. The game is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from players. It is an example of a Cellular Automaton. One interacts with the Game of Life by creating an initial configuration and observing how it evolves. The universe of the Game of Life is an infinite two-dimensional grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbours, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur: • Any live cell with fewer than two live neighbours dies, as if by loneliness. • Any live cell with more than three live neighbours dies, as if by overcrowding. • Any live cell with two or three live neighbours lives, unchanged, to the next generation.
133 • Any dead cell with exactly three live neighbours comes to life.
The initial pattern constitutes the ’seed’ of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed 97 births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick. The rules continue to be applied repeatedly to create further generations.
DR
AF
T
Write a program that runs the Game of Life. Your grid must contain a minimum of 100 by 100 cells.
AF
DR T
Chapter
21
Problem Set 17
AF
T
This section contains exercises and problems require a network. In other words, the problems involve communicating over a LAN or perhaps the Internet. PROBLEM 164. Difficulty: 4
DR
Morse Code is a communication system where letters are indicated by combinations of dots (short beeps) and dashes (long beeps). See Table 21.1Morse Codetable.21.1 for a key. Write a program that transmits Morse Code from one computer to another over a LAN in real time. This can either be a console application, or you can use a GUI. The receiving computer can either employ sound or a flashing object of some sort to reveal the received message [6]. Input ..
.
Output ..
.
PROBLEM 165.
Difficulty: 4
Modify the above program to use the keyboard’s built in LEDs to receive messages. That is, flash the (for example) Caps Lock light on the keyboard to indicate Morse Code.
135
136
CHAPTER 21. PROBLEM SET 17 a b c d e f g h i j k l m n o p
Samuel Finley Breese Morse (April 27 1791 to April 2 1872), from the USA, was the creator of a single-wire telegraph system and Morse code.
. . . . . . . . . . .
.
. . . . . . . . . . . . . .
.
q r s t u v w x y z error wait end msg end work inv xmit /
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1 2 3 4 5 6 7 8 9 0 . , : ) ( ? =
. . . . .
. . . . .
. . . . .
. . . . .
. . . . . .
. . . . . . . . . . . . . . . . . . . . .
T
Table 21.1: Morse Code
.
DR
..
AF
Input
Output ..
.
PROBLEM 166.
Difficulty: 4
Write a program that transmits and receives text from one computer to another over a LAN. This can either be a console application, or a window interface can be designed. Allow the two users to see a history of both sides of the conversation. As an additional challenge, modify the code to recognise smilies, and substitute the smilies with icon representations. InputHello, how are you?
OutputHello, how are you?
137 PROBLEM 167.
Difficulty: 4
Search the Internet for a form that needs to be completed, or create your own. The form should require information such as your name, surname, email address and so forth. Forms like these are used when subscribing to newsletters or registering for membership of a site. Write a program that automatically completes the form for you. Then test if the program can be used with similar forms on other sites. Be aware that this problem involves writing badly-behaved software, in the sense that you will be abusing someone else’s website. Not only will you be abusing their service, but you will be wasting a lot of bandwidth during testing. Contact the site’s web-master first and obtain permission, or even better, create your own website.
Input
AF
T
N/A
DR
Output N/A
PROBLEM 168.
Difficulty: 4
The Turing Test is a test created by the British mathematician Alan Turing (1912-1954) [4] to judge whether or not a computer is intelligent or not. A user sits at a computer and either converses with another computer or with a person over a network.
Write a program that consists of a client and a server. The client is simply a chat client. The server allows a user to chat with the person at the client, or the server can itself carry on the conversation. There must be no indication of who the user is speaking to.
InputHello I am fine. How are you? What is your favourite movie?
138
CHAPTER 21. PROBLEM SET 17
OutputHi. How are you? I am good. My favourite movie is Blade Runner. But I also like Casablanca.
PROBLEM 169.
Difficulty: 4
Write a program that fetches a Web page (html, xhtml file or perhaps an RSS file) and parses it, looking for particular information. For example, you might want to look for a stock price, or a MP3 URL. Some HTTP responses you might see are in Table 21.2Problem Set 17table.21.2. If the response is not a 200, then you must display an appropriate error code.
CODE MEANING 200 OK 400 Bad Request Unauthorized Forbidden
404
Not Found
405
Method lowed
406
Not Acceptable
407
Proxy Authentication Required
408
Request Timeout
500 501
Internal Server Error Not Implemented
502
Bad Gateway
DR
AF
T
401 403
NOTE The request has succeeded The request could not be understood by the server due to malformed syntax. The request requires user authentication. The server understood the request, but is refusing to fulfil it. The server has not found anything matching the URI. The request method is not allowed. Typically when trying to execute a normal document or display a script. According to the client’s request, it isn’t capable of handling the response. This code is similar to 401 (Unauthorized), but indicates that the client must first authenticate itself with the proxy. The client did not produce a request within the time that the server was prepared to wait. The server encountered an unexpected condition which prevented it from fulfilling the request. The server does not support the functionality required to fulfil the request. The server is a gateway or proxy and received an invalid response from the upstream server it accessed in attempting to fulfil the request. Continued...
Not
Al-
139 503
Service Unavailable
504
Gateway Timeout
600
Malformed URI
601
Connection Timed Out Unknown Error
602
The server is currently unable to handle the request due to temporary overloading or maintenance of the server. The server is a gateway or proxy and did not receive a timely response from the upstream server. The link checking program was not able to parse the URI. This means that the URI was either empty, or not a valid URI. The server did not respond before the connection timed out. Some other error occurred in contacting the server, making the request, or parsing the response. This could be due to a mangled or incorrectly formatted response from the server.
Table 21.2: HTTP Responses PROBLEM 170.
Difficulty: 3
DR
AF
T
Write an program that uses ICMP packets to determine if a networked computer is online or not. Your program will operate in a similar fashion to the ”ping” command.
Input upordown 192.9.202.5
Output Machine responded.
PROBLEM 171.
Difficulty: 5
Write an electronic language dictionary that shows entries for two different languages. For example, English and German. The program must be able to connect to a server to update its word list. Input Output
AF
DR T
Chapter
22
Problem Set 18
DR
AF
T
This section contains problems that require distributed or parallel processing. That is, the algorithms run on more than a single computer. Evidently, this is more difficult than writing algorithms for a single computer. It is suggested that some research is undertaken before tackling these problems. There are three reasons why writing parallel programs is sometimes a good idea [1].
1. Some problems are easier to solve using parallel constructs because of inherent parallelism 2. Though some problems are not parallel, efficiency can be gained by dividing the work amongst multiple processors 3. The nature of some systems requires them to run on networked processors. These are known as distributed systems
PROBLEM 172.
Difficulty: 4
Problem 85Problem Set 05pcount.85 was to draw the Mandelbrot set. Generate and draw the Mandelbrot set using parallel programming. Input 141
142
CHAPTER 22. PROBLEM SET 18
DR
AF
T
Output
Chapter
23
Problem Set 19
DR
AF
T
This section contains five problems that may take several weeks or months to solve and require in-depth knowledge of the chosen language, as well as considerable domain knowledge. Considerable research will be involved, as well as teamwork. Perhaps they should more properly be considered projects.
PROBLEM 173.
Difficulty: 6
An operating system is the software component of a computer system that is responsible for the management and coordination of activities and the sharing of the resources of the computer. The operating system acts as a host for application programs that are run on the machine. One of the functions of an operating system is to handle the details of the operation of the hardware. This relieves application programs from having to manage these details. This also makes it easier for programmers to write applications. Almost all computers use an operating system. Write a small operating system. Implement as many of the following as you can, in order.
1. Bootstraping 2. Process management 3. Memory management 143
144
CHAPTER 23. PROBLEM SET 19
4. Disk and file systems 5. Device Driver management 6. Networking 7. Security 8. Graphical user interfaces
PROBLEM 174.
Difficulty: 6
Lisp (List Processing) is the second-oldest high-level programming language and is still in use today; it was invented in 1958 by McCarthy. Lisp is a functional programming language. That is to say, a Lisp program is composed of functions [9]. The most widely known general-purpose Lisp dialects are Common Lisp and Scheme.
AF
T
Write a LISP interpreter for Common Lisp. the ANSI standard.
DR
Your interpreter can be written on Windows, Linux, FreeBSD or any other OS you have access to. As a challenge you can implement it on your own OS from Problem 173Problem Set 19pcount.173. PROBLEM 175.
Difficulty: 6
Prolog stands for Programming in Logic. Write a prolog compiler/interpreter. PROBLEM 176.
Difficulty: 6
BASIC (Beginner’s All-purpose Symbolic Instruction Code) is a high-level programming languages that was designed in 1964 by John George Kemeny and Thomas Eugene Kurtz at Dartmouth College. BASIC remains popular to this day, notably in the form of Visual Basic.NET. Write a BASIC compiler. It is not necessary to write an IDE. Your compiler can be written on Windows, Linux, FreeBSD or any other OS you have access to. As a challenge you can implement it on your own OS from Problem 173Problem Set 19pcount.173. PROBLEM 177.
Difficulty: 6
145 A relational database is a database that groups data using common attributes found in the data set. For example, a data set containing sales transactions can be grouped by the year the transaction occurred, sale price and so on. Relational databases are normally queried using Structured Query Language (SQL). SQL is a programming language for querying and modifying data and managing databases. SQL allows the retrieval, insertion, updating, and deletion of data, as well as the creation, modification and deletion of tables and databases. Write a relational database program that implements the SQL language. At a minimum, the database must have the following features: Transactions must be atomic, consistent, isolated, and durable (ACID). Implement SQL92. As a challenge you can implement it on your own OS from Problem 173Problem Set 19pcount.173.
T
Difficulty: 6
AF
PROBLEM 178.
DR
Obtain a star catalogue from the Internet and write planetarium software. Allow users to see the positions of the stars, planets, minor planets and comets in the sky. Allow them to set their position on Earth, and their date and time. Using the mouse, a user must be able to point at an object in the sky and a label identifying the object should be temporarily displayed. As an additional challenge, the positions of artificial satellites can also be included. Some good catalogues to use are: • SAO Star Catalog: http://tdc-www.harvard.edu/catalogs/sao.html • Sloan Digital Sky Survey: http://www.sdss.org/background/index.html
AF
DR T
Chapter
24
Problem Set 20
DR
AF
T
This section contains a selection of problems that were initially used for a class studying prolog. Prolog is a general purpose logic programming language. It is often used for learning artificial intelligence and computational linguistics. Prolog was conceived in the 1970s by a group around Alain Colmerauer in Marseille. The first Prolog system was developed in 1972 by Colmerauer and Philippe Roussel. A good prolog implementation to use is SWI-Prolog, which has been under development since 1987. It can be found at http://www.swi-prolog.org. However, why not use the prolog interpreter you developed in a previous exercise? PROBLEM 179. Difficulty: 1 Write all necessary clauses to define the following relationships. father(X,Y). /* X is the father of Y */ mother(X,Y). /* X is the mother of Y */ male(X). /* X is a male */ female(X). /* X is a female */ parent(X,Y). /* X is a parent of Y */ sister of(X,Y). /* X is a sister of Y */ brother of(X,Y). /* X is a brother of Y */ sibling(X,Y). /* X is a sibling of Y */
Input sister of(callie,frank). 147
148
CHAPTER 24. PROBLEM SET 20
brother of(lola,joe).
Output false false
PROBLEM 180.
Difficulty: 1
Given the following facts: pop(sa,48). pop(usa,306). pop(nigeria,148).
AF
T
area(sa,1.22). area(usa,9.82). area(nigeria,0.92).
DR
where pop(X,Y) indicates the population Y in millions of country X and area(X,Y) indicates the population Y in millions of the country X. Write a rule in the same file that determines population density, i.e. number of people per square kilometre. Then write some appropriate queries. Input 9 ?- density(sa, Y).
Output Y = 39.3443.
PROBLEM 181.
Difficulty: 1
Write a number of facts that indicate a number of people like various foods or drinks. For example likes(frank,milk).
149 likes(joe,cookies).
Write predicates to determine shared or common interests. Input compatible(joe,frank).
Output false
PROBLEM 182.
Difficulty: 1
T
Modify your answer to Problem 181Problem Set 20pcount.181 to show compatibility between people, based on number of shared interests. Output can be phrased as a ranked list of paired people.
AF
Input
DR
compatible(X,Y).
Output X Y X Y
= = = =
joe lola joe frank
PROBLEM 183.
Difficulty: 1
Find the last element of a list. Input ?- my last(X,[a,b,c,d]).
Output
150
CHAPTER 24. PROBLEM SET 20
DR
AF
T
X=d
Bibliography
H.E. Bal and D. Grune. Programming Language Essentials. Pearson Education Limited, 1994.
[2]
N. Dale and D. Teague. C++ plus Data Structures. Jones and Bartlett Publishers, Inc., second edition, 2001.
[3]
R. Eckler. Making the Alphabet Dance. MacMillan, 1996.
[4]
D. Nelson (Ed.). The Penguin Dictionary of Mathematics. Penguin Books, 1998.
[5]
V.J. Garg. Elements of Distributed Computing. John Wiley and Sons, Inc, 2002.
[6]
T.J. Glover. Pocket Ref. Sequioa Publishing, Inc., 2007.
[7]
Y. Hardy and W.-H. Steeb. Birkhauser Verlag, 2000.
[8]
S. Harris and J Ross. Beginning Algorithms. Wiley Publishing, Inc., 2006.
[9]
P.A. Henning and H Vogelsang. Programmiersprachen. Carl Hanser Verlag, 2007.
DR
AF
T
[1]
Classical and Quantum Computing.
[10] J.A. Irwin. Astrophysics. John Wiley and Sons, Inc., 2007. [11] J. Sharp J. Berry, T. Graham and E. Berry. A-Z of Mathematics. McGrawHill, 2003. [12] J. Kleinberg and E. Tardos. Algorithm Design. Addison-Wesley, 2006. [13] D. Knuth. The Art of Computer Programming, Volume 3. Addison-Wesley, third edition, 1997. [14] S. McConnell. Code Complete. Microsoft Press, second edition, 2004. 151
152
BIBLIOGRAPHY
[15] J. Meeus. Astronomical Algorithms. Willmann-Bell, Inc, 2000. [16] J. Mongan and N. Suojanen. Programming Interviews. John Wiley and Sons, Inc., 2000. [17] NIST. Dictionary of Algorithms and Data Structures. NIST, 2009. http: //www.nist.gov/dads/. [18] F. Piper and S. Murphy. Cryptography. Oxford University Press, 2002. [19] I. Ridpath and J. Woodruff (Eds.). Astronomy Dictionary. George Philip Ltd., 1995. [20] K. H. Rosen. Elementary Number Theory and its Applications. Addison Wesley, 2005. [21] S. Russel and P. Norvig. Artificial Intelligence: A Modern Approach. Prentice Hall, second edition, 2003. [22] M.A. Seeds. Foundations of Astronomy. Thomson Brooks/Cole, ninth edition, 2007.
AF
T
[23] A.B. Shiflet and G.W. Shiflet. Introduction to Computational Science. Princeton University Press, 2006.
DR
[24] S.S. Skiena. The Algorithm Design Manual. Springer Verlag, 1998. [25] S.S. Skiena and M.A. Revilla. Programming Challenges. Springer-Verlag, 2003. [26] U. McGovern T. Anderson and H. Norris (Eds). Super-Mini Book of Facts. Chambers Harrap Publishers, Inc., 2004. [27] Georgia Tech. Traveling Salesman Problem. Georgia tech, 2009. http: //www.tsp.gatech.edu/. [28] A. Hardy W.-H. Steeb, Y. Hardy and R. Stoop. Problems and Solutions in Scientific Computing. World Scientific, 2004. [29] W. Vetterling W. Press, S. Teukolsky and B. Flannery. Numerical Recipes in C. Cambridge, 1992. [30] P. Zeitz. The Art and Craft of Problem Solving. John Wiley and Sons, Inc., 1999. [31] D. Zidel. Basic Business Calculations. Penguin, 2001.
Index
Binary Search, 110 Binary Search Tree, 87 Birthday, 51 Body Mass Index, 69 Breadth-first Search, 111 Brute Force Method, 89 Bubble Sort, 103
AF
Calendar, 70 Canasta, 99 Cash Register, 124 Cellular Automaton, 132 Chat Program, 136 Check Digit, 131 Checkers, 93 Chess, 94, 95 Collatz Conjecture, 66 Complex Numbers, 122 Compound Increase and Decrease, 69 Constructor, 24 Containers, 81 Control Structure, Repetition, 34 Control Structure, Selection, 36 Control Structure, Sequence, 33 Conway, John, 132 Crossword, 102
DR
Absolute Number, 64 Abstract Data Types, 81 Abu Ja’far Muhammad ibn Musa al-Khwarizmi, 16 Account Class, 122 ACID, 145 Algorithm, 15 Anagram, 114 Angstr¨ om, 122 Array, Three-Dimensional, 61 Arrays, Addition of, 60 Arrays, Largest Element, 57 Arrays, Mean, 58, 59 Arrays, Median, 59 Arrays, Mode, 59 Arrays, Range, 58 Arrays, Smallest Element, 58 Arrays, Sum, 57 Asterisk Diamonds, 46 Asterisk Pyramid, 45 Asterisk Rope, 34 Asterisk Square, 35 Asterisk Triangle, 41, 42 Asterisk Walkway, 33 Asteroids, 102 Average Marks, 37
T
8-Queens Problem, 128
Database, 144 de Fermat, Pierre, 67 Depth-first search, 111 Destructor, 24
Backgammon, 93 BASIC, 144 Beggar My Neighbour, 99 153
154
INDEX Languages, Procedural, 22 Letter Distribution Analysis, 90 LIFO, 86 Linked List, 82 LISP, 144 List, 81 Lottery, 64 Lunar Lander, 101
Dictionary, 139 Dining Philosophers, 117 Doubly Linked List, 82 Drawing Circles, 74 Eratosthenes of Cyrene, 75 Eratosthenes’ Sieve, 75 Erd¨ os Numbers, 77 Escape Velocity, 70
AF
DR
Game of Life, 132 Go, 95 Goldbach’s Conjecture, 76 Goldbach, Christian, 76
T
Factorial, 127 Femtometre, 122 Fermat Numbers, 67 Fibonacci Numbers, 67 FIFO, 83 File Access, 52 File Sorting, 51 Flight Control, 72 Form Agent, 137
Hashing Passwords, 131 Hello World, 32 Hello World 2, 32 Hello World 3, 32 Highest Common Factor, 65 Histogram, 50
ICMP, 139 Increase, 38 Initials, 46 Insertion Sort, 104 International Society of Mad Hatters, 113 Irrational Numbers, 73 Julian Day, 71 Kaprekar’s Constant, 68 Kemeny, John George, 144 Knapsack Problem, 117 Knuth, Donald, 50, 104 Kurtz, Thomas Eugene, 144
Mammal Class, 123 Mandelbrot Set, 79 Mandelbrot Set (distributed), 141 Maple, 17 Maximum of two numbers, 44 Mergesort, 106 Mileage Table, 62 Military Time, 123 Money Changer, 124 Morse Code, 135 Morse, Samuel, 136 Mowing the Lawn, 132 Noughts and Crosses, 93 Operating System, 143 Palindromes (Numbers), 76, 77 Palindromes (Words), 115 Passwords, 130 Perfect Numbers, 76 Permutations, 90 Pi, 74 Ping, 139 Planetarium, 145 Poker, 99, 100 Postfix Notation, 114 Prefix Notation, 114 Prime Factors, 78 Prime Numbers, 75, 78 Priorty Queue, 84 Problem Solving Steps, 12 Projects, 143 Prolog, 144, 147 Queue, 83 Quicksort, 106
INDEX
155
Radioactive Decay, 129 Roche’s Limit, 73
Vehicle Class, 123 Volume of a Sphere, 37 Wells, H.G., 90 Wolves and Chickens, 113 Word Change, 115 Word Count, 52 World Wide Web, 138 Zeitz, Paul, 11
AF DR
Temperature Conversion, 38 Tic-Tac-Toe, 93 Time in Words, 45 Timer, 129 Towers of Hanoi, 128 Trabb Pardo, Luis, 50 Trabb Pardo-Knuth Algorithm, 50 Transposition Cipher, 90 Travelling Salesman Problem, 116 Trees, 86 Turing Test, 137 Turing, Alan, 137 Two’s Complement, 64
T
Sarkovskii’s theorem, 74 Scalinger, Jospeh Justus, 71 SciLab, 17 Selection Sort, 105 Sequential Search, 109, 110 Sharkovsky, Oleksandr Mikolaivich, 74 Shellsort, 105 Sorted Priority Queues, 85 Space Invaders, 102 Spellcheck, 53 SQL, 145 SQL92, 145 Stack, 86 String Splitting, 47 String Swapping, 36 Substitution Cipher, 89 Surface Area, 37