-
-
Save Q00R/0718b5da56bc9f413f22303b2a17cec7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://www.w3resource.com/java-exercises/array/index.php#editorr | |
https://www.ntu.edu.sg/home/ehchua/programming/java/J2a_BasicsExercises.html | |
https://adriann.github.io/programming_problems.html (Shown Below) | |
Simple Programming Problems | |
Whenever I’m TA for a introductory CS class where students learn some programming language, I have trouble coming up with good exercises. Problems from Project Euler and the like are usually much too difficult for beginners, especially if they don’t have a strong background in mathematics. | |
This page is a collection of progressively more difficult exercises that are suitable for people who just started learning. It will be extended as I come up with new exercises. Except for the GUI questions, exercises are generally algorithmic and should be solvable without learning any libraries. The difficulty of the exercises of course somewhat depends on the programming language you use. The List exercises for example are more complicated in languages like C that don’t have build-in support for lists. | |
I suppose they are also useful, although much easier, whenever an experienced person wants to learn a new language. | |
This guide has been translated to Chinese by yifeitao Simple Programming Problems in Chinese | |
Before you begin | |
Learning to program means learning how to solve problems using code. Conceptually it is not very difficult to write a program that solves a problem that you can solve yourself. The skill you need to acquire is thinking very precisely about how you solve the problem and breaking it down into steps that are so simple that a computer can execute them. I encourage you to first solve a few instances of a problem by hand and think about what you did to find the solution. For example if the task is sorting lists, sort some short lists yourself. A reasonable method would be to find the smallest element, write it down and cross it out of the original list and repeat this process until you have sorted the whole list. Then you have to teach the computer 1) how to find the smallest element, 2) how to write it down, 3) how to cross it out, and wrap this in a loop. Then continue this task breakdown process until you’re confident you know how to write the necessary program. | |
To make good progress in your programming task, you need to test your work as early and as thoroughly as possible. Everybody makes mistakes while programming and finding mistakes in programs consumes a very large part of a programmer’s work-day. Finding a problem in a small and easy piece of code is much simpler than trying to spot it in a large program. This is why you should try to test each sub task you identified during your task-breakdown by itself. Only after you’re confident that each part works as you expect you can attempt to plug them together. Make sure you test the complete program as well, errors can creep in in the way the different parts interact. You should try to automate your tests. The easier it is to test your program, the freer you are in experimenting with changes. | |
The last important point is how you express your thoughts as code. In the same way that you can express the same argument in different ways in a normal English essay, you can express the same problem-solving method in different ways in code. Try for brevity. The lines that you don’t write are the lines where you can be sure that the don’t have bugs. Don’t be afraid to Google for idiomatic ways of doing the things you’d like to do (after you tried doing them yourself!). Remember that you don’t write the program for the computer, you write it for other humans (maybe a future you!). Choose names that explain things, add comments where these names don’t suffice. Never comment on what the code is doing, only write comments that explain why. | |
This is a bad example: | |
// This function checks whether a number is even | |
def f(x): | |
// compute x modulo 2 and check whether it is zero | |
if modulo(x,2) == 0: | |
// the number is even | |
return True | |
else: | |
// the number is odd | |
return False | |
The exact same idea is much easier to understand if you write it like this: | |
def is_divisible(number, divisor): | |
return modulo(number, divisor) == 0 | |
def is_even(number): | |
return is_divisible(number, 2) | |
Better naming and a better task breakdown make the comments obsolete. Revise your code just as you would revise an essay. Sketch, write, delete, reformulate, ask others what they think. Repeat until only the crispest possible expression of your idea remains. Revisit code you’ve written a while ago to see whether you can improve it with things you’ve learned since. | |
Elementary | |
Write a program that prints ‘Hello World’ to the screen. | |
Write a program that asks the user for their name and greets them with their name. | |
Modify the previous program such that only the users Alice and Bob are greeted with their names. | |
Write a program that asks the user for a number n and prints the sum of the numbers 1 to n | |
Modify the previous program such that only multiples of three or five are considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17 | |
Write a program that asks the user for a number n and gives them the possibility to choose between computing the sum and computing the product of 1,…,n. | |
Write a program that prints a multiplication table for numbers up to 12. | |
Write a program that prints all prime numbers. (Note: if your programming language does not support arbitrary size numbers, printing all primes up to the largest number you can easily represent is fine too.) | |
Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed. It counts only as one try if they input the same number multiple times consecutively. | |
Write a program that prints the next 20 leap years. | |
Write a program that computes the sum of an alternating series where each element of the series is an expression of the form | |
( | |
( | |
− | |
1 | |
) | |
k | |
+ | |
1 | |
) | |
/ | |
( | |
2 | |
* | |
k | |
− | |
1 | |
) | |
for each value of | |
k | |
from 1 to a million, multiplied by 4. Or, in more mathematical notation | |
4 | |
⋅ | |
∑ | |
k | |
= | |
1 | |
10 | |
6 | |
( | |
− | |
1 | |
) | |
k | |
+ | |
1 | |
2 | |
k | |
− | |
1 | |
= | |
4 | |
⋅ | |
( | |
1 | |
− | |
1 | |
/ | |
3 | |
+ | |
1 | |
/ | |
5 | |
− | |
1 | |
/ | |
7 | |
+ | |
1 | |
/ | |
9 | |
− | |
1 | |
/ | |
11 | |
… | |
) | |
. | |
Lists, Strings | |
If your language of choice doesn’t have a build in list and/or string type (e.g. you use C), these exercises should also be solvable for arrays. However, some solutions are very different between an array-based list (like C++’s vector) and a pointer based list (like C++’s list), at least if you care about the efficiency of your code. So you might want to either find a library, or investigate how to implement your own linked list if your language doesn’t have it. | |
Write a function that returns the largest element in a list. | |
Write function that reverses a list, preferably in place. | |
Write a function that checks whether an element occurs in a list. | |
Write a function that returns the elements on odd positions in a list. | |
Write a function that computes the running total of a list. | |
Write a function that tests whether a string is a palindrome. | |
Write three functions that compute the sum of the numbers in a list: using a for-loop, a while-loop and recursion. (Subject to availability of these constructs in your language of choice.) | |
Write a function on_all that applies a function to every element of a list. Use it to print the first twenty perfect squares. The perfect squares can be found by multiplying each natural number with itself. The first few perfect squares are 1*1= 1, 2*2=4, 3*3=9, 4*4=16. Twelve for example is not a perfect square because there is no natural number m so that m*m=12. (This question is tricky if your programming language makes it difficult to pass functions as arguments.) | |
Write a function that concatenates two lists. [a,b,c], [1,2,3] → [a,b,c,1,2,3] | |
Write a function that combines two lists by alternatingly taking elements, e.g. [a,b,c], [1,2,3] → [a,1,b,2,c,3]. | |
Write a function that merges two sorted lists into a new sorted list. [1,4,6],[2,3,5] → [1,2,3,4,5,6]. You can do this quicker than concatenating them followed by a sort. | |
Write a function that rotates a list by k elements. For example [1,2,3,4,5,6] rotated by two becomes [3,4,5,6,1,2]. Try solving this without creating a copy of the list. How many swap or move operations do you need? | |
Write a function that computes the list of the first 100 Fibonacci numbers. The first two Fibonacci numbers are 1 and 1. The n+1-st Fibonacci number can be computed by adding the n-th and the n-1-th Fibonacci number. The first few are therefore 1, 1, 1+1=2, 1+2=3, 2+3=5, 3+5=8. | |
Write a function that takes a number and returns a list of its digits. So for 2342 it should return [2,3,4,2]. | |
Write functions that add, subtract, and multiply two numbers in their digit-list representation (and return a new digit list). If you’re ambitious you can implement Karatsuba multiplication. Try different bases. What is the best base if you care about speed? If you couldn’t completely solve the prime number exercise above due to the lack of large numbers in your language, you can now use your own library for this task. | |
Write a function that takes a list of numbers, a starting base b1 and a target base b2 and interprets the list as a number in base b1 and converts it into a number in base b2 (in the form of a list-of-digits). So for example [2,1,0] in base 3 gets converted to base 10 as [2,1]. | |
Implement the following sorting algorithms: Selection sort, Insertion sort, Merge sort, Quick sort, Stooge Sort. Check Wikipedia for descriptions. | |
Implement binary search. | |
Write a function that takes a list of strings an prints them, one per line, in a rectangular frame. For example the list ["Hello", "World", "in", "a", "frame"] gets printed as: | |
********* | |
* Hello * | |
* World * | |
* in * | |
* a * | |
* frame * | |
********* | |
Write function that translates a text to Pig Latin and back. English is translated to Pig Latin by taking the first letter of every word, moving it to the end of the word and adding ‘ay’. “The quick brown fox” becomes “Hetay uickqay rownbay oxfay”. | |
Intermediate | |
Write a program that outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 (in this order) such that the result is 100. For example 1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100. | |
Write a program that takes the duration of a year (in fractional days) for an imaginary planet as an input and produces a leap-year rule that minimizes the difference to the planet’s solar year. | |
Implement a data structure for graphs that allows modification (insertion, deletion). It should be possible to store values at edges and nodes. It might be easiest to use a dictionary of (node, edgelist) to do this. | |
Write a function that generates a DOT representation of a graph. | |
Write a program that automatically generates essays for you. | |
Using a sample text, create a directed (multi-)graph where the words of a text are nodes and there is a directed edge between u and v if u is followed by v in your sample text. Multiple occurrences lead to multiple edges. | |
Do a random walk on this graph: Starting from an arbitrary node choose a random successor. If no successor exists, choose another random node. | |
Write a program that automatically converts English text to Morse code and vice versa. | |
Write a program that finds the longest palindromic substring of a given string. Try to be as efficient as possible! | |
Think of a good interface for a list. What operations do you typically need? You might want to investigate the list interface in your language and in some other popular languages for inspiration. | |
Implement your list interface using a fixed chunk of memory, say an array of size 100. If the user wants to add more stuff to your list than fits in your memory you should produce some kind of error, for example you can throw an exception if your language supports that. | |
Improve your previous implementation such that an arbitrary number of elements can be stored in your list. You can for example allocate bigger and bigger chunks of memory as your list grows, copy the old elements over and release the old storage. You should probably also release this memory eventually if your list shrinks enough not to need it anymore. Think about how much bigger the new chunk of memory should be so that your performance won’t be killed by allocations. Increasing the size by 1 element for example is a bad idea. | |
If you chose your growth right in the previous problem, you typically won’t allocate very often. However, adding to a big list sometimes consumes considerable time. That might be problematic in some applications. Instead try allocating new chunks of memory for new items. So when your list is full and the user wants to add something, allocate a new chunk of 100 elements instead of copying all elements over to a new large chunk. Think about where to do the book-keeping about which chunks you have. Different book keeping strategies can quite dramatically change the performance characteristics of your list. | |
Implement a binary heap. Once using a list as the base data structure and once by implementing a pointer-linked binary tree. Use it for implementing heap-sort. | |
Implement an unbalanced binary search tree. | |
Implement a balanced binary search tree of your choice. I like (a,b)-trees best. | |
Compare the performance of insertion, deletion and search on your unbalanced search tree with your balanced search tree and a sorted list. Think about good input sequences. If you implemented an (a,b)-tree, think about good values of a and b. | |
Advanced | |
Given two strings, write a program that efficiently finds the longest common subsequence. | |
Given an array with numbers, write a program that efficiently answers queries of the form: “Which is the nearest larger value for the number at position i?”, where distance is the difference in array indices. For example in the array [1,4,3,2,5,7], the nearest larger value for 4 is 5. After linear time preprocessing you should be able to answer queries in constant time. | |
Given two strings, write a program that outputs the shortest sequence of character insertions and deletions that turn one string into the other. | |
Write a function that multiplies two matrices together. Make it as efficient as you can and compare the performance to a polished linear algebra library for your language. You might want to read about Strassen’s algorithm and the effects CPU caches have. Try out different matrix layouts and see what happens. | |
Implement a van Emde Boas tree. Compare it with your previous search tree implementations. | |
Given a set of d-dimensional rectangular boxes, write a program that computes the volume of their union. Start with 2D and work your way up. | |
GUI | |
Write a program that displays a bouncing ball. | |
Write a Memory game. | |
Write a Tetris clone | |
Open Ended | |
Write a program that plays Hangman as good as possible. For example you can use a large dictionary like this and select the letter that excludes most words that are still possible solutions. Try to make the program as efficient as possible, i.e. don’t scan the whole dictionary in every turn. | |
Write a program that plays Rock, Paper, Scissors better than random against a human. Try to exploit that humans are very bad at generating random numbers. | |
Write a program that plays Battle Ship against human opponents. It takes coordinates as input and outputs whether that was a hit or not and its own shot’s coordinates. | |
Other Collections | |
Of course I’m not the first person to come up with the idea of having a list like this. | |
John Dalbey’s collection | |
Several small problems Programming Practice | |
CPE 101 Projects | |
Code Kata | |
99 Lisp Problems, 99 Haskell Problems. Most of these can also be done in other languages. | |
Rosetta Code Programming Tasks. These come with solutions in many languages! | |
Code Golf Challenges. The goal here is to solve the problem with as few characters as possible. | |
SPOJ Problems. This is a list of more than 13000 Problems! | |
Code Abbey According to Github user RodionGork, this is less mathy than Project Euler. | |
L-99: Ninety-Nine Lisp Problems | |
Based on a Prolog problem list by [email protected] | |
Working with lists | |
P01 (*) Find the last box of a list. | |
Example: | |
* (my-last '(a b c d)) | |
(D) | |
P02 (*) Find the last but one box of a list. | |
Example: | |
* (my-but-last '(a b c d)) | |
(C D) | |
P03 (*) Find the K'th element of a list. | |
The first element in the list is number 1. | |
Example: | |
* (element-at '(a b c d e) 3) | |
C | |
P04 (*) Find the number of elements of a list. | |
P05 (*) Reverse a list. | |
P06 (*) Find out whether a list is a palindrome. | |
A palindrome can be read forward or backward; e.g. (x a m a x). | |
P07 (**) Flatten a nested list structure. | |
Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively). | |
Example: | |
* (my-flatten '(a (b (c d) e))) | |
(A B C D E) | |
Hint: Use the predefined functions list and append. | |
P08 (**) Eliminate consecutive duplicates of list elements. | |
If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed. | |
Example: | |
* (compress '(a a a a b c c a a d e e e e)) | |
(A B C A D E) | |
P09 (**) Pack consecutive duplicates of list elements into sublists. | |
If a list contains repeated elements they should be placed in separate sublists. | |
Example: | |
* (pack '(a a a a b c c a a d e e e e)) | |
((A A A A) (B) (C C) (A A) (D) (E E E E)) | |
P10 (*) Run-length encoding of a list. | |
Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E. | |
Example: | |
* (encode '(a a a a b c c a a d e e e e)) | |
((4 A) (1 B) (2 C) (2 A) (1 D)(4 E)) | |
P11 (*) Modified run-length encoding. | |
Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists. | |
Example: | |
* (encode-modified '(a a a a b c c a a d e e e e)) | |
((4 A) B (2 C) (2 A) D (4 E)) | |
P12 (**) Decode a run-length encoded list. | |
Given a run-length code list generated as specified in problem P11. Construct its uncompressed version. | |
P13 (**) Run-length encoding of a list (direct solution). | |
Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem P09, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X. | |
Example: | |
* (encode-direct '(a a a a b c c a a d e e e e)) | |
((4 A) B (2 C) (2 A) D (4 E)) | |
P14 (*) Duplicate the elements of a list. | |
Example: | |
* (dupli '(a b c c d)) | |
(A A B B C C C C D D) | |
P15 (**) Replicate the elements of a list a given number of times. | |
Example: | |
* (repli '(a b c) 3) | |
(A A A B B B C C C) | |
P16 (**) Drop every N'th element from a list. | |
Example: | |
* (drop '(a b c d e f g h i k) 3) | |
(A B D E G H K) | |
P17 (*) Split a list into two parts; the length of the first part is given. | |
Do not use any predefined predicates. | |
Example: | |
* (split '(a b c d e f g h i k) 3) | |
( (A B C) (D E F G H I K)) | |
P18 (**) Extract a slice from a list. | |
Given two indices, I and K, the slice is the list containing the elements between the I'th and K'th element of the original list (both limits included). Start counting the elements with 1. | |
Example: | |
* (slice '(a b c d e f g h i k) 3 7) | |
(C D E F G) | |
P19 (**) Rotate a list N places to the left. | |
Examples: | |
* (rotate '(a b c d e f g h) 3) | |
(D E F G H A B C) | |
* (rotate '(a b c d e f g h) -2) | |
(G H A B C D E F) | |
Hint: Use the predefined functions length and append, as well as the result of problem P17. | |
P20 (*) Remove the K'th element from a list. | |
Example: | |
* (remove-at '(a b c d) 2) | |
(A C D) | |
P21 (*) Insert an element at a given position into a list. | |
Example: | |
* (insert-at 'alfa '(a b c d) 2) | |
(A ALFA B C D) | |
P22 (*) Create a list containing all integers within a given range. | |
If first argument is smaller than second, produce a list in decreasing order. | |
Example: | |
* (range 4 9) | |
(4 5 6 7 8 9) | |
P23 (**) Extract a given number of randomly selected elements from a list. | |
The selected items shall be returned in a list. | |
Example: | |
* (rnd-select '(a b c d e f g h) 3) | |
(E D A) | |
Hint: Use the built-in random number generator and the result of problem P20. | |
P24 (*) Lotto: Draw N different random numbers from the set 1..M. | |
The selected numbers shall be returned in a list. | |
Example: | |
* (lotto-select 6 49) | |
(23 1 17 33 21 37) | |
Hint: Combine the solutions of problems P22 and P23. | |
P25 (*) Generate a random permutation of the elements of a list. | |
Example: | |
* (rnd-permu '(a b c d e f)) | |
(B A D C E F) | |
Hint: Use the solution of problem P23. | |
P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list | |
In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficients). For pure mathematicians, this result may be great. But we want to really generate all the possibilities in a list. | |
Example: | |
* (combination 3 '(a b c d e f)) | |
((A B C) (A B D) (A B E) ... ) | |
P27 (**) Group the elements of a set into disjoint subsets. | |
a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities and returns them in a list. | |
Example: | |
* (group3 '(aldo beat carla david evi flip gary hugo ida)) | |
( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) ) | |
... ) | |
b) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups. | |
Example: | |
* (group '(aldo beat carla david evi flip gary hugo ida) '(2 2 5)) | |
( ( (ALDO BEAT) (CARLA DAVID) (EVI FLIP GARY HUGO IDA) ) | |
... ) | |
Note that we do not want permutations of the group members; i.e. ((ALDO BEAT) ...) is the same solution as ((BEAT ALDO) ...). However, we make a difference between ((ALDO BEAT) (CARLA DAVID) ...) and ((CARLA DAVID) (ALDO BEAT) ...). | |
You may find more about this combinatorial problem in a good book on discrete mathematics under the term "multinomial coefficients". | |
P28 (**) Sorting a list of lists according to length of sublists | |
a) We suppose that a list contains elements that are lists themselves. The objective is to sort the elements of this list according to their length. E.g. short lists first, longer lists later, or vice versa. | |
Example: | |
* (lsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o))) | |
((O) (D E) (D E) (M N) (A B C) (F G H) (I J K L)) | |
b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort the elements of this list according to their length frequency; i.e., in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later. | |
Example: | |
* (lfsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o))) | |
((i j k l) (o) (a b c) (f g h) (d e) (d e) (m n)) | |
Note that in the above example, the first two lists in the result have length 4 and 1, both lengths appear just once. The third and forth list have length 3 which appears twice (there are two list of this length). And finally, the last three lists have length 2. This is the most frequent length. | |
Arithmetic | |
P31 (**) Determine whether a given integer number is prime. | |
Example: | |
* (is-prime 7) | |
T | |
P32 (**) Determine the greatest common divisor of two positive integer numbers. | |
Use Euclid's algorithm. | |
Example: | |
* (gcd 36 63) | |
9 | |
P33 (*) Determine whether two positive integer numbers are coprime. | |
Two numbers are coprime if their greatest common divisor equals 1. | |
Example: | |
* (coprime 35 64) | |
T | |
P34 (**) Calculate Euler's totient function phi(m). | |
Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m. | |
Example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1. | |
* (totient-phi 10) | |
4 | |
Find out what the value of phi(m) is if m is a prime number. Euler's totient function plays an important role in one of the most widely used public key cryptography methods (RSA). In this exercise you should use the most primitive method to calculate this function (there are smarter ways that we shall discuss later). | |
P35 (**) Determine the prime factors of a given positive integer. | |
Construct a flat list containing the prime factors in ascending order. | |
Example: | |
* (prime-factors 315) | |
(3 3 5 7) | |
P36 (**) Determine the prime factors of a given positive integer (2). | |
Construct a list containing the prime factors and their multiplicity. | |
Example: | |
* (prime-factors-mult 315) | |
((3 2) (5 1) (7 1)) | |
Hint: The problem is similar to problem P13. | |
P37 (**) Calculate Euler's totient function phi(m) (improved). | |
See problem P34 for the definition of Euler's totient function. If the list of the prime factors of a number m is known in the form of problem P36 then the function phi(m) can be efficiently calculated as follows: Let ((p1 m1) (p2 m2) (p3 m3) ...) be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula: | |
phi(m) = (p1 - 1) * p1 ** (m1 - 1) + (p2 - 1) * p2 ** (m2 - 1) + (p3 - 1) * p3 ** (m3 - 1) + ... | |
Note that a ** b stands for the b'th power of a. | |
P38 (*) Compare the two methods of calculating Euler's totient function. | |
Use the solutions of problems P34 and P37 to compare the algorithms. Take the number of logical inferences as a measure for efficiency. Try to calculate phi(10090) as an example. | |
P39 (*) A list of prime numbers. | |
Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range. | |
P40 (**) Goldbach's conjecture. | |
Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers (much larger than we can go with our Prolog system). Write a predicate to find the two prime numbers that sum up to a given even integer. | |
Example: | |
* (goldbach 28) | |
(5 23) | |
P41 (**) A list of Goldbach compositions. | |
Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition. | |
Example: | |
* (goldbach-list 9 20) | |
10 = 3 + 7 | |
12 = 5 + 7 | |
14 = 3 + 11 | |
16 = 3 + 13 | |
18 = 5 + 13 | |
20 = 3 + 17 | |
In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than say 50. Try to find out how many such cases there are in the range 2..3000. | |
Example (for a print limit of 50): | |
* (goldbach-list 1 2000 50) | |
992 = 73 + 919 | |
1382 = 61 + 1321 | |
1856 = 67 + 1789 | |
1928 = 61 + 1867 | |
Logic and Codes | |
P46 (**) Truth tables for logical expressions. | |
Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2 and equ/2 (for logical equivalence) which succeed or fail according to the result of their respective operations; e.g. and(A,B) will succeed, if and only if both A and B succeed. Note that A and B can be Prolog goals (not only the constants true and fail). | |
A logical expression in two variables can then be written in prefix notation, as in the following example: and(or(A,B),nand(A,B)). | |
Now, write a predicate table/3 which prints the truth table of a given logical expression in two variables. | |
Example: | |
* table(A,B,and(A,or(A,B))). | |
true true true | |
true fail true | |
fail true fail | |
fail fail fail | |
P47 (*) Truth tables for logical expressions (2). | |
Continue problem P46 by defining and/2, or/2, etc as being operators. This allows to write the logical expression in the more natural way, as in the example: A and (A or not B). Define operator precedence as usual; i.e. as in Java. | |
Example: | |
* table(A,B, A and (A or not B)). | |
true true true | |
true fail true | |
fail true fail | |
fail fail fail | |
P48 (**) Truth tables for logical expressions (3). | |
Generalize problem P47 in such a way that the logical expression may contain any number of logical variables. Define table/2 in a way that table(List,Expr) prints the truth table for the expression Expr, which contains the logical variables enumerated in List. | |
Example: | |
* table([A,B,C], A and (B or C) equ A and B or A and C). | |
true true true true | |
true true fail true | |
true fail true true | |
true fail fail true | |
fail true true true | |
fail true fail true | |
fail fail true true | |
fail fail fail true | |
P49 (**) Gray code. | |
An n-bit Gray code is a sequence of n-bit strings constructed according to certain rules. For example, | |
n = 1: C(1) = ['0','1']. | |
n = 2: C(2) = ['00','01','11','10']. | |
n = 3: C(3) = ['000','001','011','010',´110´,´111´,´101´,´100´]. | |
Find out the construction rules and write a predicate with the following specification: | |
% gray(N,C) :- C is the N-bit Gray code | |
Can you apply the method of "result caching" in order to make the predicate more efficient, when it is to be used repeatedly? | |
P50 (***) Huffman code. | |
First of all, consult a good book on discrete mathematics or algorithms for a detailed description of Huffman codes! | |
We suppose a set of symbols with their frequencies, given as a list of fr(S,F) terms. Example: [fr(a,45),fr(b,13),fr(c,12),fr(d,16),fr(e,9),fr(f,5)]. Our objective is to construct a list hc(S,C) terms, where C is the Huffman code word for the symbol S. In our example, the result could be Hs = [hc(a,'0'), hc(b,'101'), hc(c,'100'), hc(d,'111'), hc(e,'1101'), hc(f,'1100')] [hc(a,'01'),...etc.]. The task shall be performed by the predicate huffman/2 defined as follows: | |
% huffman(Fs,Hs) :- Hs is the Huffman code table for the frequency table Fs | |
Binary Trees | |
A binary tree is either empty or it is composed of a root element and two successors, which are binary trees themselves. | |
In Lisp we represent the empty tree by 'nil' and the non-empty tree by the list (X L R), where X denotes the root node and L and R denote the left and right subtree, respectively. The example tree depicted opposite is therefore represented by the following list: | |
(a (b (d nil nil) (e nil nil)) (c nil (f (g nil nil) nil))) | |
Other examples are a binary tree that consists of a root node only: | |
(a nil nil) or an empty binary tree: nil. | |
You can check your predicates using these example trees. They are given as test cases in p54.lisp. | |
P54A (*) Check whether a given term represents a binary tree | |
Write a predicate istree which returns true if and only if its argument is a list representing a binary tree. | |
Example: | |
* (istree (a (b nil nil) nil)) | |
T | |
* (istree (a (b nil nil))) | |
NIL | |
P55 (**) Construct completely balanced binary trees | |
In a completely balanced binary tree, the following property holds for every node: The number of nodes in its left subtree and the number of nodes in its right subtree are almost equal, which means their difference is not greater than one. | |
Write a function cbal-tree to construct completely balanced binary trees for a given number of nodes. The predicate should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree. | |
Example: | |
* cbal-tree(4,T). | |
T = t(x, t(x, nil, nil), t(x, nil, t(x, nil, nil))) ; | |
T = t(x, t(x, nil, nil), t(x, t(x, nil, nil), nil)) ; | |
etc......No | |
P56 (**) Symmetric binary trees | |
Let us call a binary tree symmetric if you can draw a vertical line through the root node and then the right subtree is the mirror image of the left subtree. Write a predicate symmetric/1 to check whether a given binary tree is symmetric. Hint: Write a predicate mirror/2 first to check whether one tree is the mirror image of another. We are only interested in the structure, not in the contents of the nodes. | |
P57 (**) Binary search trees (dictionaries) | |
Use the predicate add/3, developed in chapter 4 of the course, to write a predicate to construct a binary search tree from a list of integer numbers. | |
Example: | |
* construct([3,2,5,7,1],T). | |
T = t(3, t(2, t(1, nil, nil), nil), t(5, nil, t(7, nil, nil))) | |
Then use this predicate to test the solution of the problem P56. | |
Example: | |
* test-symmetric([5,3,18,1,4,12,21]). | |
Yes | |
* test-symmetric([3,2,5,7,1]). | |
No | |
P58 (**) Generate-and-test paradigm | |
Apply the generate-and-test paradigm to construct all symmetric, completely balanced binary trees with a given number of nodes. Example: | |
* sym-cbal-trees(5,Ts). | |
Ts = [t(x, t(x, nil, t(x, nil, nil)), t(x, t(x, nil, nil), nil)), t(x, t(x, t(x, nil, nil), nil), t(x, nil, t(x, nil, nil)))] | |
How many such trees are there with 57 nodes? Investigate about how many solutions there are for a given number of nodes? What if the number is even? Write an appropriate predicate. | |
P59 (**) Construct height-balanced binary trees | |
In a height-balanced binary tree, the following property holds for every node: The height of its left subtree and the height of its right subtree are almost equal, which means their difference is not greater than one. | |
Write a predicate hbal-tree/2 to construct height-balanced binary trees for a given height. The predicate should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree. | |
Example: | |
* hbal-tree(3,T). | |
T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), t(x, nil, nil))) ; | |
T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), nil)) ; | |
etc......No | |
P60 (**) Construct height-balanced binary trees with a given number of nodes | |
Consider a height-balanced binary tree of height H. What is the maximum number of nodes it can contain? | |
Clearly, MaxN = 2**H - 1. However, what is the minimum number MinN? This question is more difficult. Try to find a recursive statement and turn it into a predicate minNodes/2 defined as follwos: | |
% minNodes(H,N) :- N is the minimum number of nodes in a height-balanced binary tree of height H. | |
(integer,integer), (+,?) | |
On the other hand, we might ask: what is the maximum height H a height-balanced binary tree with N nodes can have? | |
% maxHeight(N,H) :- H is the maximum height of a height-balanced binary tree with N nodes | |
(integer,integer), (+,?) | |
Now, we can attack the main problem: construct all the height-balanced binary trees with a given nuber of nodes. | |
% hbal-tree-nodes(N,T) :- T is a height-balanced binary tree with N nodes. | |
Find out how many height-balanced trees exist for N = 15. | |
P61 (*) Count the leaves of a binary tree | |
A leaf is a node with no successors. Write a predicate count-leaves/2 to count them. | |
% count-leaves(T,N) :- the binary tree T has N leaves | |
P61A (*) Collect the leaves of a binary tree in a list | |
A leaf is a node with no successors. Write a predicate leaves/2 to collect them in a list. | |
% leaves(T,S) :- S is the list of all leaves of the binary tree T | |
P62 (*) Collect the internal nodes of a binary tree in a list | |
An internal node of a binary tree has either one or two non-empty successors. Write a predicate internals/2 to collect them in a list. | |
% internals(T,S) :- S is the list of internal nodes of the binary tree T. | |
P62B (*) Collect the nodes at a given level in a list | |
A node of a binary tree is at level N if the path from the root to the node has length N-1. The root node is at level 1. Write a predicate atlevel/3 to collect all nodes at a given level in a list. | |
% atlevel(T,L,S) :- S is the list of nodes of the binary tree T at level L | |
Using atlevel/3 it is easy to construct a predicate levelorder/2 which creates the level-order sequence of the nodes. However, there are more efficient ways to do that. | |
P63 (**) Construct a complete binary tree | |
A complete binary tree with height H is defined as follows: The levels 1,2,3,...,H-1 contain the maximum number of nodes (i.e 2**(i-1) at the level i, note that we start counting the levels from 1 at the root). In level H, which may contain less than the maximum possible number of nodes, all the nodes are "left-adjusted". This means that in a levelorder tree traversal all internal nodes come first, the leaves come second, and empty successors (the nil's which are not really nodes!) come last. | |
Particularly, complete binary trees are used as data structures (or addressing schemes) for heaps. | |
We can assign an address number to each node in a complete binary tree by enumerating the nodes in levelorder, starting at the root with number 1. In doing so, we realize that for every node X with address A the following property holds: The address of X's left and right successors are 2*A and 2*A+1, respectively, supposed the successors do exist. This fact can be used to elegantly construct a complete binary tree structure. Write a predicate complete-binary-tree/2 with the following specification: | |
% complete-binary-tree(N,T) :- T is a complete binary tree with N nodes. (+,?) | |
Test your predicate in an appropriate way. | |
P64 (**) Layout a binary tree (1) | |
Given a binary tree as the usual Prolog term t(X,L,R) (or nil). As a preparation for drawing the tree, a layout algorithm is required to determine the position of each node in a rectangular grid. Several layout methods are conceivable, one of them is shown in the illustration below. | |
In this layout strategy, the position of a node v is obtained by the following two rules: | |
x(v) is equal to the position of the node v in the inorder sequence | |
y(v) is equal to the depth of the node v in the tree | |
In order to store the position of the nodes, we extend the Prolog term representing a node (and its successors) as follows: | |
% nil represents the empty tree (as usual) | |
% t(W,X,Y,L,R) represents a (non-empty) binary tree with root W "positioned" at (X,Y), and subtrees L and R | |
Write a predicate layout-binary-tree/2 with the following specification: | |
% layout-binary-tree(T,PT) :- PT is the "positioned" binary tree obtained from the binary tree T. (+,?) | |
Test your predicate in an appropriate way. | |
P65 (**) Layout a binary tree (2) | |
An alternative layout method is depicted in the illustration opposite. Find out the rules and write the corresponding Prolog predicate. Hint: On a given level, the horizontal distance between neighboring nodes is constant. | |
Use the same conventions as in problem P64 and test your predicate in an appropriate way. | |
P66 (***) Layout a binary tree (3) | |
Yet another layout strategy is shown in the illustration opposite. The method yields a very compact layout while maintaining a certain symmetry in every node. Find out the rules and write the corresponding Prolog predicate. Hint: Consider the horizontal distance between a node and its successor nodes. How tight can you pack together two subtrees to construct the combined binary tree? | |
Use the same conventions as in problem P64 and P65 and test your predicate in an appropriate way. Note: This is a difficult problem. Don't give up too early! | |
Which layout do you like most? | |
P67 (**) A string representation of binary trees | |
Somebody represents binary trees as strings of the following type (see example opposite): | |
a(b(d,e),c(,f(g,))) | |
a) Write a Prolog predicate which generates this string representation, if the tree is given as usual (as nil or t(X,L,R) term). Then write a predicate which does this inverse; i.e. given the string representation, construct the tree in the usual form. Finally, combine the two predicates in a single predicate tree-string/2 which can be used in both directions. | |
b) Write the same predicate tree-string/2 using difference lists and a single predicate tree-dlist/2 which does the conversion between a tree and a difference list in both directions. | |
For simplicity, suppose the information in the nodes is a single letter and there are no spaces in the string. | |
P68 (**) Preorder and inorder sequences of binary trees | |
We consider binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. | |
a) Write predicates preorder/2 and inorder/2 that construct the preorder and inorder sequence of a given binary tree, respectively. The results should be atoms, e.g. 'abdecfg' for the preorder sequence of the example in problem P67. | |
b) Can you use preorder/2 from problem part a) in the reverse direction; i.e. given a preorder sequence, construct a corresponding tree? If not, make the necessary arrangements. | |
c) If both the preorder sequence and the inorder sequence of the nodes of a binary tree are given, then the tree is determined unambiguously. Write a predicate pre-in-tree/3 that does the job. | |
d) Solve problems a) to c) using difference lists. Cool! Use the predefined predicate time/1 to compare the solutions. | |
What happens if the same character appears in more than one node. Try for instance pre-in-tree(aba,baa,T). | |
P69 (**) Dotstring representation of binary trees | |
We consider again binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. Such a tree can be represented by the preorder sequence of its nodes in which dots (.) are inserted where an empty subtree (nil) is encountered during the tree traversal. For example, the tree shown in problem P67 is represented as 'abd..e..c.fg...'. First, try to establish a syntax (BNF or syntax diagrams) and then write a predicate tree-dotstring/2 which does the conversion in both directions. Use difference lists. | |
Multiway Trees | |
A multiway tree is composed of a root element and a (possibly empty) set of successors which are multiway trees themselves. A multiway tree is never empty. The set of successor trees is sometimes called a forest. | |
In Prolog we represent a multiway tree by a term t(X,F), where X denotes the root node and F denotes the forest of successor trees (a Prolog list). The example tree depicted opposite is therefore represented by the following Prolog term: | |
T = t(a,[t(f,[t(g,[])]),t(c,[]),t(b,[t(d,[]),t(e,[])])]) | |
P70B (*) Check whether a given term represents a multiway tree | |
Write a predicate istree/1 which succeeds if and only if its argument is a Prolog term representing a multiway tree. | |
Example: | |
* istree(t(a,[t(f,[t(g,[])]),t(c,[]),t(b,[t(d,[]),t(e,[])])])). | |
Yes | |
P70C (*) Count the nodes of a multiway tree | |
Write a predicate nnodes/1 which counts the nodes of a given multiway tree. | |
Example: | |
* nnodes(t(a,[t(f,[])]),N). | |
N = 2 | |
Write another version of the predicate that allows for a flow pattern (o,i). | |
P70 (**) Tree construction from a node string | |
We suppose that the nodes of a multiway tree contain single characters. In the depth-first order sequence of its nodes, a special character ^ has been inserted whenever, during the tree traversal, the move is a backtrack to the previous level. | |
By this rule, the tree in the figure opposite is represented as: afg^^c^bd^e^^^ | |
Define the syntax of the string and write a predicate tree(String,Tree) to construct the Tree when the String is given. Work with atoms (instead of strings). Make your predicate work in both directions. | |
P71 (*) Determine the internal path length of a tree | |
We define the internal path length of a multiway tree as the total sum of the path lengths from the root to all nodes of the tree. By this definition, the tree in the figure of problem P70 has an internal path length of 9. Write a predicate ipl(Tree,IPL) for the flow pattern (+,-). | |
P72 (*) Construct the bottom-up order sequence of the tree nodes | |
Write a predicate bottom-up(Tree,Seq) which constructs the bottom-up sequence of the nodes of the multiway tree Tree. Seq should be a Prolog list. What happens if you run your predicate backwords? | |
P73 (**) Lisp-like tree representation | |
There is a particular notation for multiway trees in Lisp. Lisp is a prominent functional programming language, which is used primarily for artificial intelligence problems. As such it is one of the main competitors of Prolog. In Lisp almost everything is a list, just as in Prolog everything is a term. | |
The following pictures show how multiway tree structures are represented in Lisp. | |
Note that in the "lispy" notation a node with successors (children) in the tree is always the first element in a list, followed by its children. The "lispy" representation of a multiway tree is a sequence of atoms and parentheses '(' and ')', which we shall collectively call "tokens". We can represent this sequence of tokens as a Prolog list; e.g. the lispy expression (a (b c)) could be represented as the Prolog list ['(', a, '(', b, c, ')', ')']. Write a predicate tree-ltl(T,LTL) which constructs the "lispy token list" LTL if the tree is given as term T in the usual Prolog notation. | |
Example: | |
* tree-ltl(t(a,[t(b,[]),t(c,[])]),LTL). | |
LTL = ['(', a, '(', b, c, ')', ')'] | |
As a second, even more interesting exercise try to rewrite tree-ltl/2 in a way that the inverse conversion is also possible: Given the list LTL, construct the Prolog tree T. Use difference lists. | |
Graphs | |
A graph is defined as a set of nodes and a set of edges, where each edge is a pair of nodes. | |
There are several ways to represent graphs in Prolog. One method is to represent each edge separately as one clause (fact). In this form, the graph depicted below is represented as the following predicate: | |
edge(h,g). | |
edge(k,f). | |
edge(f,b). | |
... | |
We call this edge-clause form. Obviously, isolated nodes cannot be represented. Another method is to represent the whole graph as one data object. According to the definition of the graph as a pair of two sets (nodes and edges), we may use the following Prolog term to represent the example graph: | |
graph([b,c,d,f,g,h,k],[e(b,c),e(b,f),e(c,f),e(f,k),e(g,h)]) | |
We call this graph-term form. Note, that the lists are kept sorted, they are really sets, without duplicated elements. Each edge appears only once in the edge list; i.e. an edge from a node x to another node y is represented as e(x,y), the term e(y,x) is not present. The graph-term form is our default representation. In SWI-Prolog there are predefined predicates to work with sets. | |
A third representation method is to associate with each node the set of nodes that are adjacent to that node. We call this the adjacency-list form. In our example: | |
[n(b,[c,f]), n(c,[b,f]), n(d,[]), n(f,[b,c,k]), ...] | |
The representations we introduced so far are Prolog terms and therefore well suited for automated processing, but their syntax is not very user-friendly. Typing the terms by hand is cumbersome and error-prone. We can define a more compact and "human-friendly" notation as follows: A graph is represented by a list of atoms and terms of the type X-Y (i.e. functor '-' and arity 2). The atoms stand for isolated nodes, the X-Y terms describe edges. If an X appears as an endpoint of an edge, it is automatically defined as a node. Our example could be written as: | |
[b-c, f-c, g-h, d, f-b, k-f, h-g] | |
We call this the human-friendly form. As the example shows, the list does not have to be sorted and may even contain the same edge multiple times. Notice the isolated node d. (Actually, isolated nodes do not even have to be atoms in the Prolog sense, they can be compound terms, as in d(3.75,blue) instead of d in the example). | |
When the edges are directed we call them arcs. These are represented by ordered pairs. Such a graph is called directed graph. To represent a directed graph, the forms discussed above are slightly modified. The example graph opposite is represented as follows: | |
Arc-clause form | |
arc(s,u). | |
arc(u,r). | |
... | |
Graph-term form | |
digraph([r,s,t,u,v],[a(s,r),a(s,u),a(u,r),a(u,s),a(v,u)]) | |
Adjacency-list form | |
[n(r,[]),n(s,[r,u]),n(t,[]),n(u,[r]),n(v,[u])] | |
Note that the adjacency-list does not have the information on whether it is a graph or a digraph. | |
Human-friendly form | |
[s > r, t, u > r, s > u, u > s, v > u] | |
Finally, graphs and digraphs may have additional information attached to nodes and edges (arcs). For the nodes, this is no problem, as we can easily replace the single character identifiers with arbitrary compound terms, such as city('London',4711). On the other hand, for edges we have to extend our notation. Graphs with additional information attached to edges are called labelled graphs. | |
Arc-clause form | |
arc(m,q,7). | |
arc(p,q,9). | |
arc(p,m,5). | |
Graph-term form | |
digraph([k,m,p,q],[a(m,p,7),a(p,m,5),a(p,q,9)]) | |
Adjacency-list form | |
[n(k,[]),n(m,[q/7]),n(p,[m/5,q/9]),n(q,[])] | |
Notice how the edge information has been packed into a term with functor '/' and arity 2, together with the corresponding node. | |
Human-friendly form | |
[p>q/9, m>q/7, k, p>m/5] | |
The notation for labelled graphs can also be used for so-called multi-graphs, where more than one edge (or arc) are allowed between two given nodes. | |
P80 (***) Conversions | |
Write predicates to convert between the different graph representations. With these predicates, all representations are equivalent; i.e. for the following problems you can always pick freely the most convenient form. The reason this problem is rated (***) is not because it's particularly difficult, but because it's a lot of work to deal with all the special cases. | |
P81 (**) Path from one node to another one | |
Write a predicate path(G,A,B,P) to find an acyclic path P from node A to node b in the graph G. The predicate should return all paths via backtracking. | |
P82 (*) Cycle from a given node | |
Write a predicate cycle(G,A,P) to find a closed path (cycle) P starting at a given node A in the graph G. The predicate should return all cycles via backtracking. | |
P83 (**) Construct all spanning trees | |
Write a predicate s-tree(Graph,Tree) to construct (by backtracking) all spanning trees of a given graph. With this predicate, find out how many spanning trees there are for the graph depicted to the left. The data of this example graph can be found in the file p83.dat. When you have a correct solution for the s-tree/2 predicate, use it to define two other useful predicates: is-tree(Graph) and is-connected(Graph). Both are five-minutes tasks! | |
P84 (**) Construct the minimal spanning tree | |
Write a predicate ms-tree(Graph,Tree,Sum) to construct the minimal spanning tree of a given labelled graph. Hint: Use the algorithm of Prim. A small modification of the solution of P83 does the trick. The data of the example graph to the right can be found in the file p84.dat. | |
P85 (**) Graph isomorphism | |
Two graphs G1(N1,E1) and G2(N2,E2) are isomorphic if there is a bijection f: N1 -> N2 such that for any nodes X,Y of N1, X and Y are adjacent if and only if f(X) and f(Y) are adjacent. | |
Write a predicate that determines whether two graphs are isomorphic. Hint: Use an open-ended list to represent the function f. | |
P86 (**) Node degree and graph coloration | |
a) Write a predicate degree(Graph,Node,Deg) that determines the degree of a given node. | |
b) Write a predicate that generates a list of all nodes of a graph sorted according to decreasing degree. | |
c) Use Welch-Powell's algorithm to paint the nodes of a graph in such a way that adjacent nodes have different colors. | |
P87 (**) Depth-first order graph traversal (alternative solution) | |
Write a predicate that generates a depth-first order graph traversal sequence. The starting point should be specified, and the output should be a list of nodes that are reachable from this starting point (in depth-first order). | |
P88 (**) Connected components (alternative solution) | |
Write a predicate that splits a graph into its connected components. | |
P89 (**) Bipartite graphs | |
Write a predicate that finds out whether a given graph is bipartite. | |
Miscellaneous Problems | |
P90 (**) Eight queens problem | |
This is a classical problem in computer science. The objective is to place eight queens on a chessboard so that no two queens are attacking each other; i.e., no two queens are in the same row, the same column, or on the same diagonal. | |
Hint: Represent the positions of the queens as a list of numbers 1..N. Example: [4,2,7,3,6,8,5,1] means that the queen in the first column is in row 4, the queen in the second column is in row 2, etc. Use the generate-and-test paradigm. | |
P91 (**) Knight's tour | |
Another famous problem is this one: How can a knight jump on an NxN chessboard in such a way that it visits every square exactly once? | |
Hints: Represent the squares by pairs of their coordinates of the form X/Y, where both X and Y are integers between 1 and N. (Note that '/' is just a convenient functor, not division!) Define the relation jump(N,X/Y,U/V) to express the fact that a knight can jump from X/Y to U/V on a NxN chessboard. And finally, represent the solution of our problem as a list of N*N knight positions (the knight's tour). | |
P92 (***) Von Koch's conjecture | |
Several years ago I met a mathematician who was intrigued by a problem for which he didn't know a solution. His name was Von Koch, and I don't know whether the problem has been solved since. | |
Anyway the puzzle goes like this: Given a tree with N nodes (and hence N-1 edges). Find a way to enumerate the nodes from 1 to N and, accordingly, the edges from 1 to N-1 in such a way, that for each edge K the difference of its node numbers equals to K. The conjecture is that this is always possible. | |
For small trees the problem is easy to solve by hand. However, for larger trees, and 14 is already very large, it is extremely difficult to find a solution. And remember, we don't know for sure whether there is always a solution! | |
Write a predicate that calculates a numbering scheme for a given tree. What is the solution for the larger tree pictured above? | |
P93 (***) An arithmetic puzzle | |
Given a list of integer numbers, find a correct way of inserting arithmetic signs (operators) such that the result is a correct equation. Example: With the list of numbers [2,3,5,7,11] we can form the equations 2-3+5+7 = 11 or 2 = (3*5+7)/11 (and ten others!). | |
P94 (***) Generate K-regular simple graphs with N nodes | |
In a K-regular graph all nodes have a degree of K; i.e. the number of edges incident in each node is K. How many (non-isomorphic!) 3-regular graphs with 6 nodes are there? See also a table of results and a Java applet that can represent graphs geometrically. | |
P95 (**) English number words | |
On financial documents, like cheques, numbers must sometimes be written in full words. Example: 175 must be written as one-seven-five. Write a predicate full-words/1 to print (non-negative) integer numbers in full words. | |
P96 (**) Syntax checker (alternative solution with difference lists) | |
In a certain programming language (Ada) identifiers are defined by the syntax diagram (railroad chart) opposite. Transform the syntax diagram into a system of syntax diagrams which do not contain loops; i.e. which are purely recursive. Using these modified diagrams, write a predicate identifier/1 that can check whether or not a given string is a legal identifier. | |
% identifier(Str) :- Str is a legal identifier | |
P97 (**) Sudoku | |
Sudoku puzzles go like this: | |
Problem statement Solution | |
. . 4 | 8 . . | . 1 7 9 3 4 | 8 2 5 | 6 1 7 | |
| | | | | |
6 7 . | 9 . . | . . . 6 7 2 | 9 1 4 | 8 5 3 | |
| | | | | |
5 . 8 | . 3 . | . . 4 5 1 8 | 6 3 7 | 9 2 4 | |
--------+---------+-------- --------+---------+-------- | |
3 . . | 7 4 . | 1 . . 3 2 5 | 7 4 8 | 1 6 9 | |
| | | | | |
. 6 9 | . . . | 7 8 . 4 6 9 | 1 5 3 | 7 8 2 | |
| | | | | |
. . 1 | . 6 9 | . . 5 7 8 1 | 2 6 9 | 4 3 5 | |
--------+---------+-------- --------+---------+-------- | |
1 . . | . 8 . | 3 . 6 1 9 7 | 5 8 2 | 3 4 6 | |
| | | | | |
. . . | . . 6 | . 9 1 8 5 3 | 4 7 6 | 2 9 1 | |
| | | | | |
2 4 . | . . 1 | 5 . . 2 4 6 | 3 9 1 | 5 7 8 | |
Every spot in the puzzle belongs to a (horizontal) row and a (vertical) column, as well as to one single 3x3 square (which we call "square" for short). At the beginning, some of the spots carry a single-digit number between 1 and 9. The problem is to fill the missing spots with digits in such a way that every number between 1 and 9 appears exactly once in each row, in each column, and in each square. | |
P98 (***) Nonograms | |
Around 1994, a certain kind of puzzles was very popular in England. The "Sunday Telegraph" newspaper wrote: "Nonograms are puzzles from Japan and are currently published each week only in The Sunday Telegraph. Simply use your logic and skill to complete the grid and reveal a picture or diagram." As a Prolog programmer, you are in a better situation: you can have your computer do the work! Just write a little program ;-). | |
The puzzle goes like this: Essentially, each row and column of a rectangular bitmap is annotated with the respective lengths of its distinct strings of occupied cells. The person who solves the puzzle must complete the bitmap given only these lengths. | |
Problem statement: Solution: | |
|_|_|_|_|_|_|_|_| 3 |_|X|X|X|_|_|_|_| 3 | |
|_|_|_|_|_|_|_|_| 2 1 |X|X|_|X|_|_|_|_| 2 1 | |
|_|_|_|_|_|_|_|_| 3 2 |_|X|X|X|_|_|X|X| 3 2 | |
|_|_|_|_|_|_|_|_| 2 2 |_|_|X|X|_|_|X|X| 2 2 | |
|_|_|_|_|_|_|_|_| 6 |_|_|X|X|X|X|X|X| 6 | |
|_|_|_|_|_|_|_|_| 1 5 |X|_|X|X|X|X|X|_| 1 5 | |
|_|_|_|_|_|_|_|_| 6 |X|X|X|X|X|X|_|_| 6 | |
|_|_|_|_|_|_|_|_| 1 |_|_|_|_|X|_|_|_| 1 | |
|_|_|_|_|_|_|_|_| 2 |_|_|_|X|X|_|_|_| 2 | |
1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 | |
2 1 5 1 2 1 5 1 | |
For the example above, the problem can be stated as the two lists [[3],[2,1],[3,2],[2,2],[6],[1,5],[6],[1],[2]] and [[1,2],[3,1],[1,5],[7,1],[5],[3],[4],[3]] which give the "solid" lengths of the rows and columns, top-to-bottom and left-to-right, respectively. Published puzzles are larger than this example, e.g. 25 x 20, and apparently always have unique solutions. | |
P99 (***) Crossword puzzle | |
Given an empty (or almost empty) framework of a crossword puzzle and a set of words. The problem is to place the words into the framework. | |
The particular crossword puzzle is specified in a text file which first lists the words (one word per line) in an arbitrary order. Then, after an empty line, the crossword framework is defined. In this framework specification, an empty character location is represented by a dot (.). In order to make the solution easier, character locations can also contain predefined character values. The puzzle opposite is defined in the file p99a.dat, other examples are p99b.dat and p99d.dat. There is also an example of a puzzle (p99c.dat) which does not have a solution. | |
Words are strings (character lists) of at least two characters. A horizontal or vertical sequence of character places in the crossword puzzle framework is called a site. Our problem is to find a compatible way of placing words onto sites. | |
Hints: (1) The problem is not easy. You will need some time to thoroughly understand it. So, don't give up too early! And remember that the objective is a clean solution, not just a quick-and-dirty hack! | |
(2) Reading the data file is a tricky problem for which a solution is provided in the file p99-readfile.lisp. Use the predicate read_lines/2. | |
(3) For efficiency reasons it is important, at least for larger puzzles, to sort the words and the sites in a particular order. For this part of the problem, the solution of P28 may be very helpful. | |
Last modified: Mon Oct 16 21:23:19 BRT 2006 | |
Programming Practice Problems | |
Easy Problems Moderate Problems | |
Easy Problems | |
+-------------------------+ | |
¦ 34 ¦ 21 ¦ 32 ¦ 41 ¦ 25 ¦ | |
+----+----+----+----+-----¦ | |
¦ 14 ¦ 42 ¦ 43 ¦ 14 ¦ 31 ¦ | |
+----+----+----+----+-----¦ | |
¦ 54 ¦ 45 ¦ 52 ¦ 42 ¦ 23 ¦ | |
+----+----+----+----+-----¦ | |
¦ 33 ¦ 15 ¦ 51 ¦ 31 ¦ 35 ¦ | |
+----+----+----+----+-----¦ | |
¦ 21 ¦ 52 ¦ 33 ¦ 13 ¦ 23 ¦ | |
+-------------------------+ | |
1. Do you like treasure hunts? In this problem you are to write a program to explore the above array for a treasure. The values in the array are clues. Each cell contains an integer between 11 and 55; for each value the ten's digit represents the row number and the unit's digit represents the column number of the cell containing the next clue. Starting in the upper left corner (at 1,1), use the clues to guide your search of the array. (The first three clues are 11, 34, 42). The treasure is a cell whose value is the same as its coordinates. Your program must first read in the treasure map data into a 5 by 5 array. Your program should output the cells it visits during its search, and a message indicating where you found the treasure. | |
2. Write a program to search for the "saddle points" in a 5 by 5 array of integers. A saddle point is a cell whose value is greater than or equal to any in its row, and less than or equal to any in its column. There may be more than one saddle point in the array. Print out the coordinates of any saddle points your program finds. Print out "No saddle points" if there are none. | |
3. In the game of chess, a queen can attack pieces which are on the same row, column, or diagonal. A chessboard can be represented by an 8 by 8 array. A 1 in the array represents a queen on the corresponding square, and a O in the array represents an unoccupied square. Your program is to read the location of two queens and then update the array appropriately. Then process the board and indicate whether or not the two queens are positioned so that they attack each other. | |
4. One classic method for composing secret messages is called a square code. The spaces are removed from the english text | |
and the characters are written into a square (or rectangle). For example, the sentence "If man was meant to stay on the | |
ground god would have given us roots" is 54 characters long, so it is written into a rectangle with 7 rows and 8 columns. | |
ifmanwas | |
meanttos | |
tayonthe | |
groundgo | |
dwouldha | |
vegivenu | |
sroots | |
The coded message is obtained by reading down the columns going left to right. For example, the message above is coded as: | |
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau | |
In your program, have the user enter a message in english with no spaces between the words. Have the maximum message length be 81 | |
characters. Display the encoded message. (Watch out that no "garbage" characters are printed.) Here are some more examples: | |
Input Output | |
haveaniceday hae and via ecy | |
feedthedog fto ehg ee dd | |
chillout clu hlt io | |
5. The results from the mayor's race have been reported by each precinct as follows: | |
Candidate Candidate Candidate Candidate | |
Precinct A B C D | |
1 192 48 206 37 | |
2 147 90 312 21 | |
3 186 12 121 38 | |
4 114 21 408 39 | |
5 267 13 382 29 | |
Write a program to do the following: | |
a. Read the raw vote totals from a data file that contains one row for each precinct. | |
b. Display the table with appropriate headings for the rows and columns. | |
c. Compute and display the total number of votes received by each candidate and | |
the percent of the total votes cast. | |
d. If any one candidate received over 50% of the votes, the program should print | |
a message declaring that candidate the winner. | |
e. If no candidate received 50% of the votes, the program should print a message | |
declaring a run-off between the two candidates receiving the highest number of | |
votes; the two candidates should be identified by their letter names. | |
f. For testing, run the program with the above data, and also with another | |
data file where Candidate C receives only 108 votes in precinct 4. | |
Moderate Problems | |
Write a program to find all the sentences, or consecutive sequence of sentences, in a text file where: min <= length <= max. | |
Assume that a sentence ends in a period, question mark, or exclamation point. | |
In the special case of quoted sentences (that begin with quotes or an apostrophe), include the terminating quote mark or apostrophe. | |
Count all blanks and punctuation, but assume only one blank between sentences. | |
(All EOL characters should be converted to blanks). | |
Precondition: Min and Max will be positive integers less than 1000, and Min <= Max. | |
The name of the text file is to be provided as a command line argument (not read from Standard Input). | |
For example, given this text: | |
Black is white. Day is night. Understanding is ignorance. | |
Truth is fiction. Safety is danger. | |
If min = max = 16 then the output is | |
"Black is white." | |
If min = max = 18 then the output is | |
"Truth is fiction." | |
"Safety is danger." | |
If min = 30 and max = 37 then the output is | |
"Truth is fiction. Safety is danger." | |
because the two sentences are consecutive sentences with the desired length. | |
Here is a sample text file for Alice in Wonderland. | |
1. Write a program to convert roman numerals into their arabic equivalent. | |
INPUT REQUIREMENTS | |
Read one or more roman numerals from standard input. Process one line at a time. Each input line contains only one roman numeral, starting in column one. Assume the characters are all upper case with no embedded blanks. | |
OUTPUT REQUIREMENTS | |
The arabic equivalent of each input roman numeral is displayed on standard output, starting in column one. | |
FUNCTIONAL REQUIREMENTS | |
Here are the arabic equivalents for roman symbols: | |
The "basic" roman symbols The "auxiliary" roman symbols | |
I X C M V L D | |
1 10 100 1000 5 50 500 | |
Convert the roman numeral to arabic processing the symbols from left to right according to the following rules: | |
1. A symbol following one of greater or equal value adds to its value. (E.g., XII = 12) | |
2. A symbol preceding one of greater value subtracts its value.(E.g., IV = 4; XL = 40) | |
ERROR HANDLING REQUIREMENTS | |
In each of the error conditions below, display the given message and skip the numeral and continue processing the next line. | |
"Invalid character in input. Valid characters are I,V,X,L,C,D,M." | |
Only the listed characters are valid. | |
"Invalid numeral: can't subtract auxiliary symbol." | |
It is not permitted to subtract an "auxiliary" symbol. (CML, not LM = 950; XLV not VL, = 45). | |
"Invalid numeral: two consecutive subtractions." | |
Can't do two subtractions in a row, thus LIVX is illegal. | |
"Invalid numeral: additions don't decrease." | |
Additions must decrease, as you go from left to right. Thus, each symbol added must have a value equal or less than the last symbol which was added. Thus, LIIX is wrong, cause we added L, added I, subtracted I, then try to add X. | |
Phone "words" | |
Each number on the telephone dial (except 0 and 1) corresponds to three alphabetic characters. Those correspondences are: | |
2 ABC | |
3 DEF | |
4 GHI | |
5 JKL | |
6 MNO | |
7 PRS | |
8 TUV | |
9 WXY | |
Given a seven digit telephone number, print all 2187 possible "words" that number spells. (They may not be real english words, but just some sequence of characters). Since the digits 0 and 1 have no alphabetic equivalent, an input number which contains those digits should be rejected. The input will be one or more seven digit integers from standard input. | |
The problem can be made a bit more challenging by outputting more than one word per line. Usually about seven words will fit on a line. | |
Frequency of letter pairs | |
Write a program to count the occurrences of all letter pairs in a sample of text (like the first paragraph of the Constitution). Disregard differences between lower and upper case letters. (Blanks are not considered as letters). Output the 100 most frequent letter pairs, in order by percent of total. Also show which percent of total pairs is accounted for by this list of 100. Your program should correctly process situations where the input file is empty or where less than 100 pairs occur. | |
Sample output | |
th 2.37% in 2.20% fj 2.00% ... (6 per line) | |
... | |
(100 letter pairs) | |
Output represents 73.44% of 23641 letter pairs. | |
Computing "subword" combinations. | |
Accept any number of lines of input entered from standard input. A valid line contains a word and a number. The word comes first, and is up to twenty alphabetic characters (A-Z) in upper or lower case. The word may be preceeded and followed by any number of blanks. The number is a decimal integer greater than zero, and may be followed by any number of blanks or a return. Input is terminated by EOF character. For each input word, print all possible "subwords" that have as many characters as specified by the number. A "subword" is a n-letter word comprised of only characters that are found in the given word. If you are familiar with the game Scrabble, it's as though the input word is your pool of letters, and you want to find all possible arrangements of n letters from your pool. .nf For example, CAT 2 would produce CA CT AC AT TA TC and DOG 1 would produce D O G and BIRD 3 would produce BIR BID IRD RID DIR RIB ... Note, that we are producing combinations WITHOUT replacement, so in the BIRD 3 example, BBB and RRR are NOT possible subwords. The output should echo the input line to standard output, followed by the list of subwords, one word per line, left justified. Each set of output words should be followed by one blank line. The program should respond to invalid input by echoing the input line to the output, and then issuing a one line message indicating the nature of the error: | |
"Illegal character in word" | |
"Illegal character in number" | |
"Number greater than length of word" | |
"Word longer than 20 characters" | |
After issuing the message, processing should resume with the next input line. When all input has been processed, issue a message indicating the number of input words that were processed (including word with errors) e.g., "End of input encountered, 4 words processed." | |
Calculating bowling match scores | |
A bowling match consists of ten frames. Each frame except for the tenth consists of one or two balls, or attempts to knock down the ten pins at the end of the alley. Doing so on the first ball of the frame is called a strike, and the second ball of the frame is not rolled. Knocking down all ten pins with both balls (having left some up with the first ball) is called a spare. If both attempts to knock down the pins leave some standing, the frame is called an open frame. A spare in the tenth frame gives the bowler one extra ball; a strike in the tenth gives him or her two extra balls. A bowling score is computed as follows. A strike counts as 10 points plus the sum of the next two balls. A spare counts as 10 points plus the next ball. Any other balls merely count as themselves, as do any bonus balls rolled as a result of a strike or a spare in the tenth frame. Suppose for example that the sequence of balls was | |
9 1 0 10 10 10 6 2 7 3 8 2 10 9 0 9 1 10 | |
The score for the ten frames would be | |
Frame score | |
----- ----- | |
1 10 | |
2 30 | |
3 56 | |
4 74 | |
5 82 | |
6 100 | |
7 120 | |
8 139 | |
9 148 | |
10 168 | |
Write a program to accept from standard input the scores for a sequence of balls and output the scores for the ten frames. There may be multiple lines of input, where each input line will be the scores for one player. The scores will be separated by one or more blanks. You may assume that the number of scores on the line is valid. | |
Lotto Guesser | |
Cobbletown has a lottery (a small version of California's Lotto) in which players guess four number between 1 and 9. Larry likes to play and thinks he has a scheme to pick winning numbers. He keeps a history of past winning numbers in a text data file. Larry thinks that if a number hasn't occurred recently then it is more likely to show up as a winner. (Obviously Larry isn't familiar with the statistical fact that each number has an equal likelihood of being picked, since each week's drawing is an independent event). Larry wants us to write a program to assist him in his wacky scheme. | |
INPUT REQUIREMENTS | |
The lotto history data: a file of unknown length, with four integers per line. Each integer is in the range 1 to 9. | |
OUTPUT REQUIREMENTS | |
1. The four least frequently occurring integers in the history data. (That is, counting all the weeks, the four numbers that appeared fewer times than any others). | |
2. The one integer with longest time since last occurrence. (That is, if you count backward from now, the number for which you count the most weeks since it occurred). | |
FUNCTIONAL REQUIREMENTS | |
(You may assume that no data validity checking is required). | |
1. Determine and display the four integers which occur least often in the history data. | |
Note: To make the problem easier, if there is a tie between two or more numbers for fourth place, it doesn't matter which one is printed. | |
2. Determine and display the integer which has gone the longest without appearing in a winning sequence. | |
At a minimum your program must work correctly for the following sample data. | |
Test Data | |
1 2 3 4 | |
5 6 7 8 | |
8 7 6 5 | |
1 5 6 7 | |
4 3 2 1 | |
Castles and Creatures | |
Write a program to play a simple "adventure"-style interactive game. The adventure world consists of up to five castles each of which has up to seven rooms (35 total). Each room has a treasure, worth a certain number of points, and a creature guarding the treasure. The treasure can be captured by bluffing or fighting the creature. Bluffing always has a 30% chance of succeeding. The odds for winning a fight vary from creature to creature. The object of the game is to visit different rooms and gain as many treasure points as possible. The player begins with 9 lives and each fight lost costs a life. (There's no penalty for losing a bluff.) When all the lives (or all treasures) are gone the game ends. The adventure world information (like castle and room names) is stored in a text file. The program must read the text file and create a data structure to represent the world. (HINT: Use a record structure for each room.) The program must handle interaction with the player, including display of menus for castle and room choices, display of current lives and treasure points accumulated, and responding to one-character commands to fight, bluff, or move around the world. | |
Sudoku Solver | |
Sudoku Solver assignment | |
Last modified on 10/18/2014 09:37:40Last modified on 05/13/2001 12:36:16 | |
Programming Practice Problems | |
Easy Problems Moderate Problems | |
Easy Problems | |
+-------------------------+ | |
¦ 34 ¦ 21 ¦ 32 ¦ 41 ¦ 25 ¦ | |
+----+----+----+----+-----¦ | |
¦ 14 ¦ 42 ¦ 43 ¦ 14 ¦ 31 ¦ | |
+----+----+----+----+-----¦ | |
¦ 54 ¦ 45 ¦ 52 ¦ 42 ¦ 23 ¦ | |
+----+----+----+----+-----¦ | |
¦ 33 ¦ 15 ¦ 51 ¦ 31 ¦ 35 ¦ | |
+----+----+----+----+-----¦ | |
¦ 21 ¦ 52 ¦ 33 ¦ 13 ¦ 23 ¦ | |
+-------------------------+ | |
1. Do you like treasure hunts? In this problem you are to write a program to explore the above array for a treasure. The values in the array are clues. Each cell contains an integer between 11 and 55; for each value the ten's digit represents the row number and the unit's digit represents the column number of the cell containing the next clue. Starting in the upper left corner (at 1,1), use the clues to guide your search of the array. (The first three clues are 11, 34, 42). The treasure is a cell whose value is the same as its coordinates. Your program must first read in the treasure map data into a 5 by 5 array. Your program should output the cells it visits during its search, and a message indicating where you found the treasure. | |
2. Write a program to search for the "saddle points" in a 5 by 5 array of integers. A saddle point is a cell whose value is greater than or equal to any in its row, and less than or equal to any in its column. There may be more than one saddle point in the array. Print out the coordinates of any saddle points your program finds. Print out "No saddle points" if there are none. | |
3. In the game of chess, a queen can attack pieces which are on the same row, column, or diagonal. A chessboard can be represented by an 8 by 8 array. A 1 in the array represents a queen on the corresponding square, and a O in the array represents an unoccupied square. Your program is to read the location of two queens and then update the array appropriately. Then process the board and indicate whether or not the two queens are positioned so that they attack each other. | |
4. One classic method for composing secret messages is called a square code. The spaces are removed from the english text | |
and the characters are written into a square (or rectangle). For example, the sentence "If man was meant to stay on the | |
ground god would have given us roots" is 54 characters long, so it is written into a rectangle with 7 rows and 8 columns. | |
ifmanwas | |
meanttos | |
tayonthe | |
groundgo | |
dwouldha | |
vegivenu | |
sroots | |
The coded message is obtained by reading down the columns going left to right. For example, the message above is coded as: | |
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau | |
In your program, have the user enter a message in english with no spaces between the words. Have the maximum message length be 81 | |
characters. Display the encoded message. (Watch out that no "garbage" characters are printed.) Here are some more examples: | |
Input Output | |
haveaniceday hae and via ecy | |
feedthedog fto ehg ee dd | |
chillout clu hlt io | |
5. The results from the mayor's race have been reported by each precinct as follows: | |
Candidate Candidate Candidate Candidate | |
Precinct A B C D | |
1 192 48 206 37 | |
2 147 90 312 21 | |
3 186 12 121 38 | |
4 114 21 408 39 | |
5 267 13 382 29 | |
Write a program to do the following: | |
a. Read the raw vote totals from a data file that contains one row for each precinct. | |
b. Display the table with appropriate headings for the rows and columns. | |
c. Compute and display the total number of votes received by each candidate and | |
the percent of the total votes cast. | |
d. If any one candidate received over 50% of the votes, the program should print | |
a message declaring that candidate the winner. | |
e. If no candidate received 50% of the votes, the program should print a message | |
declaring a run-off between the two candidates receiving the highest number of | |
votes; the two candidates should be identified by their letter names. | |
f. For testing, run the program with the above data, and also with another | |
data file where Candidate C receives only 108 votes in precinct 4. | |
Moderate Problems | |
Write a program to find all the sentences, or consecutive sequence of sentences, in a text file where: min <= length <= max. | |
Assume that a sentence ends in a period, question mark, or exclamation point. | |
In the special case of quoted sentences (that begin with quotes or an apostrophe), include the terminating quote mark or apostrophe. | |
Count all blanks and punctuation, but assume only one blank between sentences. | |
(All EOL characters should be converted to blanks). | |
Precondition: Min and Max will be positive integers less than 1000, and Min <= Max. | |
The name of the text file is to be provided as a command line argument (not read from Standard Input). | |
For example, given this text: | |
Black is white. Day is night. Understanding is ignorance. | |
Truth is fiction. Safety is danger. | |
If min = max = 16 then the output is | |
"Black is white." | |
If min = max = 18 then the output is | |
"Truth is fiction." | |
"Safety is danger." | |
If min = 30 and max = 37 then the output is | |
"Truth is fiction. Safety is danger." | |
because the two sentences are consecutive sentences with the desired length. | |
Here is a sample text file for Alice in Wonderland. | |
1. Write a program to convert roman numerals into their arabic equivalent. | |
INPUT REQUIREMENTS | |
Read one or more roman numerals from standard input. Process one line at a time. Each input line contains only one roman numeral, starting in column one. Assume the characters are all upper case with no embedded blanks. | |
OUTPUT REQUIREMENTS | |
The arabic equivalent of each input roman numeral is displayed on standard output, starting in column one. | |
FUNCTIONAL REQUIREMENTS | |
Here are the arabic equivalents for roman symbols: | |
The "basic" roman symbols The "auxiliary" roman symbols | |
I X C M V L D | |
1 10 100 1000 5 50 500 | |
Convert the roman numeral to arabic processing the symbols from left to right according to the following rules: | |
1. A symbol following one of greater or equal value adds to its value. (E.g., XII = 12) | |
2. A symbol preceding one of greater value subtracts its value.(E.g., IV = 4; XL = 40) | |
ERROR HANDLING REQUIREMENTS | |
In each of the error conditions below, display the given message and skip the numeral and continue processing the next line. | |
"Invalid character in input. Valid characters are I,V,X,L,C,D,M." | |
Only the listed characters are valid. | |
"Invalid numeral: can't subtract auxiliary symbol." | |
It is not permitted to subtract an "auxiliary" symbol. (CML, not LM = 950; XLV not VL, = 45). | |
"Invalid numeral: two consecutive subtractions." | |
Can't do two subtractions in a row, thus LIVX is illegal. | |
"Invalid numeral: additions don't decrease." | |
Additions must decrease, as you go from left to right. Thus, each symbol added must have a value equal or less than the last symbol which was added. Thus, LIIX is wrong, cause we added L, added I, subtracted I, then try to add X. | |
Phone "words" | |
Each number on the telephone dial (except 0 and 1) corresponds to three alphabetic characters. Those correspondences are: | |
2 ABC | |
3 DEF | |
4 GHI | |
5 JKL | |
6 MNO | |
7 PRS | |
8 TUV | |
9 WXY | |
Given a seven digit telephone number, print all 2187 possible "words" that number spells. (They may not be real english words, but just some sequence of characters). Since the digits 0 and 1 have no alphabetic equivalent, an input number which contains those digits should be rejected. The input will be one or more seven digit integers from standard input. | |
The problem can be made a bit more challenging by outputting more than one word per line. Usually about seven words will fit on a line. | |
Frequency of letter pairs | |
Write a program to count the occurrences of all letter pairs in a sample of text (like the first paragraph of the Constitution). Disregard differences between lower and upper case letters. (Blanks are not considered as letters). Output the 100 most frequent letter pairs, in order by percent of total. Also show which percent of total pairs is accounted for by this list of 100. Your program should correctly process situations where the input file is empty or where less than 100 pairs occur. | |
Sample output | |
th 2.37% in 2.20% fj 2.00% ... (6 per line) | |
... | |
(100 letter pairs) | |
Output represents 73.44% of 23641 letter pairs. | |
Computing "subword" combinations. | |
Accept any number of lines of input entered from standard input. A valid line contains a word and a number. The word comes first, and is up to twenty alphabetic characters (A-Z) in upper or lower case. The word may be preceeded and followed by any number of blanks. The number is a decimal integer greater than zero, and may be followed by any number of blanks or a return. Input is terminated by EOF character. For each input word, print all possible "subwords" that have as many characters as specified by the number. A "subword" is a n-letter word comprised of only characters that are found in the given word. If you are familiar with the game Scrabble, it's as though the input word is your pool of letters, and you want to find all possible arrangements of n letters from your pool. .nf For example, CAT 2 would produce CA CT AC AT TA TC and DOG 1 would produce D O G and BIRD 3 would produce BIR BID IRD RID DIR RIB ... Note, that we are producing combinations WITHOUT replacement, so in the BIRD 3 example, BBB and RRR are NOT possible subwords. The output should echo the input line to standard output, followed by the list of subwords, one word per line, left justified. Each set of output words should be followed by one blank line. The program should respond to invalid input by echoing the input line to the output, and then issuing a one line message indicating the nature of the error: | |
"Illegal character in word" | |
"Illegal character in number" | |
"Number greater than length of word" | |
"Word longer than 20 characters" | |
After issuing the message, processing should resume with the next input line. When all input has been processed, issue a message indicating the number of input words that were processed (including word with errors) e.g., "End of input encountered, 4 words processed." | |
Calculating bowling match scores | |
A bowling match consists of ten frames. Each frame except for the tenth consists of one or two balls, or attempts to knock down the ten pins at the end of the alley. Doing so on the first ball of the frame is called a strike, and the second ball of the frame is not rolled. Knocking down all ten pins with both balls (having left some up with the first ball) is called a spare. If both attempts to knock down the pins leave some standing, the frame is called an open frame. A spare in the tenth frame gives the bowler one extra ball; a strike in the tenth gives him or her two extra balls. A bowling score is computed as follows. A strike counts as 10 points plus the sum of the next two balls. A spare counts as 10 points plus the next ball. Any other balls merely count as themselves, as do any bonus balls rolled as a result of a strike or a spare in the tenth frame. Suppose for example that the sequence of balls was | |
9 1 0 10 10 10 6 2 7 3 8 2 10 9 0 9 1 10 | |
The score for the ten frames would be | |
Frame score | |
----- ----- | |
1 10 | |
2 30 | |
3 56 | |
4 74 | |
5 82 | |
6 100 | |
7 120 | |
8 139 | |
9 148 | |
10 168 | |
Write a program to accept from standard input the scores for a sequence of balls and output the scores for the ten frames. There may be multiple lines of input, where each input line will be the scores for one player. The scores will be separated by one or more blanks. You may assume that the number of scores on the line is valid. | |
Lotto Guesser | |
Cobbletown has a lottery (a small version of California's Lotto) in which players guess four number between 1 and 9. Larry likes to play and thinks he has a scheme to pick winning numbers. He keeps a history of past winning numbers in a text data file. Larry thinks that if a number hasn't occurred recently then it is more likely to show up as a winner. (Obviously Larry isn't familiar with the statistical fact that each number has an equal likelihood of being picked, since each week's drawing is an independent event). Larry wants us to write a program to assist him in his wacky scheme. | |
INPUT REQUIREMENTS | |
The lotto history data: a file of unknown length, with four integers per line. Each integer is in the range 1 to 9. | |
OUTPUT REQUIREMENTS | |
1. The four least frequently occurring integers in the history data. (That is, counting all the weeks, the four numbers that appeared fewer times than any others). | |
2. The one integer with longest time since last occurrence. (That is, if you count backward from now, the number for which you count the most weeks since it occurred). | |
FUNCTIONAL REQUIREMENTS | |
(You may assume that no data validity checking is required). | |
1. Determine and display the four integers which occur least often in the history data. | |
Note: To make the problem easier, if there is a tie between two or more numbers for fourth place, it doesn't matter which one is printed. | |
2. Determine and display the integer which has gone the longest without appearing in a winning sequence. | |
At a minimum your program must work correctly for the following sample data. | |
Test Data | |
1 2 3 4 | |
5 6 7 8 | |
8 7 6 5 | |
1 5 6 7 | |
4 3 2 1 | |
Castles and Creatures | |
Write a program to play a simple "adventure"-style interactive game. The adventure world consists of up to five castles each of which has up to seven rooms (35 total). Each room has a treasure, worth a certain number of points, and a creature guarding the treasure. The treasure can be captured by bluffing or fighting the creature. Bluffing always has a 30% chance of succeeding. The odds for winning a fight vary from creature to creature. The object of the game is to visit different rooms and gain as many treasure points as possible. The player begins with 9 lives and each fight lost costs a life. (There's no penalty for losing a bluff.) When all the lives (or all treasures) are gone the game ends. The adventure world information (like castle and room names) is stored in a text file. The program must read the text file and create a data structure to represent the world. (HINT: Use a record structure for each room.) The program must handle interaction with the player, including display of menus for castle and room choices, display of current lives and treasure points accumulated, and responding to one-character commands to fight, bluff, or move around the world. | |
Sudoku Solver | |
Sudoku Solver assignment | |
Last modified on 10/18/2014 09:37:40Last modified on 05/13/2001 12:36:16 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment