Programming Problems and Exercises

by E. Dembskey Draft Version: 2014-01-01

DR

AF

T

This work is dedicated to Rudolf Dembskey

DR

AF

T

Contents
Contents List of Tables List of Figures 1 Introduction 2 Problem Solving 2.1 A note on plagiarism . . . . . . . . . . . . . . . . . . . . . . . . 2.2 A note on working in the industry . . . . . . . . . . . . . . . . 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 !) . . . 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 . . . . . . . 5 Problem Set 01 6 Problem Set 02 7 Problem Set 03 3 3 5 6 7 11 13 13 15 15 16 17 17 18 18 18 18 19 21 21 22 27 27 28 29 31 41 49

DR

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . and O(N logN ) . . . . . . . . . . . . . . . . . .

AF

T

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

4 8 Problem Set 04 9 Problem Set 05 10 Problem Set 06 11 Problem Set 07 12 Problem Set 08 13 Problem Set 09 14 Problem Set 10 15 Problem Set 11 16 Problem Set 12 17 Problem Set 13 18 Problem Set 14

CONTENTS 57 63 81 89 93 99 101 103 109 113 121

20 Problem Set 16 21 Problem Set 17 22 Problem Set 18 23 Problem Set 19 24 Problem Set 20 Bibliography Index

AF

T

19 Problem Set 15

127 129 135 141 143 147 151 153

DR

List of Tables
3.1 9.1 Comparison of Rates of Growth . . . . . . . . . . . . . . . . . . . . Calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 71

20.1 Half-Lives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 21.1 Morse Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 21.2 HTTP Responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

DR
5

AF

T

List of Figures
10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 12.1 12.2 12.3 12.4 List . . . . . . . . . . . Singly Linked List . . . Doubly Linked List . . . Queue . . . . . . . . . . Queue after ENQUEUE Queue after DEQUEUE Stack . . . . . . . . . . Stack after PUSH . . . Stack after POP . . . . Tic Tac Toe . . Checkers Board Chess Board . Go Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 83 83 84 85 85 87 87 87 94 94 96 97

DR

AF

T
6

Chapter

1
AF
A beginning is the time for taking the most delicate care that the balances are correct. - PRINCESS IRULAN, in Dune (1965)

Introduction

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.

DR
7

T

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. 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

DR

AF

T

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 evan.dembskey@gmail.com. A small PayPal donation to evan.dembskey@gmail.com will be appreciated.

E. Dembskey Michigan, January 2014

Legal matters

This book is copyright c 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.

DR

AF

T

DR AF T

Chapter

2
AF
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)

Problem Solving

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

DR

T

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. 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.

DR

AF

T

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

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.

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.

DR

AF

Avoid the temptation to use code off the Internet!

T

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. 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.

DR

AF

T

Chapter

3
AF DR
15

Algorithm Complexity

3.1

Introduction

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<N; i++)

T

Form ever follows function. - LOUIS HENRI SULLIVAN (Lippincott’s Magazine (March 1896))

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<N; i++) { B[i] = A[i] + B[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. 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

DR

AF

T

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].

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

DR

AF

T

3.4

Linear Time: 0(N )

18

CHAPTER 3. ALGORITHM COMPLEXITY

3.5

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. 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].

DR

AF

T

3.6

Cubic Time: 0(N 3 )

3.8. EXPONENTIAL TIME: O(2n )

19

3.8

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 !)

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.

DR

AF

T

CHAPTER 3. ALGORITHM COMPLEXITY

Table 3.1: Comparison of Rates of Growth
a Consider

the universe itself is only approximately 4.323 × 1017 seconds old! [22] [10]

20

DR

AF

T

N 1 2 4 8 16 32 64 128 256

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

N3 1 8 64 512 4096 32768 262144 2097152 16777216

2N 2 4 16 256 65536 4294967296 1.845 × 1019 a 3.403 × 1038 1.158 × 1077

O(N !) 1 2 24 40320 2.092 × 1013 2.631 × 1035 1.269 × 1089 3.856 × 10215 8.578 × 10506

Chapter

4
AF
Language shapes the way we think, and determines what we can think about. - BENJAMIN LEE WHORF

Languages

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”.

DR
21

T

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. 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; }

DR

AF

T

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. The following code converts a number into a letter denoting a day of the week.

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.

DR

AF

T

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. • 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.

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); };

DR

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.

AF

T

// // // // //

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. 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.

DR

AF

T

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.

1. 2. 3. 4. 5. 6. 7. 8.

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).

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

DR

AF

T

4.3. DEGREE OF ABSTRACTION

27

4.3

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
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. Examples of compiled languages are C and C++.

Interpreted languages

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#.

DR

AF

T

28

CHAPTER 4. LANGUAGES

4.5

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
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

DR

AF

T

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
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.

6th generation

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#.

DR

AF

T

DR AF T

Chapter

5
AF
Practice yourself, for heaven’s sake, in little things; and thence proceed to greater. - EPICTETUS (Discourses IV.I)

Problem Set 01

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!

DR
31

T

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 Hello World

Input 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

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.

AF

T

PROBLEM 2.

Difficulty: 1

33
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.

Hello World I’m doing okay!

None Output **********

PROBLEM 5.

Difficulty: 1

• 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

DR

Input

AF

In which type of variable would you store the following values? This will depend on the language you have chosen.

T

34
The exercises following Problem 4Problem Set 01pcount.4 clearly show the second basic control structure, repetition .

CHAPTER 5. PROBLEM SET 01 • string • 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 Output * * * * * * * * * * PROBLEM 7.

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

DR

AF

T

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 None

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

DR

AF

T

36
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

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

Zero Five Fifteen Eighty-nine

PROBLEM 12.

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

DR

AF

T

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: 56%

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:

DR

AF

PROBLEM 14.

Difficulty: 2

T

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

IncreaseAmount × 100 BaseAmount

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:

(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

Celsius 0 1 2 ... 100

Fahrenheit 32 33.8 35.6 ... 212

DR

AF

T

DR AF T

Chapter

6
AF T

Problem Set 02

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

DR

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.

Output

* ** *** **** ***** ****** ******* ******** ********* **********

PROBLEM 20.

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

DR

AF

T

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

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

DR

AF

T

Output

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

In the case n = 15, then:

3.318229 3.318229

PROBLEM 24.

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)

DR

AF

T

Output

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. Input 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

DR

AF

T

46 None.

CHAPTER 6. PROBLEM SET 02

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

* * *** *** ***** ***** ******* ******* ****************** ******* ******* ***** ***** *** *** * *

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

DR

Output

AF

T

None.

47 None.

Output

eeeeee e eeeeee e eeeeee

jjjjjj j j j jjjj

ddddd d d d d d d ddddd

PROBLEM 29.

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. Input

Output

Himself against wrong does wrong does who he. Who he acts unjustly acts to unjustly himself, he because himself makes bad.

DR

AF

He who does wrong does wrong against himself. He who acts unjustly acts unjustly to himself, because he makes himself bad.

T

DR AF T

Chapter

7
AF
Difficulty: 2

Problem Set 03

This set contains problems that reinforce I/O concepts. A number of them will require file manipulation. PROBLEM 30.

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

DR
49

Write a program that inputs a string of keyboard characters and outputs the characters in reverse order.

T

50 1.2 5.8 15.15

CHAPTER 7. PROBLEM SET 03

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 For example, if the input is 1 4 9 15 12 then your output would look like:

Output 1: * 4: **** 9: ********* 15: *************** 12: ************

PROBLEM 33.

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.

DR

AF

T

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

Output

PROBLEM 35.

Difficulty: 3

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

DR

AF

31

T

52 2 4 8 9 18 54 141 ...

CHAPTER 7. PROBLEM SET 03

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 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

DR

AF

T

53 Enter filename: testlog.txt

Output Exists Rights: Read, Write, Delete Access date: 2002-07-21 Filesize: 19681114 bytes

PROBLEM 38.

Difficulty: 3

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.

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

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.

AF

T

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 lst

Output 17/07/2009 22/03/2006 12/09/2007 22:11 12:10 21:39 3 File(s)

PROBLEM 40.

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

DR

AF
0 dir.txt 1,501 ITN20BT_ST_20061.txt 3,006,590 vs2005.tif 3,008,091 bytes

T

55 1 File(s) 3,008,091 bytes

DR

AF

T

DR AF T

Chapter

8
AF T

Problem Set 04

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

DR

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.

58 64591

CHAPTER 8. PROBLEM SET 04

Output Largest = 9

PROBLEM 43.

Difficulty: 2

Write a program to find the smallest of the elements of an array. Input 64591

Output Smallest = 1

PROBLEM 44.

Difficulty: 2

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

DR

AF

T

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 =

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

DR

AF

T

PROBLEM 47.

Difficulty: 2

60 Mode = 5

CHAPTER 8. PROBLEM SET 04

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

PROBLEM 50.

Difficulty: 3

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.

DR

Inputasdgfhfh

AF

Write a program to determine if an array is in alphabetical order.

T

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

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

DR

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

AF

T

62 Output

CHAPTER 8. PROBLEM SET 04

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.

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

DR

Input

AF

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.

T

Chapter

9
AF T

Problem Set 05

This section contains exercises and problems that involve number manipulation and maths. PROBLEM 57. Difficulty: 3 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.

DR
63

64 7 8 Coca Cola 11 Coca 13 14 Coca Cola ...

CHAPTER 9. PROBLEM SET 05

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.

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.

DR

PROBLEM 59.

Difficulty: 2

AF

Output

T

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.

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

DR

AF

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.

T

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. 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

DR

AF

T

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”. 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.

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.

DR

None.

AF

Input

T

68 Output 3, 5, 17...

CHAPTER 9. PROBLEM SET 05

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.

Input: 1: 321 2: 981 3: 972 4: 963 5: 954

213 - 123 - 189 - 279 - 369 - 459

= = = = =

198 792 693 594 495

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

DR

AF

T

Here is an example series:

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 Weight in kilograms? 75 Height in metres? 1.7

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

DR
r n ) 100

AF

T

A = P (1 + ( Compound Decrease

(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:

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 Input Output PROBLEM 70. Difficulty: 3 M 5.98 × 1024 1.899 × 1027 r 6.38 × 106 7.145 × 107

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.

DR

AF

T

Ve =

2GM r

(9.4)

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.

M FEBRUARY 2 9 16 23

T 3 10 17 24

W 4 11 18 25

T 5 12 19 26

F 6 13 20 27

S 7 14 21 28

S 1 8 15 22

PROBLEM 71.

Table 9.1: Calendar Difficulty: 3

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:

DR

AF

T

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.
2

(9.6)

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 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.

DR

AF

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.

T

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:

L = 2.44r

3

ρP /ρS

(9.8)

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, φ

DR

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.

AF

T

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

Draw8thCircle(int r);

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].

DR

Input

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].

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: 1. Write a list of numbers from 2 to the largest number you want to test for primality. Call this List A. 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

DR

AF

T

76 12357

CHAPTER 9. PROBLEM SET 05

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...

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

DR

AF

T

PROBLEM 79.

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?). Input 3 196 265

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

DR

AF

T

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

Input 10 16

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

DR

AF

T

Given a number N, express it as a product of its prime factors.

79 Output Prime Not a Prime
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.

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 Output

DR

AF

T

DR AF T

Chapter

10
AF T

Problem Set 06

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

DR

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.

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 • iterator: Creates an iterator for all elements of the list

Input 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.

DR

AF

• clear: Deletes all elements from a list

T

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

1

2

3

4

5

Figure 10.3: Doubly Linked List PROBLEM 90. Difficulty: 3

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.

DR

AF

T

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 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.

Output

Refer to figures 10.5Queue after ENQUEUEfigure.10.5 and 10.6Queue after DEQUEUEfigure.10.6.

DR

AF
1 2 3 4 5 Figure 10.4: Queue Difficulty: 3

PROBLEM 92.

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

T

85

1 2 3 4 5 6 Figure 10.5: Queue after ENQUEUE

2 3

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.

DR
6

5

AF

4

T

86 Input Output PROBLEM 94. Difficulty: 3

CHAPTER 10. PROBLEM SET 06

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.

Implement a stack using an array that can perform the following operations:

• 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

DR

• pop: Deletes and returns the value at the top of a stack.

AF

• push: Adds a value to the top of the stack.

T

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 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

DR
3 2 1

Figure 10.8: Stack after PUSH

AF

T

88 Output

CHAPTER 10. PROBLEM SET 06

DR

AF

T

Chapter

11
AF T

Problem Set 07

This section contains a series of cryptographic problems that range from the simple to the fairly complex. PROBLEM 96. Difficulty: 3 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

DR

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

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

DR

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?

AF

T

91 N: O: P: Q: R: 3 S: T: 7 U: V: 2 W: X: Y: Z:

DR

AF

T

DR AF T

Chapter

12
AF T

Problem Set 08

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

DR
93

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

94

CHAPTER 12. PROBLEM SET 08

Figure 12.1: Tic Tac Toe

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.

DR
Figure 12.2: Checkers Board

AF

T

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 Output PROBLEM 107. Difficulty: 4

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.

DR

AF

T

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.

97

Figure 12.4: Go Board

DR

AF

T

DR AF T

Chapter

13
AF T

Problem Set 09

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

DR

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.

100 Input Output PROBLEM 113. Difficulty: 4

CHAPTER 13. PROBLEM SET 09

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.

Input

DR

AF

Output

T

Chapter

14
AF
Difficulty: 4

Problem Set 10

PROBLEM 115.

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

DR

T

This section contains problem about the creation of miscellaneous games. Some of them may require graphics programming.

102 player’s actions.

CHAPTER 14. PROBLEM SET 10

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 PROBLEM 117. Difficulty: 4

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

DR

AF

T

Chapter

15
AF T

Problem Set 11

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

DR

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.

First Pass: (54321 (45321 (43521 (43251

) ) ) )

( ( ( (

45321 43521 43251 43215

) ) ) )

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

DR

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.

AF

T

105 Write a program to sort an array using an insertion sort algorithm. Input 53421 acbed

Output 12345 abcde

PROBLEM 121. 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

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

DR

Input

AF

Write a program to sort an array using a selection sort algorithm.

T

106 53421 acbed

CHAPTER 15. PROBLEM SET 11

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

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.

DR

Thus the list is divided into two parts that are sorted independently.

AF

T

• All greater items are placed on the right of the sorted item

107 Input 53421 acbed

Output 12345 abcde

DR

AF

T

DR AF T

Chapter

16
AF T

Problem Set 12

12345 21344 2rf42 ewggt f45ff

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

DR

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:

110 uihhe

CHAPTER 16. PROBLEM SET 12

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 PROBLEM 127. Difficulty: 3

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

DR

AF

T

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. 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

DR

PROBLEM 130.

Difficulty: 3

AF

Output

T

DR AF T

Chapter

17
AF T

Problem Set 13

This set is about implementing some interesting algorithms. They may be of particular use in job interviews. PROBLEM 131. Difficulty: 4 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:

DR
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

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

DR

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.

AF

T

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

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

DR

Input

AF

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.

T

116 it? Input

CHAPTER 17. PROBLEM SET 13

For example, to change SETTLE to BANKER:

Output SETTLE settee setter better batter banter BANKER

PROBLEM 137.

Difficulty: 3

Input 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

DR

AF

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.

T

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. Write a program that selects the highest value of items without exceeding the maximum weight.

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

DR

Input

AF

T

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. 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. 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

DR

AF

T

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. • 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.

DR

AF

T

120 Input Output

CHAPTER 17. PROBLEM SET 13

DR

AF

T

Chapter

18
AF T

Problem Set 14

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

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

DR
121

Write a class that when instantiated, prints ’Hello, World’ to the screen.

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

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.

Derive a class from the class in Problem 143Problem Set 14pcount.143 that

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:

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.

AF

T

newBalance = previousBalance + previousBalance * (1 + interestRate).

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. Input Output PROBLEM 148.

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

DR

AF

T

124 90 minutes

CHAPTER 18. PROBLEM SET 14

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

Output 50 = 2 20 = 1 10 = 0 5=0 2=2 1=0

PROBLEM 151.

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

DR

AF

T

125 5C 1C done

Output 9.99 14.98 22.97 22.97 25.27 Change = .50C, .20C, .2C, .1C Float now: 2 * 20 N, 5C, 1C, 20 * .2C

DR

AF

T

DR AF T

Chapter

19
AF T

Problem Set 15

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

DR

128 Input 4

CHAPTER 19. PROBLEM SET 15

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 • 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

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

DR

AF

• No disk may be placed on top of a smaller disk

T

Chapter

20
AF T

Problem Set 16

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

DR

130 Input Some stuff

CHAPTER 20. PROBLEM SET 16

Output Quantity present:

Substance Carbon-14 Rhodium-106 Strontium-90 Uranium-222 Uranium-235 PROBLEM 158.

Half-Life 5715 years 29.9 seconds 29.1 years 1 microsecond 704 million years

Table 20.1: Half-Lives Difficulty: 3

• 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

DR

AF

Secure passwords are part of the foundation of good security. Some guidelines for constructing good passwords are:

T

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. 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

DR

AF

T

132 PROBLEM 161.

CHAPTER 20. PROBLEM SET 16

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. 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.

PROBLEM 163.

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.

DR

Output

AF

Input

T

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. Write a program that runs the Game of Life. Your grid must contain a minimum of 100 by 100 cells.

DR

AF

T

DR AF T

Chapter

21
AF T

Problem Set 17

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 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.

DR
135

136
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.

CHAPTER 21. PROBLEM SET 17 a b c d e f g h i j k l m n o p . . . . . . . . . . . . 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 . , : ) ( ? = . . . . .

. . . . .

. . . . . . . . . . . . . . .

. . . . .

. . . . .

. . . . . .

. . . . . . . . . . . . . . . . . . . . .

Table 21.1: Morse Code

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?

DR

..

.

AF

Input

T

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 N/A

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?

DR

AF

T

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 401 403 404 405 Unauthorized Forbidden Not Found Method lowed Not

Al-

406 407

Not Acceptable Proxy Authentication Required Request Timeout Internal Server Error Not Implemented Bad Gateway

408 500 501 502

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...

DR

AF

T

139 503 Service Unavailable 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.

504 600

Gateway Timeout Malformed URI

601 602

Connection Timed Out Unknown Error

Table 21.2: HTTP Responses PROBLEM 170. Difficulty: 3

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

DR

AF

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.

T

DR AF T

Chapter

22
AF T

Problem Set 18

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

DR

142 Output

CHAPTER 22. PROBLEM SET 18

DR

AF

T

Chapter

23
AF T

Problem Set 19

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

DR

144 4. Disk and file systems 5. Device Driver management 6. Networking 7. Security 8. Graphical user interfaces

CHAPTER 23. PROBLEM SET 19

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.

Write a LISP interpreter for Common Lisp. the ANSI standard.

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

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.

AF

T

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.

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

DR

AF

T

PROBLEM 178.

Difficulty: 6

DR AF T

Chapter

24
AF T

Problem Set 20

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

DR

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.

148 brother of(lola,joe).

CHAPTER 24. PROBLEM SET 20

Output false false

PROBLEM 180.

Difficulty: 1

Given the following facts: pop(sa,48). pop(usa,306). pop(nigeria,148).

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).

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.

AF

T

area(sa,1.22). area(usa,9.82). area(nigeria,0.92).

149 likes(joe,cookies).

Write predicates to determine shared or common interests. Input compatible(joe,frank).

Output false

PROBLEM 182.

Difficulty: 1

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.

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

DR

compatible(X,Y).

AF

Input

T

150 X=d

CHAPTER 24. PROBLEM SET 20

DR

AF

T

Bibliography

[1] [2] [3] [4] [5] [6] [7] [8] [9]

H.E. Bal and D. Grune. Programming Language Essentials. Pearson Education Limited, 1994. N. Dale and D. Teague. C++ plus Data Structures. Jones and Bartlett Publishers, Inc., second edition, 2001.

V.J. Garg. Elements of Distributed Computing. John Wiley and Sons, Inc, 2002. T.J. Glover. Pocket Ref. Sequioa Publishing, Inc., 2007. Y. Hardy and W.-H. Steeb. Birkhauser Verlag, 2000. Classical and Quantum Computing.

S. Harris and J Ross. Beginning Algorithms. Wiley Publishing, Inc., 2006. P.A. Henning and H Vogelsang. Programmiersprachen. Carl Hanser Verlag, 2007.

[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

DR

D. Nelson (Ed.). The Penguin Dictionary of Mathematics. Penguin Books, 1998.

AF

R. Eckler. Making the Alphabet Dance. MacMillan, 1996.

T

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.

[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.

DR

AF

T

[23] A.B. Shiflet and G.W. Shiflet. Introduction to Computational Science. Princeton University Press, 2006.

Index

8-Queens Problem, 128 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 Backgammon, 93 BASIC, 144 Beggar My Neighbour, 99 153

DR

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 Database, 144 de Fermat, Pierre, 67 Depth-first search, 111 Destructor, 24

T

Binary Search, 110 Binary Search Tree, 87 Birthday, 51 Body Mass Index, 69 Breadth-first Search, 111 Brute Force Method, 89 Bubble Sort, 103

154 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 Factorial, 127 Femtometre, 122 Fermat Numbers, 67 Fibonacci Numbers, 67 FIFO, 83 File Access, 52 File Sorting, 51 Flight Control, 72 Form Agent, 137 Game of Life, 132 Go, 95 Goldbach’s Conjecture, 76 Goldbach, Christian, 76 Hashing Passwords, 131 Hello World, 32 Hello World 2, 32 Hello World 3, 32 Highest Common Factor, 65 Histogram, 50

INDEX Languages, Procedural, 22 Letter Distribution Analysis, 90 LIFO, 86 Linked List, 82 LISP, 144 List, 81 Lottery, 64 Lunar Lander, 101 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

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

DR

AF

T

INDEX Radioactive Decay, 129 Roche’s Limit, 73 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 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 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

155

DR

AF

T

Sign up to vote on this title
UsefulNot useful