– More Collections: Return to Lisp Problems Solutions

1 Last Item

Find the last item in an List of String objects

1.1 Solution

1: String lastItem(List<String> a)
2: {
3:     return  a.get(a.size()-1);
4: }

2 Last Item Generic

Find the last item in a Generic List

2.1 Solution

1: Object gLastItem(List<?> a)
2: {
3:     return  a.get(a.size()-1);
4: }

3 Last But One

Find the last but one item in a List

3.1 Solution

1: Object lastButOneItem(List<?> a)
2: {
3:     if (a.size() > 1) 
4:  return  a.get(a.size()-2);
5:     else  
6:  return "List too small";
7: }

4 Iterate through the Elements of a List

Iterate through the Elements of a List, printing them out in turn

4.1 Solution

1: void printEach(List<?> a)
2: {
3:     for (Object e: a)
4:     {
5:  System.out.println(e);
6:     }        
7: }

or using a stream

1: void streamPrintEach(List<?> list)
2: {
3:     list
4:  .stream()
5:  .forEach(System.out::println);
6: 
7: }

5 Eliminate consecutive duplicates from a List.

Write a method that removes consecutive duplicates from a List. The order of the elements should not be changed.

5.1 Solution

1: List<?> removeDuplicates(List<?> a)
2: {
3:     for (int i = 0; i<a.size()-1; i++)
4:     {
5:  if(a.get(i) == a.get(i+1)) a.remove(a.get(i));        
6:     }
7:     return a;
8: }

6 Eliminate consecutive duplicates from a List using HashSet

Remembering that a HashSet cannot contain duplicates, repeat the above question using a HashSet

6.1 Solution

1: HashSet<String> hashRemoveDuplicates(List<String> a)
2: {
3:     HashSet<String> hSet = new HashSet<String>(a);
4:     return hSet;
5: }

7 RLE

Run-length encoding of a list. Consecutive duplicates of elements are encoded as pairs where N is the number of duplicates of the element E.

Note this solution uses the Pair class, defined in the question

7.1 Solution

 1: List<Pair> RLE(List<?> list)
 2: {
 3:     List<Pair> encoded = new ArrayList<Pair>();
 4:     for (int i = 0; i < list.size(); i++)
 5:     {
 6:     int runLength = 1;
 7:     while (i < list.size() -1 && list.get(i) == list.get(i+1))
 8:     {
 9:         runLength++;
10:         i++;
11:     }
12: 
13:      Pair<Object> pair = new Pair<Object>(runLength, list.get(i));
14:      encoded.add(pair);
15:     }
16:     return encoded;
17: 
18: }

8 Decode a run-length encoded list

Given a run-length code list generated in a previous problem, construct its uncompressed version.

Note this solution uses the Pair class, defined in the question

8.1 Solution

 1: List<Object> decodeRLE(List<Pair> list)
 2: {
 3: 
 4:     List<Object> decoded = new ArrayList<Object>();
 5:     for (Pair pair: list)
 6:     {
 7:     for (int i =0; i<(int)pair.count; i++)
 8:     {
 9:         decoded.add(pair.value);
10:     }
11:     }
12: 
13:     return decoded;
14: }

9 Duplicate the elements of a list

9.1 Solution

 1: List<String> dupli(List<String> list)
 2: {
 3:     List<String> dup = new ArrayList<String>();
 4: 
 5:     for(String s: list)
 6:     {
 7:     dup.add(s);
 8:     dup.add(s);
 9:     }
10: 
11:     return dup;
12: }

or, using a stream

1: List<String> streamDupli(List<String> list)
2: {
3:     List<String> dupli = list
4:              .stream()
5:              .collect(Collectors.toList());
6: 
7:     return dupli;        
8: 
9: }

10 Replicate the elements of a list a given number of times

10.1 Solution

 1: List<String> repli(List<String> list, int num)
 2: {
 3:     List<String> rep = new ArrayList<String>();
 4: 
 5:     for(String s: list)
 6:     {
 7:     for (int i=0; i<num; i++)
 8:     {
 9:         rep.add(s);
10:     }
11:     }
12: 
13:     return rep;
14: }

7: More Collections: Return to Lisp Problems

These problems were inspired by the 99 Lisp problems. Lisp is a very different language to Java; its use of lists means it’s not appropriate to emulate all the original problems in Java, however, there is some benefit in practising the use of Java collections.

The introduction of lambda functions in Java8 made me rethink how best to approach these problems. There are three things being practised here: collections, generics and lambdas. I’ve split up the questions so that they give a chance to practice these different skills.

1 Last Item

Find the last item in an List of String objects

1.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(lastItem(myList));
3:  *** Output ***
4: spoon

2 Last Item Generic

Find the last item in a Generic List

2.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: List<Integer> anotherList = new ArrayList<>(asList(1,2,3));
3: System.out.println(gLastItem(myList));
4: System.out.println(gLastItem(anotherList));
5:  *** Output ***
6: spoon
7: 3

3 Last But One

Find the last but one item in a List

3.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(lastButOneItem(myList));
3:  *** Output ***
4: fork

4 Iterate through the Elements of a List

Iterate through the Elements of a List, printing them out in turn

4.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(printEach(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

5 Eliminate consecutive duplicates from a List

Write a method that removes consecutive duplicates from a List. The order of the elements should not be changed.

5.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2: printEach(removeDuplicates(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

6 Eliminate consecutive duplicates from a List using HashSet

Remembering that a HashSet cannot contain duplicates, repeat the above question using a HashSet

6.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2: printEach(removeDuplicates(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

Remembering that a HashSet cannot contain duplicates

7 RLE

Run-length encoding of a list. Consecutive duplicates of elements are encoded as pairs where N is the number of duplicates of the element E.

Use this Pair class

 1: class Pair<T>
 2:    {
 3:        int count;
 4:        T value;
 5: 
 6:        Pair(int count, T value) 
 7:        {
 8:        this.count = count;
 9:        this.value = value;
10:        }
11: 
12:        void print()
13:        {
14:        System.out.print("("+ count + ", " + value +") ");
15:        }
16:    } 

7.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2:  List<Pair> rle = RLE(myList);
3:  for (Pair r: rle)
4:  {
5:      r.print();
6:  }
7:  System.out.println("");
8:  *** Output ***
9: (2, knife) (1, fork) (2, spoon)

8 Decode a run-length encoded list

Given a run-length code list generated in a previous problem, construct its uncompressed version.

8.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2:     List<Pair> rle = RLE(myList);
 3:     for (Pair r: rle)
 4:     {
 5:         r.print();
 6:     }
 7:     System.out.println("");
 8: 
 9:     List<Object> decoded = decodeRLE(rle);
10: 
11:     for (Object o: decoded)
12:     {
13:         System.out.println(o);
14:     }
15:  *** Output ***
16: (2, knife) (1, fork) (2, spoon) 
17: knife
18: knife
19: fork
20: spoon
21: spoon

9 Duplicate the elements of a list

9.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2: printEach(dupli(myList));
 3:  *** Output ***
 4: knife
 5: knife
 6: knife
 7: knife
 8: fork
 9: fork
10: spoon
11: spoon
12: spoon
13: spoon

10 Replicate the elements of a list a given number of times

10.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2: printEach(repli(myList,3));
 3:  *** Output ***
 4: knife
 5: knife
 6: knife
 7: knife
 8: knife
 9: knife
10: fork
11: fork
12: fork
13: spoon
14: spoon
15: spoon
16: spoon
17: spoon
18: spoon

– Strings, Arrays and Collections Solutions

6 Strings Arrays and Collections Solutions

6.1 Print 2D Array

The following code creates a 3 x 3 tic-tac-toe grid filled with Xs.

 1: void tictactoe()
 2:    {
 3:       String [][] grid = new String[3][3];
 4: 
 5:       for(int i = 0; i<grid.length; i++)
 6:       {
 7: 	  for (int j = 0; j<grid.length; j++)
 8: 	  {
 9: 	      grid[i][j] = "X";
10: 	  }
11:       }
12:       printArray(grid);
13: 
14:    }

Write a method that will print a 2D array of any size. Test it using the 3 x 3 tic-tac-toe grid given above

6.1.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	tictactoe();
 6:     }
 7: 
 8: 
 9:     void tictactoe()
10:     {
11:        String [][] grid = new String[3][3];
12: 
13:        for(int i = 0; i<grid.length; i++)
14:        {
15: 	   for (int j = 0; j<grid.length; j++)
16: 	   {
17: 	       grid[i][j] = "X";
18: 	   }
19:        }
20:        printArray(grid);
21: 
22:     }
23: 
24:     void printArray(String [][] grid)
25:     {
26: 	for(int i = 0; i<grid.length; i++)
27: 	{
28: 	    for(int j = 0; j<grid.length; j++)
29: 	    {
30: 		System.out.print(" | " + grid[i][j]);
31: 	    }
32: 	    System.out.println(" | ");
33: 	}
34:     }
35: 
36:     public static void main(String[] args) {
37: 	// TODO code application logic here
38: 	new NNStringArray();
39:     }
40: }

6.2 Chess Board

Create an 8 x 8 Array to represent a chess board. Print out the array with alternate ‘X’ and ‘O’ entries as shown in the example:

6.2.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	chess();
 6:     }
 7: 
 8:     void printArray(String [][] grid)
 9:     {
10: 	for(int i = 0; i<grid.length; i++)
11: 	{
12: 	    for(int j = 0; j<grid.length; j++)
13: 	    {
14: 		System.out.print(" | " + grid[i][j]);
15: 	    }
16: 	    System.out.println(" | ");
17: 	}
18:     }
19: 
20:     void chess()
21:     {
22:        String [][] grid = new String[8][8];
23:        boolean fill = true;
24: 
25:        for(int i = 0; i<grid.length; i++)
26:        {
27: 	   for (int j = 0; j<grid.length; j++)
28: 	   {
29: 	       grid[i][j] = fill ? "X" : "O";
30: 	       fill = !fill;
31: 	   }
32: 	   fill = !fill;
33:        }
34:        printArray(grid);
35:     }
36: 
37:     public static void main(String[] args) {
38: 	// TODO code application logic here
39: 	new NNStringArray();
40:     }
41: }

6.3 Digits to Words

Write a method that will convert digits into words

6.3.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	System.out.println(digitsToWords("35001922"));
 6:     }
 7: 
 8:     String digitsToWords(String s)
 9:     {
10: 	String words = "";
11: 	String [] digits = {"Oh","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
12: 
13: 	for (int i = 0; i<s.length();i++)
14: 	{
15: 	    int number = Integer.parseInt(s.substring(i,i+1));
16: 	    words = words + digits[number] + " ";
17: 	}
18: 
19: 	return words;
20:     }
21:     public static void main(String[] args) {
22: 	// TODO code application logic here
23: 	new NNStringArray();
24:     }
25: }

6.4 Time to Words

Write a method that will convert time to words. For example, 4:10 is “Ten past four” and 4:55 is “Five to Five”

6.4.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	System.out.println(timeToWords("2:05"));
 6: 	System.out.println(timeToWords("2:47"));
 7: 	System.out.println(timeToWords("12:00"));
 8: 	System.out.println(timeToWords("2:00"));
 9: 	System.out.println(timeToWords("12:30"));
10: 	System.out.println(timeToWords("4:29"));
11: 	System.out.println(timeToWords("7:25"));
12: 	System.out.println(timeToWords("12:45"));
13: 	System.out.println(timeToWords("12:55"));
14:     }
15: 
16:     String timeToWords(String s)
17:     {
18: 	String time = "";
19: 	String [] input = s.split(":");
20: 
21: 	String [] times = {"o'clock","one","two","three","four", "five", "six",
22: 		"seven","eight","nine","ten","eleven","twelve","thirteen","fourteen",
23: 		"quarter","sixteen","seventeen","eighteen","nineteen","twenty",
24: 		"twenty one","twenty two","twenty three","twenty four",
25: 		"twenty five","twenty six","twenty seven","twenty eight",
26: 		"twenty nine","half past"};
27: 
28:        int hours = Integer.parseInt(input[0]);
29:        int minutes = Integer.parseInt(input[1]);
30: 
31:        //Watch out for e.g. 12:50 = Ten to One
32:        String sayMinutesp = minutes%5 != 0 ? " minutes" : "";
33:        if (hours  == 12 && minutes > 30) hours = 1;
34: 
35:        if (minutes == 0)
36:        {
37: 	     time = times[hours] + " o'clock";
38:        }
39:        else if (minutes == 15)
40:        {
41: 	   time = "Quarter past " + times[hours];
42:        }
43:        else if (minutes == 45)
44:        {
45: 	   time = "Quarter to " + times[hours];
46:        }
47:        else if (minutes>30)
48:        {
49: 	   time = times[60-minutes]+ sayMinutesp +  " to " + times[hours];
50:        }
51:        else
52:        {
53: 	   time = times[minutes] + sayMinutesp + " past " + times[hours];
54:        }
55: 
56: 	return time;
57:     }
58: 
59:     public static void main(String[] args) {
60: 	// TODO code application logic here
61: 	new NNStringArray();
62:     }
63: }

6.5 Morse Code Arrays

Write a program using arrays that translates plain text into morse code.

A B C D E F G
.- -… -.-. -.. . ..-. –.
H I J K L M
…. .. .— -.- .-..
N O P Q R S T
-. .–. –.- .-.
U V W X Y Z
..- …- .– -..- -.– __..

6.5.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	System.out.println(morse("I never saw a purple cow"));
 6:     }
 7: 
 8:     String morse(String s)
 9:     {
10: 	s = s.toLowerCase();
11: 	String cipherText = "";
12: 	String code [] = {".-","-...","-.-.","-..",".","..-.","--.", "....",
13: 	    "..", ".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
14: 	    "...","-","..-","...-",".--","-..-","-.--","--..", "/"};
15: 
16: 	for (int i = 0; i<s.length(); i++)
17: 	{
18: 	    int number = s.charAt(i) == ' ' ? 26 : s.charAt(i)-97;
19: 	    cipherText = cipherText + code[number] + " ";
20: 	}
21: 
22: 	return cipherText;
23:     }
24:     public static void main(String[] args) {
25: 	// TODO code application logic here
26: 	new NNStringArray();
27:     }
28: }

6.6 Demorse Code Arrays

Now write a program using arrays that translates morse back to plain text.

6.6.1 Solution

 1: public class NNStringArray {
 2: 
 3:     NNStringArray()
 4:     {
 5: 	System.out.println(demorse(".. / -. . ...- . .-. / ... .- .-- / .- / .--. ..- .-. .--. .-.. . / -.-. --- .--"));
 6:     }
 7: 
 8:     String demorse(String s)
 9:     {
10: 	s = s.toLowerCase();
11: 	String cipher = "";
12: 	String code [] = {".-","-...","-.-.","-..",".","..-.","--.", "....",
13: 	    "..", ".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
14: 	    "...","-","..-","...-",".--","-..-","-.--","--..", "/"};
15: 
16: 	String [] letters = s.split("\\s+");
17: 	String plainText= "";
18: 
19: 
20: 	for (int i = 0; i<letters.length;i++)
21: 	{
22: 	    String letter = letters[i].trim();
23: 	    if (letter.equals("/"))
24: 	    {
25: 		plainText = plainText + " ";
26: 	    }
27: 	    else
28: 	    {
29: 		String decode = "";
30: 		for(int j = 0; j <code.length; j++)
31: 		{
32: 		    if (letter.equals(code[j]))
33: 		    {
34: 			char c = (char)(j+97);
35: 			plainText = plainText + Character.toString(c);
36: 		    }
37: 		}
38: 	    }
39: 	}
40: 
41: 	return plainText;
42:     }
43: 
44:     public static void main(String[] args) {
45: 	// TODO code application logic here
46: 	new NNStringArray();
47:     }
48: }

6.7 Morse Code Hashmap

Rewrite the Morse Code program using Hashmap

6.7.1 Solution

 1: import java.util.HashMap;
 2: import java.util.Map;
 3: import java.util.Map.Entry;
 4: 
 5: public class NNStringArray {
 6: 
 7:     Map <String, String> morse = new HashMap<String, String>();
 8: 
 9:     NNStringArray()
10:     {
11: 	morse.put("a" , ".-");
12: 	morse.put("b" , "-...");
13: 	morse.put("c" , "-.-.");
14: 	morse.put("d" , "-..");
15: 	morse.put("e" , ".");
16: 	morse.put("f" , "..-.");
17: 	morse.put("g" , "--.");
18: 	morse.put("h" , "....");
19: 	morse.put("i" , "..");
20: 	morse.put("j" , ".---");
21: 	morse.put("k" , "-.-");
22: 	morse.put("l" , ".-..");
23: 	morse.put("m" , "--");
24: 	morse.put("n" , "-.");
25: 	morse.put("o" , "---");
26: 	morse.put("p" , ".--.");
27: 	morse.put("q" , "--.-");
28: 	morse.put("r" , ".-.");
29: 	morse.put("s" , "...");
30: 	morse.put("t" , "-");
31: 	morse.put("u" , "..-");
32: 	morse.put("v" , "...-");
33: 	morse.put("w" , ".--");
34: 	morse.put("x" , "-..-");
35: 	morse.put("y" , "-.--");
36: 	morse.put("z" , "--..");
37: 	morse.put(" " , "/");
38: 
39: 	System.out.println(morseHash("I never saw a purple cow"));
40:     }
41: 
42:     String morseHash(String s)
43:     {
44: 	 s = s.toLowerCase();
45: 	 String cipherText = "";
46: 
47: 	 for (int i = 0; i<s.length(); i++)
48: 	 {
49: 	     cipherText = cipherText + morse.get(s.substring(i,i+1)) + " ";
50: 
51: 	 }
52: 
53: 	 return cipherText;
54:     }
55: 
56:     public static void main(String[] args) {
57: 	// TODO code application logic here
58: 	new NNStringArray();
59:     }
60: }

6.8 Demorse Code Hashmap

Rewrite the Demorse Code program using Hashmap

6.8.1 Solution

 1: import java.util.HashMap;
 2: import java.util.Map;
 3: import java.util.Map.Entry;
 4: 
 5: public class NNStringArray {
 6: 
 7:     Map <String, String> morse = new HashMap<String, String>();
 8: 
 9:     NNStringArray()
10:     {
11: 	morse.put("a" , ".-");
12: 	morse.put("b" , "-...");
13: 	morse.put("c" , "-.-.");
14: 	morse.put("d" , "-..");
15: 	morse.put("e" , ".");
16: 	morse.put("f" , "..-.");
17: 	morse.put("g" , "--.");
18: 	morse.put("h" , "....");
19: 	morse.put("i" , "..");
20: 	morse.put("j" , ".---");
21: 	morse.put("k" , "-.-");
22: 	morse.put("l" , ".-..");
23: 	morse.put("m" , "--");
24: 	morse.put("n" , "-.");
25: 	morse.put("o" , "---");
26: 	morse.put("p" , ".--.");
27: 	morse.put("q" , "--.-");
28: 	morse.put("r" , ".-.");
29: 	morse.put("s" , "...");
30: 	morse.put("t" , "-");
31: 	morse.put("u" , "..-");
32: 	morse.put("v" , "...-");
33: 	morse.put("w" , ".--");
34: 	morse.put("x" , "-..-");
35: 	morse.put("y" , "-.--");
36: 	morse.put("z" , "--..");
37: 	morse.put(" " , "/");
38: 
39: 	System.out.println(demorseHash(".. / -. . ...- . .-. / ... .- .-- / .- / .--. ..- .-. .--. .-.. . / -.-. --- .--"));
40: 
41:     }
42: 
43: 
44:     String demorseHash(String s)
45:     {
46: 	String [] letters = s.split("\\s+");
47: 	String plaintext = "";
48: 
49: 	for (int i = 0; i<letters.length; i++)
50: 	{
51: 	    for (Entry<String, String> entry : morse.entrySet()) {
52: 		if (entry.getValue().equals(letters[i])) {
53: 		    plaintext = plaintext + entry.getKey();
54: 		}
55: 	    }
56: 	}
57: 	return plaintext;
58:     }
59: 
60: 	public static void main(String[] args) {
61: 	// TODO code application logic here
62: 	new NNStringArray();
63:     }
64: }

6: Strings, Arrays and Collections

6 Strings, Arrays and Collections

6.1 Print 2D Array

The following code creates a 3 x 3 tic-tac-toe grid filled with Xs.

 1: void tictactoe()
 2:    {
 3:       String [][] grid = new String[3][3];
 4: 
 5:       for(int i = 0; i<grid.length; i++)
 6:       {
 7: 	  for (int j = 0; j<grid.length; j++)
 8: 	  {
 9: 	      grid[i][j] = "X";
10: 	  }
11:       }
12:       printArray(grid);
13: 
14:    }

Write a method that will print a 2D array of any size. Test it using the 3 x 3 tic-tac-toe grid given above

6.1.1 Example

1: tictactoe()
2:  *** Output ***
3:  | X | X | X |
4:  | X | X | X |
5:  | X | X | X |

6.2 Chess Board

Create an 8 x 8 Array to represent a chess board. Print out the array with alternate ‘X’ and ‘O’ entries as shown in the example:

6.2.1 Example

 1: chess();
 2:  *** Output ***
 3:  | X | O | X | O | X | O | X | O |
 4:  | O | X | O | X | O | X | O | X |
 5:  | X | O | X | O | X | O | X | O |
 6:  | O | X | O | X | O | X | O | X |
 7:  | X | O | X | O | X | O | X | O |
 8:  | O | X | O | X | O | X | O | X |
 9:  | X | O | X | O | X | O | X | O |
10:  | O | X | O | X | O | X | O | X |

6.3 Digits to Words

Write a method that will convert digits into words

6.3.1 Example

1: System.out.println(digitsToWords("35001922"));
2:  *** Output ***
3: Three Five Oh Oh One Nine Two Two

6.4 Time to Words

Write a method that will convert time to words. For example, 4:10 is “Ten past four” and 4:55 is “Five to Five”

6.4.1 Example

 1: System.out.println(timeToWords("2:05"));
 2: System.out.println(timeToWords("2:47"));
 3: System.out.println(timeToWords("12:00"));
 4: System.out.println(timeToWords("2:00"));
 5: System.out.println(timeToWords("12:30"));
 6: System.out.println(timeToWords("4:29"));
 7: System.out.println(timeToWords("7:25"));
 8: System.out.println(timeToWords("12:45"));
 9: System.out.println(timeToWords("12:55"));
10:  *** Output ***
11: five past two
12: thirteen minutes to two
13: twelve o'clock
14: two o'clock
15: half past past twelve
16: twenty nine minutes past four
17: twenty five past seven
18: Quarter to one
19: five to one

6.5 Morse Code Arrays

Write a program using arrays that translates plain text into morse code.

A B C D E F G
.- -… -.-. -.. . ..-. –.
H I J K L M
…. .. .— -.- .-..
N O P Q R S T
-. .–. –.- .-.
U V W X Y Z
..- …- .– -..- -.– __..

6.5.1 Example

1: String s = "I never saw a purple cow"
2: 
3: morse(s)
4:  *** Output ***
5: .. / -. . ...- . .-. / ... .- .-- / .- / .--. ..- .-. .--. .-.. . / -.-. --- .--

6.6 Demorse Code Arrays

Now write a program using arrays that translates morse back to plain text.

6.6.1 Example

1: String s = ".. -././...-/./.-. .../.-/.-- .- .--./..-/.-./.--./.-../. -.-./---/.--"
2: 
3: deMorse(s)
4:  *** Output ***
5: "I never saw a purple cow"

6.7 Morse Code Hashmap

Rewrite the Morse Code program using Hashmap

6.7.1 Example

1: String s = "I never saw a purple cow"
2: morseHash(s)
3:  *** Output ***
4: .. / -. . ...- . .-. / ... .- .-- / .- / .--. ..- .-. .--. .-.. . / -.-. --- .--

6.8 Demorse Code Hashmap

Rewrite the Demorse Code program using Hashmap

6.8.1 Example

1: String s = ".. -././...-/./.-. .../.-/.-- .- .--./..-/.-./.--./.-../. -.-./---/.--"
2: deMorseHash(s)
3:  *** Output ***
4: "I never saw a purple cow"

– Arithmetic Solutions

5.1 Primes

Determine whether a given integer number is prime.

5.1.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:
 6:         System.out.println(isPrime(7));
 7:     }
 8:
 9:     boolean isPrime(int a)
10:     {
11:         //Special cases
12:         if(a==1) return false;
13:         if(a==2) return true;
14:
15:          boolean prime = true;
16:          int count = 2;
17:
18:          do
19:          {
20:              if (a%count==0)
21:              {
22:                  prime = false;
23:              }
24:              count++;
25:          } while(prime == true && count*count <=a);
26:
27:          return prime;
28:     }
29:
30:      public static void main(String[] args)
31:      {
32:         new NNArithmetic();
33:      }
34:  }
35:

5.2 GCD

Use Euclid’s Algorithm to determine the Greatest Common Divisor of two positive integer numbers

5.2.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:
 6:         System.out.println(gcd (1071, 462));
 7:         System.out.println(gcd (6, 35));
 8:         System.out.println(gcd (36, 63));
 9:     }
10:
11:
12:     int gcd(int a, int b)
13:     {
14:          if(b>a)  //Make sure the first number is largest
15:          {
16:              int temp = a;
17:              a = b;
18:              b = temp;
19:          }
20:
21:          while(b>0)
22:          {
23:              int remainder = a%b;
24:              a = b;
25:              b = remainder;
26:          }
27:
28:          return a;
29:      }
30:
31:      public static void main(String[] args)
32:      {
33:         new NNArithmetic();
34:      }
35:  }
36:

5.3 Coprimes

Determine whether two positive integer numbers are coprime. Two numbers are coprime if their greatest common divisor equals 1.

5.3.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:          System.out.println(isCoprime(35,64));
 6:     }
 7:
 8:     int gcd(int a, int b)
 9:     {
10:          if(b>a)  //Make sure the first number is largest
11:          {
12:              int temp = a;
13:              a = b;
14:              b = temp;
15:          }
16:
17:          while(b>0)
18:          {
19:              int remainder = a%b;
20:              a = b;
21:              b = remainder;
22:          }
23:
24:          return a;
25:      }
26:
27:
28:     boolean isCoprime(int a, int b)
29:     {
30:           return (gcd(a,b) ==1) ? true : false;
31:     }
32:
33:      public static void main(String[] args)
34:      {
35:         new NNArithmetic();
36:      }
37:  }
38:

5.4 Totient Function

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.
For example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1.

5.4.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:         System.out.println(phi(10));
 6:     }
 7:
 8:     int gcd(int a, int b)
 9:     {
10:          if(b>a)  //Make sure the first number is largest
11:          {
12:              int temp = a;
13:              a = b;
14:              b = temp;
15:          }
16:
17:          while(b>0)
18:          {
19:              int remainder = a%b;
20:              a = b;
21:              b = remainder;
22:          }
23:
24:          return a;
25:      }
26:
27:     boolean isCoprime(int a, int b)
28:     {
29:           return (gcd(a,b) ==1) ? true : false;
30:     }
31:
32:     int phi(int m)
33:     {
34:          if (m==1) return 1; //Special Case
35:
36:          int phi = 0;
37:          for(int i = 1; i<m; i++)
38:          {
39:              if (isCoprime(m,i)) phi++;
40:          }
41:          return phi;
42:     }
43:
44:      public static void main(String[] args)
45:      {
46:         new NNArithmetic();
47:      }
48:  }
49:

5.5 Prime Factors

Write a method that prints the prime factors of a given positive integer

5.5.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:         printPrimeFactors(315);
 6:         printPrimeFactors(98);
 7:     }
 8:
 9:     void printPrimeFactors(int n)
10:     {
11:          for(int i = 2; i*i<=n; i++)
12:          {
13:              while(n%i == 0)
14:              {
15:                  System.out.print(i + " ");
16:                  n = n/i;
17:              }
18:          }
19:          if(n>1) System.out.print(n + "\n");
20:          else System.out.println("");
21:     }
22:
23:      public static void main(String[] args)
24:      {
25:         new NNArithmetic();
26:      }
27:  }
28:

5.6 List of Primes

Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.

5.6.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:         printPrimesInRange(10,20);
 6:     }
 7:
 8:     boolean isPrime(int a)
 9:     {
10:         //Special cases
11:         if(a==1) return false;
12:         if(a==2) return true;
13:
14:          boolean prime = true;
15:          int count = 2;
16:
17:          do
18:          {
19:              if (a%count==0)
20:              {
21:                  prime = false;
22:              }
23:              count++;
24:          } while(prime == true && count*count <=a);
25:
26:          return prime;
27:     }
28:     void printPrimesInRange(int a , int b)
29:     {
30:          for (int i = a; i<=b; i++)
31:          {
32:              if (isPrime(i)) System.out.print(i + " ");
33:          }
34:          System.out.println("");
35:     }
36:      public static void main(String[] args)
37:      {
38:         new NNArithmetic();
39:      }
40:  }
41:

5.7 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. Write a predicate to find the two prime numbers that sum up to a given even number.

5.7.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:         printGoldbachPair(28);
 6:         printGoldbachPair(1856);
 7:     }
 8:
 9:     boolean isPrime(int a)
10:     {
11:         //Special cases
12:         if(a==1) return false;
13:         if(a==2) return true;
14:
15:          boolean prime = true;
16:          int count = 2;
17:
18:          do
19:          {
20:              if (a%count==0)
21:              {
22:                  prime = false;
23:              }
24:              count++;
25:          } while(prime == true && count*count <=a);
26:
27:          return prime;
28:     }
29:     int [] goldbachPair(int n)
30:     {
31:          int count = 2;
32:          int [] pair = new int[2];
33:          boolean foundPair = false;
34:          while(foundPair == false && count <= n/2)
35:          {
36:              if(isPrime(count) && isPrime(n-count))
37:              {
38:                  foundPair = true;
39:                  pair [0] = count;
40:                  pair [1] = (n-count);
41:              }
42:              count++;
43:          }
44:          return pair;
45:     }
46:
47:     void printGoldbachPair(int n)
48:     {
49:          int [] pair = goldbachPair(n);
50:          System.out.println(pair[0] + " + " + pair [1] + " = " + n);
51:     }
52:
53:
54:      public static void main(String[] args)
55:      {
56:         new NNArithmetic();
57:      }
58:  }
59:

5.8 More Goldbach

Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition.
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.

5.8.1 Solution

 1:  public class NNArithmetic {
 2:
 3:     NNArithmetic()
 4:     {
 5:         printGoldbachList(9, 20);
 6:         printGoldbachList(1,2000,50);
 7:     }
 8:
 9:     boolean isPrime(int a)
10:     {
11:         //Special cases
12:         if(a==1) return false;
13:         if(a==2) return true;
14:
15:          boolean prime = true;
16:          int count = 2;
17:
18:          do
19:          {
20:              if (a%count==0)
21:              {
22:                  prime = false;
23:              }
24:              count++;
25:          } while(prime == true && count*count <=a);
26:
27:          return prime;
28:     }
29:     int [] goldbachPair(int n)
30:     {
31:          int count = 2;
32:          int [] pair = new int[2];
33:          boolean foundPair = false;
34:          while(foundPair == false && count <= n/2)
35:          {
36:              if(isPrime(count) && isPrime(n-count))
37:              {
38:                  foundPair = true;
39:                  pair [0] = count;
40:                  pair [1] = (n-count);
41:              }
42:              count++;
43:          }
44:          return pair;
45:     }
46:
47:     void printGoldbachPair(int n)
48:     {
49:          int [] pair = goldbachPair(n);
50:          System.out.println(pair[0] + " + " + pair [1] + " = " + n);
51:     }
52:
53:     void printGoldbachList(int a, int b)
54:     {
55:          if(a%2==1) a++; // make sure start on even number
56:          for (int i = a ; i<=b ; i+=2)
57:          {
58:              printGoldbachPair(i);
59:          }
60:
61:     }
62:
63:     void printGoldbachList(int a, int b, int min)
64:     {
65:          if(a%2==1) a++; // make sure start on even number
66:          for (int i = a ; i<=b ; i+=2)
67:          {
68:              int [] pair = goldbachPair(i);
69:              if(pair[0] > min && pair[1] > min) printGoldbachPair(i);
70:          }
71:     }
72:
73:      public static void main(String[] args)
74:      {
75:         new NNArithmetic();
76:      }
77:  }

5: Arithmetic

5.1 Primes

Determine whether a given integer number is prime.

5.1.1 Example

1:  System.out.println(isPrime(7));
2:   *** Output ***
3:  true

5.2 GCD

Use Euclid’s Algorithm to determine the Greatest Common Divisor of two positive integer numbers

5.2.1 Example

1:   System.out.println(gcd (1071, 462));
2:   System.out.println(gcd (6, 35));
3:   System.out.println(gcd (36, 63));
4:   *** Output ***
5:  21
6:  1
7:  9

5.3 Coprimes

Determine whether two positive integer numbers are coprime. Two numbers are coprime if their greatest common divisor equals 1.

5.3.1 Example

1:  System.out.println(isCoprime(35,64));
2:   *** Output ***
3:  true

5.4 Totient Function

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.
For example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1.

5.4.1 Example

1:  System.out.println(phi(10));
2:   *** Output ***
3:  4

5.5 Prime Factors

Write a method that prints the prime factors of a given positive integer

5.5.1 Example

1:  printPrimeFactors(315);
2:  printPrimeFactors(98);
3:   *** Output ***
4:  3 3 5 7
5:  2 7 7

5.6 List of Primes

Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.

5.6.1 Example

1:  printPrimesInRange(10,20);
2:   *** Output ***
3:  11 13 17 19

5.7 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.
Write a predicate to find the two prime numbers that sum up to a given even number.

5.7.1 Example

1:  printGoldbachPair(28);
2:  printGoldbachPair(1856);
3:   *** Output ***
4:  5 + 23 = 28
5:  67 + 1789 = 1856

5.8 More Goldbach

Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition.  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.

5.8.1 Example

 1:  printGoldbachList(9, 20);
 2:  printGoldbachList(1,2000,50);
 3:   *** Output ***
 4:  3 + 7 = 10
 5:  5 + 7 = 12
 6:  3 + 11 = 14
 7:  3 + 13 = 16
 8:  5 + 13 = 18
 9:  3 + 17 = 20
10:  73 + 919 = 992
11:  61 + 1321 = 1382
12:  67 + 1789 = 1856
13:  61 + 1867 = 1928

– String Solutions

4.1 Count Words

Write a method that returns the number of words in a String

4.1.1 Solution

 1:  public class NNStrings {
 2:
 3:      NNStrings()
 4:      {
 5:          String sentence = "I never saw a purple cow";
 6:          System.out.println(countWords(sentence));
 7:      }
 8:
 9:      int countWords(String s)
10:      {
11:         String [] words = s.split("\\s+");
12:         return words.length;
13:      }
14:
15:      public static void main(String[] args) {
16:          // TODO code application logic here
17:          new NNStrings();
18:      }
19:  }

4.2 Count the letter ‘e’

Write a method that counts the instances of the letter ‘e’ in a string.

4.2.1 Solution

 1:  public class NNStrings {
 2:
 3:      NNStrings()
 4:      {
 5:          String sentence = "I never saw a purple cow";
 6:          System.out.println(countEs(sentence));
 7:      }
 8:
 9:      int countEs(String s)
10:      {
11:          int count = 0;
12:          for(int i=0; i<s.length(); i++)
13:          {
14:              if(s.substring(i,i+1).matches("e"))
15:                  count++;
16:          }
17:          return count;
18:      }
19:
20:      public static void main(String[] args) {
21:          // TODO code application logic here
22:          new NNStrings();
23:      }
24:  }

4.3 Count Alphanumerics

Write a method that returns the number of alphanumeric characters (A-Z, a-z and 0-9) in a string.

4.3.1 Solution

 1:  public class NNStrings {
 2:
 3:      NNStrings()
 4:      {
 5:          String sentence = "I never saw a purple cow";
 6:          String title = "1984 by George Orwell.";
 7:          System.out.println(countChars(sentence));
 8:          System.out.println(countChars(title));
 9:      }
10:
11:      int countChars(String s)
12:      {
13:          int count = 0;
14:          for(int i=0; i<s.length(); i++)
15:          {
16:              if(s.substring(i,i+1).matches("[A-Za-z0-9]"))
17:                  count++;
18:          }
19:          return count;
20:      }
21:
22:      public static void main(String[] args) {
23:          // TODO code application logic here
24:          new NNStrings();
25:      }
26:  }

4.4 Reverse String

Write a method that returns a string, reversed

4.4.1 Solution

 1:  public class NNStrings {
 2:
 3:      NNStrings()
 4:      {
 5:          String sentence = "I never saw a purple cow";
 6:          System.out.println(reverse(sentence));
 7:          System.out.println(reverseH(sentence));
 8:          System.out.println(reverseSB(sentence));
 9:      }
10:
11:      // A Haskell-y solution
12:      String reverse(String s)
13:      {
14:          String reverse= "";
15:          for (int i = 0; i<s.length(); i++)
16:          {
17:              reverse = s.substring(i,i+1) + reverse;
18:          }
19:          return reverse;
20:      }
21:
22:      // A recursive Haskell-y solution
23:      String reverseH(String s)
24:      {
25:          if (s.length() == 0) return "";
26:          else if (s.length() == 1) return s;
27:          else return  reverseH(s.substring(1)) + s.substring(0,1);
28:      }
29:
30:      //A StringBuffer solution
31:      String reverseSB(String s)
32:      {
33:          String reverse = new StringBuffer(s).reverse().toString();
34:          return reverse;
35:      }
36:      public static void main(String[] args) {
37:          // TODO code application logic here
38:          new NNStrings();
39:      }
40:  }

4.5 Palindromes

Write a method to test if a string is a Palindrome

4.5.1 Solution

 1:  public class NNStrings {
 2:
 3:      NNStrings()
 4:      {
 5:          String sentence = "I never saw a purple cow";
 6:          String palindrome = "rotavator";
 7:          System.out.println(isPalindrome(sentence));
 8:          System.out.println(isPalindrome(palindrome));
 9:      }
10:
11:      // A Haskell-y solution
12:      String reverse(String s)
13:      {
14:          String reverse= "";
15:          for (int i = 0; i<s.length(); i++)
16:          {
17:              reverse = s.substring(i,i+1) + reverse;
18:          }
19:          return reverse;
20:      }
21:      boolean isPalindrome(String s)
22:      {
23:          return s.equals(reverse(s)) ? true : false;
24:      }
25:
26:      public static void main(String[] args) {
27:          // TODO code application logic here
28:          new NNStrings();
29:      }
30:  }

4.6 More Palindromes

Write an improved palindrome method that will disregard spaces, punctuation and case and thus recognise sentences such as “A man, a plan, a canal, Panama!” as a palindrome.

4.6.1 Solution

 1:  public class NNStrings {
 2:
 3:      NNStrings()
 4:      {
 5:          System.out.println(isImpPalindrome(pal2));
 6:      }
 7:
 8:      // A Haskell-y solution
 9:      String reverse(String s)
10:      {
11:          String reverse= "";
12:          for (int i = 0; i<s.length(); i++)
13:          {
14:              reverse = s.substring(i,i+1) + reverse;
15:          }
16:          return reverse;
17:      }
18:
19:      boolean isImpPalindrome(String s)
20:      {
21:          String lower = s.toLowerCase();
22:          String stripped = lower.replaceAll("[^A-Za-z0-9]", "");
23:          return stripped.equals(reverse(stripped)) ? true : false;
24:      }
25:
26:      public static void main(String[] args) {
27:          // TODO code application logic here
28:          new NNStrings();
29:      }
30:  }

4.7 Remove v*w*ls

Write a method that will replace the vowels in a word with asterisks

4.7.1 Solution

 1:  public class NNStrings {
 2:
 3:      NNStrings()
 4:      {
 5:          String sentence = "I never saw a purple cow";
 6:          System.out.println(star(sentence));
 7:      }
 8:
 9:
10:      String star(String s)
11:      {
12:          return s.replaceAll("[AEIOUaeiou]", "*");
13:      }
14:
15:      public static void main(String[] args) {
16:          // TODO code application logic here
17:          new NNStrings();
18:      }
19:  }

4.8 Spell Out

Write a method to spell out words so that, for example, This becomes T-H-I-S.

4.8.1 Solution

 1:  public class NNStrings {
 2:
 3:      NNStrings()
 4:      {
 5:          String sentence = "I never saw a purple cow";
 6:          System.out.println(spellOut(sentence));
 7:      }
 8:
 9:      String spellOut(String s)
10:      {
11:          s = s.toUpperCase();
12:          String spell = "";
13:          for (char c: s.toCharArray())
14:          {
15:              spell = spell + c + "-";
16:          }
17:
18:          spell = spell.replaceAll("-\\s+-|-$"," ");
19:          return spell;
20:      }
21:
22:
23:      public static void main(String[] args) {
24:          // TODO code application logic here
25:          new NNStrings();
26:      }
27:  }

4.9 Substitution Cipher

In a simple substitution cipher, A =1 , B=2, C=3 etc. Write a method that encodes a sentence using this cipher

4.9.1 Solution

 1:  public class NNStrings {
 2:
 3:      NNStrings()
 4:      {
 5:          System.out.println(encode("Hello World"));
 6:      }
 7:      String encode(String s)
 8:      {
 9:          String encoding = "";
10:          s=s.toLowerCase();
11:          String [] words = s.split("\\s+");
12:          for (String word : words)
13:          {
14:              for(int i = 0; i<word.length() - 1 ; i++)
15:              {
16:                  encoding = encoding + ((int)word.charAt(i)-96) + ",";
17:              }
18:              encoding = encoding + ((int)word.charAt(word.length()-1)-96) + " ";
19:          }
20:
21:          return encoding;
22:      }
23:
24:      public static void main(String[] args) {
25:          // TODO code application logic here
26:          new NNStrings();
27:      }
28:  }

4.10 Decoder

Write a decoder method for your substitution Cipher

4.10.1 Solution

 1:  public class NNStrings {
 2:
 3:      NNStrings()
 4:      {
 5:          System.out.println(decode("9 14,5,22,5,18 19,1,23 1 16,21,18,16,12,5 3,15,23"));
 6:      }
 7:
 8:      String decode(String s)
 9:      {
10:          String decoding = "";
11:          String [] words = s.split("\\s+");
12:          for (String word : words)
13:          {
14:              String [] codes = word.split(",");
15:              for (String code: codes)
16:              {
17:                  int c = Integer.parseInt(code.trim());
18:                  decoding = decoding + (char)(c+96);
19:              }
20:              decoding = decoding + " ";
21:          }
22:          return decoding;
23:      }
24:
25:      public static void main(String[] args) {
26:          // TODO code application logic here
27:          new NNStrings();
28:      }
29:  }

4: Strings

4.1 Count Words

Write a method that returns the number of words in a String

4.1.1 Example

1:  String s = "I never saw a purple cow"
2:
3:  System.out.println(countWords(s));
4:   *** Output ***
5:  6

4.2 Count the letter ‘e’

Write a method that counts the instances of the letter ‘e’ in a string.

4.2.1 Example

1:  String s = "I never saw a purple cow"
2:
3:  System.out.println(countEs(s));
4:   *** Output ***
5:  3

4.3 Count Alphanumerics

Write a method that returns the number of alphanumeric characters (A-Z, a-z and 0-9) in a string.

4.3.1 Example

1:  String s = "1984 by George Orwell."
2:
3:  System.out.println(countChars(s));
4:   *** Output ***
5:  18

4.4 Reverse String

Write a method that returns a string, reversed

4.4.1 Example

1:  String s = "I never saw a purple cow"
2:
3:  System.out.println(reverse(s));
4:   *** Output ***
5:  woc elprup a was reven I

4.5 Palindromes

Write a method to test if a string is a Palindrome

4.5.1 Example

1:  String sentence = "I never saw a purple cow"
2:  String palindrome = "rotavator"
3:
4:  System.out.println(isPalindrome(sentence));
5:  System.out.println(isPalindrome(palindrome));
6:   *** Output ***
7:  False
8:  True

4.6 More Palindromes

Write an improved palindrome method that will disregard spaces, punctuation and case and thus recognise sentences such as “A man, a plan, a canal, Panama!” as a palindrome.

4.6.1 Example

1:  String s = "I never saw a purple cow"
2:  String p = "Rise to vote, Sir!"
3:
4:  System.out.println(isPalindrome(s));
5:  System.out.println(isPalindrome(p));
6:   *** Output ***
7:  False
8:  True

4.7 Remove v*w*ls

Write a method that will replace the vowels in a word with asterisks

4.7.1 Example

1:  String s = "I never saw a purple cow"
2:
3:  star(s)
4:   *** Output ***
5:   * n*v*r s*w * p*rpl* c*w

4.8 Spell Out

Write a method to spell out words so that, for example, This becomes T-H-I-S.

4.8.1 Example

1:  String s = "I never saw a purple cow"
2:
3:  spellOut(s)
4:   *** Output ***
5:  I N-E-V-E-R S-A-W A P-U-R-P-L-E C-O-W

4.9 Substitution Cipher

In a simple substitution cipher, A =1 , B=2, C=3 etc. Write a method that encodes a sentence using this cipher

4.9.1 Example

1:  String s = "Hello World"
2:
3:  encode(s)
4:   *** Output ***
5:  8,5,12,12,15 23,15,18,12,4

4.10 Decoder

Write a decoder method for your substitution Cipher

4.10.1 Example

1:  String s = "9 14,5,22,5,18 19,1,23 1 16,21,18,16,12,5 3,15,23"
2:
3:  decode(s)
4:   *** Output ***
5:  i never saw a purple cow

– Array Solutions

3 Array Solutions

3.1 Print Array

Write a method that prints out a string array, one element per line

3.1.1 Solution

    public class NNArrays {
    NNArrays()
    {
        String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
        printArray(breakfast);
        //Alternative Method
        printArrayAlt(breakfast);
    }
    void printArray(String [] array)
    {
        for(int i = 0; i<array.length; i++)
        {
            System.out.println(array[i]);
        }
    }
    //Alternative method using for each loop
    void printArrayAlt(String [] array)
    {
        for(String s: array)
        {
            System.out.println(s);
        }
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.2 Last Element of Array

Write a method that returns the last element of a string array

3.2.1 Solution

    public class NNArrays {
    NNArrays()
    {
        String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
      System.out.println(lastElement(breakfast));
    }
    String lastElement(String [] array)
    {
        return array[array.length-1];
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.3 Last But One Element of Array

Write a method that returns the last but one element of a string array

3.3.1 Solution

    public class NNArrays {
    NNArrays()
    {
        String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
        //Added two extra arrays for testing
        String [] coin = {"Heads", "Tails"};
        String [] lonely = {"solo"};
        System.out.println(lastButOne(breakfast));
        System.out.println(lastButOneSafer(breakfast));
        System.out.println(lastButOneSafer(coin));
        System.out.println(lastButOneSafer(lonely));
    }
    String lastButOne(String [] array)
    {
        return array[array.length-2];
    }
    // The previous method will throw an
    // arrayIndexOutOfBoundsException for arrays of length <2.
    // This method will return an empty string if length <2
    String lastButOneSafer(String [] array)
    {
        if (array.length<2)
        {
            return "";
        }
        else
        {
            return array[array.length-2];
        }
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.4 Reverse an Array

Write a method that returns elements of an Array in reverse order

3.4.1 Solution

    public class NNArrays {
    NNArrays()
    {
        String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
        //Added two extra arrays for testing
        String [] coin = {"Heads", "Tails"};
        String [] lonely = {"solo"};
        printArray(reverse(breakfast));
        printArray(reverse(coin));
        printArray(reverse(lonely));
    }
    void printArray(String [] array)
    {
        for(int i = 0; i<array.length; i++)
        {
            System.out.println(array[i]);
        }
    }
    String [] reverse(String [] array)
    {
        for(int i = 0; i<array.length/2;i++)
        {
            String temp = array[i];
            array[i] = array[array.length-i-1];
            array[array.length-i-1] = temp;
        }
        return array;
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.5 Palindromic Arrays

Write a method that tests to see if an array is palindromic, i.e. the elements are the same when reversed.

3.5.1 Solution

    public class NNArrays {
    NNArrays()
    {
        String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
        String [] lonely = {"solo"};
        String [] palindromic = {"Sausage", "Eggs", "Beans",
                                 "Beans", "Eggs", "Sausage"};
        System.out.println(isPalindrome(palindromic));
        System.out.println(isPalindrome(breakfast));
        System.out.println(isPalindrome(lonely));
    }
    boolean isPalindrome(String [] array)
    {
        boolean isPal = true;
        for (int i = 0; i<array.length/2; i++)
        {
            if (!array[i].equals(array[array.length -i -1]))
                isPal = false;
        }
        return isPal;
    }
    // The following method doesn't work.
    // Need to compare individual elements
    boolean isPalindromeWrong(String [] array)
    {
        if (array.equals(reverse(array)))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    String [] reverse(String [] array)
    {
        for(int i = 0; i<array.length/2;i++)
        {
            String temp = array[i];
            array[i] = array[array.length-i-1];
            array[array.length-i-1] = temp;
        }
        return array;
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.6 Consecutive Duplicates

Write a method to print out an int array with consecutive duplicates eliminated

3.6.1 Solution

    public class NNArrays {
    NNArrays()
    {
        int [] nums = {1,1,3,3,3,2,2,2,1,1,1,1,4,4,4,4};
        int [] num2 = {1,1};
        int [] num1 = {1};
        compress(nums);
        compress(num2);
        compress(num1);
    }
    void compress(int [] array)
    {
        System.out.println(array[0]);
        for (int i = 1; i<array.length; i++)
        {
            if (array[i]!=array[i-1])
            {
                System.out.println(array[i]);
            }
        }
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.7 Pack Duplicates

Pack consecutive duplicates of a char array into Strings

3.7.1 Solution

    public class NNArrays {
    NNArrays()
    {
        char [] letters = {'a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'};
        pack(letters);
    }
    void pack(char [] array)
    {
        String s = Character.toString(array[0]);
        for(int i = 1; i<array.length; i++)
        {
            if(array[i] != array [i-1])
            {
                System.out.print(s+ ", ");
                s = Character.toString(array[i]);
            }
            else
            {
                s = s + array[i];
            }
        }
        System.out.println(s);
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3: Arrays

3.1 Print Array

Write a method that prints out a string array, one element per line

3.1.1 Example

 1:  String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
 2:
 3:  printArray(breakfast)
 4:   *** Output ***
 5:  Sausage
 6:  Eggs
 7:  Beans
 8:  Bacon
 9:  Tomatoes
10:  Mushrooms

3.2 Last Element of Array

Write a method that returns the last element of a string array

3.2.1 Example

1:  String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"}
2:
3:  System.out.println(lastElement(breakfast));
4:   *** Output ***
5:  Mushrooms

3.3 Last But One Element of Array

Write a method that returns the last but one element of a string array

3.3.1 Example

1:  String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"}
2:
3:  System.out.println(lastButOne(breakfast));
4:   *** Output ***
5:  Tomatoes

3.4 Reverse an Array

Write a method that reverses the elements of an Array

3.4.1 Example

 1:  String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
 2:
 3:  System.out.println(reverse(breakfast));
 4:   *** Output ***
 5:  : Mushrooms
 6:  : Tomatoes
 7:  : Bacon
 8:  : Beans
 9:  : Eggs
10:  : Sausage
11:  : Tails

3.5 Palindromic Arrays

Write a method that tests to see if an array is palindromic, i.e. the elements are the same when reversed.

3.5.1 Example

1:  String [] palindromic = {"Sausage", "Eggs", "Beans", "Beans", "Eggs", "Sausage"};
2:  String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"}
3:
4:  System.out.println(isPalindrome(palindromic));
5:  System.out.println(isPalindrome(breakfast));
6:   *** Output ***
7:  True
8:  False

3.6 Consecutive Duplicates

Write a method to print out an int array with consecutive duplicates eliminated

 1:  int [] nums = {1,1,3,3,3,2,2,2,1,1,1,1,4,4,4,4};
 2:
 3:  compress(nums)
 4:   *** Output ***
 5:  : 1
 6:  : 3
 7:  : 2
 8:  : 1
 9:  : 4
10:  : 1
11:  : 1
12:

3.7 Pack Duplicates

Pack consecutive duplicates of a char array into Strings

1:  char [] letters = {'a' 'a' 'a' 'a' 'b' 'c' 'c' 'a' 'a' 'd' 'e' 'e' 'e' 'e'};
2:
3:  pack(nums)
4:   *** Output ***
5:  : aaaa, b, cc, aa, d, eeee
6: