Week 9: Exercises

1. Frequent Words

Write a method

string[] topWords(string filename, int n)

that reads a file and returns an array of the n most frequent words in the file, listed in descending order of frequency. If the file has fewer than n distinct words, return an array of all words in the file. Use the C# collection classes.

2. Smallest Number of Coins

Write a method int[] smallest(int sum, int[] coins) that takes a integer and an array of coin denominations. The method should determine the smallest number of coins needed to form the given sum. The method should return an array with the coin values that sum to the given values. For example, if sum = 30 and coins = { 1, 15, 25 }, the method will return the numbers { 15, 15 }.

3. Stair Climbing

A staircase has n steps from bottom to top. A person walks up the staircase, and can take up to m steps at a time. Write a function

int stairs(int n, int m)

that returns the number of different ways in which the person may climb the stairs.

4. Carrots and Parsley

We wish to plant a garden with N beds in a row, each containing either carrots or parsley. No two adjacent beds may contain parsley. Write a method int garden(int n) that returns the number of possible ways in which the garden can be planted.