+ All Categories
Home > Documents > Programming Problems and Exercises

Programming Problems and Exercises

Date post: 11-Apr-2015
Category:
Upload: evandembskey2183
View: 9,413 times
Download: 11 times
Share this document with a friend
Description:
A short collection of programming problems and exercises. Please make comments and suggestions.
155
DRAFT Programming Problems and Exercises by E. Dembskey Draft Version: 2014-01-01
Transcript
Page 1: Programming Problems and Exercises

DRAFT

Programming Problems and Exercisesby

E. DembskeyDraft Version: 2014-01-01

Page 2: Programming Problems and Exercises

DRAFT

This work is dedicated toRudolf Dembskey

Page 3: Programming Problems and Exercises

DRAFT

Contents

Contents 3

List of Tables 5

List of Figures 6

1 Introduction 7

2 Problem Solving 112.1 A note on plagiarism . . . . . . . . . . . . . . . . . . . . . . . . 132.2 A note on working in the industry . . . . . . . . . . . . . . . . 13

3 Algorithm Complexity 153.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.2 Big-O Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . 163.3 Constant Time: 0(1) . . . . . . . . . . . . . . . . . . . . . . . . 173.4 Linear Time: 0(N) . . . . . . . . . . . . . . . . . . . . . . . . . 173.5 Quadratic Time: 0(N2) . . . . . . . . . . . . . . . . . . . . . . 183.6 Cubic Time: 0(N3) . . . . . . . . . . . . . . . . . . . . . . . . . 183.7 Logarithmic Time: O(logN) and O(NlogN) . . . . . . . . . . . 183.8 Exponential Time: O(2n) . . . . . . . . . . . . . . . . . . . . . 183.9 Factorial Time: O(N !) . . . . . . . . . . . . . . . . . . . . . . . 19

4 Languages 214.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.2 Programming Paradigm . . . . . . . . . . . . . . . . . . . . . . 224.3 Degree of Abstraction . . . . . . . . . . . . . . . . . . . . . . . 274.4 Method of Execution . . . . . . . . . . . . . . . . . . . . . . . . 274.5 Generations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

5 Problem Set 01 31

6 Problem Set 02 41

7 Problem Set 03 49

3

Page 4: Programming Problems and Exercises

DRAFT

4 CONTENTS

8 Problem Set 04 57

9 Problem Set 05 63

10 Problem Set 06 81

11 Problem Set 07 89

12 Problem Set 08 93

13 Problem Set 09 99

14 Problem Set 10 101

15 Problem Set 11 103

16 Problem Set 12 109

17 Problem Set 13 113

18 Problem Set 14 121

19 Problem Set 15 127

20 Problem Set 16 129

21 Problem Set 17 135

22 Problem Set 18 141

23 Problem Set 19 143

24 Problem Set 20 147

Bibliography 151

Index 153

Page 5: Programming Problems and Exercises

DRAFT

List of Tables

3.1 Comparison of Rates of Growth . . . . . . . . . . . . . . . . . . . . 20

9.1 Calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

20.1 Half-Lives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

21.1 Morse Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13621.2 HTTP Responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

5

Page 6: Programming Problems and Exercises

DRAFT

List of Figures

10.1 List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8210.2 Singly Linked List . . . . . . . . . . . . . . . . . . . . . . . . . . . 8310.3 Doubly Linked List . . . . . . . . . . . . . . . . . . . . . . . . . . . 8310.4 Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8410.5 Queue after ENQUEUE . . . . . . . . . . . . . . . . . . . . . . . . 8510.6 Queue after DEQUEUE . . . . . . . . . . . . . . . . . . . . . . . . 8510.7 Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8710.8 Stack after PUSH . . . . . . . . . . . . . . . . . . . . . . . . . . . 8710.9 Stack after POP . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

12.1 Tic Tac Toe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9412.2 Checkers Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9412.3 Chess Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9612.4 Go Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

6

Page 7: Programming Problems and Exercises

DRAFT

Chapter 1Introduction

A beginning is the time for taking the most delicate carethat the balances are correct.

- PRINCESS IRULAN, in Dune (1965)

Experience has shown that students’ programming ability and confidence im-proves after extensive programming practice and problem solving. These graded1

exercises and problems are intended to provide practice opportunities for pro-gramming students in a structured manner. This document is not intended asa stand-alone textbook, but rather as a supplement to an existing textbook orcourse material.

It is also common to be given short programming problems to solve whenapplying for a programming job. This document can help prepare for this kindof interview, though this is not it’s primary purpose. For more help in preparingfor interviews, refer to [16]. It can also be used to prepare for programmingcompetitions, though a better book for this purpose would be [25].

This document now includes more than 150 exercises and problems, a chapteron programming paradigms and approaches, a chapter on algorithm complexityand advice on problem solving strategies for the student. Proper problemsolving skills are absolutely necessary, as programming problems are solvedwith the mind, not the fingers. There is now also advice on proper programmingpractices and program structure.

1Grading problems is a problem itself, and open to interpretation.

7

Page 8: Programming Problems and Exercises

DRAFT

8 CHAPTER 1. INTRODUCTION

This document follows the convention outlined by Paul Zeitz [30]. Accordingto 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 specifictechniques are applied, but which techniques are to be used is not a mystery.In contrast, a problem demands much thought and resourcefulness before thecorrect approach is found. Though this document is titled Programming Prob-lems, the majority of the problems are in fact exercises, meant to keep pacewith 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. Thendesign a solution. Some solutions warrant only mental designs, but some willrequire the use of some methodology, even if only pen and paper. Then codethe solution. After a working solution is obtained, review the solution. Try toimprove the solution by looking for improvements that reduce time and spacecomplexity.

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 wereoriginally presented in International School for Scientific Computing (ISSC)courses around the world 2. Many are are used for lab practice for the subjectsITN20BT, AIT401T, DPC401T and IIS401T at The Tshwane University ofTechnology in South Africa. A subset has been presented to DSO401T andDEV401T students at UNISA. Some problems, such as those aimed specificallyat 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 thatdifferent from the effort required to write a program to determine interest.Thus, from some points of view, nothing new will be learnt by solving bothproblems. However, from a lecturer’s point of view, having a variety of problemsstaves 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 exercisesand problems. Every student should solve these problems themselves as partof their computer science or ICT education. New to this version is a difficultyrating for the problems. The easiest problems, which can be solved in lessthan a minute, are rated as Difficulty: 1. Problems which can be solved in lessthan 10 minutes are rated Difficulty: 2. Problems that should take less thanan hour and a half or so (100 minutes) are Difficulty: 3. Those that would

2See http://issc.uj.ac.za for more information on ISSC courses

Page 9: Programming Problems and Exercises

DRAFT

9

require two full working-days (1000 minutes) are Difficulty: 4.Difficulty: 5 isa full working month (10000 minutes). Difficulty: 6 will take no longer thantwo 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 programmermay suffer under a problem that another solves in minutes, but the roles mayvery well be reversed with a different problem. Skill, ability to concentrate andmotivation vary sharply, so the difficulty rating should be used as an guideonly.

Some problems throw light on subjects as diverse as astronomy, physics, biol-ogy, computer science, economics and finance, gaming and chemistry. This isin the spirit of broadening one’s horizons.

This document is a work in progress. Suggestions, criticisms and errata arealways welcome. Please send them to [email protected]. A smallPayPal donation to [email protected] will be appreciated.

E. DembskeyMichigan, January 2014

Legal mattersThis 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 problemsto 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.

Page 10: Programming Problems and Exercises

DRAFT

Page 11: Programming Problems and Exercises

DRAFT

Chapter 2Problem Solving

We can face our problem. We can arrange suchfacts we have with order and method.

- HERCULE POIROT, in Murder on the Orient Express (1934)

To succeed, planning alone is insufficient.One must improvise as well.

- SALVOR HARDIN, in Foundation (1951)

Not only must a programmer learn the syntax of his or her chosen language,the nuances of their development and deployment environments, but he or shemust become accomplished problem-solvers. This aspect is clearly the mostdifficult, and it is still argued whether programmers are born or made, thequestion hinging off the matter of whether or not problem-solving is a talentor a skill.

Paul Zeitz provides a useful analogy. You are standing at the base of a tallmountain, 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 trya more focused strategy, like trying to climb the mountain along a particularroute. Now you begin to think about the tactics of the situation, or howto achieve the strategy. Suppose you intend to climb the mountain along thenorth ridge, but there is a wide river and a deep canyon to cross. Specific tacticsfor negotiating these obstacles must be developed. The final task is to moveon to the specific tools that will be required. These are specific techniques toaccomplish very narrow, specific tasks. For example, when crossing the canyon,

11

Page 12: Programming Problems and Exercises

DRAFT

12 CHAPTER 2. PROBLEM SOLVING

specific ropes and knots are chosen to create a bridge [30]. This analogy ishighly pertinent to software development, as it demonstrates that tools arejust 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 aproblem. Some form of this process is used no matter the complexity of theproblem. It is not a linear process; often new conditions arise, or existing con-ditions become better understood, necessitating a new approach to a problemand the loss of completed work. Returning to an earlier step is a common oc-currence, and should be accepted as a natural part of the work. The six stepsare:

1. Identify the problem: The first step towards solving a problem is toidentify the problem. Strange as it may sound, this is an often neglectedstep in the problem solving process. In the classroom or lab, problemshave mostly been identified for the student. However, sometimes theproblem is not obvious, and much effort is wasted on what initially ap-pears to be the problem, leaving the real problem lurking undiscoveredin the background.

2. Understand the problem: The second step is to come to an under-standing of what is involved in the problem. Ask yourself if it is a singleproblem, or if there are more than one problem to solve. You must alsothink about what you know, and decide whether any research is requiredto fully understand the problem.

3. Identify alternate ways to solve the problem: Develop and applymultiple strategies. The first solution that comes to mind may not bethe best solution. Solutions can have unintended consequences. Formu-late a number of solutions and determine to the best of your ability theconsequences of each of these solutions.

4. Select the best way to solve the problem from the list of al-ternative solutions: Refine your strategy and develop specific tactics.Think about the process and results; is your method working or shouldyou go back a step or two?

5. List instructions that enable the problem to be solved: Choosethe correct tools to use and use them. Some research might be requiredbefore deciding which tool is best.

6. Evaluate the solution: Is the solution a good one? What have youlearnt from both the programming and the process that you can applyto your next project? Don’t underestimate the importance of this step.Often a problem is solved under pressure from a deadline, leading to aless than optimal solution. The consequences of the solution now becomeapparent. In time, a better solution may be found.

Page 13: Programming Problems and Exercises

DRAFT

2.1. A NOTE ON PLAGIARISM 13

There are many variations on this theme. The important lesson to take away isthat some problem solving method is required; some method is usually betterthan no method. However, some methods are better than others, and somemethods suit particular circumstances and people better than others. Rigiditylimits success.

One of the most powerful techniques is to break problems down into smallerpieces which are more easily solved. This permits us to see details which arehidden when looking at the big picture. Often the true nature of the problemis 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 thisbook, and even most of the problems a programmer encounters in the courseof a day’s work. The temptation to take this route is particularly acute whenone is under pressure to solve a problem by some particular point in time.

Avoid the temptation to use code off the Internet!

The biggest problem with using code that you do not understand is that therewill be unexpected consequences. The code may appear to work initially, butmay fail at a critical time. Even worse, the code may introduce a securityproblem. Without a good understanding of the code, you will be back at thebeginning of the journey, but perhaps with a bigger problem.

By all means, join Web forums and mailing lists related to your job and askquestions. If you don’t understand the answer, even if it works, make the effortto understand it. Some day you, or someone else, will have to maintain thatcode. It’s likely if you did not understand it, that you did not document itproperly. It is sometimes easier to re-write code than to understand writtencode. Don’t be the cause of problems in the future to save a few moments oftime now.

2.2 A note on working in the industry

The goals of professors and managers often differ. Computer Science graduatesare taught to be computer scientists, not programmers. Industry needs pro-grammers and hires computer scientists for this purpose. While not a recipefor total disaster, this disconnect is the source of much frustration.

Page 14: Programming Problems and Exercises

DRAFT

14 CHAPTER 2. PROBLEM SOLVING

The Computer Science graduate may have achieved a distinction writing pro-grams no larger than a thousand lines, while in industry he or she is expectedto work on programs orders of magnitude larger. With larger programs comesa concomitant increase in complexity. The skill of analysing and understandinglarge and complex programs must be learnt. One may argue that there is asmuch of the study of human nature in this task as of the study of programsand programming.

A word of advice for the graduate; if you plan on making a career of pro-gramming, in your own time, study the broader view. This includes projectmanagement, systematic testing, documentation, working with other people’scode, having other people work on your code, code quality and systems ar-chitecture. If you have not had the opportunity to apply the knowledge youhave gained in a synthesised manner, take the time to think about it. Problemsolving while learning typically involves solving problems that are limited inscope, while the working programmer must call on all his or her knowledge innew and creative ways.

Page 15: Programming Problems and Exercises

DRAFT

Chapter 3Algorithm Complexity

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

3.1 Introduction

An algorithm is a code-recipe that is used to solve a problem; it produces correctoutput given some input. The question arises: how do programmers measurethe work that algorithms perform, with a view to comparing two algorithmsto determine the most efficient? We usually consider two dimensions; com-putational space (memory) and computational time (how many operations).When comparing two algorithms for efficiency, the first solution is to code thealgorithms and then compare the execution time and space of the algorithms.Common sense suggests that the algorithm with the shortest execution timeand smallest space is the most efficient algorithm. However, this may not beentirely accurate. All we have determined is that a particular algorithm is moreefficient than another particular algorithm on a specific computer at a specifictime.

For most cases, computational space is less used as a measure than computa-tional time, because space is reusable while time is not. An example of thiscan be seen in the case of adding two arrays of integers. In the first example athird array is used, thus making the space complexity 3N.

for(int i = 0;i<N; i++)

15

Page 16: Programming Problems and Exercises

DRAFT

16 CHAPTER 3. ALGORITHM COMPLEXITY

The name algorithm honoursthe Arabic mathematician Abu

Ja’far Muhammad ibn Musaal-Khwarizmi. He lived in

present-day Iraq, at around 800AD.

{

C[i] = A[i] + B[i];

}

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 twoissues with this method. Firstly, it is language dependent. Secondly, it varieswith 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, inmany 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 inter-ested in worst-case complexity, because it gives a guaranteed upper bound forhow much resource a algorithm will use. Using best-case complexity is not thatuseful, except as a contrast to worst-case complexity. It also gives us a lowerbound for resources used. Average-case complexity is useful, but can be verydifficult to determine.

We can generally conclude that a problem is efficiently solved when a polynomial-time algorithm has been found for it (O(LogN), O(N), O(N2), O(N3) and soon).

3.2 Big-O Notation

The complexity of an algorithm is usually defined in terms of the order ofmagnitude of the number of operations required to perform a function. Thisis denoted by a capital O, followed by an expression representing some growthrelative 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

Page 17: Programming Problems and Exercises

DRAFT

3.3. CONSTANT TIME: 0(1) 17

to 64!. The number 128! exceeded the calculator’s capacity. For 128! we thusturned to SciLab, which yielded a result1. For 256! even SciLab failed. For thiswe 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 boundedtime [2]. Performance is not affected by the size of the problem. This does notguarantee a fast algorithm, only that it will always take the same amount oftime 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), becauseall elements in an array can be directly accessed through its index [2].

3.4 Linear Time: 0(N)

In O(N) an algorithm performs a number of operations directly proportional tothe number of items being processed. That is to say, its running time is at mosta constant factor times the size of the input. Algorithms that run in O(N) areusually quite acceptable [8]. An example of an O(N) algorithm is a programthat writes all the elements of a list into a file. If N is the number of elementsin the list, we can determine the time taken to execute the algorithm as follows:

time− to− open− file+ (N × time− to− write− one− element) + time−to− close− file

The algorithm is O(N) because the only important operation we need to mea-sure is (N × time − to − write − one − element). Time increases in a linearfashion as N increases [2].

One way to get a algorithm that runs in linear time is to process the inputin a single pass, spending a constant amount of time on each input item.Other algorithms achieve it for more subtle reasons. For example, an algorithmrunning on a high-speed switch on the Internet can only perform a constantamount of computational work on each packet. [12].

1http://www.scilab.org2http://www.maplesoft.com

Page 18: Programming Problems and Exercises

DRAFT

18 CHAPTER 3. ALGORITHM COMPLEXITY

3.5 Quadratic Time: 0(N2)

Algorithms that run in quadratic time may be a programmer’s worst night-mare. They are only usable on the smallest problems, on which they workreasonably quickly. However, as N increases, the situation rapidly gets out ofhand.

The example of a group of people meeting for the first time and needing toshake each other’s hands is often provided [8]. If three people meet, there are3 + 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(N2) [2].

3.6 Cubic Time: 0(N3)

A few moments contemplation of Table 3.1Comparison of Rates of Growthtable.3.1reveals everything you want to know about the efficiency of a O(N3) algorithm.An example is a routine that increments every element in a three-dimensionaltable of integers [2]

3.7 Logarithmic Time: O(logN) and O(NlogN)

Logarithmic time is better than O(N), but not as good as O(1). The runningtime 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, therun time will increase only by a factor of 20 [8].

Finding a value in list of sorted elements using the binary search algorithm isO(log2N) [2].

The better sort algorithms such as Quicksort, Heapsort and Mergesort areO(Nlog2N) [2].

Page 19: Programming Problems and Exercises

DRAFT

3.8. EXPONENTIAL TIME: O(2n) 19

3.8 Exponential Time: O(2n)

Algorithms with complexities which cannot be bounded by polynomial func-tions are called exponential time algorithms. This order of algorithms is verycostly. Execution time increases dramatically as N increases. Some problemsof 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 refer-ring to Table 3.1Comparison of Rates of Growthtable.3.1 we see that for evenrelatively small values of N the situation is untenable.

Page 20: Programming Problems and Exercises

DRAFT

20 CHAPTER 3. ALGORITHM COMPLEXITY

NO

(N)

O(LogN

)O

(Nlog

N)

N2

N3

2N

O(N

!)1

10

11

12

12

21

24

84

24

42

816

64

16

248

83

24

64

512

256

4032016

164

64

256

4096

65536

2.092

×10

13

3232

5160

1024

32768

4294967296

2.631

×10

35

6464

6384

4096

262144

1.845×

1019a

1.269×

1089

128

128

7896

16384

2097152

3.403×

1038

3.856×

10215

256

256

82048

65536

16777216

1.158×

1077

8.578×

10506

Tab

le3.1

:C

om

pariso

nof

Rates

of

Grow

th

aConsid

erth

euniverse

itselfis

only

approxim

ately

4.323×

1017seco

ndsold![22][10]

Page 21: Programming Problems and Exercises

DRAFT

Chapter 4Languages

Language shapes the way we think,and determines what we can think about.

- BENJAMIN LEE WHORF

Thought is the blossom; language the bud;action the fruit behind it.

- RALPH WALDO EMERSON

4.1 Introduction

The next question is may be that of which programming language to use.There are many thousands of languages in existence, which makes it difficultfor a beginner to choose an appropriate language. As in all things, an organ-ising principle1 is required. Modern programming languages can be classifiedaccording to a number of criteria [9]. The most important of these criteria are

• Programming paradigm

• Degree of abstraction

• Method of execution

1Sometimes that principle goes under the name of ”teacher” or ”professor”.

21

Page 22: Programming Problems and Exercises

DRAFT

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 otherparadigms. Programming paradigms function as an organising principle, an ap-proach 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 lan-guage. It can also be used in an event-driven manner. Programming paradigmswill continue to change and grow, as computing capabilities increase.

Procedural Programming Languages

Procedural programming specifies a list of operations that the program mustcomplete to reach the desired state. Each program has a starting state, a listof 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 codethat perform specific tasks. When combined, a software solution is produced.By splitting a program into small pieces, procedural programming allows asection of code to be re-used in the program without making multiple copies ofthe code. It also makes it easier for programmers to understand and maintaincomplex program structure.

Two of the most popular procedural programming languages are Ada, C, C++.Pascal, Modula-2, COBOL, FORTRAN and BASIC. Most procedural lan-guages are designed explicitly for compilation.

The following procedural code example, in C, shows how to determine a bankcharge according to bank balance.

if(account_balance < 300)

{

service_charge = 10;

}

else

{

service_charge = 5;

}

Page 23: Programming Problems and Exercises

DRAFT

4.2. PROGRAMMING PARADIGM 23

Structured Programming Languages

Structured programming is a special type of procedural programming. Addi-tional tools are provided to manage the complexity of larger programs. Pro-grammers break program structure into small pieces of code variously calledmethods, subroutines, procedures, functions or routines. These are easily un-derstood and combined to produce a final software solution. Structured pro-gramming is often associated with a ”top-down” architectural approach. Thetop-down approach begins with an initial overview of the system that containsminimal details about the different parts. Subsequent design iterations thenadd increasing detail to the components until the design is complete.

In many langauges pre-written routines are supplied, like the string routinesstrcopy 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 adesign method for designing systems ( [1]). In object-oriented programs, thedesigner specifies both the data structures and the types of operations that canbe applied to those data structures. The combination of data and operationsis coded as a class and instantiated (executed) as an object. A program isa collection of cooperating objects. Objects can store state information andinteract with other objects, but generally each object should have a a well-defined 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. Aclass thus describes a collection of variables and methods. These methodshave different levels of accessibility.

Page 24: Programming Problems and Exercises

DRAFT

24 CHAPTER 4. LANGUAGES

• A distinguishing feature of object-orientated programming is that newclasses can be derived from a parent class. These derived classes inheritthe attributes and behaviour of the parent, but they can also be extendedwith new data structures and methods.

• The list of available methods of an object represents all the possibleinteractions it can have with external objects, which means that it is aconcise specification of what the object does. New classes can be addedto a system that uses the interfaces of the existing classes.

• Encapsulation is an essential characteristic of OOP. It refers to how theimplementation details of a particular class are hidden from all objectsoutside of the class. Programmers specify what information in an objectcan be shared with other objects.

• Objects of different types can receive the same message and respond indifferent ways. This is called polymorphism. The different objects needto have only the same interface while the calling object does not need toknow exactly what type of object it is calling, only that is has a methodof a specific name with defined arguments.

Object-orientated languages often feature constructors. The constructor is afunction that is automatically called when an instance of a class is created.Theconstructor is used to initialize class member variables, allocate memory or doany other necessary startup tasks.

The destructor is a function that is automatically called just before the object isdestroyed. 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 othercleanup chores.

The most popular object-oriented programming languages include Java, VisualBasic, C#, C++, and Python.

In the following example, in C++, a class called Fract is shown. The imple-mentation of the method is procedural.

class fract{

long numerator; // Attribute

long denominator; // Attribute

public: // Access rights

fract(long value); // Constructor

void addition(long value); // Method

};

Page 25: Programming Problems and Exercises

DRAFT

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 ex-ample, one thread might monitor the mouse and keyboard for user input, whileanother thread performs database operations.

Popular concurrent languages include Ada and Java.

Functional Programming

Functional programming has its roots in lambda-calculus and are designed asa higher-level, more abstract notation than most other language paradigms.They define subroutines and programs as mathematical functions. pure func-tional languages use no value assignments. These languages are most frequentlyused in various types of mathematical problem solving.

Most programming languages use a state that is repeatedly modified. Lan-guage statements are typically executed for their side-effects on the state. Infunctional languages this is not allowed; functions cannot have side-effects onthe state of a program. The exception is when the state is carried around inthe arguments of the functions [1]. This is known as referential transparency.

Popular functional languages include LISP, F# and Mathematica. XSLT isone of the newest examples of a functional language.

In the following example, in LISP, a function called adiff returns the absolutedifference 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 lettingthe programmer specify what the problem is, rather than how to solve it. Alogic program consists of facts and properties about a problem; it’s the job ofthe system to find a solution to the problem.

Page 26: Programming Problems and Exercises

DRAFT

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. HornLogic is the basis for the most important logic programming language - Prolog.

In the Prolog example below, relationships are created between family mem-bers.

1. father(fenton,joe).

2. father(fenton,frank).

3. father(angus,david).

4. sibling(fenton,angus).

5. sibling(angus,fenton).

6. male(joe).

7. male(frank).

8. 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 deter-mined by user actions. This is in contrast to batch programming, where flowis determined when the program is written. Event-driven programming is usedfor interactive programs, such as word processors and spreadsheets. The pro-gram usually has an event loop, which repeatedly checks for interesting events,such as a keypress or mouse movement. Events cause the execution of triggerfunctions, 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, thecode 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

Page 27: Programming Problems and Exercises

DRAFT

4.3. DEGREE OF ABSTRACTION 27

4.3 Degree of Abstraction

The degree of abstraction defines how far the semantics of a language are fromthe basic commands used by a microprocessor. The lowest degree of abstractionis Machine Code. Machine Code is directly understood by a processor. Thenext level of abstraction is assembler. Higher-level languages vary in their levelof abstraction.

4.4 Method of Execution

Compiled languages

Compiled languages use a program called a compiler to translate source codeinto machine instructions, which is saved to a separate executable file. The useof a precompiler allows for optimisation and high execution speeds. A compileris 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 sourcecode by a program called an interpreter. This distinction refers to the imple-mentation, 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 interme-diate form is called bytecode in Java and Common Intermediate Language inC#. At runtime, the intermediate form is compiled into an executable. Usu-ally the final step involves a virtual machine. This has the benefit of makingthe code portable across platforms.

Examples of mixed languages are Java and C#.

Page 28: Programming Problems and Exercises

DRAFT

28 CHAPTER 4. LANGUAGES

4.5 Generations

Another language classification in general use is that of generations. There aresix recognised generations. To some degree the six generations overlap withthe degree of abstraction of the programming language. The six generationsare as follows (See [1] for more information).

1st generation

These are machine languages, and are the oldest programming languages. Thistype of program was typically entered via routing wires or flipping switches on afront panel. Thus they talk directly to specific hardware, and are not portable.

2nd generation

These are assembly languages. Assembly is considerably easier to learn thanmachine code, but is still considered difficult by the average programmer. Anassembler converts the assembler language statements into machine language.Below is an example of such a program.

; Hello World for Intel Assembler

mov ax,cs

mov ds,ax

mov ah,9

mov dx, offset Hello

int 21h

xor ax,ax

int 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. Earlyexamples are Cobol and Fortran, but C and other modern languages are also

Page 29: Programming Problems and Exercises

DRAFT

4.6. CONCLUSION 29

classified as 3rd generation languages. A compiler converts the statements ofa 3rd generation programming language into machine language.

4th generation

These are application languages. It is typical of application languages to exhibitstrong data support. Data are self-describing and persistent. Most 4th genera-tion languages incorporate information about the problem domain and of userinterfaces [1]. Fourth generation languages are designed to reduce program-ming 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 ofthe programmer explicitly designing algorithms, problems are solve using con-straints. They are intended to allow non-specialists to apply AI techniques;the problem is specified and the computer solves the problem. Prolog is anexample of a simple 5th generation language.

6th generation

There are still differing opinions as to what constitutes the 6th generation ofprogramming languages. Perhaps a defining characteristic is that this genera-tion exhibits learning behaviour. An example may be a neural net, though inthe 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. Lovelyas prolog is, one is more likely to find gainful employment with a thoroughknowledge of Java, or C#.

Page 30: Programming Problems and Exercises

DRAFT

Page 31: Programming Problems and Exercises

DRAFT

Chapter 5Problem Set 01

Practice yourself, for heaven’s sake, in little things;and thence proceed to greater.

- EPICTETUS (Discourses IV.I)

Exercise is the beste instrument in learnyng.- ROBERT RECORDE (The Whetstone of Witte)

This chapter is the first that contains the actual exercises and problems. Eachset is designed to be a more-or-less self-contained unit. A student will typicallywork on a single set before moving onto the next one. Of course, this is merelya 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 improvehis or her programming skills and ”feel” for which problems are tractable ornot.

Output is given as an example only (when possible), and is not be indicativeof the results of all possible inputs.

This section contains warm-up exercises for the beginning programmer. Eachproblem should take no more than a few minutes to solve and requires onlyrudimentary knowledge of the language. These exercises will typically be as-

1There are considerable rewards for solving some of the problems!

31

Page 32: Programming Problems and Exercises

DRAFT

32 CHAPTER 5. PROBLEM SET 01

signed after an hour or two of instruction. No input processing is required, asall variables will be hard-coded.

PROBLEM 1. Difficulty: 1

The venerable Hello World program is traditionally used to give a first tasteof 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

PROBLEM 2. Difficulty: 1

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.

Input

None.

Output

Hello WorldI’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

Page 33: Programming Problems and Exercises

DRAFT

33

The exercises listed asProblems 1 and 2 shouldclearly demonstrate the firstbasic control structure,sequence. When the program isrequired to print a second line,the code to do so is placedafter the code that prints thefirst line. If this was not thecase, programming wouldeither be impossible or very,very complex.

Hello WorldI’m doing okay!

PROBLEM 4. Difficulty: 1

Write a program using a for loop that prints ”*” 10 times on the screen, all onone line.

Input

None

Output

**********

PROBLEM 5. Difficulty: 1

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

Input

• 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

Page 34: Programming Problems and Exercises

DRAFT

34 CHAPTER 5. PROBLEM SET 01

The exercises followingProblem 4Problem Set

01pcount.4 clearly show thesecond basic control structure,

repetition.

• string

• int

• etc...

PROBLEM 6. Difficulty: 1

Write a program using a for loop that prints ”*” 10 times on the screen, oneasterisk 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 1to 10 and prints the result.

Input

None

Output

55

PROBLEM 8. Difficulty: 1

Page 35: Programming Problems and Exercises

DRAFT

35

Write a program using a loop of your choice that multiplies all the numbersbetween 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 aster-isks. 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 anumber between 0 and 9. Print the number as a word corresponding to thenumber in the variable. For this exercise, the number in the variable can behardcoded; no interaction is required. Run the application a few times to testit, but remember to change the number in the variable before you recompile orinterpret.

Input

05

Page 36: Programming Problems and Exercises

DRAFT

36 CHAPTER 5. PROBLEM SET 01

Problem 10Problem Set01pcount.10 demonstrates theuse of the third basic control

structure, selection. These arealso 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

Output

ZeroFive

PROBLEM 11. Difficulty: 2

Expand your solution to exercise 10Problem Set 01pcount.10 to include valuesfrom 0 to 999. Can you approach solving this problem like you did for exercise10Problem Set 01pcount.10, or is there a more efficient way?

Input

051589

Output

ZeroFiveFifteenEighty-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 strTwoto the screen, then write the code to swap the values of strOne and strTwo andprint them again.

Note that you must change the values of the string variables, not just printthem in a different order!

Input

None

Output

Page 37: Programming Problems and Exercises

DRAFT

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%

PROBLEM 14. Difficulty: 2

The surface area of a square or rectangle can be determined by multiplyingthe length by the breadth. Write a program to determine the surface area of agiven 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 outputwould be:

300 square metres

PROBLEM 15. Difficulty: 2

The volume of a sphere can be determined by the following formula:

Page 38: Programming Problems and Exercises

DRAFT

38 CHAPTER 5. PROBLEM SET 01

V =4

3πr2 (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

A common business calculation is to determine the percentage that the priceof some product or service has increased [31]. The formula used is:

IncreaseAmount

BaseAmount× 100 (5.2)

Write a program to determine the increase for some set of figures. Note thatin 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:

50000200000 × 100 = 0.25 = 25%

PROBLEM 17. Difficulty: 2

Produce a table of Celsius and the equivalent Fahrenheit temperatures from0C to 100C. Fahrenheit can be converted from Celsius by multiplying by 9,

Page 39: Programming Problems and Exercises

DRAFT

39

dividing by 5 and adding 32.

Input

None

Output

Celsius Fahrenheit

0 32

1 33.8

2 35.6

... ...

100 212

Page 40: Programming Problems and Exercises

DRAFT

Page 41: Programming Problems and Exercises

DRAFT

Chapter 6Problem Set 02

This section contains a selection of trickier problems, and should perhaps betackled after 3-4 hours of instruction. Some problems will be the work of a fewminutes to solve. Others may take longer and require the student to think alittle deeper.

PROBLEM 18. Difficulty: 2

Write a program using two for loops to produce the following pattern of aster-isks. Print only a single asterisk to the screen at a time.

Input

None.

Output

*

**

***

****

*****

******

*******

41

Page 42: Programming Problems and Exercises

DRAFT

42 CHAPTER 6. PROBLEM SET 02

********

*********

**********

PROBLEM 19. Difficulty: 2

Write a program using one for loop to produce the following pattern of aster-isks. 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 letteris a vowel, echo the letter on the screen. If the letter is a consonant, printan error message. Note that while it is fun to use insulting or sarcastic errormessages while developing programs for yourself, never do it for programs thatyou write for your company, school or university.

Input

ABDE

Page 43: Programming Problems and Exercises

DRAFT

43

Output

AError!Error!E

PROBLEM 21. Difficulty: 2

Write a method/function that receives two numbers as arguments and returnsthe value of their product.

Input

56

Output

30

PROBLEM 22. Difficulty: 2

Write a recursive method/function to take the value 3 to the power of someother number.

Input

4

Output

81

PROBLEM 23. Difficulty: 2

Write a program which calculates the sum

Page 44: Programming Problems and Exercises

DRAFT

44 CHAPTER 6. PROBLEM SET 02

1 +1

2+

1

3+ ...+

1

n(6.1)

for any given positive integer n. The program must contain two methods whichcan 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

Output

In the case n = 15, then:

3.3182293.318229

PROBLEM 24. Difficulty: 2

Write a program that prints determines the larger of 2 numbers and the largerof 3 numbers. Each section must use its own method. Method overloadingmust 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)

Page 45: Programming Problems and Exercises

DRAFT

45

Input

5 99 10 3

Output

910

PROBLEM 25. Difficulty: 3

Write a program that takes the system time, convert it into words, and printthe result.

Input

5:005:105:155:305:455:47

Output

Five o’clockTen minutes past fiveQuarter past fiveHalf past fiveQuarter to sixThirteen 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

Page 46: Programming Problems and Exercises

DRAFT

46 CHAPTER 6. PROBLEM SET 02

None.

Output

*

***

*****

*******

*********

PROBLEM 27. Difficulty: 4

Write a program using for loops to produce the following pattern of asterisks.Print only a single asterisk to the screen at a time.

Input

None.

Output

* *

*** ***

***** *****

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

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

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

***** *****

*** ***

* *

PROBLEM 28. Difficulty: 3

Write a program that prints your initials on the screen. Compose each initialwith six lines of small initials, as in the following example. Note that in theexample it is assumed the initials will be hardcoded; an improvement to theprogram will be to input the initials.

Input

Page 47: Programming Problems and Exercises

DRAFT

47

None.

Output

eeeeee jjjjjj ddddd

e j d d

eeeeee j d d

e j d d

eeeeee jjjj ddddd

PROBLEM 29. Difficulty: 3

Write a program that takes a string which contains a number of words. Splitthe string into its component parts. Store each word in its own string. Todisplay the result, print the strings in random, reverse, or some other order.

Input

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

Output

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

Page 48: Programming Problems and Exercises

DRAFT

Page 49: Programming Problems and Exercises

DRAFT

Chapter 7Problem Set 03

This set contains problems that reinforce I/O concepts. A number of them willrequire file manipulation.

PROBLEM 30. Difficulty: 2

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

Input

Joy to the world

Output

dlrow eht ot yoJ

PROBLEM 31. Difficulty: 2

Write a program that reads three floating point numbers from the keyboard.Then add the three numbers and calculate the arithmetic mean (average).

Input

49

Page 50: Programming Problems and Exercises

DRAFT

50 CHAPTER 7. PROBLEM SET 03

1.25.815.15

Output

7.38

PROBLEM 32. Difficulty: 3

Write a program that takes 5 input values and displays these values in a his-togram form using asterisks. Write the program using loops, and then againwithout 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 Knuthand Luis Trabb Pardo to illustrate the evolution of computer programminglanguages. The algorithm reads eleven numbers from an input device, storesthem in an array and then processes them in reverse order, applying a user-defined function to each value and reporting either the value of the function ora 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 num-ber, for example, 100.

Page 51: Programming Problems and Exercises

DRAFT

51

Input

None.

Output

PROBLEM 34. Difficulty: 3

Write a program that accepts as input the user’s birthday. Then display thenumber of days between the user’s birthday and the following 1st of January.

Input

Month? 12Day? 01

Output

31

PROBLEM 35. Difficulty: 3

Write a program that opens a file, sorts the contents, and saves the sorted fileunder 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 (seesection 15Problem Set 11chapter.15).

Input

8921814154...4

Output

Page 52: Programming Problems and Exercises

DRAFT

52 CHAPTER 7. PROBLEM SET 03

24891854141...

PROBLEM 36. Difficulty: 3

Write a program which asks for the name of a file and then counts the numberof words in the file. A word is defined as any sequence of symbols separatedby 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 ofSpecies. Until recently the great majority of naturalists believed that specieswere immutable productions, and had been separately created. This view hasbeen ably maintained by many authors. Some few naturalists, on the otherhand, have believed that species undergo modification, and that the existingforms of life are the descendants by true generation of pre-existing forms. pass-ing over allusions to the subject in the classical writers, the first author whoin modern times has treated it in a scientific spirit was Buffon. But as hisopinions fluctuated greatly at different periods, and as he does not enter onthe causes or means of the transformation of species, I need not here enter ondetails.

Output

131 words

PROBLEM 37. Difficulty: 2

Write a program that prompts the user for a filename. The program then out-puts whether or not a file of that name exists, what the access rights on thefile are, when last the file was accessed and the size of the file.

Input

Page 53: Programming Problems and Exercises

DRAFT

53

Enter filename: testlog.txt

Output

ExistsRights: Read, Write, DeleteAccess date: 2002-07-21Filesize: 19681114 bytes

PROBLEM 38. Difficulty: 3

Write a program that accepts input from the user in the form of text dataof arbitrary length. When the user has entered their data, allow the user tosave their data to a text file. Upon saving the file, perform a spell check. Toaccomplish this each word in the user’s text file must be compared against alist of words in another file. If a word in the user’s file is close, but exactlythe same as a word in the spell check file, show the user that their might be aspelling error, and include a line number for them.

The spell check file should contain as many words as possible, but for the sakeof this exercise, perhaps 50-100 of the most common words will suffice.

The problem arises of what kind of metric to use to decide if a word is misspeltor not. This is a problem for the programmer. One suggestion is to comparethe two words, and if the word lengths are the same or 1 character shorter orlonger, and the words differ at most2 characters, then suggest an alternativespelling. In words of the same length, a one or two character difference mightindicate an error.

To substantially improve the utility of this program, allow users to select aword 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-knownAnna Pavlovna Scherer, maid of honour and favourite of the Empress MaryaFedorovna. With these words she greetd Prince Vasili Kuragin, a man ofhigh rank and importance, who was the first to arrive at her reception. AnnaPavlovna had had a coff for some days. She was, as she said, suffering from la

Page 54: Programming Problems and Exercises

DRAFT

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 somerelevant data about the file, for example, the date it was last modified. Includea line of output showing the number of files found.

Input

lst

Output

17/07/2009 22:11 0 dir.txt

22/03/2006 12:10 1,501 ITN20BT_ST_20061.txt

12/09/2007 21:39 3,006,590 vs2005.tif

3 File(s) 3,008,091 bytes

PROBLEM 40. Difficulty: 4

Create a modified version of the above directory listing program that shows athumbnail to indicate the type of file. If the file is an image file, it may be agood idea to show a thumbnail image of the file instead.

Input

lst

Output

12/09/2001 11:39 3,006,590 Knossos.bmp

Page 55: Programming Problems and Exercises

DRAFT

55

1 File(s) 3,008,091 bytes

Page 56: Programming Problems and Exercises

DRAFT

Page 57: Programming Problems and Exercises

DRAFT

Chapter 8Problem Set 04

Many computational problems find their solution in arrays. Arrays are usedfor holding sets of items that are of the same kind, and allows a general wayto access all of them. For example, an array is useful for holding a set ofexamination marks, and performing some operation on them. This problemset provides practice with arrays.

The value of the elements may be hardcoded or input at runtimePROBLEM 41. Difficulty: 2

Write a program to find the sum of the elements of an array.

Input

6 4 5 9 1

Output

Sum = 25

PROBLEM 42. Difficulty: 2

Write a program to find the largest of the elements of an array.

Input

57

Page 58: Programming Problems and Exercises

DRAFT

58 CHAPTER 8. PROBLEM SET 04

6 4 5 9 1

Output

Largest = 9

PROBLEM 43. Difficulty: 2

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

Input

6 4 5 9 1

Output

Smallest = 1

PROBLEM 44. Difficulty: 2

Write a program to find the range of the elements of an array.

Input

6 4 5 9 1

Output

Range = 1 to 9

PROBLEM 45. Difficulty: 2

Write a program to find the mean of the elements of an array.

Input

6 4 5 9 1

Page 59: Programming Problems and Exercises

DRAFT

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 =

PROBLEM 47. Difficulty: 2

Write a program to find the median of the elements of an array.

Input

6 4 5 9 1

Output

Median = 5

PROBLEM 48. Difficulty: 2

Write a program to find the mode of the elements of an array.

Input

6 4 5 9 1 5 9 5

Output

Page 60: Programming Problems and Exercises

DRAFT

60 CHAPTER 8. PROBLEM SET 04

Mode = 5

PROBLEM 49. Difficulty: 2

Write a program to rotate the elements of an array. Move the value of the firstelement into the second element, the value of the second into the third and soon. Move the value of the last element into the first.

Input

19830121

Output

11983012

PROBLEM 50. Difficulty: 3

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

Inputasdgfhfh

OutputNot in order

PROBLEM 51. Difficulty: 3

Write a program that reads in 55 integers. Output them in reverse order inthe form of a triangle. One integer should appear on the first line, two on thesecond, 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 togive a 3rd two-dimensional array. The arrays should be at least 5 rows by 5columns. Display only the 3rd array i.e. the sum array.

Page 61: Programming Problems and Exercises

DRAFT

61

Consider the space complexity problem. How much space can be saved byusing only two arrays? Can you devise an experiment to show the benefit ofusing two versus three arrays? Is there a benefit?

Input

First array:

1 1 1 1 12 2 2 2 23 3 3 3 34 4 4 4 41 2 3 4 5

Second array:

1 1 1 1 12 2 2 2 23 3 3 3 34 4 4 4 45 5 5 5 5

Output

2 2 2 2 24 4 4 4 46 6 6 6 68 8 8 8 86 7 8 9 10

PROBLEM 53. Difficulty: 3 Write a program that increments everyelement in a three-dimensional array of integers. Write the program in sucha way that the dimensions of the array can be chosen at runtime. For largerarrays, it would be better to then assign all elements a random value.

Input

Enter dimension? 3

Page 62: Programming Problems and Exercises

DRAFT

62 CHAPTER 8. PROBLEM SET 04

Output

27 elements populatedElements 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 3Incremented 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 fill-up from 10 to 50 litres in increments of 5 litres. Show the range of distancestravelled in increments of 10 kilometres.

Input

Output

PROBLEM 55. Difficulty: 3

Write a program that takes as its input either a character or string. Examinean array for any occurrence of this character or string, and remove it. Shiftthe subsequent elements of the array to fill the gap.

Input

Output

PROBLEM 56. Difficulty: 3

Write a program which sorts the contents of a two-dimensional array, rowby row, so that they are in ascending order when read left to right. Leavethe elements in their respective rows. Can this be achieved without usingadditional arrays for storage?

Input

Output

Page 63: Programming Problems and Exercises

DRAFT

Chapter 9Problem Set 05

This section contains exercises and problems that involve number manipulationand maths.PROBLEM 57. Difficulty: 3

This problem may have been originally designed by Jeff Atwood on the CodingHorror blog.

Write a program that prints the numbers from 1 to 100. But for multiples ofthree 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 ”CocaCola”1.

Input

None.

Output

12Coca4ColaCoca

1Coca Cola is a trademarked name. It’s use here does not constitute a challenge to thattrademark.

63

Page 64: Programming Problems and Exercises

DRAFT

64 CHAPTER 9. PROBLEM SET 05

78CocaCola11Coca1314Coca Cola...

PROBLEM 58. Difficulty: 2

The two’s complement is a method of storing signed integers. It is used in mostpresent day CPUs [7]. Write a program that shows how to obtain the negativeof a number, and how to add and subtract, using two’s complement.

Input

Output

PROBLEM 59. Difficulty: 2

Write a program which reads an integer N and returns its absolute value. If Nis positive, we merely produce N. If N is negative, we remove the sign.

Input

5-10

Output

510

PROBLEM 60. Difficulty: 2

Produce a sequence of six random numbers between 1 and 49. These can thenbe used to play the National lottery. The odds on getting the right numbersare 13,983,816 to 1.

Page 65: Programming Problems and Exercises

DRAFT

65

Input

None.

Output

3 6 12 17 24 4010 11 19 27 36 41

PROBLEM 61. Difficulty: 3

The highest common factor (HCF) of two positive integers x and y is the largestinteger that divides each of x and y exactly. For example, the HCF of 45 and30 is 15.

Here is a form of Euclid’s algorithm for finding the HCF of two integers. Let’ssay we want to find the HCF of 36 and 90.

Write down the numbers: 36 90Then write down their difference: 36 90 54Form a ”number chain” by repeatedly writing down the difference between thelast two numbers, stopping when you get to zero.The last non-zero number is the HCF:36 90 54 36 18 18 0The HCF of 36 and 90 is 18

Write a program that inputs two positive integers and outputs their HCF.

Input

First Number: 36Second Number: 90

Output

Answer: 18

Page 66: Programming Problems and Exercises

DRAFT

66 CHAPTER 9. PROBLEM SET 05

PROBLEM 62. Difficulty: 3

The Collatz conjecture is an unsolved conjecture in mathematics, named afterLothar Collatz, who proposed it in 1937. The conjecture is also known as the3n + 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, ifwe 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 avariation, you can write a program that uses a brute force method to determineif the Collatz conjecture is true, and runs the algorithm against a large set ofnumbers, say 1 to 100,000,000 (or higher). In this case, only cases that disprovethe conjecture will be displayed.

Input

15224

Output

15: 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1224: 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 acceptstwo arbitrary integers. Then print the lowest and highest cycle lengths for everynumber between, and including, the two input integers. The cycle length is thenumber of numbers generated to generate the 1 (including the 1).

Input

Page 67: Programming Problems and Exercises

DRAFT

67

2 41 10

Output

1 71 20

PROBLEM 64. Difficulty: 3

Fibonacci numbers are a sequence of numbers named after the Italian mathe-matician Leonardo of Pisa (c.1175-c.1250), whose book Liber Abaci, publishedin 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 to-gether. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. Write aprogram that uses iteration to print the first 25 Fibonacci numbers.

Input

None.

Output

0, 1, 1, 2, 3, 5, 8, 13, 21, 34...

PROBLEM 65. Difficulty: 3

A Fermat number, named after the French mathematician Pierre de Fermat(1601-65) who first studied them, is a positive integer of the form Fn = 22

n

+1.The first 3 Fermat numbers are 3, 5, 17 [4].

Write a program to display the first 6 Fermat numbers.

Input

None.

Page 68: Programming Problems and Exercises

DRAFT

68 CHAPTER 9. PROBLEM SET 05

Output

3, 5, 17...

PROBLEM 66. Difficulty: 3

Take any 3-digit number and arrange its digits in descending order and in as-cending order and subtract. Repeat with the result, remembering to arrangethe numbers digits in the correct order. Eventually, all 3 digit numbers (ex-cept when all digits are the same, like 333) will end up as 495. This is calledKaprekar’s Constant, after the famous Indian mathematician. Having neverreceived any formal postgraduate training, for his entire career (1930-1962) hewas 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.

Here is an example series:

Input: 2131: 321 - 123 = 1982: 981 - 189 = 7923: 972 - 279 = 6934: 963 - 369 = 5945: 954 - 459 = 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

Page 69: Programming Problems and Exercises

DRAFT

69

PROBLEM 67. Difficulty: 3

Body Mass Index (BMI) gives an accurate measure of obesity. In order todetermine BMI, determine height in metres and weight in kilograms, and usethe formula below [26].

BMI =weight(kg)

height(m)2(9.1)

Write a program that determines BMI. If the BMI is less than 18, then theuser is underweight, if between 19 and 25 their weight is normal, if 26-30 theyare overweight. If BMI is over 30, they are obese.

Input

Weight in kilograms? 75Height in metres? 1.7

Output

Your weight is NORMAL.

PROBLEM 68. Difficulty: 3

The formulae used for the compound increase or decrease of money, popula-tions 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 presentvalue of a sum before an increase or decrease, n is the number of increases ordecreases that have been taken over a given time and r is the rate of interestfor the time period between each increase.

Compound Increase

A = P (1 + (r

100)n (9.2)

Compound Decrease

Page 70: Programming Problems and Exercises

DRAFT

70 CHAPTER 9. PROBLEM SET 05

A = P (1− (r

100)n (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 as-tronomical body. The following formula can be used when considering escapevelocities from planets:

Ve =

√2GM

r(9.4)

Here G is the gravitational constant 6.67 × 10−11m3/s2kg, M is the mass ofthe astronomical body in kilograms and r is its radius in meters.

Write a program to calculate escape velocity. You can use the following:

Planet M rEarth 5.98× 1024 6.38× 106

Jupiter 1.899× 1027 7.145× 107

Input

Output

PROBLEM 70. Difficulty: 3

Write a program that prints a calendar for a given year. Your calendar mustinclude 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 whetherto print the week days vertically to the left of the month or horizontally above.

Page 71: Programming Problems and Exercises

DRAFT

71

Input

Welcome to Print-a-Calendar! For which year would you like a calendar? 2009

Output

One example month is shown. For this exercise, show all 12 months.

FEBRUARY

M T W T F S S1

2 3 4 5 6 7 89 10 11 12 13 14 1516 17 18 19 20 21 2223 24 25 26 27 28

Table 9.1: CalendarPROBLEM 71. Difficulty: 3

The Julian Day is a continuous count of days and fractions of days from thebeginning 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 JulianDay was originally conceived in 1582 by the French Chronologist Joseph JustusScalinger (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 dayfor the 1st of January, 2008 at 00:00:00.0 UT is JD 2454466.50000. The for-mulae are below, where Y is the year, M the month number (1 for January, 2for 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 .0and .99. For example the 5th of the month at 12:00 will be 5.5, and the20th 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 inthe 13th or 14th month of the preceding year. Now determine the following:

Page 72: Programming Problems and Exercises

DRAFT

72 CHAPTER 9. PROBLEM SET 05

A = INT (Y

100) (9.5)

B = 2−A+ INT (A

4) (9.6)

If the date is before October the 4th, 1582, then B = 0. 2

The require Julian Day is then:

JD = INT (365.25(Y + 4716)) + INT (30.6001(M + 1))

+D +B − 1524.5(9.7)

Write a program to calculate the Julian Day for a given time and date. Forexample, October 4th 1957 at 19:26, the launch of Sputnik 1 (the first artificialsatellite, made in the USSR), or August 25th 2012, the day that Neil Arm-strong died.

Input

Year: 1957Month: 10Day: 4Hour: 19Minute: 26

Output

JD: 2,436,116.31

Note that depending on how your machine represents numbers, the answer forthe example may differ slightly

PROBLEM 72. Difficulty: 3

2It was on this date that the Julian Calendar was discarded in favour of the GregorianCalendar, which corrected for the accumulated error in the former.

Page 73: Programming Problems and Exercises

DRAFT

73

Write a program that, given the coordinates of two aeroplanes in flight, andtheir headings, that determines whether or not they will collide with one an-other.

Input

Output

PROBLEM 73. Difficulty: 3

Roche’s Limit is the approximate point where a satellite will be torn apart bytidal forces. It assumes the satellite is only held together by it’s own gravity, sothe Roche Limit is not used for artificial satellites like the International SpaceStation. 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)

Write a program that determine’s Roche’s Limit for a given planet and its satel-lite. For test data you can use the Earth-Moon system, where r = 6378, ρP =5.497 and ρS = 3.36.

Input

r : 6378ρP : 5.497ρS : 3.36

Output

Roche Limit = 18337.34662

PROBLEM 74. Difficulty: 3

An irrational number is a number that cannot be written as a rational num-ber [11]. Some examples are:

√2,√

3, π, e, φ

Page 74: Programming Problems and Exercises

DRAFT

74 CHAPTER 9. PROBLEM SET 05

Write a program to generate the first 1,000,000 numbers of each of these irra-tional numbers. Save the results in a file for later use. This problem is perhapsmore difficult that it appears on the surface, as you may have to create a wayto store very large numbers.

Input

π

Output

3.1415...

PROBLEM 75. Difficulty: 3

Write a function that draws the upper eighth of a circle. Centre the circleat (0,0), with a given radius r. The upper eighth is defined as the positionstarting at 12 ’o clock on a clock face [16].

Input

Draw8thCircle(int r);

Output

PROBLEM 76. Difficulty: 3

Oleksandr Mikolaivich Sharkovsky is a Ukrainian mathematician. Sarkovskii’stheorem describes an ordering of natural numbers according to which period-icities 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 samesequence multiplied by 2, then by 22 and so on. Lastly, the powers of 2 indecreasing order [28].

Page 75: Programming Problems and Exercises

DRAFT

75

Write a program that accepts as input two integers. Determine whether forthose 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 as-tronomer . Among his many accomplishments was the determination of thecircumference of the Earth [4].

The Sieve of Eratosthenes is a simple algorithm for finding all prime numbersup 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 forprimality. Call this List A.

2. Write the number 2, the first prime number, in another list for primesfound. 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 thisnumber into List B.

5. Strike off this number and all multiples of this number from List A. Thecrossing-off of multiples can be started at the square of the number, aslower 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 highestnumber in List A, all the numbers remaining in List A are prime.

Using Eratosthenes’ sieve, write a program that can produce all the primenumbers greater than zero and less than or equal to some largest number Max.

Input

Max? 10

Output

Page 76: Programming Problems and Exercises

DRAFT

76 CHAPTER 9. PROBLEM SET 05

1 2 3 5 7

PROBLEM 78.

A number P is said to be perfect if P is equal to the sum of all its factor ex-cluding itself. Example, 6 is perfect, so is 28. Write a program to determineperfect numbers [11].

Input

None.

Output

6, 28, 496...

PROBLEM 79.

Christian Goldbach (1690-1764) was a German mathematician. Goldbach’sConjecture is that any even number is the sum of two primes. Write a pro-gram to test Goldbach’s Conjecture over a range of numbers. What can youdeduce from the results.

Input

Output

PROBLEM 80.

A palindrome is a number that reads the same forwards and backwards, like12321. Write a program that tests input integers for the palindrome property.

This is a similar problem to one of the previous problems (Problem 135ProblemSet 13pcount.135).

Input

12321

Page 77: Programming Problems and Exercises

DRAFT

77

24664223442

Output

PalindromePalindromeNot palindrome

PROBLEM 81.

Write a program that accepts as input an arbitrary integer. Take the reverse ofthe 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 numberof iterations it took to reach the palindrome. To prevent an infinite loop, limitthe program to some upper bound of iterations (100, 1,000,000, 100,000,000?).

Input

3196265

Output

Palindrome: 9339 in 4 iterationsNo PalindromePalindrome: 6666 in 3 iterations

PROBLEM 82.

The Hungarian mathematician Paul Erdos is one of the most famous and pro-lific mathematicians of all time. It is considered an honour to have co-authoreda paper with him. Not everybody got a chance to do so, so the best they coulddo was publish with someone who co-authored a paper with Erdos. This gaverise to the so-called Erdos number. An author who has published with Erdosgets an Erdos number of 1. If someone publishes with someone with an Erdosnumber of 1, then his or her Erdos number is 2. And so on. If there is noconnection then the Erdos number is infinity [25].

Write a program that accepts two string parameters. The first string willrepresent the primary author, the one whom his or her own Erdos number

Page 78: Programming Problems and Exercises

DRAFT

78 CHAPTER 9. PROBLEM SET 05

will be applied. The second string will contain another author. Then take asinput a file containing a list of papers, some of them by the authors entered inthe strings. The program will calculate a number for the second author thatrelates him or her to the first author in the same manner as Erdos numbersrelate authors to Paul Erdos.

Input

File? nonlinear.txtFirst Author? WH SteebSecond Author? Y Hardy

Output

Number: 1

PROBLEM 83. Difficulty: 4

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

Input

1016

Output

2 * 52 * 2 * 2 * 2

PROBLEM 84. Difficulty: 4

Given a number N, determine whether it is a prime. Do not use EratosthenesSieve.

Input

1315

Page 79: Programming Problems and Exercises

DRAFT

79

Benoit Mandelbrot (1924 -2010) was a Polish-born Frenchand American mathematician.His most famous contributionswere in the field of fractals, theterm which he coined.

Output

PrimeNot a Prime

PROBLEM 85. Difficulty: 4

A Mandelbrot set is a set of mathematical points that forms a two-dimensionalfractal shape. Generate and draw the Mandelbrot set.

Input

Output

Page 80: Programming Problems and Exercises

DRAFT

Page 81: Programming Problems and Exercises

DRAFT

Chapter 10Problem Set 06

An abstract data type is a collection of well-defined operations that can beperformed on a particular structure [24]. Containers are abstract data typesthat permit storage and retrieval of data items independently of content. Themost commonly encountered containers are stacks, queues and tables. Thesecan implemented using arrays or linked lists. Other containers are dictionaries,binary search trees and priority queues.

This section contains exercises and problems about data structures like lists,queues and stacks. In some cases, depending on the approach taken, they alsoprovide practice with arrays.PROBLEM 86. Difficulty: 3

A list is an ordered collection of elements supporting random access to eachelement, like an array. Lists preserve insertion order and makes no attempt topreserve the uniqueness of values. Lists are dynamic. Write a program thatcreates 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

Page 82: Programming Problems and Exercises

DRAFT

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

• clear: Deletes all elements from a list

Input

Output

PROBLEM 88. Difficulty: 3

A singly linked list is a data structure holding a series of elements which con-tain 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 (onefor 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 whichcontain both a data item, a pointer to the next element in the list and apointer to the previous element.

Page 83: Programming Problems and Exercises

DRAFT

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 attheir ends. A cyclic linked list has an end node that points back to one of theearlier nodes. An acyclic linked list is NULL terminated. Write a program thatdetermines 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 first-in-first-out (FIFO) basis. That means that the first value to go in is the firstvalue to come out. There are two main operations that can be performed on aqueue, a node can be added to the end of a queue and a node can be removedfrom the head of a queue.

Implement a queue using an array that can perform the following operations.

Page 84: Programming Problems and Exercises

DRAFT

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 wereENQUEUED in order, 1, 2, 3, 4 and then 5. If we perform the opera-tion of ENQUEUE on it, or add an element, then figure 10.5Queue afterENQUEUEfigure.10.5 will result; we have added element number 6. Thenif we were to perform an DEQUEUE operation, the first element that was EN-QUEUED 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 afterDEQUEUEfigure.10.6.

5

4

3

2

1

Figure 10.4: Queue

PROBLEM 92. Difficulty: 3

A priority queue is a type of queue that provides access to the largest elementwithin it [8]. Using an unsorted queue, create a modified dequeue operation

Page 85: Programming Problems and Exercises

DRAFT

85

6

5

4

3

2

1

Figure 10.5: Queue after ENQUEUE

6

5

4

3

2

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 performa sort, but modify the enqueue operation to automatically insert new valuesin a sorted order. Then the dequeue operation will automatically remove thelargest item at the end of the queue.

Page 86: Programming Problems and Exercises

DRAFT

86 CHAPTER 10. PROBLEM SET 06

Input

Output

PROBLEM 94. Difficulty: 3

A stack is a data structure holding data items which are processed in a last-in-first-out (LIFO) basis. The operations performed on stack data structuresare pop (removing the top element) and push (adding a new element). Afrequently used metaphor is the idea of a stack of plates in a spring loadedcafeteria stack. Only the top plate is visible and accessible to the user, allother plates remain hidden. As new plates are added, each new plate becomesthe 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 thesecond 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:

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

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

• peek: Returns but does not delete the value at the top of a stack.

• size: Obtains the number of elements in a stack. In figure 10.7Stackfigure.10.7,size will return 3.

• isEmpty: Determines whether or not a stack is empty. In figure 10.7Stackfigure.10.7,isEmpty will return false.

• clear: Deletes all elements from a stack. In figure 10.7Stackfigure.10.7,clear will delete elements 1 to 3.

Input

Figure 10.7Stackfigure.10.7 shows a representation of a stack with three ele-ments in it. The elements were PUSHed in order, 1, 2, then 3. Thus if wePEEK, we will get a return value of 3. If we PUSH, then the stack will looklike figure 10.8Stack after PUSHfigure.10.8 and a PEEK will return a value of4. If we perform a POP, then a value of 4 will be returned, the element 4 willbe deleted and the stack will look like figure 10.9Stack after POPfigure.10.9.

Output

Page 87: Programming Problems and Exercises

DRAFT

87

Refer to figures 10.8Stack after PUSHfigure.10.8 and 10.9Stack after POPfigure.10.9.

1

2

3

Figure 10.7: Stack

1

2

3

4

Figure 10.8: Stack after PUSH

1

2

3

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, andits right child is greater or equal to its value [16].

Write a program that implements both a tree and a BSD.

Input

Page 88: Programming Problems and Exercises

DRAFT

88 CHAPTER 10. PROBLEM SET 06

Output

Page 89: Programming Problems and Exercises

DRAFT

Chapter 11Problem Set 07

This section contains a series of cryptographic problems that range from thesimple to the fairly complex.PROBLEM 96. Difficulty: 3

In cryptography, a substitution cipher is a method of encryption by which unitsof plaintext are substituted with ciphertext according to a regular system;the ”units” may be single letters, pairs of letters, triplets of letters or somecombination of the above. The receiver deciphers the text by performing aninverse substitution. Substitution over a single letter can be demonstrated bywriting out the alphabet in some order to represent the substitution. Thisis termed a substitution alphabet. The cipher alphabet may be shifted orreversed or scrambled in a more complex fashion, in which case it is calleda mixed alphabet or deranged alphabet. A common example of this is the”Caesar Cipher”, described by Julius Caesar in his book The Gallic Wars. Inthis method each letter in the alphabet is replaced by the letter three placesafter 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 forcemethod. This is a method that merely checks each possible answer until a

89

Page 90: Programming Problems and Exercises

DRAFT

90 CHAPTER 11. PROBLEM SET 07

decipherment is achieved. Write a program to decipher ciphertext created bythe above substitution cipher program, using the brute force method.

PROBLEM 98. Difficulty: 3

In classical cryptography, a transposition cipher changes one character from theplaintext to another (to decrypt the reverse is done). That is, the order of thecharacters is changed. The simplest form of this method is the MonoalphabeticCipher, in which we write the alphabet in a randomly chosen order beneath thealphabet written in alphabetic order. The key is then the order in which therandom letters are written [18]. Write a program to implement a transpositioncipher.

PROBLEM 99. Difficulty: 3

Determine the number of possible keys for the above Monoalphabetic Cipher.

PROBLEM 100. Difficulty: 3

Write a program that takes as its input a text file and produces a histogramof the relative frequencies of all the letters in the textfile. What do you noticeabout the distribution of the letters? How can we use this knowledge to deci-pher ciphertext? If we use as input a file containing ciphertext, have we madeany progress in deciphering it?

Input

The Time Traveler (for so it will be convenient to speak of him) was expoundinga recondite matter to us.

Output

A: 3B:C:D:E: 12F:G:H: 2I: 6J:K:L:M: 3

Page 91: Programming Problems and Exercises

DRAFT

91

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

Page 92: Programming Problems and Exercises

DRAFT

Page 93: Programming Problems and Exercises

DRAFT

Chapter 12Problem Set 08

This set of problems covers board games. They are arranged from the simpleto the extremely difficult to program, but most are still turn-based two-playergames. The intention is to develop a game in which a player plays against thecomputer. However, it makes sense to first develop a two player game, thenupdate the program to include the computer player.PROBLEM 101. Difficulty: 3

Write a program to play the game of Tic-Tac-Toe, also known as Noughts andCrosses. This game is played on a three-by-three grid. Players alternate byplacing either a ”X” or a ”0” in one of the squares of the grid. The winner isthe 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 aprogram to play the game of checkers.

Input

Output

PROBLEM 103. Difficulty: 4

93

Page 94: Programming Problems and Exercises

DRAFT

94 CHAPTER 12. PROBLEM SET 08

Figure 12.1: Tic Tac Toe

Figure 12.2: Checkers Board

Write a program to play the game of Backgammon.

Input

Output

PROBLEM 104. Difficulty: 4

Chess is one of the oldest and most popular board games. It is played on aneight-by-eight grid. Each player has 16 separate pieces; 8 pawns, 2 rooks, 2knights, 2 bishops, 1 king and 1 queen. Write a program that reads a chessboardand determines if a king is under attack or not.

Page 95: Programming Problems and Exercises

DRAFT

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 theprocess; players must email each other directly.

Input

Output

PROBLEM 108.

Write a program that allows one player to play the the game of chess againsta computer opponent. The computer opponent must be able to play againstweak and strong players. That is to say, the program must have an option toset the level of the computer opponent.

Input

Output

PROBLEM 109.

Page 96: Programming Problems and Exercises

DRAFT

96 CHAPTER 12. PROBLEM SET 08

Figure 12.3: Chess Board

Go is a popular Japanese board game. Write a program to play the game of Go.

Input

Output

Page 97: Programming Problems and Exercises

DRAFT

97

Figure 12.4: Go Board

Page 98: Programming Problems and Exercises

DRAFT

Page 99: Programming Problems and Exercises

DRAFT

Chapter 13Problem Set 09

This set of problems covers card games. They are arranged from the simpleto the extremely difficult to program, but most are still turn-based two-playergames. The intention is to develop a game in which a player plays against thecomputer. However, it makes sense to first develop a two player game, thenupdate the program to include the computer player.

There are many excellent books and websites that will describe the rules of thevarious 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

Page 100: Programming Problems and Exercises

DRAFT

100 CHAPTER 13. PROBLEM SET 09

Input

Output

PROBLEM 113. Difficulty: 4

Write a program to play poker over email. Use a server to manage the process.

Input

Output

PROBLEM 114. Difficulty: 4

Write a program to play poker over email. Do not use a server to manage theprocess; players must email each other directly.

Input

Output

Page 101: Programming Problems and Exercises

DRAFT

Chapter 14Problem Set 10

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

PROBLEM 115. Difficulty: 4

Lunar Lander is an vector graphics arcade game released by Atari in 1979. Theobject of the game is to pilot a lunar landing module to a safe landing on themoon. Players can move left or right, and must use thrusters to control thelander’s descent.

The terrain of the moon is very jagged and has only a few flat areas appropriatefor landing. These areas are highlighted with a flashing bonus multiplier, whichis higher for smaller areas. If the player successfully lands the module, he orshe is awarded points based on how good the landing was and the difficulty ofthe landing site. If he or she crashes, no points are awarded, but instead theplayer receives a fuel penalty. In either case, the game starts another roundwith a different set of terrain and the player’s remaining fuel. The game is overwhen 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 aftthrusters to slow its descent. The player uses a proportional throttle to adjustthe strength of the thrusters. Three buttons provide the ability to rotate thecraft clockwise and counter-clockwise, and to ”abort” an approach by firingthe thrusters at full strength for a short time. Each action uses up the craft’slimited fuel, and when fuel has run out, the lander stops responding to the

101

Page 102: Programming Problems and Exercises

DRAFT

102 CHAPTER 14. PROBLEM SET 10

player’s actions.

Write a program that implements Lunar Lander, using vector graphics.

Input

Output

PROBLEM 116. Difficulty: 4

Write a program to implement an Asteroids clone.

Input

Output

PROBLEM 117. Difficulty: 4

Space Invaders, originally released in 1978, was designed by Tomohiro Nishikadofor the Japanese company Taito. It is a two-dimensional fixed shooter game.Nishikado credits the Atari game Breakout as his inspiration. Space Invadersin turn inspired the creation of many games and revolutionised the video gameindustry. 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 ablank crossword with clues, and a separate solution sheet on another page.

Input

Output

Page 103: Programming Problems and Exercises

DRAFT

Chapter 15Problem Set 11

This set of problems is about implementing common sort algorithms. Sortingis the basic building block around which many other algorithms are built. Weobtain an amazing amount of programming power applicable to a number ofproblems when we understand sorting [24].

Searching, finding the closest pair given a set of n numbers, testing for elementuniqueness, determining frequency distribution, selection and convex hulls areall 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 manytimes each of these two fundamental operations have to be performed and howcomputationally expensive they are.

For the task of sorting N elements, the best algorithms require on the order ofseveral times NLog2N operations. The algorithm inventor tries to reduce theconstant N to as small a value as possible [29].

PROBLEM 119.

103

Page 104: Programming Problems and Exercises

DRAFT

104 CHAPTER 15. PROBLEM SET 11

A bubble sort algorithm compares pairs of adjacent1 items in an array andswaps them if they are out of order, and repeats the process until the array issorted. At the end of the first past the largest element in the array will havebubbled to the end of the array. Subsequent passes will repeat the process untilthe array is ordered smallest to largest element. As the bubblesort is inefficient(O(N2)), 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 nameand 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 firstpass. In each step, elements written in bold are being compared. Clearly, thenumber 5 is ”bubbled” from it’s position in the array 0 to position 4.

First Pass:( 5 4 3 2 1 ) ( 4 5 3 2 1 )( 4 5 3 2 1 ) ( 4 3 5 2 1 )( 4 3 5 2 1 ) ( 4 3 2 5 1 )( 4 3 2 5 1 ) ( 4 3 2 1 5 )

Write a program to sort an array using a bubble sort algorithm. Ensure thatthe algorithm makes as many passes of the array as necessary to completelysort the array.

Input

53421acbed

Output

12345abcde

PROBLEM 120.

An insertion sort algorithm scans an array until an out of order element isfound. The scan is then temporarily halted while a backward scan is made tofind the correct position to insert the out of order element. Elements that arebypassed during the backward scan are moved up one position to make roomto insert the out of order element.

1Nearest in space or position; immediately adjoining without intervening space

Page 105: Programming Problems and Exercises

DRAFT

105

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

Input

53421acbed

Output

12345abcde

PROBLEM 121.

A selection sort algorithm finds the smallest element in an array and moves itto the first position in the array by swapping it with the element currently infirst position. Each subsequent pass places one more element in place.

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

Input

53421acbed

Output

12345abcde

PROBLEM 122.

Shellsort breaks a large list of items into many smaller sublists. These aresorted independently using an insertion sort. The trick lies in repeating theprocess a number of times with careful creation of larger and larger sublists,until the whole list is sorted.

Implement the shellsort algorithm.

Input

Page 106: Programming Problems and Exercises

DRAFT

106 CHAPTER 15. PROBLEM SET 11

53421acbed

Output

12345abcde

PROBLEM 123.

The quicksort algorithm uses a divide-and-conquer approach. Smaller andsmaller parts of the list are processed until sorting is complete. Typically arecursive 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

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

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

Implement the quicksort algorithm.

Input

53421acbed

Output

12345abcde

PROBLEM 124.

Mergesort takes a list of unsorted items, divides it in two and recursively dividesthe sublists, merges each sublist with the next higher sublist until the list issorted.

Implement the mergesort algorithm.

Page 107: Programming Problems and Exercises

DRAFT

107

Input

53421acbed

Output

12345abcde

Page 108: Programming Problems and Exercises

DRAFT

Page 109: Programming Problems and Exercises

DRAFT

Chapter 16Problem Set 12

This set includes search and graph traversal exercises and problems . Theseprograms will search through data to find some specific datum. For some ofthe search problems we can use two specially prepared files that contains (forexample) 100,000 five character alphanumeric strings. One file will be sorted,the other unsorted. For example:

12345213442rf42ewggtf45ff

A graph consists of a set of vertices and a set of vertice edges. They can beused to represent essentially any relationship. For example, they can modela 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 themin terms of graphs. However, designing novel graph algorithms is a difficulttask [24].PROBLEM 125. Difficulty: 3

Write a program that searches for a specific five character alphanumeric stringin the file discussed above. Search by checking each string in order, from thefirst string until the desired string is found. This is known as a sequentialsearch. For this exercise, the unsorted file can be used.

Input

109

Page 110: Programming Problems and Exercises

DRAFT

110 CHAPTER 16. PROBLEM SET 12

uihhe

Output

Found at line 47,987.

PROBLEM 126. Difficulty: 3

Write a program to run the sequential search at least 1000 times, using arandomly selected string for each search. Store the line number each string isfound 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 datais searched by repeatedly dividing the search interval in half, beginning witha search interval equals to the total data. If the value of the search key is lessthan the item in the middle of the interval, the interval is narrowed to the firsthalf of the data. If the value is higher, then the search interval is narrowed itto the upper half. This is repeated until the value is found or the interval isempty.

Write a program to search the sorted file for a given string using a binary searchalgorithm.

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

Page 111: Programming Problems and Exercises

DRAFT

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 tothe 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 unexploredvertices 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 radiatingslowly from the starting vertex.

Create an application to demonstrate the breadth-first search. One possibilityis to implement a search on the tree in Problem 95Problem Set 06pcount.95.

Input

Output

PROBLEM 130. Difficulty: 3

By storing the vertices in a LIFO stack, we explore the graph by following avertical path. We only back up and follow the next path when there are nomore undiscovered vertices in the current path.

Create an application to demonstrate the depth-first search. One possibility isto implement a search on the tree in Problem 95Problem Set 06pcount.95.

Input

Output

Page 112: Programming Problems and Exercises

DRAFT

Page 113: Programming Problems and Exercises

DRAFT

Chapter 17Problem Set 13

This set is about implementing some interesting algorithms. They may be ofparticular use in job interviews.PROBLEM 131. Difficulty: 4

The Wolves and Chickens problem is stated as follows. Three chickensand three wolves are on one side of a river, along with a boat that can holdone 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 wolvesin that same place [21, pg. 90]. Solve the problem by implementing a programthat searches for a solution. Choose an appropriate search algorithm, such asbreadth-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 hisor her hat on an individually numbered peg. Unfortunately, the hatters getvery excited during the course of the party and by the end none of them canremember their peg number. As a result each hatter simply takes a hat atrandom and heads for home.

If there are n hatters, the probability that each hatter picks the correct hat is:

113

Page 114: Programming Problems and Exercises

DRAFT

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 picksthe correct hat. Write a program that estimates this probability when thenumber of hatters is large.

Input

Output

PROBLEM 133. Difficulty: 3

Prefix notation is a non-conventional notation for writing arithmetic expres-sions. The standard way of writing arithmetic expressions, also known as infixnotation, positions a binary operator between the operands, e.g., 3 + 4, whilein 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 expres-sions with binary operators is that parentheses are not required since there isno ambiguity about the order of operations. For example, the prefix represen-tation of 5 - (4 - 2) is -5 - 4 2, while the prefix representation of (5 - 4) - 2is - - 5 4 2. The prefix notation is also known as Polish notation, due to JanLukasiewicz, a Polish logician, who invented it around 1920.

Similarly, in postfix notation, or reverse Polish notation, the operator is po-sitioned after the operands. For example, postfix representation of the infixexpression (5 - 4) - 2 is 5 4 - 2-.

Write a program that translates a prefix arithmetic expression into a postfixarithmetic expression and vice versa.

This is good practice for your Lisp compiler, which is one of the last problemsin 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 anotherphrase such as ”item” and ”time”. Anagrams may be several words long suchas ”Dormitory” and ”A Dirty Room”. Note that two phrases may be anagramsof each other even if each phrase has a different number of words [3]. Write a

Page 115: Programming Problems and Exercises

DRAFT

115

program to determine if two phrases are anagrams of each other. The programshould prompt the user for two phrases, each entered on a separate line. Theprogram should not be case-sensitive.

Input

Goodness meDormitory

Output

Not an anagramAnagram

PROBLEM 135. Difficulty: 3

A palindrome is a word or phrase that reads the same in the reverse directionas 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 phrasecan be hard-coded or entered by the user.

Input

Live not on evilRoses are red

Output

PalindromeNot 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 thataccepts as input two words of equal length, and converts the first word intothe second word by changing only one letter at a time. Each intermediate stepmust be a real word in the same language as the first and second words. Output each intermediate step.

Is it even possible to write such a program? If so, what order of complexity is

Page 116: Programming Problems and Exercises

DRAFT

116 CHAPTER 17. PROBLEM SET 13

it?

Input

For example, to change SETTLE to BANKER:

Output

SETTLEsetteesetterbetterbatterbanterBANKER

PROBLEM 137. Difficulty: 3

Modify the above problem to accept words of different length. Then allow fordeletion of letters and addition of letters in each round. Each intermediateword must still be a real word in the same language as the original two words.

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 visitingall of the cities and returning to your starting point. In the standard versionwe study, the travel costs are symmetric in the sense that travelling from cityX 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 ofthe most intensely studied problems in computational mathematics and yet noeffective solution method is known for the general case. The TSP belongs toa class of problems known as NP-complete [12]. Indeed, the resolution of theTSP would settle the P versus NP problem and fetch a $1,000,000 prize fromthe Clay Mathematics Institute.

Although the complexity of the TSP is still unknown, for over 50 years its studyhas led the way to improved solution methods in many areas of mathematical

Page 117: Programming Problems and Exercises

DRAFT

117

optimization [27].

Formally, this algorithm is defined as: Find a path through a weighted graphwhich starts and ends at the same vertex, includes every other vertex exactlyonce, and minimizes the total cost of edges [17].

Write a program to implement the TPS. Start with a low number of cities, andincrease by one per execution of the program. What does this teach you aboutthis 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 valueto 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 themaximum weight.

Input

Output

PROBLEM 140. Difficulty: 5

Imagine a circular table with five philosophers seated about it. These worthygentlemen spend their time thinking, eating and drinking. While eating, theyare 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 betweeneach philosopher. Thus each philosopher has one fork to his or her left and onefork to his or her right. As spaghetti is difficult to serve and eat with a singlefork each philosopher must eat with two forks. The philosopher can only usethe fork on his or her immediate left or right.

The philosophers never speak to each other, which creates a dangerous possibil-ity of deadlock when every philosopher holds a left fork and waits perpetuallyfor 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

Page 118: Programming Problems and Exercises

DRAFT

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 unableto acquire both forks due to a timing issue. For example there might be a rulethat the philosophers put down a fork after waiting five minutes for the otherfork to become available and wait a further five minutes before making theirnext attempt. This scheme eliminates the possibility of deadlock (the systemcan always advance to a different state) but still suffers from the problem oflivelock. If all five philosophers appear in the dining room at exactly the sametime and each picks up their left fork at the same time the philosophers willwait five minutes until they all put their forks down and then wait a furtherfive minutes before they all pick them up again.

The lack of available forks is an analogy to the locking of shared resources in realcomputer programming, a situation known as concurrency. Locking a resourceis a common technique to ensure the resource is accessed by only one programor chunk of code at a time. When the resource a program is interested in isalready locked by another one, the program waits until it is unlocked. Whenseveral programs are involved in locking resources, deadlock might happen,depending on the circumstances. For example, one program needs two files toprocess. When two such programs lock one file each, both programs wait forthe other one to unlock the other file, which will never happen.

Write a program to simulate the dining philosophers problem. Then look forsolutions to the problem, and incorporate them into your solution. There arethree well known solutions to the problem. They are:

• Waiter Solution : A waiter is introduced to the table. Philosophers mustask his permission before taking up any forks. Because the waiter is awareof 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 onehas to wait for the waiter’s permission, which is not given until a fork hasbeen released. The logic is kept simple by specifying that philosophersalways 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 as-signing a partial order, or hierarchy, to the resources (the forks, in thiscase), and establishing the convention that all resources will be requestedin order, and released in reverse order, and that no two resources unre-lated by order will ever be used by a single unit of work at the sametime. Here, the resources (forks) will be numbered 1 through 5, in someorder, and each unit of work (philosopher) will always pick up the lower-numbered fork first, and then the higher-numbered fork, from among thetwo forks he plans to use. Then, he will always put down the highernumbered fork first, followed by the lower numbered fork. In this case, if

Page 119: Programming Problems and Exercises

DRAFT

119

four of the five philosophers simultaneously pick up their lower-numberedfork, only the highest numbered fork will remain on the table, so the fifthphilosopher will not be able to pick up any fork. Moreover, only onephilosopher will have access to that highest-numbered fork, so he will beable to eat using two forks. When he finishes using the forks, he will putdown the highest-numbered fork first, followed by the lower-numberedfork, freeing another philosopher to grab the latter and begin eating.This is often the most practical solution for real world Computer Scienceproblems; by assigning a constant hierarchy of locks, and by enforcingthe ordering of obtaining the locks this problem can be avoided.

• Chandy / Misra Solution: In 1984, K. Mani Chandy and J. Misra pro-posed a different solution to the Dining Philosophers problem to allow forarbitrary agents (numbered P1, ..., Pn) to contend for an arbitrary num-ber of resources (numbered R1, ..., Rm). Unlike in Dijkstra’s solution,these labellings can be arbitrary. For every pair of philosophers contend-ing for a resource, create a fork and give it to the philosopher with thelower ID. Each fork can either be dirty or clean. Initially, all forks aredirty. When a philosopher wants to use a set of resources (i.e. eat), hemust obtain the forks from his contending neighbours. For all such forkshe does not have, he sends a request message. When a philosopher witha fork receives a request message, he keeps the fork if it is clean, but givesit up when it is dirty. If he sends the fork over, he cleans the fork beforedoing so. After a philosopher is done eating, all his forks become dirty. Ifanother philosopher had previously requested one of the forks, he cleansthe fork and sends it.

The dining philosopher problem is an abstraction of resource allocation prob-lems. Learning about resource allocation problems and their solutions will helpin the development of robust and complex software, such as operating systemsand 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 canonly 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 everyday the work is late. Write a program to sort the orders in such a way that itminimises the fines he must pay. For each order assign a random duration of 1to 5 days, and a deadline between 1 and 50 days from the starting day. Ensurethat the total duration to complete the orders is 50.

Page 120: Programming Problems and Exercises

DRAFT

120 CHAPTER 17. PROBLEM SET 13

Input

Output

Page 121: Programming Problems and Exercises

DRAFT

Chapter 18Problem Set 14

This set contains a number of object-orientated programming (OOP) exercisesand problems. See 4.2Object-Oriented Programming Languagessubsection*.6for more information on OOP.PROBLEM 142. Difficulty: 1

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

Input

None

Output

Hello, World

PROBLEM 143. Difficulty: 2

Write a class that takes a person’s height in inches and returns the height incentimetres. One inch is 2.54 centimetres.

Input

60

121

Page 122: Programming Problems and Exercises

DRAFT

122 CHAPTER 18. PROBLEM SET 14

A femtometre is a unit oflength equivalent to 10−15

metres. It is named after theItalian-American physicist

Enrico Fermi (1901-54). It isused to measure the size of the

nuclei of atoms.

An angstrom is a unit of lengthequivalent to 10−10. It was first

used by the Swedish physicistAnders Jonas Angstrom

(1814-74) to enable him todescribe the solar spectrum. It

is largely obsolete.

Output

152.4

PROBLEM 144. Difficulty: 2

Derive a class from the class in Problem 143Problem Set 14pcount.143 thatalso returns the height in femtometres and angstroms.

Input

Output

PROBLEM 145. Difficulty: 2

Assume a bank account begins with a balance of R100 and earns interest at anannual rate of 5%. The interest is computed at the end of each year using thefollowing formula:

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

Write a class named ComputeInterest to determine and display the accountbalance at the end of each year for a ten-year period. Do not use loops.

Input

None.

Output

Starting balance: 100Year 1: 105Year 2: 100.25Year 3: 115.76Year 4: 121.55Year 5: 127.62Year 6: 134.00Year 7: 140.71Year 8: 147.74Year 9: 155.13Year 10: 162.88

PROBLEM 146.

Page 123: Programming Problems and Exercises

DRAFT

123

Write a program that adds two complex numbers together. Create a com-plex number class and use operator overloading so that the + can be used foraddition.

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. Writean application that uses this class. Then write an application called car.csthat inherits from the vehicle class, and prints numcylinders, horsepower anddisplacement.

Input

Output

PROBLEM 148.

Design and write your own class called mammal. Create three more animalclasses. Two must inherit directly from mammal and the other from one of theanimal classes.

Input

Output

PROBLEM 149.

Write a class with a method that accepts two military times (e.g. 15:00 and19:22). The class must return the number of minutes between the two times.

Input

15:0016:30

Output

Page 124: Programming Problems and Exercises

DRAFT

124 CHAPTER 18. PROBLEM SET 14

90 minutes

PROBLEM 150. Difficulty: 2

Write a class that accepts a decimal argument called amount. The class mustreturn the best spread of 1, 2, 5, 10, 20 and 50 cent coins that make up theamount.

Input

Amount? R1.29

Output

50 = 220 = 110 = 05 = 02 = 21 = 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 ofproducts, provide a total, add tax, accept money from the customer and provideappropriate change. It should also manage the cash float; initialise the registerto contain a certain amount of money, in certain denominations, and then trackthat 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 value5. Use the example as a rough guide only. It would be better to use a GUI forthis exercise.

Input

9.994.997.99totaltax20N

Page 125: Programming Problems and Exercises

DRAFT

125

5C1Cdone

Output

9.9914.9822.9722.9725.27Change = .50C, .20C, .2C, .1CFloat now: 2 * 20 N, 5C, 1C, 20 * .2C

Page 126: Programming Problems and Exercises

DRAFT

Page 127: Programming Problems and Exercises

DRAFT

Chapter 19Problem Set 15

This set contains exercises and problems that (on the whole) will be solved usingrecursion. Note that while exercises are given to write programs to computeFibonacci numbers and factorials, recursion is not a good solution to these ingeneral [14]. However, they do provide good exercises.PROBLEM 152.

Write a program using iteration to determine n!. This is ”n factorial”, which isthe 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 ofyour algorithm with the solution to the previous problem. Which appears tobe the better approach, iteration or recursion? Using recursion to determine n!is the classic example [2]. Steve McConnell states this is not a good approachto the problem (beyond using it as an exercise) [14].

127

Page 128: Programming Problems and Exercises

DRAFT

128 CHAPTER 19. PROBLEM SET 15

Input

4

Output

24

PROBLEM 154.

The Towers of Hanoi is a classic game in which disks on a peg must be movedfrom 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 andsliding it onto another rod, on top of the other disks that may alreadybe present on that rod

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

Write a program to implement this game. The user should be allowed to choosethe number of disks, say between 7 and 15. Allow a user to play the game, orthe computer to automatically solve it.

Input

Output

PROBLEM 155.

A chessboard is an 8 by 8 grid. The 8-queens problem requires us to place8 queens on the chessboard so that no queen is attacking another. A queenattacks 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

Page 129: Programming Problems and Exercises

DRAFT

Chapter 20Problem Set 16

This set contains more advanced problems. Some of the problems presentedare steps toward implementing real-world applications. Others are simply funways to spend an afternoon programming in your favourite language. Somemay 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 ofthe half-life of the substance in question. The half-life is the period of timethat it takes for the substance to decay to half its original amount [23]. Writea program that accepts as input the half-life of a substance and outputs thequantity present over time until none of the original substance is left. UseTable 20.1Half-Livestable.20.1 for input.

129

Page 130: Programming Problems and Exercises

DRAFT

130 CHAPTER 20. PROBLEM SET 16

Input

Some stuff

Output

Quantity present:

Substance Half-LifeCarbon-14 5715 yearsRhodium-106 29.9 secondsStrontium-90 29.1 yearsUranium-222 1 microsecondUranium-235 704 million years

Table 20.1: Half-Lives

PROBLEM 158. Difficulty: 3

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

• Passwords must consist of a mixture of lowercase and uppercase letters,numerical digits and possibly non-alphanumeric characters, with at leastone of each.

• Passwords must be between 6 and 20 characters in length.

• Passwords must not contain any sequence of characters immediately fol-lowed by the same sequence.

Write a program that inputs a password and then prints REJECTED if thepassword is rejected, or ACCEPTED if it adheres to the above criteria.

Input

Password: sappwordPassword: heY!2Password: Fido123!

Output

Page 131: Programming Problems and Exercises

DRAFT

131

REJECTEDREJECTEDACCEPTED

PROBLEM 159.

A password is not stored as plaintext in a database. If they were, then anyonewith access to the database could read passwords at will. To solve the problemwe save passwords as hashes. That is, we run the password through a one-wayfunction, and store the result. When a user enters their password, the samefunction is run on their plaintext password, and the resulting hash is comparedwith the hash stored in the database.

Input

Output

PROBLEM 160.

Credit cards usually have a so-called check digit. This is a single digit thatis 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 allthe 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 eightdigits. 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 therefore123465678.

Write a program to read in a nine digit integer from the keyboard and checkit for these rules. Write ”okay” or ”not okay” for the results of the test.

Input

1234567812645725

Output

123465678126425725

Page 132: Programming Problems and Exercises

DRAFT

132 CHAPTER 20. PROBLEM SET 16

PROBLEM 161.

You plan to start a lawn-mowing business in Pretoria to fund your studies.You have determined that you will have to earn R15 per hour to make a profit.Write a program to determine how much you should charge to mow a lawn.You program must determine the area of the yard that needs to be moved bysubtracting the area of all of the buildings on the land from the total area ofthe 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 ofall the buildings on the land and the lawn. The scale of the display should beadjustable between 1 cm to 1 m and 5 cm to 1m. Colour the lawn green andthe buildings brown.

Input

Output

PROBLEM 163. Difficulty: 4

The Game of Life is a cellular automaton devised by the British mathematicianJohn Conway in 1970. The game is actually a zero-player game, meaning thatits 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 Lifeby creating an initial configuration and observing how it evolves.

The universe of the Game of Life is an infinite two-dimensional grid of squarecells, each of which is in one of two possible states, live or dead. Every cellinteracts with its eight neighbours, which are the cells that are directly hori-zontally, vertically, or diagonally adjacent. At each step in time, the followingtransitions 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 over-crowding.

• Any live cell with two or three live neighbours lives, unchanged, to thenext generation.

Page 133: Programming Problems and Exercises

DRAFT

133

• Any dead cell with exactly three live neighbours comes to life.

The initial pattern constitutes the ’seed’ of the system. The first generation iscreated by applying the above rules simultaneously to every cell in the seed 97births and deaths happen simultaneously, and the discrete moment at whichthis happens is sometimes called a tick. The rules continue to be appliedrepeatedly to create further generations.

Write a program that runs the Game of Life. Your grid must contain a mini-mum of 100 by 100 cells.

Page 134: Programming Problems and Exercises

DRAFT

Page 135: Programming Problems and Exercises

DRAFT

Chapter 21Problem 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 combi-nations of dots (short beeps) and dashes (long beeps). See Table 21.1MorseCodetable.21.1 for a key. Write a program that transmits Morse Code fromone computer to another over a LAN in real time. This can either be a consoleapplication, or you can use a GUI. The receiving computer can either employsound 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 receivemessages. That is, flash the (for example) Caps Lock light on the keyboard toindicate Morse Code.

135

Page 136: Programming Problems and Exercises

DRAFT

136 CHAPTER 21. PROBLEM SET 17

Samuel Finley Breese Morse(April 27 1791 to April 2 1872),from the USA, was the creator

of a single-wire telegraphsystem and Morse code.

a . q . 1 .b . . . r . . 2 . .c . . s . . . 3 . . .d . . t 4 . . . .e . u . . 5 . . . . .f . . . v . . . 6 . . . .g . w . 7 . . .h . . . . x . . 8 . . .i . . y . 9 .j . z . . 0k . error . . . . . . . . . . . .l . . . wait . . . . , . . . .m end msg . . . : . . .n . end work . . . . ) . .o inv xmit . ( . .p . . / . . . ? . . . .

= . . .

Table 21.1: Morse Code

Input

.. .

Output

.. .

PROBLEM 166. Difficulty: 4

Write a program that transmits and receives text from one computer to anotherover a LAN. This can either be a console application, or a window interfacecan be designed. Allow the two users to see a history of both sides of theconversation.

As an additional challenge, modify the code to recognise smilies, and substitutethe smilies with icon representations.

InputHello, how are you?

OutputHello, how are you?

Page 137: Programming Problems and Exercises

DRAFT

137

PROBLEM 167. Difficulty: 4

Search the Internet for a form that needs to be completed, or create yourown. The form should require information such as your name, surname, emailaddress and so forth. Forms like these are used when subscribing to newslettersor registering for membership of a site.

Write a program that automatically completes the form for you. Then test ifthe program can be used with similar forms on other sites.

Be aware that this problem involves writing badly-behaved software, in thesense that you will be abusing someone else’s website. Not only will you beabusing their service, but you will be wasting a lot of bandwidth during test-ing. 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. Auser sits at a computer and either converses with another computer or with aperson over a network.

Write a program that consists of a client and a server. The client is simply achat client. The server allows a user to chat with the person at the client, orthe server can itself carry on the conversation. There must be no indication ofwho the user is speaking to.

InputHelloI am fine. How are you?What is your favourite movie?

Page 138: Programming Problems and Exercises

DRAFT

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 RSSfile) and parses it, looking for particular information. For example, you mightwant to look for a stock price, or a MP3 URL. Some HTTP responses youmight see are in Table 21.2Problem Set 17table.21.2. If the response is not a200, then you must display an appropriate error code.

CODE MEANING NOTE200 OK The request has succeeded400 Bad Request The request could not be understood by the server

due to malformed syntax.401 Unauthorized The request requires user authentication.403 Forbidden The server understood the request, but is refusing to

fulfil it.404 Not Found The server has not found anything matching the

URI.405 Method Not Al-

lowedThe request method is not allowed. Typically whentrying to execute a normal document or display ascript.

406 Not Acceptable According to the client’s request, it isn’t capable ofhandling the response.

407 Proxy Authentica-tion Required

This code is similar to 401 (Unauthorized), but in-dicates that the client must first authenticate itselfwith the proxy.

408 Request Timeout The client did not produce a request within the timethat the server was prepared to wait.

500 Internal Server Er-ror

The server encountered an unexpected conditionwhich prevented it from fulfilling the request.

501 Not Implemented The server does not support the functionality re-quired to fulfil the request.

502 Bad Gateway The server is a gateway or proxy and received aninvalid response from the upstream server it accessedin attempting to fulfil the request.

Continued...

Page 139: Programming Problems and Exercises

DRAFT

139

503 Service Unavailable The server is currently unable to handle the requestdue to temporary overloading or maintenance of theserver.

504 Gateway Timeout The server is a gateway or proxy and did not receivea timely response from the upstream server.

600 Malformed URI The link checking program was not able to parse theURI. This means that the URI was either empty, ornot a valid URI.

601 Connection TimedOut

The server did not respond before the connectiontimed out.

602 Unknown Error Some other error occurred in contacting the server,making the request, or parsing the response. Thiscould be due to a mangled or incorrectly formattedresponse from the server.

Table 21.2: HTTP Responses

PROBLEM 170. Difficulty: 3

Write an program that uses ICMP packets to determine if a networked com-puter is online or not. Your program will operate in a similar fashion to the”ping” command.

Input

upordown 192.9.202.5

Output

Machine responded.

PROBLEM 171. Difficulty: 5

Write an electronic language dictionary that shows entries for two differentlanguages. For example, English and German. The program must be able toconnect to a server to update its word list.

Input

Output

Page 140: Programming Problems and Exercises

DRAFT

Page 141: Programming Problems and Exercises

DRAFT

Chapter 22Problem Set 18

This section contains problems that require distributed or parallel processing.That is, the algorithms run on more than a single computer. Evidently, thisis more difficult than writing algorithms for a single computer. It is suggestedthat some research is undertaken before tackling these problems.

There are three reasons why writing parallel programs is sometimes a goodidea [1].

1. Some problems are easier to solve using parallel constructs because ofinherent parallelism

2. Though some problems are not parallel, efficiency can be gained by di-viding the work amongst multiple processors

3. The nature of some systems requires them to run on networked proces-sors. These are known as distributed systems

PROBLEM 172. Difficulty: 4

Problem 85Problem Set 05pcount.85 was to draw the Mandelbrot set. Generateand draw the Mandelbrot set using parallel programming.

Input

141

Page 142: Programming Problems and Exercises

DRAFT

142 CHAPTER 22. PROBLEM SET 18

Output

Page 143: Programming Problems and Exercises

DRAFT

Chapter 23Problem Set 19

This section contains five problems that may take several weeks or monthsto solve and require in-depth knowledge of the chosen language, as well asconsiderable domain knowledge. Considerable research will be involved, aswell 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 isresponsible for the management and coordination of activities and the sharingof the resources of the computer. The operating system acts as a host forapplication programs that are run on the machine. One of the functions of anoperating system is to handle the details of the operation of the hardware. Thisrelieves application programs from having to manage these details. This alsomakes it easier for programmers to write applications. Almost all computersuse an operating system.

Write a small operating system. Implement as many of the following as youcan, in order.

1. Bootstraping

2. Process management

3. Memory management

143

Page 144: Programming Problems and Exercises

DRAFT

144 CHAPTER 23. PROBLEM SET 19

4. Disk and file systems

5. Device Driver management

6. Networking

7. Security

8. Graphical user interfaces

PROBLEM 174. Difficulty: 6

Lisp (List Processing) is the second-oldest high-level programming languageand is still in use today; it was invented in 1958 by McCarthy. Lisp is a func-tional programming language. That is to say, a Lisp program is composed offunctions [9]. The most widely known general-purpose Lisp dialects are Com-mon Lisp and Scheme.

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

Your interpreter can be written on Windows, Linux, FreeBSD or any other OSyou have access to. As a challenge you can implement it on your own OS fromProblem 173Problem Set 19pcount.173.

PROBLEM 175. Difficulty: 6

Prolog stands for Programming in Logic.

Write a prolog compiler/interpreter.

PROBLEM 176. Difficulty: 6

BASIC (Beginner’s All-purpose Symbolic Instruction Code) is a high-level pro-gramming languages that was designed in 1964 by John George Kemeny andThomas Eugene Kurtz at Dartmouth College. BASIC remains popular to thisday, 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 OSyou have access to. As a challenge you can implement it on your own OS fromProblem 173Problem Set 19pcount.173.

PROBLEM 177. Difficulty: 6

Page 145: Programming Problems and Exercises

DRAFT

145

A relational database is a database that groups data using common attributesfound in the data set. For example, a data set containing sales transactionscan 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 managingdatabases. 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 aminimum, 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 173ProblemSet 19pcount.173.

PROBLEM 178. Difficulty: 6

Obtain a star catalogue from the Internet and write planetarium software.Allow users to see the positions of the stars, planets, minor planets and cometsin 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 alabel identifying the object should be temporarily displayed.

As an additional challenge, the positions of artificial satellites can also be in-cluded.

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

Page 146: Programming Problems and Exercises

DRAFT

Page 147: Programming Problems and Exercises

DRAFT

Chapter 24Problem Set 20

This section contains a selection of problems that were initially used for a classstudying prolog. Prolog is a general purpose logic programming language. Itis often used for learning artificial intelligence and computational linguistics.Prolog was conceived in the 1970s by a group around Alain Colmerauer inMarseille. The first Prolog system was developed in 1972 by Colmerauer andPhilippe Roussel.

A good prolog implementation to use is SWI-Prolog, which has been under de-velopment 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

Page 148: Programming Problems and Exercises

DRAFT

148 CHAPTER 24. PROBLEM SET 20

brother of(lola,joe).

Output

falsefalse

PROBLEM 180. Difficulty: 1

Given the following facts:

pop(sa,48).pop(usa,306).pop(nigeria,148).

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

where pop(X,Y) indicates the population Y in millions of country X andarea(X,Y) indicates the population Y in millions of the country X.

Write a rule in the same file that determines population density, i.e. numberof 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 ordrinks. For example

likes(frank,milk).

Page 149: Programming Problems and Exercises

DRAFT

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 com-patibility between people, based on number of shared interests. Output can bephrased as a ranked list of paired people.

Input

compatible(X,Y).

Output

X = joeY = lolaX = joeY = frank

PROBLEM 183. Difficulty: 1

Find the last element of a list.

Input

?- my last(X,[a,b,c,d]).

Output

Page 150: Programming Problems and Exercises

DRAFT

150 CHAPTER 24. PROBLEM SET 20

X = d

Page 151: Programming Problems and Exercises

DRAFT

Bibliography

[1] H.E. Bal and D. Grune. Programming Language Essentials. Pearson Ed-ucation Limited, 1994.

[2] N. Dale and D. Teague. C++ plus Data Structures. Jones and BartlettPublishers, Inc., second edition, 2001.

[3] R. Eckler. Making the Alphabet Dance. MacMillan, 1996.

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

[5] V.J. Garg. Elements of Distributed Computing. John Wiley and Sons, Inc,2002.

[6] T.J. Glover. Pocket Ref. Sequioa Publishing, Inc., 2007.

[7] Y. Hardy and W.-H. Steeb. Classical and Quantum Computing.Birkhauser Verlag, 2000.

[8] S. Harris and J Ross. Beginning Algorithms. Wiley Publishing, Inc., 2006.

[9] P.A. Henning and H Vogelsang. Programmiersprachen. Carl Hanser Ver-lag, 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. McGraw-Hill, 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

Page 152: Programming Problems and Exercises

DRAFT

152 BIBLIOGRAPHY

[15] J. Meeus. Astronomical Algorithms. Willmann-Bell, Inc, 2000.

[16] J. Mongan and N. Suojanen. Programming Interviews. John Wiley andSons, 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 PhilipLtd., 1995.

[20] K. H. Rosen. Elementary Number Theory and its Applications. AddisonWesley, 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, ninthedition, 2007.

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

[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 Solutionsin Scientific Computing. World Scientific, 2004.

[29] W. Vetterling W. Press, S. Teukolsky and B. Flannery. Numerical Recipesin 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.

Page 153: Programming Problems and Exercises

DRAFT

Index

8-Queens Problem, 128

Absolute Number, 64Abstract Data Types, 81Abu Ja’far Muhammad ibn Musa

al-Khwarizmi, 16Account Class, 122ACID, 145Algorithm, 15Anagram, 114Angstrom, 122Array, Three-Dimensional, 61Arrays, Addition of, 60Arrays, Largest Element, 57Arrays, Mean, 58, 59Arrays, Median, 59Arrays, Mode, 59Arrays, Range, 58Arrays, Smallest Element, 58Arrays, Sum, 57Asterisk Diamonds, 46Asterisk Pyramid, 45Asterisk Rope, 34Asterisk Square, 35Asterisk Triangle, 41, 42Asterisk Walkway, 33Asteroids, 102Average Marks, 37

Backgammon, 93BASIC, 144Beggar My Neighbour, 99

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

Calendar, 70Canasta, 99Cash Register, 124Cellular Automaton, 132Chat Program, 136Check Digit, 131Checkers, 93Chess, 94, 95Collatz Conjecture, 66Complex Numbers, 122Compound Increase and Decrease,

69Constructor, 24Containers, 81Control Structure, Repetition, 34Control Structure, Selection, 36Control Structure, Sequence, 33Conway, John, 132Crossword, 102

Database, 144de Fermat, Pierre, 67Depth-first search, 111Destructor, 24

153

Page 154: Programming Problems and Exercises

DRAFT

154 INDEX

Dictionary, 139Dining Philosophers, 117Doubly Linked List, 82Drawing Circles, 74

Eratosthenes of Cyrene, 75Eratosthenes’ Sieve, 75Erdos Numbers, 77Escape Velocity, 70

Factorial, 127Femtometre, 122Fermat Numbers, 67Fibonacci Numbers, 67FIFO, 83File Access, 52File Sorting, 51Flight Control, 72Form Agent, 137

Game of Life, 132Go, 95Goldbach’s Conjecture, 76Goldbach, Christian, 76

Hashing Passwords, 131Hello World, 32Hello World 2, 32Hello World 3, 32Highest Common Factor, 65Histogram, 50

ICMP, 139Increase, 38Initials, 46Insertion Sort, 104International Society of Mad Hat-

ters, 113Irrational Numbers, 73

Julian Day, 71

Kaprekar’s Constant, 68Kemeny, John George, 144Knapsack Problem, 117Knuth, Donald, 50, 104Kurtz, Thomas Eugene, 144

Languages, Procedural, 22Letter Distribution Analysis, 90LIFO, 86Linked List, 82LISP, 144List, 81Lottery, 64Lunar Lander, 101

Mammal Class, 123Mandelbrot Set, 79Mandelbrot Set (distributed), 141Maple, 17Maximum of two numbers, 44Mergesort, 106Mileage Table, 62Military Time, 123Money Changer, 124Morse Code, 135Morse, Samuel, 136Mowing the Lawn, 132

Noughts and Crosses, 93

Operating System, 143

Palindromes (Numbers), 76, 77Palindromes (Words), 115Passwords, 130Perfect Numbers, 76Permutations, 90Pi, 74Ping, 139Planetarium, 145Poker, 99, 100Postfix Notation, 114Prefix Notation, 114Prime Factors, 78Prime Numbers, 75, 78Priorty Queue, 84Problem Solving Steps, 12Projects, 143Prolog, 144, 147

Queue, 83Quicksort, 106

Page 155: Programming Problems and Exercises

DRAFT

INDEX 155

Radioactive Decay, 129Roche’s Limit, 73

Sarkovskii’s theorem, 74Scalinger, Jospeh Justus, 71SciLab, 17Selection Sort, 105Sequential Search, 109, 110Sharkovsky, Oleksandr Mikolaivich,

74Shellsort, 105Sorted Priority Queues, 85Space Invaders, 102Spellcheck, 53SQL, 145SQL92, 145Stack, 86String Splitting, 47String Swapping, 36Substitution Cipher, 89Surface Area, 37

Temperature Conversion, 38Tic-Tac-Toe, 93Time in Words, 45Timer, 129Towers of Hanoi, 128Trabb Pardo, Luis, 50Trabb Pardo-Knuth Algorithm, 50Transposition Cipher, 90Travelling Salesman Problem, 116Trees, 86Turing Test, 137Turing, Alan, 137Two’s Complement, 64

Vehicle Class, 123Volume of a Sphere, 37

Wells, H.G., 90Wolves and Chickens, 113Word Change, 115Word Count, 52World Wide Web, 138

Zeitz, Paul, 11


Recommended