Java Code Snippets: History Class Implementation and Purchase Class Variations, Study notes of Computer Science

Several java code snippets related to the implementation of a history class and variations of a purchase class. The history class includes instance methods for adding purchases, finding minimum, maximum, average, number, and percentage of purchases based on cash status. The purchase class has different implementations, one using an integer list and another using an integer variable. The document also includes comments and explanations for each code snippet.

Typology: Study notes

Pre 2010

Uploaded on 08/16/2009

koofers-user-q8s
koofers-user-q8s 🇺🇸

10 documents

1 / 21

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Wellesley College CS111 Computer Programming and Problem Solving Spring 2003
FINAL EXAM REVIEW SOLUTIONS
This final draft contains solutions to all problems.
____________________________________________________________________________
Problem 1: Sales Statistics (Data Abstraction, Arrays, Lists, Objects, Object Diagrams)
Part a.
purchases
size
h
History
3
0 1 2 3 4
Purchas[ ]
amount
cash false
82 amount
cash true
53 amount
cash false
178
Purchase Purchase Purchase
Part b. Finishing the instance methods of the History class:
public class History {
// Instance Variables:
private Purchase [ ] purchases;
private int size;
// Constructor Method:
public History (int maxEntries) {
purchases = new Purchase[maxEntries];
size = 0;
}
// Instance Methods:
public void add (int amount, boolean cash) {
if (size < purchases.length) {
purchases[size] = new Purchase(amount, cash);
size = size + 1;
}
}
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15

Partial preview of the text

Download Java Code Snippets: History Class Implementation and Purchase Class Variations and more Study notes Computer Science in PDF only on Docsity!

Wellesley College ◊ CS111 Computer Programming and Problem Solving ◊ Spring 2003

FINAL EXAM REVIEW SOLUTIONS

This final draft contains solutions to all problems.

____________________________________________________________________________

Problem 1: Sales Statistics (Data Abstraction, Arrays, Lists, Objects, Object Diagrams)

Part a.

purchases

size

h

History

Purchas[ ]

amount

cash false

82 amount

cash true

53 amount

cash false

Purchase Purchase Purchase

Part b. Finishing the instance methods of the History class:

public class History {

// Instance Variables: private Purchase [ ] purchases; private int size;

// Constructor Method: public History (int maxEntries) { purchases = new Purchase[maxEntries]; size = 0; }

// Instance Methods: public void add (int amount, boolean cash) { if (size < purchases.length) { purchases[size] = new Purchase(amount, cash); size = size + 1; } }

public int size(){ return size; }

// min() and max() are instances of the general array accumulation idiom public int min(boolean cash){ int minVal = Integer.MAX_VALUE; // Positive infinity is identity of min for (int i = 0; i < size; i ++){ if (purchases[i].getCash() == cash){ minVal = Math.min(minVal, purchases[i].getAmount()); } } return minVal; }

public int max(boolean cash){ int maxVal = Integer.MIN_VALUE; // Negative infinity is identity of max for (int i = 0; i < size; i ++){ if (purchases[i].getCash() == cash){ maxVal = Math.max(maxVal, purchases[i].getAmount()); } } return maxVal; }

public int average(boolean cash){ int sum = 0; int count = 0; for (int i = 0; i < size; i++){ if (purchases[i].getCash() == cash){ sum = sum + purchases[i].getAmount(); count = count + 1; } } if (count == 0){ return 0; } else { return sum/count; } }

public int number (boolean cash){ int count = 0; for (int i = 0; i < size; i ++) { if (purchases[i].getCash() == cash){ count = count + 1; } } return count; }

public int percentage (boolean cash){ if (size > 0){ return (number(cash) * 100)/size; } else { return 0; } } }

2) Implement Purchase class with an integer list:

public class Purchase {

// Instance Variable private IntList sale;

// Constructor Method public Purchase (int i, boolean b) { sale = prepend(i, prepend(intToBool(b), empty())); }

// Instance Methods public int getAmount () { return head(sale); }

public void setAmount (int newAmount) { sale = prepend(newAmount, tail(sale)); }

public boolean getCash () { return (head(tail(sale)) == 1); }

public void setCash (boolean newCash) { sale = prepend(head(sale), prepend(intToBool(newCash), empty())); }

// Useful helper method private bool boolToInt (boolean b) { if (b){ return 1; } else { return 0; } } }

3) Implement Purchase class as a single positive or negative integer:

public class Purchase {

// Instance Variable private int sale;

// Constructor Method public Purchase (int i, boolean b) { sale = (sign(b)) * i }

// Instance Methods public int getAmount () { return Math.abs(sale); }

public void setAmount (int newAmount) { sale = sign(sale) * Math.abs(newAmount); }

public boolean getCash () { return (sale > 0); }

public void setCash (boolean newCash) { sale = sign(newCash) * Math.Abs(sale); }

// Useful helper method public int sign (boolean b) { if (b) { return 1; } else { return –1; } } }

Part f. Implement history with 3 instance variables: maxEntries, and two IntLists:

i.

ii. Implementation

public class History {

// Instance Variables: private int maxEntries; private IntList cashes; private IntList credits;

// Constructor Method: public History (int maxEntries) { this.maxEntries = maxEntries; cashes = empty(); credits = empty(); }

// Instance Methods: public void add (int amount, boolean cash) { if (length(cashes) + length(credits) < maxEntries) { if (cash){ cashes = prepend(amount, cashes); } else { credits = prepend(amount, credits); } } }

public int min (boolean cash){ if (cash) { return minOfList(cashes); } else { return minOfList(credits); } }

public int minOfList (IntList L){ if(isEmpty(L)){ return Integer.MAX_VALUE; } else { return Math.min(head(L), minOfList(tail(L))); } }

public int size () {return length(cashes) + length(credits);}

public int max (boolean cash) { //similar to min--left as exercise. }

public int average (boolean cash){ if (cash) { if (isEmpty(cashes) { return 0; } else { return sum(cashes)/length(cashes); } } else { if (isEmpty(credits) { return 0; } else { return sum(credits)/length(cashes); } } }

private int sum (IntList L) { if (isEmpty(L)) { return 0; } else { return head(L) + sum(tail(L)); } }

private int length (IntList L) { if (isempty(L)) { return 0; } else { return 1 + length(tail(L)); } }

public int number (boolean cash){ if (cash) { return length(cashes); } else { return length(credits); } }

public int percentage (boolean cash){ if (size() != 0){ if (cashes){ return length(cashes) * 100/size(); } else { return length(credits) * 100/size(); } } else { return 0; } } }

Part g. Left as exercise for the student.

Part c. Picture World

public Picture squares(int n, Color c1, Color c2) { if (n <= 0) { return empty(); }else { return fourPics(empty(), empty(), patch(c1), squares(n-1, c2, c1); } }

Part d. Java Graphics

public void squares (Graphics g, int n, int len, Color c1, Color c2) { int x = 0; int y = 0; while (n > 0) { g.setColor(c1); g.drawRect(x,y,len,len);

// Update state variables of iteration n = n – 1; x = x + len; y = y + len/2; len = len/2; // swap colors Color temp = c1; c1 = c2; c2 = temp; } }

________________________________________________________________________________

Problem 3: Greatest Common Divisor (Iteration)

Part a. Here is the iteration table for the iterative calculation of GCDTail(95,60).

A B

Part b.

public static int GCDWhile (int A, int B) { while (B != 0) { // Need a temporary variable to perform updates! // Could make a temp for either A or B; here we choose A. int oldA = A; A = B; B = oldA % B; } return A; }

Part c. It is always possible to express a while loop as a for loop, but the result may not be

particularly natural. Indeed, in this case it would not be natural to re-express Wyla's GCDTail

program as a for loop. For loops best “fit” cases where there is a state variable controlling the

number of times through the loop that is independent of other state variables. In the case of GCD,

the state variable B controls the number of times through the loop, suggesting the following

skeleton:

public static int GCDFor (int A, int B) { for (; B != 0; update ) { // No initialization of B necessary statements } return A; }

But what should replace update and statements? One approach is to leave update blank:

public static int GCDFor (int A, int B) { for (; B != 0;) { // No initialization of B necessary // Need a temporary variable to perform updates! int oldA = A; A = B; B = oldA % B; } return A; }

Indeed, for (; test ;) { statements } is always equivalent to while (test)

{statements}. But a for loop that is missing both its initialization and update statements is not

very compelling!

If we put B = A % B in the update position, then the A in A % B (which is executed after updates)

is the value of A after the assignment, when we want the value of A before the assignment. We

need a temporary variable to circumvent this problem, as shown below:

public static int GCDFor (int A, int B) { int oldA; for (; B != 0; B = oldA % B) { // No initialization of B necessary oldA = A; A = B; } return A; }

This method is less straightforward than the while loop, which is clearer and therefore preferred.

________________________________________________________________________________

Problem 6: Inheritance (Inheritance)

Statement Printout on Java Console System.out.println((new A()).m1()); 1 System.out.println((new B()).m1()); 3 System.out.println((new C()).m1()); 4 System.out.println((new D()).m1()); 5 System.out.println((new E()).m1()); 5

________________________________________________________________________________

Problem 7: Converting Betweeen Different Forms of Iteration (Lists, Arrays, Iteration)

Part a.

// Tail Recursion public static int weightedSum (IntList L) { return weightedSumTail (L, 1, 0); }

public static int weightedSumTail (IntList L, int index, int total) { if (isEmpty(L)) { return total; } else { return weightedSumTail(tail(L), index + 1, (index*head(L)) + total); } }

// While loop public static int weightedSumWhile (IntList L) { int index = 1; int total = 0; while (!isEmpty(L)) { total = total + (index*head(L)); index = index + 1; L = tail(L); } return total; }

// For loop public static int weightedSumFor (IntList L) { int index = 1; int total = 0; for (; !isEmpty(L); L = tail(L);) { total = total + (index*head(L)); index = index + 1; } return total; }

Part b.

// While loop public static boolean isMember (int n, int [] a) { int i = a.length - 1; while ((i >= 0) && (a[i] != n)) { i = i - 1; } return (i >= 0); // Will only be true if n is in a. }

// For loop public static boolean isMemberFor (int n, int [] a) { for (int i = a.length – 1; i>=0; i--) { if a[i] == n { return true; } } return false; }

// Tail recursion public static boolean isMemberIter (int n, int [] a) { return isMemberTail(n, a, a.length - 1); }

public static boolean isMemberTail (int n, int [] a, int i) { if (i < 0) { return false; } else if (a[i] == n) { return true; } else { return isMemberTail (n, a, i-1); } }

Part c.

// For loop public static void partialSum (int [] a) { int sum = 0; for (int i = 0; i < a.length; i++) { sum = sum + a[i]; a[i] = sum; } }

// While loop public static void partialSumWhile (int [] a) { int i = 0; int sum = 0; while (i < a.length) { sum = sum + a[i]; a[i] = sum; i++; } }

// Tail recursion public static void partialSumIter (int [] a) { return partialSumTail(a,0, 0); }

public static void partialSumTail (int [] a, int i, int sum) { if (i < a.length) { int newsum = sum + a[i]; a[i] = newsum; partialSumTail(a, i+1, newsum); } }

________________________________________________________________________________

Problem 9: Iterative List Reversal (Invocation Trees, Recursion, Iteration, Lists,)

Part a.

Part b.

Tail recursive solution:

public static IntList reverseIter (IntList L) { return reverseTail(L, IL.empty()); }

public static IntList reverseTail (IntList list, IntList result) { if (IL.isEmpty(list)) { return result; } else { return reverseTail(IL.tail(list), IL.prepend(IL.head(list), result)); } }

While loop solution:

public static IntList reverseWhile (IntList L) { IntList result = IL.empty(); while (! IL.isEmpty(L)) { result = IL.prepend(IL.head(L), result); L = IL.tail(L); } return result; }

For loop solution:

public static IntList reverseFor (IntList L) { IntList result = IL.empty(); for (;! IL.isEmpty(L); L = IL.tail(L)) // Note empty initializer result = IL.prepend(IL.head(L), result); } return result; }

________________________________________________________________________________

Problem 11: Bank Accounts (Data Abstraction, Lists)

Part a.

class Account {

private int savings; private int total;

public account () { this.savings = 0; this.total = 0; }

public int getSavings() {return this.savings;} public int getChecking() {return this.total – this.savings;} public int getTotal() {return this.total;}

public void depositToSavings(int amountToAdd) { this.savings = this.savings + amountToAdd; this.total = this.total + amountToAdd; }

public void transferFromSavingsToChecking(int transferAmount) { this.savings = this.savings - transferAmount; }

public void withdrawFromChecking(int withdrawalAmount) { this.total = this.total - withdrawalAmount; } }

Part b.

class Account {

private IntList accountInfo; // List of savings, checking, total

public account () {set(0,0,0);}

// Very useful helper method private set (int s, int c, int t) { accountInfo = IL.prepend(s, IL.prepend(c, IL.prepend(t IL.empty()))); }

public int getSavings() {return IL.head(accountInfo);} public int getChecking() {return IL.head(IL.tail(accountInfo));} public int getTotal() {return IL.head(IL.tail(IL.tail(accountInfo)));}

public void depositToSavings(int amount) { set(getSavings() + amount, getChecking(),getTotal() + amount); }

public void transferFromSavingsToChecking(int amount) { set(getSavings() – amount, getChecking() + ammount, getTotal()); }

public void withdrawFromChecking(int amount) { set(getSavings(), getChecking() – amount, getTotal() – amount); } }

___________________________________________________________________________

Problem 12: End Moves (Lists of Lists, Iteration, Recursion)

Part a.

left right ans [] [6,3,7,5] [] [6] [3,7,5] [[3,7,5,6]] [6,3] [7,5] [[3,7,5,6],[6,7,5,3]] [6,3,7] [5] [[3,7,5,6],[6,7,5,3],[6,3,5,7]] [6,3,7,5] [] [[3,7,5,6],[6,7,5,3],[6,3,5,7],[6,3,7,5]]

Part b.

public static endMovesWhile (IntList L) { IntList left = IL.empty(); IntList right = L IntList ans = ILL.empty(); while (! IL.isEmpty(right)) { ans = ILL.postpend(ans, IL.append(left, IL.postpend(IL.tail(right), IL.head(right)))); left = IL.postpend(left, IL.head(right)); right = IL.tail(right); } return ans; }

Part c. Below is an alternative iteration based on the strategy suggested by the table. Note that this

strategy replaces some of the calls to postpend() (which are expensive) with calls to prepend()

(which are cheap).

public static IntListList endMovesRevIter (IntList L) { return endMovesRevTail (IL.empty(), IL.reverse(L), ILL.empty()); }

public static IntListList endMovesRevTail (IntList back, IntList rev, IntListList ans) { if (IL.isEmpty(rev)) { return ans; } else { return endMovesRevTail (IL.prepend(IL.head(rev), back), IL.tail(rev), ILL.prepend(IL.append(IL.reverse(IL.tail(rev)), IL.postpend(back, IL.head(rev))), ans)); } }