CS2 Practical 1 Basic Java Programming The purpose of this practical is to re-enforce your Java programming abilities. The practical is based on material covered in CS1. It consists of ten simple programming exercises, which you should be able to solve without much effort (the exercises do vary in difficulty). It is crucial that you write code that compiles and runs without producing any errors and that EXACTLY meets the specifications. Your code should not output anything in addition to the specified output. Your submissions will be marked by an automatic marking program. The program will fail any submissions that do not behave exactly as required. It is important to realise that you only get marks for code that compiles and runs correctly; this will be the case for all practicals in CS2 (although marking arrangements for the rest of the practicals will be different). The practical consists of three parts. Part A contains four problems, and Parts B and C each contains three problems. Each of the ten problems is worth 10 marks. The solution to each of the problems consists of one Java file (which you must create from scratch; there are no templates associated with this practical). The name of this file is specified at the end of the problem; take care that the file you submit has exactly the right name. To submit your solution to one of the problems, use the command handin P1 for example filename handin P1 Add.java The deadlines for submitting the problems in each of the three parts are: Wednesday 29 September, 11.00am for Part A, Monday 4 October, 11.00am for Part B, Monday 11 October, 11.00am for Part C. Of course, you may submit your answers to some or all of the problems earlier. The total mark out of 100 is also allocated a grade according to the University marking scale:! This is the first of the four practicals in CS2A. Each practical is worth equal credit, and the four together make up 25% of the final mark for CS2A. Remember that you will need at least a grade C (i.e. at least 50%) in your final CS2 mark 1
( CS2 Practical 1 CS2A 22/09/2004 to proceed to any of the Computer Science or Software Engineering single or joint Honours degree courses. You should also bear in mind the guidelines on plagiarism, which can be found via a link on the CS2 Web page. Note: Programs should send output to standard output (stdout), and not to the standard error stream (stderr). Part A Problem 1: Addition Write a Java program Add which takes two integers as command line arguments and outputs the sum of these integers. For example, the command java Add 3 5 should generate the output: 8 Trailing spaces and new-lines after the number is outputted will not cause the test to fail. The file you submit should be called Add.java. Problem 2: Latin Square A Latin square of size " is an "$#" array of numbers where each of the numbers %'&( )* (+"-, appears only once in each row and column. The easiest )* way to produce such a square is for the first row to be & " and for each row after that to be obtained by cycling the previous row by one place to the left. Write a program Latin which takes an integer as a command line argument and outputs such a Latin square of size specified by the integer. For example, the command java Latin 10 2
should produce the output: 1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 1 3 4 5 6 7 8 9 10 1 2 4 5 6 7 8 9 10 1 2 3 5 6 7 8 9 10 1 2 3 4 6 7 8 9 10 1 2 3 4 5 7 8 9 10 1 2 3 4 5 6 8 9 10 1 2 3 4 5 6 7 9 10 1 2 3 4 5 6 7 8 10 1 2 3 4 5 6 7 8 9 Leading and trailing empty lines will not cause the test to fail, nor will spaces at the beginnings and ends of lines. Within each line, there should be just one space character between adjacent numbers. The file you submit should be called Latin.java. Problem 3: Broken Stack The following Java class IntStack implements a Stack data structure for storing integers. It supports the following public methods: IntStack() (constructor): Creates a new empty stack. isempty(): Returns false if the stack stores at least one element and true otherwise. push(int elt): Inserts elt into the stack. pop(): Returns the element of the stack that has been inserted most recently. If the stack is empty, it throws an EmptyStackException. public class IntStack { private class StackItem { int elt; StackItem next; public StackItem(int elt, StackItem next) { this.elt = elt; this.next = nxt; private StackItem top; public IntStack() { top = null; 3
public boolean isempty() { return ( top == null ); public void push(int elt) { top = new StackItem(elt,top); public int pop() throws java.util.emptystackexception { int elt = top.elt; top = top.next; if ( isempty() ) throw new java.util.emptystackexception(); else return elt; Unfortunately, the implementation is faulty. Correct it and submit the corrected code. You may obtain an online copy of the above faulty code from the CS2A Practicals page. The file you submit should be called IntStack.java. Problem 4: Letter Diamonds Write a program Diamond which takes a small integer as a command line argument and produces a letter diamond of that size. For example, the command java Diamond 4 should produce the following output: a b c d e f g h i j k l m n o p After the letters a - z have been used, the program should continue using the letters A - Z, and then a - z and so on. 4
The line with just the a character should be the first line of the output, and the longest line should be left-justified. Within each line, there should be just one space between adjacent letters. Leading and trailing empty lines will not cause the test to fail, nor will spaces at the ends of lines. Incorrect spacing at the beginnings of lines will, however, cause the test to fail. The file you submit should be called Diamond.java. Part B Problem 5: Random Pairs Write a program Pairs which takes a list of names from a file specified as a command line argument, with one name per line of the file, and groups them into random pairs, outputting the allocation to standard output. The elements of each pair should be separated by the word and, and if there are an odd number of names, the last remaining name should be output on its own. For example, the following input: Rob Lucy Rebecca Peter Jane should produce output such as: Rob and Rebecca Peter and Lucy Jane (You need not take account of gender in the way you pair people up!) This exercise will be marked by running the program several times and checking that the output each time is a pairing of the provided names, and that it doesn t produce the same output every time it is run. The file you submit should be called Pairs.java. Problem 6: a Extraction Write a Java program AWords that reads a text file, extracts all words containing the letter a (both lowercase and uppercase a s count) from the text, and prints them to the standard output in the order in which they appear. If the same word appears several times in the text, it should be printed several 5
times. The name of the text file is given to the program as a command line argument. For example, suppose we have a text-file foo that contains the following text: AWords is a program that finds all words containing the first letter of the alphabet. Then the command java AWords foo should generate the output AWords a program that all containing alphabet The tests will not involve any punctuation symbols. The test files only contain alphanumeric characters, spaces and new-lines. The file you submit should be called AWords.java. Problem 7: Counting Distinct Words Write a Java program UniqCount which reads a text file containing a list of words in alphabetical order and writes to standard output the number of distinct words in the file. The file may contain more than one word on each line. The name of the text file is given to the program as a command line argument. For example, suppose we have a text-file words that contains the following text: consecutive dual dual multiple multiple multiple unique unique word Then the command java UniqCount words should generate the output 5 6
. &. # 8 / & : # 8 / # & : # 0 CS2 Practical 1 CS2A 22/09/2004 as there are five distinct words: consecutive, dual, multiple, unique and word. The test files will only contain alphanumeric characters, spaces and newlines. Trailing new-lines after the number is outputted will not cause the test to fail. The file you submit should be called UniqCount.java Part C Problem 8: Matrix Multiplication Write a Java class MatrixMult with a single public method: public int[][] multiply( int[][] A, int[][] B ) This method should multiply the integer matrices and and return the matrix product #. You may assume that and are square matrices of the same size. Here A[i][j] is the item in the i-th row and j-th column of the matrix A, and similarly for B and the result. The following is an example of a matrix multiplication: / &10. /2 03 &4# 657 =5 #98 /2 : #>8 /? :@ &!# ;5< ;5 The file you submit should be called MatrixMult.java. 03. A & Problem 9: Collections Write a Java class SortIntColl with a single public static method: public static Object[] sort(collection c) As the name says, a Java Collection is an object that contains a collection of other objects. 1 The method SortIntColl.sort expects a collection of Integer objects as input and returns an array that contains all Integers in the collection sorted in increasing order. The file you submit should be called SortIntColl.java. Hint: Use the method toarray() of the Collection interface and the method sort(object[]) of the Arrays class. See the Java API Specification for details. 1 Actually, Collection is just a Java interface that is implemented by various classes such as LinkedList. 7
Problem 10: Permutations (Harder!) Write a Java program Permutations which takes a word on the command line and outputs all permutations of the letters, one per line. Thus, the command java Permutations cat should output the following strings in some order: cat cta act atc tca tac Your program will only be tested on words in which none of the letters appear more than once, thus you can choose to include or exclude duplicates. You will probably find it easier to write a program that includes duplicates. Leading and trailing empty lines will not cause the test to fail, nor will spaces at the beginnings and ends of lines. The file you submit should be called Permutations.java. John Longley 8