Question 1A. Let Us Design A Class Bankaccount. A Bank Account Has An Account Number. The Bank
Question 1A. Let Us Design A Class Bankaccount. A Bank Account Has An Account Number. The Bank
The bank
gives each account a different, unique number. Each instance of this class maintains one account with an
owner, an account number and current balance.
Normally, the account numbers start with some +ve integer and keep on increasing as the new accounts
are created. We need a way to assign a new account number to each instance as it is created. A new
account can be created by giving the owner’s name and an initial amount.
Nobody should be able to manipulate instance variables directly. Methods must be provided to access (i)
name of the owner (ii) account number (iii) current balance, and (iv) deposit money in the account. [15]
class bankAccount{
private static int nextAccountNumber = 1; //next account number; It must be a static variable 2 marks
private String person; //the account owner; must be private 1 mark
private int number; //The account number; must be private 1 mark
private double balance; //the balance in the account; must be private 1 mark
//constructor method
bankAccount(String p, double b){
person = p; 1 mark
balance = b; 1 mark
number = nextAccountNumber; 1 mark
nextAccountNumber += 1; 2 marks
}
The method takes an integer and reverses it. However, it preserves the sign. For example -123 will
become -321.
class q2{
public static void main(String args[]){
double pi;
Random generator = new Random();
double x, y, dist; 2 marks for the declaration
int i,inCircle;
inCircle=0;
for (i=1; i<=1000000; i++){ 2 marks for the loop if the number of iterations are large
x = 2*generator.nextDouble(); 2 marks for the statement
y = 2*generator.nextDouble();
dist = Math.sqrt((x-1)*(x-1)+(y-1)*(y-1));
if (dist <= 1.0) inCircle += 1;
}
The two arrays are considered equal if both arrays contain the same number of elements, and all
corresponding pairs of elements in the two arrays are equal. Two objects e1 and e2 are considered
equal if (e1==null ? e2==null : e1.equals(e2)). In other words, the two arrays are equal if they contain
the same elements in the same order. Also, two array references are considered equal if both are null.
(Reference: Sun Java Docs)
Question 3b. A list of item names together with prices can be maintained in two arrays as follows:
Array items and prices are parallel arrays. If we have more data like weight of an item, price for buying
two items at a time, we would add more parallel arrays.
Is this a good strategy to maintain information? Justify your answer. If you do not like this style then
suggest an alternative and again justify your choice. [10]
/* Parallel arrays are fast to implement. However, 6 marks for giving reasons
* this in not a good programming style. At least two reasons must
* 1. Methods which operate on the parallel arrays be given
* must have all the arrays as parameters.
* 2. A method which deals with just one item must
* be passed all the corresponding elements.
* 3. Once a program has been written, it will be very
* difficult to change if a new parallel array containing
* a new property has to be added.
* 4. There is always a danger of accessing items using
* an index variable and its properties using another
* index variable.
*
* define a class whose instances are items and their 3 marks for giving solution
* associated properties.
*/
class item { 1 mark for the code
//name and properties of items
private String item;
private double price;
Is this method correct (there are no compilation errors!)? If not then show the errors with the help of an
example and correct them. [8]
class q4a{
public static int bsrch(int a[], int key) {
int left = 0;
int right = a.length -1;
int mid;
while (left < right) {
mid = (left + right)/2;
if (a[mid] == key) return mid;
if (a[mid] < key) left = mid+1;
else right = mid -1;
}
return -1;
}
Case when relational operator is < 4 marks for identifying the error with an example
Assume that a is {1,3} and key is 3
left=0, right=1, mid=0 a[mid] =1 which is < 3 therefore left=1
Now condition left<right is false and the method returns -1 which is wrong
Case when relational operator is <= 4 marks for correcting error and showing that it works
Again assume that a is {1,3} and key is 3
left=0, right=1, mid=0 a[mid]=1 which is < 3 therefore left=1
condition left<=right is true; therefore, mid=1
a[1]=3 which is same as key, therefore return 1 which is the correct answer
Question 4b. Modify the program so that it returns the left most occurrence of the key in the array in
case there are duplicate elements. Describe your algorithm.[12]
if (a[right] == key) return right; //return index if cannot find any more left occurrences 3 marks
else return -1; //return with failure otherwise
}
Question 5. We had discussed the tower of Hanoi problem. A programmer has modified our algorithm
and has produced the following recursive method:
public static void shift(int n, char source, char target, char using){
int mid;
if (n==0) return;
if (n==1) System.out.println(source+" -> "+target);
else if (n > 1) {
mid=n/2;
shift(n-mid,source,using,target);
shift(mid,source,target,using);
shift(n-mid,using,target,source);
}
}
Does it produce the desired moves? Justify your answer. How many and what moves does it generate for
3 and 4 disks respectively? [20]
This does not produce correct results. Assume a case of 4 disks d1, d2, d3, d4 (with d1 being the largest
and d4 being the smallest), and the three sticks A, B and C.
First recursive call to method shift will be shift(2,A,B,C) which will shift d3, d4 to B
Then it will call shift(2,A,C,B) which will attempt to shift d1,d2 from A to C.
However, in this process it will have to make moves: move d2 from A to B, move d1 from A to C, move
d2 from B to C.
This leads to wrong configuration because after the first move (described in the above line) stick B will
have d3 at the bottom, d4 in the middle and d2 on the top. As d2 is larger than d4 the configuration is
incorrect. 10 marks for explanation
Question 6. We have used string rotation for encryption. Let us again attempt to left rotate characters of
a string s by a number n. Assume that value of n <= s.length().
We are given a method public static String reverse(String s, int start, int end)
which reverses substring of s between indices start and end (both inclusive). For example
reverse(“abcdef”,1,3) returns “adcbef”. Write a method which rotates a string using the reverse method.
Give brief justification for your solution. Complete the method rotate.
The key to the solution is to realize that left rotation of a string of length m by n places
is equivalent to splitting the string in substrings of length n and length m-n and changing their order.
For example, if we have a string s=”abcdefghij” of length 10 and wish to left rotate it by 3 places then it
can be split into two substrings of length 3 which gives “abc” and length 7 which gives “defghij” and
changing their order in the original string which gives “defghijabc”
class FindMaxFreq{
public static int FindMaxOccur(int [] A){
int max_count = 1, max_elem = A[0];
int i, count=1;
Grading scheme
Use of another array: No credit
Using more than n comparisons
(that means you are not using the fact that arrays are sorted): 2 marks
Correct solution with n comparisons: 10 marks
Not correct solution but in the right direction (you will get partial credit): maximum 6 marks
Question 7b. All arithmetic expressions require that parenthesis be properly balanced. The number of
the left and the right parenthesis should be equal, and there must a matching right parenthesis for every
left parenthesis.
Give a method which will check whether parentheses in an expression are well formed. What data
structure will you use for solving this problem? You do not have to write Java program. It is sufficient
to describe the method. [10]
A stack can be used to find out if the parenthesis in an expression is well formed or not
class q7b{
public static void main(String args[]){
Stack x = new Stack(100);
String s = "(()()()())";
char c,d;
int i=0;
while (i<s.length()){
c = s.charAt(i);
if (c == '(') x.push(c);
else if (c==')'){
if (x.isEmpty()){
System.out.println("More right parenthesis");
return;}
else
d=x.pop();
}
}
i++;
}
if (x.isEmpty())
System.out.println("balanced parenthesis");
else System.out.println("More left parenthesis");
}
}
Question 8a. Assume a string which contains only digits and blanks. It can have both leading and
trailing blanks. An example is “ 134 12 1 0 21 “.
We wish to extract all the integer numbers out of this string and print them. For example, in this case we
will extract 134, 12, 1, 0, and 21.
Describe in English and/or Java how you will achieve this objective. [10]
/*
while string has non blank characters 10 marks if the description/code is correct.
- remove the blanks from the begining of the string Ignore minor syntactic errors in the code
- add a blank character at the end of the string
to ensure that the string ends in a blank
- find index i of the first blank in the string
- convert s[0..i-1] into a string and store in n
- print n
- remove s[0..i-1] from s
*/
class q1b{
public static void main(String args[]){
String s = " 134 12 1 0 21 ";
while (s.length() > 1){
s = s.trim();
s = s + " ";
int i = s.indexOf(" ");
int n = Integer.parseInt(s.substring(0,i));
System.out.println(n);
s = s.substring(i);
}
}
}
Question 8b. Remember the Pascal’s Triangle?! It’s rows contain binomial coefficients. If you recall we
first generated this triangle by computing nCr. However, this method had very high time complexity. In
the second method we stored information in a 2-D array and did just additions to compute the
coefficients. This method was faster but required more storage. The code for the method is given below:
Can you modify this code to reduce storage requirement? Describe your strategy. [10]
class q2b{
public static int[][] PascalTriangle1(int n){
int a[][] = new int[n][n];
for (int i=0; i<n; i++){
a[i][0]=1;
for (int j=1; j<=i; j++)
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
return a;
}
We had written a program to find minimum and maximum elements of x. The relevant code fragment is
given below. Assuming x is filled with random numbers, how many comparisons does it take to find
min and max? Can you reduce the number of comparisons? If yes then describe your strategy and
modify the code. How many comparisons does the modified code take? [10]
Reduce comparisons
• If a number is max then it cannot be min. 5 marks
• If elements of x[] are randomly distributed then x[i]>max will fail 50% of the time. This will
require a second comparison in the else clause. Therefore, total number of comparisons will be
~1.5N instead of ~2N (N is size of the array) 3 marks
x= k c Î xk = c
k
f(x) = x - c = 0 4 marks
f’(x) = kxk-1
f ( xn )
Using Newton-Raphson method iterative equation xn+1 = xn - 3 marks
f ' ( xn )
xk − c
We get xn+1 = xn - 3 marks
k * x k −1