You are on page 1of 15

University of KwaZulu-Natal

Pietermaritzburg Campus
Examinations

Computer Programming
COMP102P1
MODEL ANSWERS
Date:
Wednesday, 11th November, 2009.

Examiners:
Hugh Murrell and Deshendran Moodley

time limit: 3 hours

max marks: 100

This paper consists of EIGHT pages, excluding this one.


The last page is the API for the String class.
Make sure that no pages are missing.
Candidates may attempt all questions.

Write your answers in the GREEN book


Use the TURQUOISE book for rough work

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

Section 1: Methods
Question 1.1
Study the following Java program and write down the output it would generate.

public class Buzz {


public static void baffle (String blimp) {
System.out.println(blimp);
zippo ("ping", -5);
}
public static void zippo (String quince, int flag) {
if (flag < 0) {
System.out.println (quince + " zoop");
} else {
System.out.println("ik");
baffle (quince);
System.out.println ("boo-wa-ha-ha");
}
}
public static void main (String[] args) {
zippo ("rattle", 13);
}
}
[5]

ik
rattle
ping zoop
boo-wa-ha-ha

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

Question 1.2
Write a Java method, uniqueChars, that takes a string as input and returns a string containing one of each character occurring in the input string. The ordering of the characters
in the returned string does not matter.
For example uniqueChars("mississippi") should return "misp".

public static String uniqueChars(String s){


String r = "";
for (int i=0; i<s.length();i++){
boolean in=false;
for (int j=0; j<r.length();j++){
if(s.charAt(i)==r.charAt(j))in=true;
};
if(!in)r=r+s.charAt(i);
}
return r;
}

[10]

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

Question 1.3
A string is said to be a doubloon if every letter that appears in the string appears exactly
twice. For example, the following strings are all doubloons:
abba, anna, appall, appearer, appeases, arraigning, beriberi,
bilabial, boob, caucasus, coco, dada, deed, emmett, hannah,
horseshoer, intestines, isis, mama, mimi, murmur, noon, otto, papa,
peep, reappear, redder, sees, shanghaiings, toto
Write a method called isDoubloon that returns true if the given string is a doubloon and
false otherwise. You may assume that all the characters in the input string are alphabetic
and lower case.
[10]

public static boolean isDoubloon(String s){


String r=uniqueChars(s);
for(int i=0; i<r.length(); i++){
int c=0;
for(int j=0; j<s.length(); j++){
if(r.charAt(i)==s.charAt(j))c++;
}
if(c!=2) return false;
}
return true;
}

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

Section 2: Arrays
Question 2.1
What output will be produced by the following code:
double[] data = { 8.0, 10.0, 14.0, 10.0, 8.0 };
double[] smoothed = new double[data.length];
int d = data.length-1;
smoothed[d] = data[d];
for (int i = 0; i < d; i++){
smoothed[i] = 0.5*(data[i]+data[i+1]);
System.out.print(smoothed[i]+" , ");
}
System.out.println(smoothed[d]);
[5]

9.0 , 12.0 , 12.0 , 9.0 , 8.0

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

Question 2.2
Write a Java method named areFactors that takes a positive integer, n and an array of
positive integers, and returns true if all the numbers in the array are factors of n otherwise
it returns false.
For example:
int[] f = {2,3,9};
System.out.println(areFactors(54, f))
should print true.
Also write down what your method would return if the passed array was empty and explain
in English whether or not this result is acceptable.
[10]

public static boolean areFactors(int n, int[] facs){


for(int i=0; i<facs.length; i++){
if ((n%facs[i])!=0) return false;
}
return true;
}

areFactors(54,{2,3,9}) returns true


areFactors(54,{2,5,9}) returns false
areFactors(54,{}) returns true
because everything in the list is a factor of 54.

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

Question 2.3
Shown below are the first 7 rows of Pascals triangle in which each element (apart from
the 1s) is obtained by summing the two elements above.

1
1
1
1
1
1
1

2
3

4
5

6
10

15

1
3

1
4

10
20

1
5

15

1
6

a) Write a Java method, nextRow, that given an array of integers representing one row
of Pascals triangle will return an array of integers representing the next row down.
For example:
int[] r = {1, 4, 6, 4, 1};
int[] nr = nextRow(r);
for(int i=0; i<nr.length; i++) System.out.print(nr[i]+" ");
System.out.println();
should print: 1, 5, 10, 10, 5, 1.

public static int[] nextRow(int[] row){


int[] next = new int[row.length+1];
next[0]=1;
for(int i=1; i<row.length; i++){
next[i]=row[i-1]+row[i];
}
next[next.length-1]=1;
return next;
}

[10]

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

b) Write a Java method, sumOfPascalRows, that given an integer n will return the sum
of all the elements in the first n rows of Pascals triangle.
[10]

public static int sumOfPascalRows(int n){


int p=1;
for (int i=1; i<=n; i++) p=p*2;
return p-1;
}

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

Section 3: Recursion
Question 3.1
The Catalan numbers are a sequence of positive integers defined recursively by:

C0 = 1

and

Cn =

n1
X

Ck Cn1k

for

n > 0.

k=0

a) Write down the first 6 Catalan numbers.

[3]

1 1 2 5 14 42

b) Write a recursive Java method called Catalan such that Catalan(n) returns the
Catalan number, Cn .
[7]

public static int Catalan(int n){


if (n==0) return 1;
int cat=0;
for(int k=0; k<=n-1; k++){
cat=cat+Catalan(k)*Catalan(n-1-k);
}
return cat;
}

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

Question 3.2
Write a recursive method called sumOfBits that takes a positive integer as input and
returns a positive integer as output. The output should be the sum of the bits in the
binary representation of the input.
For example:
sumOfBits(6)
sumOfBits(7)
sumOfBits(8)

should return
should return
should return

2
3
1
[5]

public static int sumOfBits(int n){


if (n<=0) return 0;
return n%2 + sumOfBits(n/2);
}

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

Section 4: Object Oriented Programming


Consider the game of BattleShips played on a n m grid. (That is n rows by m columns).
The following Java code outlines a BattleShips class in which a constructor and a display
method are provided in full.
public class battleShipGrid {
char[][] grid;
// grid positions
int nR;
// number of rows
int nC;
// number of cols
// constructor
public battleShipGrid(int r, int c){
nR=r;
nC=c;
grid = new char[nR][nC];
for(int i=0; i<nR; i++){
for(int j=0; j<nC; j++){
grid[i][j]=.;
}
}
}
// display the grid
public void showGrid(){
for(int i=0; i<nR; i++){
for(int j=0; j<nC; j++){
System.out.print(grid[i][j]);
}
System.out.println();
}
}
}

10

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

11

Question 4.1
You will notice that in the constructor all grid positions are empty as represented by
the . character. Write a method for the battleShipGrid class that will populate your
battleship grid with n ships. Ships are represented by the $ character and are placed at
random points on the grid. Use the method signature provided below.
public void populateGrid(int n){
// your code goes here
if (n<0 || n> nR*nC){
System.out.println("error: invalid no of ships requested -> "+n );
System.exit(0);
}
int count=0;
while(count<n){
int row = (int) (Math.random()*nR);
int col = (int) (Math.random()*nC);
// System.out.println(row+","+col+"->"+grid[row][col]);
if (grid[row][col]==.){
grid[row][col]=$;
count++;
}
}

}
[10]

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

12

Question 4.2
Write a method for the battleShipGrid class that will kill all ships on the grid within a
radius d of an explosive epicenter (r, c). Killed ships are represented by the # character.
Use the method signature provided below.
public void killShips(int r, int c, int d){
// your code goes here
for(int i=0; i<nR; i++){
for(int j=0; j<nC; j++){
if (grid[i][j]!=. && (r-i)*(r-i)+(c-j)*(c-j) < d*d){
grid[i][j]=#;
}
}
}
}
[10]

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

13

Question 4.3
Write down a code snippet for a Java application that:
creates a battleship grid of 11 rows and 21 columns,
populates the grid with 50 ships
sinks all ships within a radius of 4 units from the center of the grid.
displays the grid showing both sunk and surviving ships
[5]

battleShipGrid bsg = new battleShipGrid(11,21);


bsg.showGrid();
bsg.populateGrid(50);
bsg.showGrid();
bsg.killShips(6,11,4);
bsg.showGrid();

UKZN (pmb campus) Examinations: November 2009.


Computer Programming (COMP102)

String API

14

You might also like