Monday

November 30, 2015
Posted by **Ben** on Friday, May 28, 2010 at 7:29am.

Write a Function

You will be given one of the following problems to solve using and writing Java functions.

1.

Given a list of words, return an array which indicates the frequency that each letter occurs. For example, in the list [”apple”, ”bob”], [ ’a’ -> 1, ’b’->2, ’e’->1, ’l’->1, ’o’->, ’p’->2] . The order of the array does not matter and a Frequency class will be provided.

2.

Given a list of words, indicate whether the list constitutes a ”Word Lad- der.” A Word Ladder is a series of words where each succeeding word changes by only one letter. You may not assume that all words will be of the same length, and you may not assume the length of the list.

3.

Given an integer greater than 2, X, return an array populated with all prime numbers up to and including X.

- computer science -
**MathMate**, Friday, May 28, 2010 at 8:29am1.

Check with your teacher if the list is supposed to be case sensitive. From the context of the question, it should not be.

In this case, convert all the strings into lowercase and compare using the String.toLowerCase() method before comparison.

The comparison can be done character by character using the String.charAt(i) method.

Use an array of size 26 to store the frequencies. Do not forget to initialize the array (or the Frequency class values).

Read the Java API for more details.

http://java.sun.com/javase/6/docs/api/

or to download the API to your computer:

http://java.sun.com/javase/downloads/index.jsp#docs

- computer science -
**MathMate**, Friday, May 28, 2010 at 8:42am2.

First compare the lengths of the successive words using String.length().

If they equal, then compare letter by letter, and count the number of different letters. If the difference equals 1, continue the "ladder".

You may have to convert all letters to lowercase before the comparison.

3. There are plenty of algorithms for finding prime numbers. One of them is to test the divisibility by primes. You will have to create a list of primes, starting with 2, which is assumed to be a prime. Test all odd numbers starting from 3. Whenever you find that the number does not divide by the numbers on your prime list, you have found a prime, and add it to your prime list.

For example 3 does not divide by 2, so add 3 to the prime list. 5 does not divide by 2 and 3, add it to the prime list. Likewise, 7 is added to the prime list. 9 divides by 3, so skip it.

11 does not divide by 2,3... so it is a prime.

You do not have to test all the primes on the prime list. If the square of the prime on the prime list exceeds the number X to be tested, X can be declared a prime. For example, for 11, it is not divisible by 2,3, but 5²>11, so 11 can be declared a prime.

It may sound complicated, if you post your pseudocode or the Java code, you can get further help.