Week 13: Exercises

1. Rotation

Write a Haskell program that reads a rectangular matrix of integers from standard input. For example:

3 9 8
2 5 12
1 7 4

The program should print out the matrix rotated 90 degrees to the right:

1 2 3
7 5 9
4 12 8

2. Guessing Game

a) Write a program in which the computer thinks of a number from 1 to 1000, and the human player has to guess it.

b) Now write a similar program in which the human player thinks of a number, and the computer has to guess it.

3. Grep

Write a Haskell program that is like the command-line utility 'grep'. It should take two command-line arguments: a string to search for, plus a filename. It should print out all lines in the file that contain the given string.

4. Find

Write a Haskell program that is like the command-line utility 'find'. It should take one command-line argument: a string. The program should look in the current directory and all subdirectories (recursively) for files whose names contain the given string, and print out the (relative) paths of these files, one per line.

5. Minimum Number of Coins

Write a function minCoins :: [Int] -> Int -> Maybe [Int] that takes a list of coin denominations and a sum, and returns a minimal list of coins which can be used to form the sum. Any denomination may be used multiple times in forming the sum. For example, min_coins [1, 2, 5, 10] 9 might return Just [2, 2, 5]. If the sum cannot be formed from the given coins, return Nothing.

6. Integer Partition

Write a function partition :: [Int] -> Maybe ([Int], [Int]) that takes a list of integers and determines whether it can be partitioned into two sets whose sum is equal. If so, the function should return a Just with two lists containing the numbers in each set. If not, it should return Nothing.

7. Graph Paths

In Haskell, we may represent a graph in adjacency-list representation using an association list that maps each vertex to a list of its neighbors:

type Graph a = [(a, [a])]

For example, consider this undirected graph:

We may represent it as

graph = [ ('a', "ce"), ('b', "de"), ('c', "adf"), ('d', "bcef"),
          ('e', "bdf"), ('f', "cdeg"), ('g', "f") ]

a) Write a function

adjacent :: Eq a => Graph a -> a -> [a]

that returns a list of a vertex's neighbors in a graph.

b) Write a function

paths :: Eq a => Graph a -> a -> a -> [[a]]

that takes a graph and the ids of start and end vertices v and w, and returns a list of all possible paths from v to w, where a path is represented as a list of vertices. A path may not contain the same vertex twice.

8. 3-Coloring a Graph

Write a function that takes a graph in adjacency list representation and returns a 3-coloring of the graph if one exists, or otherwise Nothing.