Problem 1

On the assignment 2, we are dealing more with graphics, e.g. rectangles and lines and some more loops like for .. loop. It is using the acm library which helps from hiding some of the java implementations.

In the assignment 1 above link, I outline how to compile and run the problems within a standard eclipse and in this assignment 2 we are using the same idea of using the run configuration to run the correct java file that we are working on.

Here is the Problem 1 : Brick Pyramids, “Write a GraphicsProgram subclass that draws a pyramid consisting of bricks arranged in horizontal rows, so that the number of bricks in each row decreases by one as you move up the pyramid.

The pyramid should be centered at the bottom of the window and should use constants for the following parameters:

BRICK_WIDTH The width of each brick (30 pixels)
BRICK_HEIGHT The height of each brick (12 pixels)
BRICKS_IN_BASE The number of bricks in the base (12)

The numbers in parentheses show the values for this diagram, but you must be able to change those values in your program and still produce a reasonable picture.

My answer, was to start from the bottom of the pyramid and build up, with building up we are wanting to go from the BRICKS_IN_BASE to 1 (or >0) and then find the middle part of the screen (getWidth / 2) (this finds the middle of the screen – the width divided by 2), but since we are wanting to start the pyramid bricks from the left then minus from this middle of the screen (I called this startX) the number of bricks width that we want to build on that level divided by 2 (this is because we figure out the bricks size (number of bricks for this level) * the number that we are putting on this level (e.g. 10) then divide this by 2, which gives a offset to start from)

The startY means where we want to start the building of bricks, which is at the bottom of the screen (-1 so we can see the bottom of the brick height (BRICK_HEIGHT)).

Here is the source code for this assignment but I have included the full assignment code in the above zip file and also the PDF which is the assignment questions.

/*
 * File: Pyramid.java
 * Name: Genux (Ian Porter)
 * Section Leader: 
 * ------------------
 * This file is the starter file for the Pyramid problem.
 * It includes definitions of the constants that match the
 * sample run in the assignment, but you should make sure
 * that changing these values causes the generated display
 * to change accordingly.
 */
 
import acm.graphics.*;
import acm.program.*;
 
public class Pyramid extends GraphicsProgram {
 
/** Width of each brick in pixels */
	private static final int BRICK_WIDTH = 30;
 
/** Width of each brick in pixels */
	private static final int BRICK_HEIGHT = 12;
 
/** Number of bricks in the base of the pyramid */
	private static final int BRICKS_IN_BASE = 12;
 
	public void run() {
		/* You fill this in. */
		int startY = getHeight()-BRICK_HEIGHT;
		int startX;
		for (int i = BRICKS_IN_BASE; i >0; i--)
		{
			startX = getWidth() / 2;
			startX -= i * (BRICK_WIDTH/2);
			for (int j = i; j > 0; j--)
			{
				GRect rect = new GRect(startX,startY,BRICK_WIDTH,BRICK_HEIGHT);
				add(rect);
				startX += BRICK_WIDTH;
			}
			startY -= BRICK_HEIGHT;
		}
	}
}

Problem 4

This is the problem 4 “As an exercise in solving algorithmic problems, program Karel to place a single beeper at the center of 1st Street. For example, if Karel starts in the world”. In solving this problem, you may count on the following facts about the world:

  • Karel starts at 1st Avenue and 1st Street, facing east, with an infinite number of beepers in its bag.
  • The initial state of the world includes no interior walls or beepers.
  • The world need not be square, but you may assume that it is at least as tall as it is wide.
  • Your program, moreover, can assume the following simplifications:
    1. If the width of the world is odd, Karel must put the beeper in the center square.
    2. If the width is even, Karel may drop the beeper on either of the two center squares.
  • It does not matter which direction Karel is facing at the end of the run.

To me the answer is when you move from one side to the other and count the number of steps, and then once you hit the right side wall, go back length /2 steps and then place the beeper, and below is my answer in code, once again the zip file attached is the full assignment 1 with each problem and also the PDF file which includes the assignment in full.

/*
 * File: MidpointFindingKarel.java
 * -------------------------------
 * When you finish writing it, the MidpointFindingKarel class should
 * leave a beeper on the corner closest to the center of 1st Street
 * (or either of the two central corners if 1st Street has an even
 * number of corners).  Karel can put down additional beepers as it
 * looks for the midpoint, but must pick them up again before it
 * stops.  The world may be of any size, but you are allowed to
 * assume that it is at least as tall as it is wide.
 */
 
import stanford.karel.*;
 
public class MidpointFindingKarel extends SuperKarel {
 
	private int middleI =0;
 
	// find the middle by move across until hitting the end
	private void findTheMiddle()
	{
		while (!frontIsBlocked())
		{
			move();
			middleI++;
		}
 
	}
 
	// move half the way back, and place the beeper
	private void placeBeeperInTheMiddle()
	{
		for (int i=0; i < (middleI /2); i++)
			move();
		putBeeper();
	}
 
	// You fill in this part
	public void run()
	{
		findTheMiddle();
		turnAround();
		placeBeeperInTheMiddle();
	}
}

Problem 3

The problem 3 is “In this exercise, your job is to get Karel to create a checkerboard pattern of beepers inside an empty rectangular world, as illustrated in the following before-and-after diagram:”

Karels checkboard
Karels checkboard

The way that I viewed the problem is that the robot (Karel) had to move along the either in Up / Down or Left / Right and place a beeper every other step, so in basics if he moves up, he will move up 1 place see if he is able to move any more, if not turn right and if the front is not blocked move forward and right again to go back down the aisle next to the previous one we have just been up and whilst moving up and down the aisle to place a beeper every other step ( so need to keep check of the steps) or you could do the same process but going left and right instead, e.g. move right first to the end of that aisle and then go up if able to and then turn around and move left along the aisle above the previous aisle.

Here is my implementation of both ideas, again the source code for the assignment 1 is attached above in the zip file and also the PDF with the full assignment details.

/*
 * File: CheckerboardKarel.java
 * ----------------------------
 * When you finish writing it, the CheckerboardKarel class should draw
 * a checkerboard using beepers, as described in Assignment 1.  You
 * should make sure that your program works for all of the sample
 * worlds supplied in the starter folder.
 */
 
import stanford.karel.*;
 
public class CheckerboardKarel extends SuperKarel {
 
	private boolean putBeeper = true;
 
	private void placeBeeperAndMove()
	{
		while (true)
		{
			if (putBeeper) {
				putBeeper();
				putBeeper = false;
			} else
				putBeeper = true;
 
			if (frontIsBlocked()) break;
			move();
		}
	}
 
	private void goUpAndDown()
	{
		boolean turnLeft = true;
 
		while (true)
		{
			if (turnLeft) 
				turnLeft();
			else 
				turnRight();
			placeBeeperAndMove();
			turnLeft = (turnLeft == true ? false : true);
			if (turnLeft)
				turnLeft();
			else
				turnRight();
			if (frontIsBlocked()) break;
			move();
		}
	}
 
	public void goLeftAndRight()
	{
		boolean turnLeft = true;
 
		while (true)
		{
			placeBeeperAndMove();
			if (turnLeft) 
				turnLeft();
			else 
				turnRight();
			if (frontIsBlocked()) break;
			move();
			if (turnLeft)
				turnLeft();
			else
				turnRight();
			turnLeft = (turnLeft == true ? false : true);
		}
	}
 
	// You fill in this part
	public void run()
	{
		// go up and down 
		//goUpAndDown();
		// go left and right
		goLeftAndRight();
	}
}

Problem 2

The basics of problem 2 is “Karel has been hired to repair the damage done to the Quad in the 1989 earthquake. In particular, Karel is to repair a set of arches where some of the stones (represented by beepers, of course) are missing from the columns supporting the arches”, which means that you have to replace empty places with a beeper!. The rules are:

Karel may count on the following facts about the world:

  • Karel starts at 1st Avenue and 1st Street, facing east, with an infinite number of beepers.
  • The columns are exactly four units apart, on 1st, 5th, 9th Avenue, and so forth.
  • The end of the columns is marked by a wall immediately after the final column. This wall section appears after 13th Avenue in the example, but your program should work for any number of columns.
  • The top of the column is marked by a wall, but Karel cannot assume that columns are always five units high, or even that all columns are the same height.
  • Some of the corners in the column may already contain beepers representing stones that are still in place. Your program should not put a second beeper on these corners.

Remember to change the run configurations as from the previous post on how to setup the environment to the StoneMasonKarel for the main class, here is the my java file for this problem 2.

My way of fixing the stones is to go up the supporting line and replace the stones (beepers) and then come back down again and move along 4 positions if able to, and repeat, since in the rules you the height of the building can change which is why I come back down again from the top of the buildings.

/*
 * File: StoneMasonKarel.java
 * --------------------------
 * The StoneMasonKarel subclass as it appears here does nothing.
 * When you finish writing it, it should solve the "repair the quad"
 * problem from Assignment 1.  In addition to editing the program,
 * you should be sure to edit this comment so that it no longer
 * indicates that the program does nothing.
 */
 
import stanford.karel.*;
 
public class StoneMasonKarel extends SuperKarel {
 
	// move up the row and find replace any missing "stones"
	// checking to make sure that we have not reached the top
	private void replaceStones()
	{
		// check for a stone or wall! move in that direction
		while (true)
		{
			if (!beepersPresent())
				putBeeper();
			if (frontIsBlocked()) break;
			move();
		}
	}
 
	private void comeBackDown()
	{
		turnAround();
		while (!frontIsBlocked())
			move();
	}
 
	// need to go up and down move 4 and then up and down
	private void moveAlong()
	{
		while (true)
		{
			turnLeft();
			replaceStones();
			comeBackDown();
			turnLeft();
			if (!frontIsBlocked())
				for (int i =0; i < 4; i++)
					move();
			else
				break;
		}
 
	}
 
	public void run()
	{
		moveAlong();
	}
}

again the zile file attached is the whole assignment 1 problems, so you can download that for the full source code and the PDF assignment details.

Problem 1

To start off with, I am using Eclipse and have attached my settings to get it to work with this assignment.

And now to actual run the code you need to include some things from the acm.jar file, since that is what is mainly being used to hide allot of the Java main implementations. So if you goto the the Package Explorer on the left hand side, and double click on the Package->default packages->CollectNewsPaper.java then to setup the environment for running this java file you need to goto Run->Run Configurations.. on the left options make sure that Java Applications -> New configuration is selected and then select the Project name as the Package and then tick the “include system libraries when searching for the main class” and also the “include inherited mains when searching for the main class”, then on the “main class” option, click search and find the CollectNewsPaper. Here is a image of how it should look.

Eclipse CS106A settings
Eclipse CS106A settings

Now, you should just see a robot (Karel) in the top left of the house and that is about it, we need to write the run() method for him to pick up the newspaper, so alter the code to the below.

/*
 * File: CollectNewspaperKarel.java
 * --------------------------------
 * At present, the CollectNewspaperKarel subclass does nothing.
 * Your job in the assignment is to add the necessary code to
 * instruct Karel to walk to the door of its house, pick up the
 * newspaper (represented by a beeper, of course), and then return
 * to its initial position in the upper left corner of the house.
 */
 
import stanford.karel.*;
 
public class CollectNewspaperKarel extends SuperKarel {
 
	private void getPaper()
	{
		move();
		turnRight();
		move();
		turnLeft();
		move();
		move();
	}
 
	private void pickUpPaper()
	{
		pickBeeper();
	}
 
	private void goBack()
	{
		// turn around basically
		turnRight();
		turnRight();
		move();
		move();
		move();
		turnRight();
		move();
		turnRight();
	}
 
	public void turnLeft()
	{
		turnRight();
		turnRight();
		turnRight();
	}
 
	// You fill in this part
	public void run()
	{
		getPaper();
 
		pickUpPaper();
 
		goBack();
	}
}

and then run again and if you click “start” he will go and pick up the newspaper and return back to where he started from.

I am finding this CS106A fun. In the above zip file there is the full source code for all of the parts to assignment 1, and also the assignment in a PDF file. But I shall place each part on a different post.

Threading – run another part of the program in a separate process

Threading in Java is very similar to the threading in c#, just like the example that I did before (threading in c sharp, running different-parts-of-the-program-at-once. What threading does is to allow for a part of your program to be run from within another process, this process runs normally independently of the main program (you can have links if you wanted to so some memory references).

The operating system gives the impression that it is running allot of programs at the same time, but what is happening that allot of processes (programs) have access to the CPU for a limited amount of time, e.g. 10 milliseconds, and then leave the CPU execution stage whilst another process will enter there CPU execution stage (this is the part where the program is actually doing something).

So lets say that you want to spawn off another process that will talk to a server to get information back e.g. a tab browsing on a modern web browser, whilst you look at another part of the main program e.g another tab, and communicate with that one e.g. type in your login details etc.

So let start with a example of how to create a thread-able program. Here my class basicThread extends the class Thread, which encapsulate the thread-able interface.

public class basicThread extends Thread {

this thread-able interface basically only wants to have the method “run” implemented”, since that is what is called when you start the new thread.

	public void run()
	{
		System.out.println("Before my sleep");
		for (int i =0; i < 10; i++)
		{....

and then in your main program you just need to create a basicThread class and call the start method (from the Thread class that basicThread class inherited from)

		// create the thread, a thread is independent of the main program
		basicThread me = new basicThread();
		// then start it. this calls the run method
		me.start();

and that is it, it will spawn off another process that will run separately in time from the main process.

Here is the full source code, I have also included a file zip that has the source code and also the class files attached, save this as callThread.java

public class callThread {
	public static void main(String[] args) {
		// create the thread, a thread is independent of the main program
		basicThread me = new basicThread();
		// then start it. this calls the run method
		me.start();
 
		// so if the basic thread had that pause it in..
		System.out.println("main thread here!!");
		for (int j =0; j < 5; j++)
		{		
			System.out.println("Mainthread about to sleep at number : "+j);
			// need to pause the main thread
			try{
			  Thread.currentThread().sleep(100);//sleep for 1000 ms
			}	catch(Exception ie){
			}
		}
		System.out.println("End of the main thread");
 
	}
 
}

save this as basicThread.java

public class basicThread extends Thread {
	public void run()
	{
		System.out.println("Before my sleep");
		for (int i =0; i < 10; i++)
		{
			System.out.println("basicThread sleeping at number : "+i);
			try {
				sleep(45);
			} catch (InterruptedException e)
			{
				System.out.println("could not sleep long enought there was a error!!");
			}
 
		}
		System.out.println("after the sleep :)");
	}
}

here is the output, as you can see the mainthread and the basicthread outputs interrupt each other just like any other process does within a CPU.

main thread here!!
Before my sleep
Mainthread about to sleep at number : 0
basicThread sleeping at number : 0
basicThread sleeping at number : 1
basicThread sleeping at number : 2
Mainthread about to sleep at number : 1
basicThread sleeping at number : 3
basicThread sleeping at number : 4
Mainthread about to sleep at number : 2
basicThread sleeping at number : 5
basicThread sleeping at number : 6
Mainthread about to sleep at number : 3
basicThread sleeping at number : 7
basicThread sleeping at number : 8
Mainthread about to sleep at number : 4
basicThread sleeping at number : 9
after the sleep :)
End of the main thread

ArrayList and ListIterator

An ArrayList is basically a array of objects that are managed within a List interface. This basically means that Java will do the management of the List and you just need to either add to that list/change the values/remove items.

The way that the ArrayList is defined is using the Generics syntax, since a ArrayList can be of any type.

ArrayList<String> names = new ArrayList<String>();

this will create a object called “names” that have a array of type String and to add names to the array you use the “add” method, the “add” method can either just have the ArrayList type (in this case a String) as a single parameter or a index into the ArrayList with the ArrayList type again.. e.g.

// normal add
names.add("Genux");
// adding at a set point
names.add("1","Genux at point 1");

to remove at a set point, there is a method called “remove” that will either take a index point or a class (e.g. will compare against a class within the ArrayList to see if there is anything that equals, if so remove from the ArrayList), in the example below I am just going to use the index point to remove from the ArrayList

names.remove(0);

you can also alter any of the names within the ArrayList with using the method “set”, here I am altering the index point 0 within the array to have the String value of “Genux new start”

names.set(0,"Genux new start");

The ListIterator is when you can iterate through a List (interface implemented object e.g ArrayList), to iterate through a list you basically go from one to the next to the next etc. the ArrayList object called names has a method that will return the list iterator object for the ListIterator to go through, the hasNext method within the ListIterator returns true if there is another value/object after the present one, the “next” method within the ListIterator returns a value/object of the type of ListIterator and then goes to the next value within the List, here is some code that uses the above that uses the hasNext and next methods.

ListIterator<String> arrayListIt = names.listIterator();
while (arrayListIt.hasNext())
{
	System.out.println("Names :"+ arrayListIt.next());
}

here is the source code in full, if you save as “ArrayListTutorial.java”

import java.util.ArrayList;
import java.util.ListIterator;
 
public class ArrayListTutorial {
 
	public static void main(String[] args) {
			ArrayList<String> names = new ArrayList<String>();
			// add names in a standard way, placing on the end in this case the start position = 0 
			names.add("Genux");
			// adding a set point
			names.add(1,"Genux at point 1");
 
			System.out.println("Starting point of the Array of names");
 
			// a ListIterator is a template (e.g. can use any type String/Integer etc) 
			// that will loop through a List object (in this case the ArrayList has implemented a List interface)
			ListIterator<String> arrayListIt = names.listIterator();
			while (arrayListIt.hasNext())
			{
				System.out.println("Names :"+ arrayListIt.next());
			}
 
			System.out.println("Alerting the starting name");
			// change the start of the array list e.g. point 0
			names.set(0,"Genux new start");
 
			// loop through the array list with a iterator
			arrayListIt = names.listIterator();
			while (arrayListIt.hasNext())
			{
				System.out.println("Names :"+ arrayListIt.next());
			}
 
			System.out.println("Removing index 0 from the ArrayList of names");
			names.remove(0);
			// loop through the array list with a iterator
			arrayListIt = names.listIterator();
			while (arrayListIt.hasNext())
			{
				System.out.println("Names :"+ arrayListIt.next());
			}
	}
}

and the output would be

Starting point of the Array of names
Names :Genux
Names :Genux at point 1
Alerting the starting name
Names :Genux new start
Names :Genux at point 1
Removing index 0 from the ArrayList of names
Names :Genux at point 1

to compile if you save the java code above as “ArrayListTutorial.java”

javac ArrayListTutorial.java
java ArrayListTutorial