Week 5: Exercises

1. Last Word Length

For this exercise and future exercises on this page, a word is a series of non-space characters separated from other words by one or more spaces.

Write a program that reads a string and prints the length of its last word, or -1 if there are no words in the string.

2. Words in a String

Write a function words(s: string): integer that returns the number of words in a string, where words are separated by one or more spaces.

3. Longest Word

Write a program that reads a string and writes its longest word.

4. Ends With

Write a function endsWith that takes two strings S and T, and returns true if S ends with T. For example, endsWith('rhubarb pie', 'pie') should return true.

5. Same Letters

Write a function sameLetters that takes two strings S and T, and returns true if S and T contain the same letters (even if some of these letters occur more times in one string than the other). Ignore case. For example, sameLetters('apple pie', 'I leap') is true.

6. Adaptive Bubble Sort

Modify our bubble sort implementation to be adaptive: after every pass, if the array is now in sorted order then the sort should stop.

7. Digit Cycle

Write a program that rotates the digits in a number: the first digit moves to the last position, and all other digits shift leftward. Do not use any strings in your implementation.

Sample input:

72884

Sample output:

28847

8. Increment the Digits

Write a function incDigits that adds 1 to every digit in an integer. If the digit is 9, it should become 0. Do not use any strings or arrays. For example, incDigits(239756) = 340867.

9. Combine the Zeroes

Write a function combineZeroes that replaces consecutive zeroes in an integer with a single zero. Do not use any strings or arrays. For example, combineZeroes(430050700) = 4305070.

10. Rotate a Matrix

Write a program that reads an integer N followed by an N x N matrix of integers and rotates it to the right.

Input:

4
2 4 6 8
8 6 4 2
1 3 7 9
9 7 3 1

Output:

9 1 8 2
7 3 6 4
3 7 4 6
1 9 2 8

11. Pythagorean triplet

(Project Euler, problem 9)

A set of three natural numbers a, b, c form a Pythagorean triplet if

a2 + b2 = c2

There is only one Pythagorean triplet for which a < b < c and a + b + c = 1000. Write a program to find it.

12. Longest Collatz Sequence

Solve Project Euler’s Problem 14.