## Saturday, December 11, 2010

I have just sent out the email with your final grades. As I mentioned in class, I gave a break to those who did very well on the final: I bumped them up a grade if they were close to the borderline. The final grade curve is as I described in class. Below is the distribution for the grades on the final test and the class as a whole.

Have a good xmas break! and, keep on programming!

## Tuesday, December 7, 2010

### Final Test

Below is the final. If you want your graded final (the paper itself) send me an email and I'll tell you when you can drop by and pick it up. I will email everyone their final grades when I'm done grading.

1. (10%) Implement a method that takes as an argument an integer `n` and then prints out the sum from 0 to 1, from 0 to 2,..., from 0 to n. For example, if you are given 10 then you will print out:
```1
3
6
10
15
21
28
36
45
55
```
```public static void gauss(int n) {
int sum = 0;
for (int i=1; i <= n; i++) {
sum += i;
System.out.println(sum);
}
}
```
2. (10%) Given the `Player` class below:
```public class Player {
public int strength;
public int defense;
public boolean magic;
}
```
implement a method ```public boolean winsAgainst(Player other)``` which returns true if the player can beat or tie `other` in a fight, false otherwise. The way you determine who wins in a fight is by following these rules:
1. If a player has `magic` and the other player does not then the player with `magic` wins if his `strength` + `defense` is greater than the other player's `defense`.
2. If both have `magic` then the one with the highest `defense` wins.
3. If neither has `magic` then the one with the highest `defense` + `magic` wins
```public boolean winsAgainst(Player other) {
if (magic && other.magic) {
return defense >= other.defense;
}
if (!magic && !other.magic) {
return (strength + defense) >= (other.defense + other.strength);
}
//exactly one of us has magic
if (magic) { //he does not have magic
return strength + defense >= other.defense;
}
//he has magic, I don't
return defense >= other.strength + other.defense;
}
```
3. (10%) What does the following program print out?
``` public static void flurberg(int x) {
if (x < 0) {
System.out.println("Turing");
return;
}
try {
int y = 10 / x;
System.out.println("VonNeuman");
}
catch (ArithmeticException e) { //division by 0 error
System.out.println("Babbage");
}
finally {
System.out.println("Lovelace");
}

}

public static void main(String[] args) {
flurberg(0);
flurberg(-1);
flurberg(1);
}
```
```Babbage
Lovelace
Turing
VonNeuman
Lovelace
```
4. (15%) In this problem you will implement a small class hierarchy to demonstrate that you understand OOP concepts. You will
1. Implement a class called `Present` that has a protected property called `name`, which is a String, and `shippingWeight`, which is an integer.
2. Implement a constructor for the `Present` which takes 2 arguments: `name` and shippingWeight, and sets the appropriate data members.
3. Implement a class called `BoardGame` which extends `Present` and has a property called `numPlayers` which is an integer and is protected.
4. Implement a 2-argument constructor for `Boardgame` with arguments `name` and `numPlayers`. All board games have a `shippingWeight = 16`. The constructor should call the parent constructor and set all property values appropriatedly.
5. Implement a class called `Clothing` which extends `Present` and has the property `size` which is a String.
```public class Present {
protected String name;

/**
* in ounces
*/
protected int shippingWeight;

public Present(String name, int shippingWeight) {
this.name = name;
this.shippingWeight = shippingWeight;
}
}
public class BoardGame extends Present {

protected int numPlayers;

public BoardGame(String name, int numPlayers) {
super(name, 16);
this.numPlayers = numPlayers;
}

}
public class Clothing extends Present {

protected String size;

public Clothing(String name, int shippingWeight, String size) {
super(name,shippingWeight);
this.size = size;
}

}
```
5. (15%) Implement a method that takes as input an array of Strings and returns the number of "sheep" in the array that appear before "zzzzz". For example:
• Given the array {"sheep", "fox", "sheep", "zzzzz"}, you return 2.
• Given the array {"fox", "fox", "zzzzz", "sheep"}, you return 0.
• Given the array {"sheep", "sheep", "sheep", "sheep"}, you return 4.
```public static int countSheepUntilDone(String[] words) {
int numSheep = 0;
for (String w : words) {
if (w.equals("sheep"))
numSheep++;
if (w.equals("zzzzz"))
return numSheep;
}
return numSheep;
}
```
6. (10%) The program shown below has one, and only one, compile-time error (which prevents this program from compiling). Write down which line has the error and explain why this is an error.
```public class FinalTest {

private String name;

private static final int numQuestions = 101;

public FinalTest(String name) {
this.name = name;
}

public String toString() {
return name + " " + FinalTest.numQuestions;
}

public static void setName(String name) {
this.name = name;
}

public static void main(String[] args) {
FinalTest NoNewbies = new FinalTest("neo");
System.out.println(NoNewbies);
NoNewbies.name = "Trinity";
}
}
```
```   public static void setName(String name) {
this.name = name;
}
```
is an error because a static method cannot access instance variables. I also accepted the answer that one could not set .name to "Trinity" because it is private. That answer is wrong because main is a method of FinalTest, but that is a more tricky question than I wanted to ask. I should have made name public.
7. (15%) The class
```public class Folder {
public Folder [] subFolders;
public int numFiles;
}
```
represents the folder hierachy in a computer filesystem. Where a folder can contain a number of files (given by `numFiles`) as well as a number of sub folders (stored in the `subFolders`) array. You will implement a recursive method for the `Folder` which returns the total number of files in the folder and all its sub-folders, sub-sub-folders, sub-sub-sub-folders, etc. For example, if the folder has numFiles=5 and has 2 subFolders each with numFiles=2 and no subFolders, then you will return 9 (that is, 5+2+2).
```public int totalFiles() {
if (subFolders == null || subFolders.length == 0) {
return numFiles;
}
int numFilesSubfolders = 0;
for (Folder f : subFolders) {
numFilesSubfolders += f.totalFiles();
}
return numFiles + numFilesSubfolders;
}
```
8. (15%) Implement the method `public static int countRepeats(int[] values)` which returns the number of numbers in `values` that appear more than once. Assume that all numbers in `values` are in the range 0 to 99 (inclusive). For example:
• Given the input array `values = {4,4,4,4,4,4}` you will return 1, as the number 4 is repeated more than once.
• Given `{1,2,3,4,95}` you will return 0 as no number is repeated.
• Given `{1,3,3,1,5}` you will return 2 as the numbers 1 and 3 are repeated.
```/**
* Counts the number of items in 'values' that appear more than once in values.
* Assume that 0 <= values[x] < 100
* @param values
* @return the number of
*/
public static int countRepeats(int[] values) {
int[] count = new int[100];//all set to 0 by default
for (int val : values) {
count[val]++;
}
int result = 0;
for (int val : count) {
if (val > 1) {
result++;
}
}
return result;
}
```

## Thursday, December 2, 2010

### Lab 23 -- Problem 3 -- Team Selection

```
Hi CSCE-145 Section 5 ... This is your Last Lab ... How about trying to do Problem 3
( TeamSelection Problem ) from the TopCoder's List of Programs.

```

## Tuesday, November 30, 2010

### Lab 22 -- Some More Programs

If you are done with the execution and understanding of the LinkedList Program, try to pick any problem from this list of topcoder problems and implement it.

MagicSpell was already implemented in lecture. You can see answer under the "Sample Programs" link, as usual.

### Lab 22 - LinkedList.java -- with Generics -- Fill in the Function Bodies

```
1) Remove the quotes. I had to put in order to get the E to print.
2) First Refer to the Book to Fill in the Similar Functions and then try yourself the non-similar ones

import java.util.ArrayList;

{

{

}

public void showList()

{

}

public int length()

{

}

{

}

{

}

public boolean onList(E target)
{

}

public ListNode<"E"> contains(E target)
{

}

public void addNodeAfterN(E theData, int n)
{

}

public void deleteAfterNodeN(int n)
{

}

public ArrayList<"E"> toArrayList()
{

}

}
```

### Lab 22 -- Driver.java -- Use this to Test

```
1) Remove the quotes round String and Record.

public class Driver {

public static void main(String[] args)
{
stringList.showList();

System.out.println("Is 'Hello' present: " + stringList.onList("Hello"));
System.out.println("Is 'Meeee' present: " + stringList.onList("Meeee"));

stringList.showList();

stringList.showList();

stringList.showList();

System.out.println("Item Deleted:");
stringList.deleteAfterNodeN(3);
stringList.showList();

System.out.println("Item Deleted:");
stringList.deleteAfterNodeN(3);
stringList.showList();

/* *********************************************** */

System.out.println(" ************************************************* ");

Record TomRecord = new Record("Tom", 12);

Record HarryRecord = new Record("Harry", 23);
RecordList.showList();

Record MyRecord = new Record("Me", 14);
System.out.println("Is 'TomRecord' present: " + RecordList.onList(TomRecord));
System.out.println("Is 'MyRecord' present: " + RecordList.onList(MyRecord));

Record Person1 = new Record("Person1", 12);
RecordList.showList();

Record Person2 = new Record("Person2", 30);
RecordList.showList();

Record Person3 = new Record("Person3", 33);
RecordList.showList();

System.out.println("Item Deleted:");
RecordList.deleteAfterNodeN(3);
RecordList.showList();

System.out.println("Item Deleted:");
RecordList.deleteAfterNodeN(3);
RecordList.showList();

}

}
```

### Lab 22 -- ListNode

```
1) Remove quotes around E.

public class ListNode<"E">
{
private E data;

public ListNode()
{
data = null;
}

{
data = newData;
}

public E getData() {
return data;
}

public void setData(E data) {
this.data = data;
}

}

}

}
```

### Lab 22 - Record Class

```
1) Remove quotes around Record

public class Record implements Comparable<"Record">
{
private String name;
private int age;

public Record()
{
this.setName("");
this.setAge(0);
}

public Record(String n, int a)
{
this.setName(n);
this.setAge(a);
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public int compareTo(Record that)
{
int returnValue;

returnValue = 0;

if(this.getName().compareTo(that.getName()) < 0)
{
returnValue = -1;
}
else if(this.getName().compareTo(that.getName()) > 0)
{
returnValue = +1;
}
else
{
if(this.getAge() < that.getAge())
returnValue = -1;
else if(this.getAge() > that.getAge())
returnValue = +1;
else
returnValue = 0;
}

return returnValue;
}

public String toString()
{
String s;
s = String.format("Name: %s , Age: %d" , this.getName(), this.getAge());
return s;
}

}
```

### Lab 22 - LinkedList with Generics -- Output

```
Good-Bye
Hello
Is 'Hello' present: true
Is 'Meeee' present: false
Good-Bye
That Me First Time
Hello
Good-Bye
That Me First Time
That Me Second Time
Hello
Good-Bye
That Me First Time
That Me Second Time
Hello
That Me 3rd Time
Item Deleted:
Good-Bye
That Me First Time
That Me Second Time
That Me 3rd Time
Item Deleted:
Good-Bye
That Me First Time
That Me Second Time
********************************************************
Name: Harry , Age: 23
Name: Tom , Age: 12
Is 'TomRecord' present: true
Is 'MyRecord' present: false
Name: Harry , Age: 23
Name: Person1 , Age: 12
Name: Tom , Age: 12
Name: Harry , Age: 23
Name: Person1 , Age: 12
Name: Person2 , Age: 30
Name: Tom , Age: 12
Name: Harry , Age: 23
Name: Person1 , Age: 12
Name: Person2 , Age: 30
Name: Tom , Age: 12
Name: Person3 , Age: 33
Item Deleted:
Name: Harry , Age: 23
Name: Person1 , Age: 12
Name: Person2 , Age: 30
Name: Person3 , Age: 33
Item Deleted:
Name: Harry , Age: 23
Name: Person1 , Age: 12
Name: Person2 , Age: 30

```

### Test 3 Averages

The averages for test 3 are shown below. As always, we will discuss about this and the final in class.

## Tuesday, November 23, 2010

### Lab test 3 - send your program to these email ids

jmvidal@gmail.com, shamik.usc@gmail.com, humayun.k1@gmail.com

### Lab Test 3 - section 6 - To do list

INPUT FILE FORMAT
(1) First Line : 10 -- Number of Items to be added to an ArrayList
(2) 10 Lines follow -- each line corresponds to data of an Item
Item Data Format :
--------------------------
Name;Color;Size;Price
(3) Line 12 : 3 -- Number of Items to search in ArrayList
(4) 3 Items' Name, Color and Size follows
----------------------------------------------------------------
Things To Do:
--------------------
(a) Read the data from the Input File
(b) Store information about each item in an ArrayList
(c) Read the names, colors and sizes from the file which are to be searched
(d) If items are there in the list corresponding to each Name,Color, and Size, then display their average price

### Lab Test 3 - Section 6 - Input File

10
Shirt;blue;S;\$40
Shirt;yellow;M;\$50
Pant;black;M;\$100
Shirt;blue;S;\$60
Pant;grey;L;\$80
Jacket;black;M;\$50
Pant;grey;S;\$60
Pant;black;M;\$110
Shirt;blue;S;\$80
T-Shirt;red;S;\$60
3
Shirt;blue;S
Pant;black;M
T-Shirt;green;M

### LabTest3 -- Section 5

```
INPUT FILE FORMAT
--------------------------------
1) First Line : 10 -- Number of Employees to be added to an ArrayList
2) 10 Lines follow -- each line corresponds to data on an Employee
Employee Data Format :
-----------------------------------
Name;Age;Salary;Office
3) Line 12 : 4 -- Number of names to search in ArrayList
5) Line 17 : 3 -- Number of names to remove from the ArrayList
6) 3 Names follow

7) Check the Output File to see what to display.

-------------------------------------------------------------------------------------------------------
Things To Do:
--------------------
a) Read the data from the Input File
b) Store informattion about each employee in an ArrayList
c) Calculate the Average Salary
d) Read the names which are to be searched to see if they are contained in the list
If contained in the list then print whether salary above or below average salary
e) Read the names which are to be removed from the ArrayList
if contained in the list then remove them.
f) Finally display the Final List.

** Check the Output File for the Output Format

```

### LabTest3 -- Output

```

Employee Data Added: Herbert 32 10000 2A41

Employee Data Added: Lander 45 15000 2A47

Employee Data Added: Winthrop 27 0 3A71

Employee Data Added: Marion 23 3000 4B25

Employee Data Added: Richard 38 20000 6A11

Employee Data Added: Jason 34 12456 4C32

Employee Data Added: Karthik 39 14567 3B33

Employee Data Added: Bernard 40 34234 4A22

Employee Data Added: Sofia 26 45676 3C56

********* BEGIN SEARCH **************
Lander is contained in the list
Employee Details :Lander 45 15000 2A47
Below Average Salary

Arnold is not contained in the list

Marion is contained in the list
Employee Details :Marion 23 3000 4B25
Below Average Salary

Shenoy is not contained in the list

********* END SEARCH **************

********* REMOVING SPECIFIC EMPLOYEE DATA **************
Lander is contained in List - hence removing ...
Jason is contained in List - hence removing ...
Sopna not contained in list
********* SPECIFIC EMPLOYEE DATA REMOVED **************

********** THE FINAL LIST IS: **************
Herbert 32 10000 2A41
Winthrop 27 0 3A71
Marion 23 3000 4B25
Richard 38 20000 6A11
Karthik 39 14567 3B33
Bernard 40 34234 4A22
Sofia 26 45676 3C56

```

### LabTest3 -- Input File

```
10
Herbert;32;\$10000;2A41
Lander;45;\$15000;2A47
Winthrop;27;7000;3A71
Marion;23;\$3000;4B25
Richard;38;\$20000;6A11
Jason;34;\$12456;4C32
Karthik;39;\$14567;3B33
Bernard;40;\$34234;4A22
Sofia;26;\$45676;3C56
4
Lander
Arnold
Marion
Shenoy
3
Lander
Jason
Sopna

```

### Test 3 Solutions

1. (20%) Implement a method called `isFileThere(String fileName)` which returns true if either `fileName` exists (is the name of a file in the filesystem) or `filename.png` exists. For example, if the file is "apple" then it should return true if either "apple" or "apple.png" refer to a file in the filesystem. Return false otherwise.
``` public static boolean isFileThere(String fileName) {
File f = new File(fileName);
if (f.exists()) {
return true;
}
f = new File(fileName + ".png");
if (f.exists()) {
return true;
}
return false;
}
```
2. (20%) What does the following program print out?
```public class Exceptional {

public void happyDays(int x, int y) throws Exception {
int a[] = {4}; //array with one item.
try {
int d = a[x];
if (y == 0) {
throw new Exception("Heeeeyyyy");
}
System.out.println("Hello Fonzie");
}
catch (IndexOutOfBoundsException e) {
System.out.println("Hello Richie");
}
}

public static void main(String[] args) {
Exceptional e = new Exceptional();
try {
e.happyDays(0,1);
e.happyDays(1,1);
e.happyDays(0,0);
} catch (Exception e1) {
System.out.println("Hello Potsie");
}
}

}
```
```public static void main(String[] args) {
Exceptional e = new Exceptional();
try {
e.happyDays(0,1);
e.happyDays(1,1);
e.happyDays(0,0);
} catch (Exception e1) {
System.out.println("Hellow Potsie");
}
System.out.println("-------");
try {
e.happyDays(1,1);
e.happyDays(0,1);
e.happyDays(0,0);
} catch (Exception e1) {
System.out.println("Hellow Potsie");
}
System.out.println("--------");
try {
e.happyDays(1,1);
e.happyDays(0,0);
e.happyDays(1,0);
} catch (Exception e1) {
System.out.println("Hellow Potsie");
}
}
Hello Fonzie
Hello Richie
Hellow Potsie
-------
Hello Richie
Hello Fonzie
Hellow Potsie
--------
Hello Richie
Hellow Potsie

```
3. (30%) Implement a recursive method that returns the mutant power of a Person. The mutant power of a Person depends on whether or not that person has the X-Gene, and how many of her ancestors have the X-Gene, with maternal lineage being doubly important.
Specifically, you are given the class
```public class Person {
public Person mother;
public Person father;
/** True if person had the X-Gene */
public boolean xgene;
}
```
where either `mother` or `father` could be null, signifying that no one up that lineage has the X-Gene (ignore them). The mutantPower of a Person Y is given by the formula:
• mutant-power(Y) = (1 if Y has X-Gene, 0 otherwise) + 2 * mutant-power(Y's mom) + mutant-power(Y's dad).
Implement `int Person.calculateMutantPower()`. For example, the code below prints out xavier's mutant power which is 3.
```public static void main(String[] args) {
Person xavier = new Person();
xavier.xgene = true;
Person mom = new Person();
mom.xgene = true;
xavier.mother = mom;
System.out.println(xavier.calculateMutantPower()); // 3
}
```
```public int calculateMutantPower () {
int power = (xgene) ? 1 : 0;
int motherPower = 0;
int fatherPower = 0;
//The base case is when both mother and father are null, in which case we just return 1.
if (mother != null) {
motherPower = mother.calculateMutantPower();
}
if (father != null) {
fatherPower = father.calculateMutantPower();
}
return power + 2*motherPower + fatherPower;
}
```
4. (30%) Implement a class called `Set` which implements a mathematical set, which we define as a bunch of elements of the same type where no element appears more than once (no repeats allowed). You will use an `ArrayList` to implement your `Set`.
The `Set` will implement 3 methods:
1. a no-argument constructor (Tip: see Listing 12.10 in your textbook)
2. an `add(...)` method which adds a new element to the set, if its not already there,
3. a `toString()` method which turns the whole set into a string, with a dash '-' between each element.
The following is an example usage of the `Set` class you will write:
```public static void main(String[] args) {
Set<String> s = new Set<String>();
System.out.println(s); //prints Hi-Hello-how are you?-
}
```
```import java.util.ArrayList;

public class Set<T> {

private ArrayList<T> list;

public Set() {
list = new ArrayList<T>(10);
}

if (!list.contains(element)) {
}
}

public String toString() {
String result = "";
for (int i=0; i < list.size();i++) {
result += list.get(i) + "-";
}
return result;
}
}
```

## Thursday, November 18, 2010

### HW7 Solution

Below is my solution to the homework:
```
import java.awt.Graphics;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Fractal extends JPanel {

private double length;

public int numLevels;

public void paintComponent(Graphics g) {
g.setColor(Color.black);
System.out.println("Drawing");
Point from = new Point(150,200);
Point to = new Point(450,200);
length = 0;
//  drawFractalLineDragon(g,from,to,numLevels,Direction.Right);
drawFractalLine(g,from,to,numLevels);

//  from = new Point(100,400);
//  Point top = new Point(300,100);
//  to = new Point(500,400);
//  drawFractalLineSierpinsky(g,from,top,to,numLevels);
System.out.println("Length of curve is " + length);
}

/**
* Draw the Sierpinsky triangle http://en.wikipedia.org/wiki/Sierpinski_triangle
* @param g
* @param from bottom-left
* @param top
* @param to bottom-right
* @param level
*/
public void drawFractalLineSierpinsky(Graphics g, Point from, Point top, Point to, int level) {
if (level == 0) {
g.drawLine(from.getX(), from.getY(), to.getX(), to.getY());
length += from.getVectorTo(to).getMagnitude();
g.drawLine(from.getX(), from.getY(), top.getX(), top.getY());
length += from.getVectorTo(top).getMagnitude();
g.drawLine(top.getX(), top.getY(), to.getX(), to.getY());
length += top.getVectorTo(to).getMagnitude();
return;
}
Point midFromTop = from.getMidPoint(top);
Point midFromTo = from.getMidPoint(to);
Point midTopTo = top.getMidPoint(to);

drawFractalLineSierpinsky(g,from, midFromTop, midFromTo,level-1);
drawFractalLineSierpinsky(g,midFromTop, top, midTopTo, level-1);
drawFractalLineSierpinsky(g,midFromTo, midTopTo, to, level-1);
}

/**
* Draws the Levy C Curve http://en.wikipedia.org/wiki/Levy_C_curve
* @param g
* @param from start point
* @param to end point
* @param level number of recursive levels.
*/
public void drawFractalLine(Graphics g, Point from, Point to, int level) {
if (level == 0) {
g.drawLine(from.getX(), from.getY(), to.getX(), to.getY());
length += from.getVectorTo(to).getMagnitude();
//   System.out.println(from + "  " + to);
return;
}
Point mid = from.getMidPoint(to);
Vector delta = from.getVectorTo(to);
delta = delta.getPerpendicularRight();
delta = delta.multiplyBy(0.5); //half its magnitude
drawFractalLine(g,from,mid,level-1);
drawFractalLine(g,mid,to,level-1);
}

public enum Direction {Right,Left};

/**
* Draws the Dragon curve http://en.wikipedia.org/wiki/Dragon_curve
* @param g
* @param from
* @param to
* @param level
* @param d
*/
public void drawFractalLineDragon(Graphics g, Point from, Point to, int level, Direction d) {
if (level == 0) {
g.drawLine(from.getX(), from.getY(), to.getX(), to.getY());
length += from.getVectorTo(to).getMagnitude();
//   System.out.println(from + "  " + to);
return;
}
Point mid = from.getMidPoint(to);
Vector delta = from.getVectorTo(to);
if (d == Direction.Right) {
delta = delta.getPerpendicularRight();
} else {
delta = delta.getPerpendicularLeft();
}
delta = delta.multiplyBy(0.5); //half its magnitude
drawFractalLineDragon(g,from,mid,level-1,Direction.Right);
drawFractalLineDragon(g,mid,to,level-1,Direction.Left);
}

/**
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Fractal Curve");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Fractal panel = new Fractal();

frame.setSize(600,600);
frame.setVisible(true);
try {
do {
String userInput = JOptionPane.showInputDialog("How Many Levels?");
panel.numLevels = Integer.parseInt(userInput);
frame.repaint(); //don't forget to re-paint it !
} while (true);
} catch (NumberFormatException e) {
//ignore it, just exit program
System.exit(0);
}
}

}
```

## Wednesday, November 17, 2010

### Lab Test 3 - Review Question

Problem 5 - Page 788

And also write a test program which will keep on asking the user for a string input and check if its a palindrome or not, by using the recursive method you have developed. The program should stop if the user enters "quit". The test program should also write all the input strings and the results (if its palindrome or not) to a text file.

### Chapter 12 Video: Generics

Below is the screencast for Chapter 12 which talks about generics. The chapter also covers dynamic data structures but we will not be focusing on those, so you can skip those sections if you want, or you can read them and be ready for CSCE 146.
Here are the slides from the textbook:

## Thursday, November 11, 2010

### Lab 21 -- Section 5 & 6 -- Tuesday November 16 -- Sorting using MergeSort

Sort a list of numbers using MergeSort(with recursion). Please work on this from before hand and you must get it to work by your deadline lab timings on Tuesday

Please Refer to the MergeSort Program given in Chapter 11 of the book
Cheers

PS: I was unable to make it to class today due to TOEFL preparations.

### Lab 20 - Section 5 and 6

Problem 4 - Page 788

### More Lectures by Better Lecturers

If you think that listening to a better lecturer will help you learn the material better then, you are in luck! As you probably know, all major Universities have their CS101-type courses online. I highly recommend MIT's 6.00: Introduction to Computer Science lectures. Another good one is Harvard's CS50.

Below is their video for binary search (using recursion, of course), which I will be talking about today.

## Tuesday, November 9, 2010

### Lab 19 - section 5 and section 6

Problem 3 - page 787

### HW 7: Fractals

In this homework you will practice recursion by drawing some well-known fractal curves. You have to use the Point and Vector classes I provide below to do your arithmetic. I will explain them in class today. The code below also creates a window and draws a line. You will use that as a starting point for your project.
The first curve you will implement is known as the Levy C Curve and its stages are shown on the first figure. A level 0 curve is just a line between two points:start and end. At level 1, instead of drawing a line between the two points, we
1. find the midpoint between the two points,
2. find the vector that is perpendicular to the line, scale it by .5
3. add the perpendicular vector to the midpoint to get a new point, call it NP
4. recursively draw a c-curve from the start to NP and another one from NP to the end point.
The above set of steps is pseudo-code for the Java recursive function you will write to draw the C Curve.
The second curve you will implement is the Dragon Curve which is nearly identical to the C curve expect that sometimes we use one perpendicular (right) and sometimes the other (left). You will implement another method which draws the Dragon curve.
The third fractal you will implement is the Sierpinsky triangle. This one is different in that, instead of drawing a line by breaking it up into two pieces, you will be drawing a triangle by breaking it up into three smaller triangles. The recursion will be similar but the drawing code will be different.
Finally, after you get these to run then go back and change them so that they calculate and printout the length of the fractal they have just drawn. That is, the sum of the length of all the little line segments.
This homework is due on Thursday, November 18 @9am. Below is the code for Point and Vector which you must use as well as a short program that draws a line, to get you started.
```public class Point {

public double x;
public double y;

/**
* We return the nearest int to the current x value.
* By keeping points as double we increase the precision of the final plot.
* We only convert to int when absolutely necessary, that is, when plotting on screen.
* @return
*/
public int getX() {
return (int) Math.round(x);
}

public int getY() {
return (int) Math.round(y);
}

public Point(int x, int y) {
this.x = x;
this.y = y;
}

public Point(double x, double y) {
this.x = x;
this.y = y;
}

public String toString() {
return x + "," + y;
}

/**
* Make a vector from this point to other
* @param other
* @return a new Vector
*/
public Vector getVectorTo(Point other) {
return new Vector(other.x - x,other.y - y);
}

/**
* Returns a Point that lies midway on the line between this point and other
* @param other
* @return a new Point
*/
public Point getMidPoint(Point other) {
return new Point((x + other.x)/ 2, (y +other.y)/ 2);
}

/**
* Move this point by vector v.
* @param v
* @return a new Point
*/
return new Point(x + v.x, y + v.y);
}

}

public class Vector extends Point {

public Vector(double x, double y) {
super(x,y);
}

/**
* The magnitude
* @return the magnitude.
*/
public double getMagnitude() {
return Math.sqrt(x*x+y*y);
}

/**
* Creates a new vector that is perpendicular to this one, pointing to the right.
* @return a new vector
*/
public Vector getPerpendicularRight() {
return new Vector(-y, x);
}

/**
* Creates a new vector that is perpendicular to this one, pointing to the left.
* @return a new vector
*/
public Vector getPerpendicularLeft() {
return new Vector(y, -x);
}

/**
* Creates a new vector like this one but scaling both coordinates by d
* @param d
* @return a new vector
*/
public Vector multiplyBy(double d) {
return new Vector(x*d, y*d);
}

}

/** Jose M Vidal
* If that's not me on the line above then I deserve 0 points on this homework. */

import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JOptionPane;

public class Fractal extends JPanel{

public int numLevels;

public void paintComponent(Graphics g) {
g.setColor(Color.black);
System.out.println("Drawing");
g.drawLine(200, 200, 400, 200);
}

/**
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Fractal Curve");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Fractal panel = new Fractal();

frame.setSize(600,600);
frame.setVisible(true);
try {
do {
String userInput = JOptionPane.showInputDialog("How Many Levels?");
panel.numLevels = Integer.parseInt(userInput);
frame.repaint(); //don't forget to re-paint it !
} while (true);
} catch (NumberFormatException e) {
//ignore it, just exit program
System.exit(0);
}
}
}
```

### HW6 Solution

Below is my solution to HW6:
```public class FileTooBigException extends Exception {
public FileTooBigException(String msg) {
super(msg);
}
}

public class NotEnoughDataException extends Exception {
public NotEnoughDataException(String msg) {
super(msg);
}
}

import java.util.Scanner;
public class Day {
private String date;
private double open;
private double high;
private double low;
private double close;
private long volume;

public double getClose() {
return close;
}

public double getVolume() {
return volume;
}

/**
* Creates a new Day object by reading values from istream:
*   date, open, high, log, close, volume: in that order.
* We assume the delimiter has been correctly set on istream so values can be read
*   by calling nextX()
* @param istream
*/
public Day (Scanner istream) {
date = istream.next();
open = istream.nextDouble();
high = istream.nextDouble();
low = istream.nextDouble();
close = istream.nextDouble();
volume = istream.nextLong();
}

public String toString() {
return date + " " + close + " " + volume;
}
}

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

public class Security {

private Day[] day;

private int lastDay;

private static final int DAY_ARRAY_SIZE = 1000;

/**
* Add day d to the history, but only if its volume > 0.
* @param d
* @throws FileTooBigException
*/
public void addDay(Day d) throws FileTooBigException {
if (d.getVolume() > 0) {
if (lastDay >= DAY_ARRAY_SIZE) {
throw new FileTooBigException("You cannot have more than " + DAY_ARRAY_SIZE + " days.");
}
day[lastDay++] = d;
}
}

public Security () {
day = new Day[DAY_ARRAY_SIZE];
lastDay = 0;
}

/** Read historical values for this security from a csv stream.
*
* @param file
* @throws FileTooBigException
*/
public void readFromStream(Scanner istream) throws FileTooBigException {
istream.useDelimiter("[,\\s]"); //separate on , or on whitespace
if (istream.hasNext()) {
istream.nextLine(); //ignore first line
}
String w = null;
while (istream.hasNext()) {
//System.out.println("----" + istream.next());
Day nextDay = new Day(istream);
}
}

public double getVolatility(int numDays) throws NotEnoughDataException {
if (numDays > lastDay) {
throw new NotEnoughDataException("Need more historical data");
}
double average = getAverageClose(numDays);
double squareDifference = 0;
for (int i=0; i < numDays; i++) {
squareDifference += Math.pow(day[i].getClose() - average, 2);
}
double deviation = squareDifference / (double) numDays;
return Math.sqrt(deviation);
}

public double getAverageClose(int numDays) {
double sum = 0;
for (int i=0; i< numDays;i++) {
sum += day[i].getClose();
}
return sum / (double)numDays;
}

public String toString() {
String result = "";
for (int i= 0; i < lastDay; i++) {
result += day[i] + "\n";
}
return result;
}

public double getMinClose(int numDays) {
double min = Double.MAX_VALUE; //assume no stock price is ever this high
for (int i = 0; i < numDays; i++) {
if (day[i].getClose() < min)
min = day[i].getClose();
}
return min;
}

public double getMaxClose(int numDays) {
double max = -1;
for (int i = 0; i < numDays; i++) {
if (day[i].getClose() > max)
max = day[i].getClose();
}
return max;
}
/**
* Returns a price distribution array, where the index of the array is the price - getMinClose(numDays)
* whose contents are the number of days we closed at that price within the last numDays.
* @param numDays
* @return array with getMaxClose(numDays) - getMinClose(numDays) + 1 values
*/

public int[] getPriceDistribution(int numDays) {
int min = (int) getMinClose(numDays);
int max = (int) getMaxClose(numDays);
int[] result = new int[max-min + 1];
for (int i =0; i < numDays; i++) {
result[(int)day[i].getClose() - min]++;
}
return result;
}

public void savePriceDistribution(String outFile,int numDays) throws FileNotFoundException {
PrintWriter out = new PrintWriter(new FileOutputStream(outFile, true));
int min = (int) getMinClose(numDays);
int[] distribution = getPriceDistribution(numDays);
for (int i =0; i < distribution.length; i++) {
int p = min + i;
out.write(p + "," + distribution[i] + "\n");
}
out.close();
}

/**
* @param args
*/
public static void main(String[] args) {
Scanner istream = null;
String inputFile = "/Users/jmvidal/data.csv";
try {
istream = new Scanner(new File(inputFile));
} catch (FileNotFoundException e) {
System.out.println("Ooops, no such input file:" + inputFile);
System.exit(1);
}

Security s = new Security(); //Security class will hold all the data
try {
} catch (FileTooBigException e1) { //file is to big to read
System.out.println(e1.getMessage());
System.exit(1);
}

System.out.println(s); //print out all the contents. Note: no days with 0 volume.

try {
System.out.println("Volatility in the last 10 days = " + s.getVolatility(10));
System.out.println("Volatility in the last 1000 days = " + s.getVolatility(1000));

} catch (NotEnoughDataException e) {
System.out.println("Sorry, not enough data." + e.getMessage());
}

System.out.println("Price Distribution for the last 10 days.");
System.out.println("price\tnumber of days");
int[] priceDistribution = s.getPriceDistribution(10); //get the distribution array
int minClose = (int)s.getMinClose(10);
for (int i=0; i < priceDistribution.length; i++) { //we need this loop to print it out
int p = minClose + i;
System.out.println(p + "\t" + priceDistribution[i]);
}

try {
//now, save the distribtion for the last 20 days to a file.
s.savePriceDistribution("/Users/jmvidal/distribution-20.csv",20);
} catch (FileNotFoundException e) {
System.exit(1);
}
}
}
```

## Monday, November 8, 2010

### Chapter 11 Video: Recursion

Chapter 11 deals with the topic of recursion. Recursion is not a language feature, it is simply having a method call itself. All programming languages are capable of recursion. Recursion is a technique that makes certain algorithms much easier to write and understand.
Here are the slides from the textbook:

## Thursday, November 4, 2010

### Java 4-Ever!

Already nominated for a Developers' Choice award:

### Chapter 10 Video

Below is the screencast for the chapter 10 which deals with reading and writing streams to files. I/O operations like these are slightly different on every programming language, but the basic ideas are the same.

The textbook slides are below.

### Lab 18 -- File Handling -- File Read/Write

Assume you are the owner of Tower Records, which sells music CDs and albums, and you decide to hold a sale to try to reduce your inventory of old records. Write a Java program to read from your inventory text file (refer below for an example file "albums.txt"), which contains information about albums and CDs, including their cost. If an album is between one year and five years old, change the cost to show a discount of 5%. If an album is between 5 years old and 10 years old, give a discount of 10%. If it is more than 10 years old, give a discount of 50%. The album information with the new pricing should be written into a new text file newalbums.txt.

Each record is represented by four lines of text in the files. The first line is the title of the album, the next line is the artist/group name, the next is the year of release, and the next is the price of the album.

Hints: Once you read in each line as a String you can parse the year of release Integer.parseInt(String s) to an int and check how old it is and give a discount on the parsed price (double). Use the substring(int index) method of the String class to get rid of the \$ sign in the front of price. Use a loop to do it for all albums.

### Lab 18 -- FileHandling -- albums.txt

No Doubt
2002
\$18.98
Revolver
The Beatles
1966
\$14.00
Dangerously in Love
Beyonce featuring Jean Paul
2003
\$18.50
Blood on the Dance Floor: History in the Making
Michael Jackson
1997
\$16.50

## Wednesday, November 3, 2010

### The Java Posse

These guys have had a podcast for five years. I'm a fan.

## Sunday, October 31, 2010

### HW 6: Finance

In this homework you will practice using exceptions and files by writing a short program that reads in stock prices and prints out, and saves to a file, some information about these prices.

One thing you will notice is that some of the days a trading volume of 0. These are holidays. These days will mess up our later calculations so when you read from a file you must skip these days.

Also, assume that there are at most 1000 days of data. If there are more in the data file, your program should throw a `FileTooBigException`.

Once you have parsed a file, your program will then calculate the volatility of the stock for the last X days, where X is an argument to your function. To calculate volatility for the last X days you

1. Calculate the average close price for the last X days. Call this `average-close`.
2. Add up the `square-difference = (closing-price - average-close) ^ 2` for every closing price in the last X days, then divide this number by X and then take its square root. That's the volatility.

The volatility tells us how much a stock price has moved, but it is only one number. We want to get a better picture of how the stock has moved. What we need is a distribution of the closing prices and the number of days, in the last X days, that the stock has closed at that price (where all prices are truncated to their integer value).

Implement a method called `int[] getPriceDistribution(int X)` which returns an array whose values are the number of days the stock has closed at that price (like a grade distribution, but for prices). Also implement `getMinClose(int X)` which returns the minimum closing price in the last X days. Then, the index 0 on the array returned by `getPriceDistribution` will be the number of days the stock closed at the price `getMinClose(X)`.

Finally, now that you have this price distribution, we'll want to save it to a CSV file. Implement a method called `savePriceDistribution(String outFile, int X` which writes the price distribution of the last X days to outfile, in CSV format.

Below is a concrete example of a `main` using the new `Security` class and the output it generates.

``` public static void main(String[] args) {
Scanner istream = null;
String inputFile = "/Users/jmvidal/data.csv";
try {
istream = new Scanner(new File(inputFile));
} catch (FileNotFoundException e) {
System.out.println("Ooops, no such input file:" + inputFile);
System.exit(1);
}

Security s = new Security(); //Security class will hold all the data
try {
} catch (FileTooBigException e1) { //file is to big to read
System.out.println(e1.getMessage());
System.exit(1);
}

System.out.println(s); //print out all the contents. Note: no days with 0 volume.

try {
System.out.println("Volatility in the last 10 days = " + s.getVolatility(10));
System.out.println("Volatility in the last 1000 days = " + s.getVolatility(1000));

} catch (NotEnoughDataException e) {
System.out.println("Sorry, not enough data." + e.getMessage());
}

System.out.println("Price Distribution for the last 10 days.");
System.out.println("price\tnumber of days");
int[] priceDistribution = s.getPriceDistribution(10); //get the distribution array
int minClose = (int)s.getMinClose(10);
for (int i=0; i < priceDistribution.length; i++) { //we need this loop to print it out
int p = minClose + i;
System.out.println(p + "\t" + priceDistribution[i]);
}

try {
//now, save the distribtion for the last 20 days to a file.
s.savePriceDistribution("/Users/jmvidal/distribution-20.csv",20);
} catch (FileNotFoundException e) {
System.exit(1);
}

}
```

And here is the output it generates:

```28-Oct-10 618.58 2187396
27-Oct-10 616.47 2242414
26-Oct-10 618.6 2513633
25-Oct-10 616.5 3158700
...well you get the idea...
...notice, no days with 0 volume...
5-Nov-09 548.65 1848039
4-Nov-09 540.33 2333629
3-Nov-09 537.29 2382892
2-Nov-09 533.99 3202875
30-Oct-09 536.12 3469738

Volatility in the last 10 days = 5.4362785064784855
Sorry, not enough data.Need more historical data
Price Distribution for the last 10 days.
price number of days
601 1
602 0
603 0
604 0
605 0
606 0
607 2
608 0
609 0
610 0
611 1
612 1
613 0
614 0
615 0
616 2
617 1
618 2
```

This homework is due Tuesday, November 9 @9:00am

## Thursday, October 28, 2010

### Lab 17 -- Solution -- Class: Driver

```

import java.util.Scanner;

public class Driver {

public static void main(String[] args)
{
boolean valid;
int num_Employees;
Employee[] data = new Employee[100];
int salary_sum = 0;
double avg_salary;

Scanner keyboard = new Scanner(System.in);

do
{
System.out.println("Number of Employees:");
num_Employees = keyboard.nextInt();
}while(num_Employees < 0 || num_Employees > 100);

int e_count = 1;
String ssnInput;
int sal;

while(e_count <= num_Employees)
{
Employee e = new Employee();

// Enter Employee Details
e.EnterEmployeeDetails(e_count);

salary_sum += e.getSalary();

// Verification of SSN (Length and Character)
do
{
valid = true;

try
{
String str = e.getSSN();
int count = 0;

// Check for SSNLength Exception
for(int i=0; i < str.length(); i++)
{
if(str.charAt(i) != '-' && str.charAt(i) != ' ')
count++;
}

if(count != 9)
{ valid = false;
throw new SSNLengthException();
}

/* **************************************** */

for(int j = 0; j < str.length(); j++ )
{
if(str.charAt(j) != '-' && str.charAt(j) != ' ')
{
if(!Character.isDigit(str.charAt(j)))
{
valid = false;
throw new SSNCharacterException();
}
}
}

}
catch(SSNLengthException exp)
{
System.out.println(exp.getMessage());
e.EnterEmployeeSSN(e_count);
}
catch(SSNCharacterException expr)
{
System.out.println(expr.getMessage());
e.EnterEmployeeSSN(e_count);
}

}while(valid == false);

data[e_count - 1] = e;

e_count++;
} // end of while

avg_salary = (double)salary_sum / num_Employees;

for(int k=0; k < num_Employees; k++)
{
if(data[k].getSalary() > avg_salary)
{
System.out.printf("EmpNumber %d: %s ABOVE SALARY  %n", k+1, data[k].toString());
}
else
System.out.printf("EmpNumber %d: %s BELOW SALARY %n", k+1, data[k].toString());
}

}
}
```

### Lab 17 -- Solution -- Class: Person

```

public class Person
{
private String name;

public Person()
{
name = "No Name Yet";
}

public Person(String initialName)
{
name = initialName;
}

public void setName(String newName)
{
name = newName;
}

public String getName()
{
return name;
}

public void writeOutput()
{
System.out.println("Name: " + name);
}

public boolean hasSameName(Person otherPerson)
{
return this.name.equalsIgnoreCase(otherPerson.name);
}
}
```

### Lab 17 -- Solution -- Class: Employee

```
import java.util.Scanner;

public class Employee extends Person
{
String SSN;
int salary;

Scanner k1 = new Scanner(System.in);
Scanner k2 = new Scanner(System.in);
Scanner k3 = new Scanner(System.in);

public Employee()
{
SSN = "";
salary = 0;
}

public Employee(String s, int sal)
{
this.SSN = s;
this.salary = sal;
}

public String getSSN() {
return SSN;
}

public void setSSN(String sSN) {
SSN = sSN;
}

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
this.salary = salary;
}

public void EnterEmployeeDetails(int empNumber)
{
// Enter Name
System.out.println("Employee " + empNumber + ":" + " Enter Name:");
super.setName(k1.nextLine());

this.EnterEmployeeSSN(empNumber);

// Enter Salary
System.out.println("Employee " + empNumber + ":" + " Enter Salary:");
this.setSalary(k3.nextInt());

}

public void EnterEmployeeSSN(int empNumber)
{
System.out.println("Employee " + empNumber + ":" + this.getName() + " :Enter SSN:");
this.setSSN(k2.nextLine());
}

public String toString()
{
String str;
str = String.format("Emp Name:%s EmpSSN:%s EmpSalary:%d", this.getName(), this.getSSN(), this.getSalary());
return str;
}
}
```

### Lab 17 -- Solution -- Class: SSNLengthException

```
public class SSNLengthException extends Exception
{
public SSNLengthException()
{
super("SSN Length not exactly 9 Characters");
}

public SSNLengthException(String msg)
{
super(msg);
}

}
```

### Lab 17 -- Solution -- Class: SSNCharacterException

```
public class SSNCharacterException extends Exception
{
public SSNCharacterException()
{
super("Inappropriate Character in SSN:Non Digit Character Found");
}

public SSNCharacterException(String msg)
{
super(msg);
}
}
```

### Lab 17 -- Section 6

Same as Section 5

### Lab 17 - Section 5 -- Exception Handling

Problem 7 -- Page 675 --For Persons Class refer to Page 552

## Wednesday, October 27, 2010

### Revised Solutions for LabTest#2 - Section 5/6 Posted

I have posted the revised solutions of LabTest#2 - Section 5/6 having replaced the ('instanceof' keyword && SuperClass to SubClass typecast ) and making accompanying modifications. ( after Prof. Vidals comments .. :) .. ). My apologies. Hope this helps.

### LabTest#2: Revised Solution -- Section 6 -- Class: Item

I had forgotton to include this before
```public class Item
{
private String name;
private int Price;

public Item()
{
name = "";
Price = 0;
}

public Item(String n, int p)
{
this.name = n;
this.Price = p;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getPrice() {
return Price;
}

public void setPrice(int price) {
Price = price;
}

}
```

### Celebrity Interview

Below is an interview with Jeff Atwood, creator of stackoverflow.

See all 3 videos here. He talks about HTML5 issues, which we will be covering in my CSCE 242 class next semester.

## Tuesday, October 26, 2010

### Not So Good Solutions

The solutions Shamik and Humayun provided below, while functional, are not really how you should solve these problems. Specifically, you should not use instanceof. You should use inheritance instead. I'll explain in class. I'm going to have to give them a B- for these solutions.

The simple rule is: never use instanceof. There are some rare occasions when its useful.

### LabTest#2: Revised Solution -- Section 5 -- Class: Dungeon

```public class Dungeon
{

private Tile[][] theDungeon;

public Dungeon()
{
theDungeon = new Tile[10][10];

for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
theDungeon[i][j] = new Tile();
}
}
}

/* ************************************************************* */

public void addMonsters(Monster m, int x, int y)
{
if(x < 0 || x > 10)
System.out.println("Out of Range");

if(y < 0 || y > 10)
System.out.println("Out of Range");

}

/* ***************************************************************** */

public void deleteMonsters(int x, int y)
{
// Gets the array of monsters at Dungeon[x][y]
Monster[] m_xy = theDungeon[x][y].getMonsters();

for(int i = 0; i < theDungeon[x][y].getSize(); i++)
{
System.out.println("Monster: "
+ m_xy[i] + " AT DUNGEON[" + x + "][" + y + "] GETS EATEN  UP");
}

// Creating an empty array of Monster[] type:
Monster[] newMonsterArray = new Monster[100];

// Replace the Monster[] array of this TILE with an empty one
theDungeon[x][y].setMonsters(newMonsterArray);
theDungeon[x][y].setSize(0);
}

/* ***************************************************************** */

// Returns the 2D Array
public Tile[][] getTheDungeon()
{
return theDungeon;
}

/* ***************************************************************** */

public String toString()
{
String Str = "";
String contents = "";

for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{

contents = theDungeon[i][j].toString();

if(!contents.equals(""))
{
Str += String.format("DUNGEON[%d][%d] CONTAINS :: %n %s %n",i, j, contents);
}
else
{
//Str += String.format("DUNGEON[%d][%d] CONTAINS :: %n EMPTY %n",i, j);
}
}
}

return Str;
}

/* ***************************************************************** */

}
```

### LabTest#2: Revised Solution -- Section 5 -- Class: Tile

```public class Tile
{
private Monster[] monsters;
private int size;

public Tile()
{
monsters = new Monster[100];
size = 0;
}

/* ******************************************************************* */

public void setSize(int s)
{
this.size = s;
}

/* ******************************************************************* */

public int getSize()
{
return this.size;
}

/* ******************************************************************* */

{
monsters[size] = m;
size++;
}

/* ******************************************************************* */

public void deleteTheMonster(Monster m)
{
int index;

// If match found then delete
if((index = this.contains(m)) >= 0)
{
for(int i = index; i < this.getSize() - 1; i++)
{
// The shift after deletion
monsters[i] = monsters[i+1];
}
size--;
}
}

/* ******************************************************************* */

public int contains(Monster m)
{
int match_index = -1;

for(int i=0; i < this.getSize(); i++)
{
if(monsters[i].getName().equalsIgnoreCase(m.getName()) && monsters[i].getMonsterType() == m.getMonsterType())
{
match_index = i;
break;
}
}

return match_index;
}

/* ******************************************************************* */

// returns the array of monsters at the particular tile
public Monster[] getMonsters()
{
return monsters;
}

/* ******************************************************************* */

// set the array of monsters for a particular tile
public void setMonsters(Monster[] m)
{
this.monsters = m;
}

/* ******************************************************************* */

// Checks to see if this CHANNEL contains anyone of Monster.MonsterType monsType
public boolean contains(Monster.MonsterType monsType)
{
boolean returnValue = false;

for(int i = 0; i < this.getSize(); i++)
{
if(monsters[i].getMonsterType() == monsType)
{
returnValue = true;
break;
}
}
return returnValue;
}

/* ******************************************************************* */

//
public String toString()
{
String str = "";

if(this.getSize() > 0)
{
for(int i = 0; i < this.getSize(); i++)
{
str += String.format("Cell[%d]: %s %n",i, monsters[i]);
}
}
return str;
}

/* ******************************************************************* */

}
```

### LabTest#2: Revised Solution -- Section 5 -- Class: Monster

```public class Monster
{
private String name;
public enum MonsterType { GOBLIN, ZOMBIE, GHOST };
public MonsterType type;

public enum LiveStatus { LIVING, DEAD };
public LiveStatus liveStat;

public Monster()
{
name = "";
}

public Monster(String n)
{
this.setName(n);
}

public void setName(String n)
{
this.name = n;
}

public String getName()
{
return this.name;
}

public void setMonsterType(MonsterType m)
{
type = m;
}

public MonsterType getMonsterType()
{
return type;
}

public void setLiveStatus(LiveStatus l)
{
liveStat = l;
}

public LiveStatus getLiveStatus()
{
return liveStat;
}

}

```

### LabTest#2: Revised Solution -- Section 5 -- Class: Goblin

```
public class Goblin extends Monster
{
private int x;
private int y;

public Goblin(String n, MonsterType m, int x, int y, Dungeon theD)
{
super(n);
super.setMonsterType(m);
this.setX(x);
this.setY(y);
super.setLiveStatus(Monster.LiveStatus.LIVING);

}

/* ************************************************************* */

// Setters and Getters

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}

/* ************************************************************** */

// Movements

// move North
public void moveNorth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes North till it finds an empty space
do
{
this.setY(this.getY() + 1);

// Wraps around ( if it goes beyond GRID)
if(this.getY() > 9)
this.setY(0);

}while(theD.getTheDungeon()[this.getX()][this.getY()].getSize() > 0);

// when it has found an empty space --> it then adds itself there
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move South
public void moveSouth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes on till it finds an empty space
do
{
this.setY(this.getY() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getY()) < 0)
this.setY(9);

}while(theD.getTheDungeon()[this.getX()][this.getY()].getSize() > 0);

// when it has found an empty space --> it then adds itself there
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move West
public void moveWest(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes on till it finds an empty space
do
{
this.setX(this.getX() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) < 0)
this.setX(9);

}while(theD.getTheDungeon()[this.getX()][this.getY()].getSize() > 0);

// when it has found an empty space --> it then adds itself there
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move West
public void moveEast(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes on till it finds an empty space
do
{
this.setX(this.getX() + 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) > 9)
this.setX(0);

}while(theD.getTheDungeon()[this.getX()][this.getY()].getSize() > 0);

// when it has found an empty space --> it then adds itself there
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

/* **************************************************************** */

public String toString()
{
String str;
//str = super.getName() + " " + super.getMonsterType().toString() + "\n";
str = String.format("%s %s", super.getName(), super.getMonsterType().toString());
return str;
}
}
```

### LabTest#2: Revised Solution -- Section 5 -- Class: Zombie

```public class Zombie extends Monster
{
private int x;
private int y;

public Zombie(String n, MonsterType m, int x, int y, Dungeon theD)
{
super(n);
super.setMonsterType(m);
this.setX(x);
this.setY(y);
super.setLiveStatus(Monster.LiveStatus.LIVING);

}

/* ****************************************************************** */

// Setters and Getters

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}

/* ************************************************************** */

// Movements

// move north
public void moveNorth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

this.setY(this.getY() + 1);

// Wraps around ( if it goes beyond GRID)
if((this.getY()) > 9)
this.setY(0);

this.TheZombieAct(theD, this.getX(), this.getY());
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move south
public void moveSouth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

this.setY(this.getY() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getY()) < 0)
this.setY(9);

this.TheZombieAct(theD, this.getX(), this.getY());
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// Move west
public void moveWest(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

this.setX(this.getX() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) < 0)
this.setX(9);

this.TheZombieAct(theD, this.getX(), this.getY());
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// Move east
public void moveEast(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

this.setX(this.getX() + 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) > 9)
this.setX(0);

this.TheZombieAct(theD, this.getX(), this.getY());
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

/* **************************************************************** */

// The Zombie's Act

public void TheZombieAct(Dungeon theD, int x, int y)
{
// The Zombie now deletes all monsters at Dungeon[x][y + 1]
theD.deleteMonsters(x, y);

// And it adds itself at Dungeon[x][y + 1] after having eaten everyone at Dungeon[x][y + 1]
}

/* **************************************************************** */

public String toString()
{
String str;
//str = super.getName() + " " + super.getMonsterType().toString() + "\n";
str = String.format("%s %s", super.getName(), super.getMonsterType().toString());
return str;
}

}
```

### LabTest#2: Revised Solution -- Section 5 -- Class: Ghost

```
public class Ghost extends Monster
{
private int x;
private int y;

public Ghost(String n, MonsterType m, int x, int y, Dungeon theD)
{
super(n);
super.setMonsterType(m);
this.setX(x);
this.setY(y);
super.setLiveStatus(Monster.LiveStatus.LIVING);

}

/* ************************************************************** */

// Getters and Setters

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}

/* ************************************************************** */

// Movements

// move north

public void moveNorth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{
// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes North till it finds a TILE without another GHOST
do
{
this.setY(this.getY() + 1);

// Wraps around ( if it goes beyond GRID)
if((this.getY()) > 9)
this.setY(0);

}while(theD.getTheDungeon()[this.getX()][this.getY()].contains(Monster.MonsterType.GHOST));

// theD.getTheDungeon() --> returns Tile[][] array
// theD.getTheDungeon()[x][y] --> returns a Tile Object --> containing Monsters[]

// Now it adds itself to this CHANNEL
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move south
public void moveSouth(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes south till it finds a TILE without another ghost
do
{
this.setY(this.getY() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getY()) < 0)
this.setY(9);

}while(theD.getTheDungeon()[this.getX()][this.getY()].contains(Monster.MonsterType.GHOST));

// theD.getTheDungeon() --> returns Tile[][] array
// theD.getTheDungeon()[x][y] --> returns a Tile Object --> containing Monsters[]

// Now it adds itself to this TILE
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move west
public void moveWest(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes west till it finds a TILE without another ghost
do
{
this.setX(this.getX() - 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) < 0)
this.setX(9);

}while(theD.getTheDungeon()[this.getX()][this.getY()].contains(Monster.MonsterType.GHOST));

// theD.getTheDungeon() --> returns Tile[][] array
// theD.getTheDungeon()[x][y] --> returns a Tile Object --> containing Monsters[]

// Now it adds itself to this CHANNEL
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

// move west
public void moveEast(Dungeon theD)
{
if(this.getLiveStatus() == Monster.LiveStatus.LIVING)
{

// Removes itself from current position
theD.getTheDungeon()[this.getX()][this.getY()].deleteTheMonster(this);

// Goes EAST till it finds a TILE without another ghost
do
{
this.setX(this.getX() + 1);

// Wraps around ( if it goes beyond GRID)
if((this.getX()) > 9)
this.setX(0);

}while(theD.getTheDungeon()[this.getX()][this.getY()].contains(Monster.MonsterType.GHOST));

// theD.getTheDungeon() --> returns Tile[][] array
// theD.getTheDungeon()[x][y] --> returns a Tile Object --> containing Monsters[]

// Now it adds itself to this CHANNEL
}
else
{
System.out.println(this.getName() + " " + this.getMonsterType() + " IS DEAD ");
}
}

/* **************************************************************** */

public String toString()
{
String str;
//str = super.getName() + " *** " + super.getMonsterType() + "\n";
str = String.format("%s %s", super.getName(), super.getMonsterType().toString());
return str;
}

}
```

### LabTest#2: Revised Solution -- Section 6 -- Class: Shoes

```public class Shoes extends Item
{
private int theSize;

public Shoes()
{
this.setSize(0);
}

public Shoes(String n, int p, int s)
{
super(n, p);
this.setSize(s);
}

public void setSize(int s)
{
this.theSize = s;
}

public int getSize()
{
return theSize;
}

public String toString()
{
String str;
str = String.format("Item Name:%s Item Price:%d Item Size:%d", super.getName(), super.getPrice(), this.getSize());
return str;
}
}
```

### LabTest#2: Revised Solution -- Section 6 -- Class: Shirt

```public class Shirt extends Item
{
public enum Size { S, M, L, XL };
private Size theSize;

public Shirt()
{
this.setSize(Size.S);
}

public Shirt(String n, int p, Size s)
{
super(n, p);
this.setSize(s);
}

public void setSize(Size s)
{
theSize = s;
}

public Size getSize()
{
return theSize;
}

public String toString()
{
String str;
str = String.format("Item Name:%s Item Price:%d Item Size:%s", super.getName(), super.getPrice(), this.getSize().toString());
return str;
}

}
```

### LabTest#2: Revised Solution -- Section 6 -- Class: Pant

```public class Pant extends Item
{
private int theSize;

public Pant()
{
this.setSize(0);
}

public Pant(String n, int p, int s)
{
super(n, p);
this.setSize(s);
}

public void setSize(int s)
{
this.theSize = s;
}

public int getSize()
{
return theSize;
}

public String toString()
{
String str;
str = String.format("Item Name:%s Item Price:%d Item Size:%d", super.getName(), super.getPrice(), this.getSize());
return str;
}
}
```

### LabTest#2: Revised Solution -- Section 6 -- Class: Shopping Cart

```public class ShoppingCart
{
public Item[] theItems;
public int item_count;
public int TotalPrice;

public ShoppingCart()
{
theItems = new Item[1000];
item_count = 0;
TotalPrice = 0;
}

/* ****************************************************************************************** */

// Setters and Getters

public int getItemCount()
{
return item_count;
}

public void setItemCount(int ic)
{
item_count = ic;
}

public void setTotalPrice(int t)
{
this.TotalPrice = t;
}

public int getTotalPrice()
{
}

public void setTheItems(Item[] t)
{
this.theItems = t;
}

public Item[] getTheItems()
{
return theItems;
}

/* ****************************************************************************************** */

{
theItems[item_count] = anItem;

item_count++;
}

/* ****************************************************************************************** */

public boolean removeItem(Item e)
{
boolean returnValue = false;
int matched_item;

if((matched_item = this.contains(e)) >= 0)
{
for(int i = matched_item; i < item_count - 1; i++)
{
theItems[i] = theItems[i+1];
}

item_count--;

this.setTotalPrice(this.getTotalPrice() - e.getPrice());
returnValue = true;
}

if(returnValue == false)
{
}
else
{
System.out.println("Item Removed:" + e);
}
return returnValue;
}

/* ****************************************************************************************** */

public int contains(Item e)
{
int item_match = -1;

for(int j = 0; j < this.getItemCount(); j++)
{
if(theItems[j].getName().equals(e.getName()) && theItems[j].getPrice() == e.getPrice())
{
item_match = j;
}
}
return item_match;
}

/* ****************************************************************************************** */

public int calculateTotalPrice()
{
this.setTotalPrice(0);

for(int i = 0 ; i < this.getItemCount(); i++)
{
TotalPrice += theItems[i].getPrice();
}

return this.getTotalPrice();
}

/* ****************************************************************************************** */

public void clear()
{
for(int j = 0; j < this.getItemCount(); j++)
{
theItems[j] = new Item("", 0);
}

// Create an empty array of Item type : Item[]
Item[] freshEmptyItems = new Item[1000];

// Set theItems to this freshEmptyItems
this.setTheItems(freshEmptyItems);

this.setItemCount(0);
this.setTotalPrice(0);

System.out.println("Cart Cleared");
}

/* ****************************************************************************************** */

public String toString()
{
boolean encountered_before;
int the_item_count;
String str = "";

for(int i = 0; i < this.getItemCount(); i++)
{
encountered_before = false;

// Check to see if encountered before
for(int j = 0; j < i; j++)
{
if(theItems[i].getName().equalsIgnoreCase(theItems[j].getName()))
{
encountered_before = true;
}
}

// if not encountered before then calculate its count
if(encountered_before == false)
{
// calculate the item_counts of each item
the_item_count = 1;
for(int k = i+1; k < this.getItemCount(); k++)
{
if(theItems[i].getName().equalsIgnoreCase(theItems[k].getName()))
{
the_item_count++;
}
}

// display
//System.out.println("Quantity = " + the_item_count + " " + theItems[i].getName());
//str += "Quantity = " + the_item_count + " " + theItems[i].getName() + "\n";
str += String.format("Quantity = %d %s %n", the_item_count, theItems[i].getName());
}

}
return str;
}

/* ****************************************************************************************** */

}

```

### LabTest#2 -- Section 6 -- Shopping Cart of Items

```
1) Create an Item class with a price and name attributes.
2) Create Shirt, Pants, and Shoes classes, with added size attribute. Shirt sizes are S,M,L,XL. Pant and shoe sizes are integers.
3) Create a shopping cart which can hold up to 1000 Items,
with methods :

b) removeItem(Item e)
c) int calculateTotal() ;returns the total price
d) clear(); removes all items from the shopping cart
e) toString(); each item in one line.
If an item is there more than once it should say
quantity=4 blue shirt
rather than "blue shirt" in 4 separate lines

```

### LabTest#2 -- Section 6 -- Driver Class ( You can use this to test your program )

```
public class Driver
{
public static void main(String[] args)
{

Shirt shirt1 = new Shirt("blue shirt", 100, Shirt.Size.M);
Shirt shirt2 = new Shirt("blue shirt", 120, Shirt.Size.S);
Shirt shirt3 = new Shirt("maroon shirt", 130, Shirt.Size.L);

Pant pant1 = new Pant("brown pant", 65, 32);
Pant pant2 = new Pant("black pant", 130, 34);
Pant pant3 = new Pant("brown pant", 100, 33);

Shoes shoe1 = new Shoes("black shoe", 200, 8);
Shoes shoe2 = new Shoes("black shoe", 200, 8);
Shoes shoe3 = new Shoes("grey shoe", 200, 8);

/* **************************************************************** */
ShoppingCart Cart = new ShoppingCart();

System.out.println("TOTAL PRICE = \$" + Cart.calculateTotalPrice());
System.out.println("ITEMS BOUGHT: \n" + Cart.toString());

/* **************************************************************** */

Cart.removeItem(shirt3);
Cart.removeItem(pant2);
Cart.removeItem(shoe2);

System.out.println("TOTAL PRICE = \$" + Cart.calculateTotalPrice());
System.out.println("ITEMS BOUGHT: \n" + Cart.toString());

/* ****************************************************************** */

Cart.clear();
System.out.println("TOTAL PRICE = \$" + Cart.calculateTotalPrice());
System.out.println("ITEMS BOUGHT: \n" + Cart.toString());

/* ******************************************************************* */

Shirt shirt4 = new Shirt("green shirt", 130, Shirt.Size.L);
Pant pant4 = new Pant("green pant", 130, 34);
Shoes shoe4 = new Shoes("green shoe", 200, 8);

System.out.println("TOTAL PRICE = \$" + Cart.calculateTotalPrice());
System.out.println("ITEMS BOUGHT: \n" + Cart.toString());

/* ******************************************************************** */

}
}

```

### LabTest#2-Section 6 -- Sample Output ( in accordance to above Driver Class)

Sorry about the minor glitch in the TotalPrice Calculation. I had forgotton to reset TotalPrice to 0 : It should be ok now
----------------------------------------------------------------------------------------
```
Item Added: Item Name: blue shirt Item Price: \$100 Item Size:M
Item Added: Item Name: blue shirt Item Price: \$120 Item Size:S
Item Added: Item Name: maroon shirt Item Price: \$130 Item Size:L
Item Added: Item Name: brown pant Item Price: \$65 Item Size:32
Item Added: Item Name: black pant Item Price: \$130 Item Size:34
Item Added: Item Name: brown pant Item Price: \$100 Item Size:33
Item Added: Item Name: black shoe Item Price: \$200 Item Size:8
Item Added: Item Name: black shoe Item Price: \$200 Item Size:8
Item Added: Item Name: grey shoe Item Price: \$200 Item Size:8
TOTAL PRICE = \$1245
ITEMS BOUGHT:
Quantity = 2 blue shirt
Quantity = 1 maroon shirt
Quantity = 2 brown pant
Quantity = 1 black pant
Quantity = 2 black shoe
Quantity = 1 grey shoe

Item Removed: Item Name: maroon shirt Item Price: \$130 Item Size:L
Item Removed: Item Name: black pant Item Price: \$130 Item Size:34
Item Removed: Item Name: black shoe Item Price: \$200 Item Size:8
TOTAL PRICE = \$785
ITEMS BOUGHT:
Quantity = 2 blue shirt
Quantity = 2 brown pant
Quantity = 1 black shoe
Quantity = 1 grey shoe

Cart Cleared
TOTAL PRICE = \$0
ITEMS BOUGHT:

Item Added: Item Name: green shirt Item Price: \$130 Item Size:L
Item Added: Item Name: green pant Item Price: \$130 Item Size:34
Item Added: Item Name: green shoe Item Price: \$200 Item Size:8
TOTAL PRICE = \$460
ITEMS BOUGHT:
Quantity = 1 green shirt
Quantity = 1 green pant
Quantity = 1 green shoe
```

### LabTest#2 -- Walk through GRID Dungeons

```
1) Create a class called Monster, with attribute name. You can have other enum variables too like :
public enum MonsterType { GOBLIN, ZOMBIE, GHOST };
public MonsterType type;
Feel free to create other enum variables ( if you feel you need more )

2) Create classes Goblin, Zombie, and Ghost which extends the Monster Class. Can  have attributes int x, int y.
3) Create Dungeon which is a (10x10) array of Tiles.
4) A Tile has a 1-D array of Monsters, which starts out empty.
5) The Dungeon class should have methods
deleteMonsters(x,y); //deletes all monster in x,y
toString();// prints out the dungeon, and its inhabitants
You can add other functions if you want to ( according to need )
6) The Monsters should all have:
moveNorth(); //moves north one
moveSouth();
moveEast();
moveWest();
except that:
the goblin will continue moving as long as there is someone else in its destination spot
the zombie kills (deletes) everyone else in its destination spot.
if a ghost lands in a Tile with another ghost, if keeps moving to the next spot.

```

### LabTest#2 -- Sample Output ( In Accordance to the Main Program given below )

• ```~~OUTPUT 1:~~
DUNGEON[1][0] CONTAINS ::    Cell[0]: Goblin1 GOBLIN
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 2:~~
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 3:~~
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN
DUNGEON[1][3] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 4:~~
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN
Cell[1]: Ghost2 GHOST
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 5:~~
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 6:~~
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Ghost1 GHOST
Cell[1]: Goblin2 GOBLIN
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN
DUNGEON[2][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE

~~OUTPUT 7:~~
Monster: Ghost1 GHOST AT DUNGEON[1][1] GETS EATEN  UP
Monster: Goblin2 GOBLIN AT DUNGEON[1][1] GETS EATEN  UP
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE
DUNGEON[1][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN

~~OUTPUT 8:~~
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE
DUNGEON[2][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN

~~OUTPUT 9:~~
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE
DUNGEON[2][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN

~~OUTPUT 10:~~
DUNGEON[1][0] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[1][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE
DUNGEON[2][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN

~~OUTPUT 11:~~
DUNGEON[1][1] CONTAINS ::
Cell[0]: Zombie1 ZOMBIE
DUNGEON[1][9] CONTAINS ::
Cell[0]: Ghost2 GHOST
DUNGEON[2][2] CONTAINS ::
Cell[0]: Goblin1 GOBLIN

```
•