Wednesday, August 31, 2011

CS106A Programming Methodology Problem Solutions: Assignment 2

EDIT: Source code files now available for download!
For full problem descriptions, click here.

Assignment two has a total of six problems, and the problems are considerably harder than those in assignment one. This is partly because of the introduction of the graphics program, and partly because of the introduction of return methods (for it creates a lot more possibilities for program decomposition). On the bright side, in this assignment we are allowed to use variables as well as various keywords (e.g., "break"), making it a lot easier to program.

Anyway, without further ado, I'll get to the problems:

Problem 1: Quadratic (Quadratic.java):
For this problem, you have to ask the user for the coefficients of a quadratic equation. Then, using the quadratic formula, your program should output the solutions. Or, if the equation has no solution, then your program should output a line saying so.

click to enlarge

This problem is very straight-forward.
//File: Quadratic.java
// --------------------
//This program is a stub for the Quadratic problem, which finds the
// roots of the quadratic equation.

import acm.program.*;

public class Quadratic extends ConsoleProgram {

	
	private void userInput() {
		//Get user input:
		println("Enter coefficients for the quadratic equation ");
		a=readInt("a: ");
		b=readInt("b: ");
		c=readInt("c: ");
	}
	
	private void printSolutions() {
		int  discriminant=b*b-4*a*c; //calculates number inside the root
		double firstSolution, secondSolution;

		//Display appropriate messages based on whether there are solutions
		if (discriminant<0){
			println("This quadratic equation has no real roots.");
		} else {
			//Calculate solutions
			firstSolution=(-b+Math.sqrt(discriminant))/(2*a);
			secondSolution=(-b-Math.sqrt(discriminant))/(2*a);
			//Output solutions
			println("The first solution is: "+firstSolution);
			println("The second solution is: "+secondSolution);
		}
	}
	public void run() {
		userInput (); //get the coefficients
		printSolutions(); //output message
	}
	
	//Private instance variables
	private static int a,b,c;

}



Problem 2: Find Range (FindRange.java)
 This program reads in a list of integers, one per line, until a sentinel value of 0 (which could be easily changed to some other value) is entered. Then, the program would output the largest and smallest integers from the list, excluding the sentinel. If the very first line of input contains the sentinel value, then the program should indicate so. And if the second line of input contains the sentinel value, the program should output the first integer as both the largest and the smallest integer.

click to enlarge

Although the program itself is simple, it is quite easy to make some logic errors. In fact, I had to fix my code a couple of times, for it failed a few certain cases.

//File: FindRange.java
//--------------------
//This program is a stub for the FindRange problem, which finds the
//smallest and largest values in a list of integers.


import acm.program.*;

public class FindRange extends ConsoleProgram {

	private static final int SENTINEL=0;
	
	//Intro: description of program
	private void intro () {
		println ("This proram finds the largest and the smallest numbers.");
	}
	
	//Gets user input until sentinel is entered
	private void userInput () {
		int input;
		while (true) {
		    input=readInt ("? ");
		 
		    //Exits when sentinel is entered
		    if (input==SENTINEL) {
			break;                 
		    }
		 
		    //Update values of maxNum and minNum if appropriate
		    if (input>maxNum||maxNum==SENTINEL) {
			maxNum=input;
		    }

         if (minNum>input||minNum==SENTINEL) {
			minNum=input;
		    }


		}
	}
	
	private void printResults() {
		
		//If the first input is the sentinel, then the boolean expression will
		//be false and no values will be output. If not, then the largest and
		//smallest numbers will be output
		if (minNum!=SENTINEL) {
		    println ("smallest: "+minNum);
		    println ("largest: "+maxNum);
		
		} else {
		    println ("No value was entered.");
		}
		
	}
	public void run() {
		intro(); //outputs program description
		userInput(); //gets a list of numbers from user
		printResults(); //Outputs the largest and smallest nums
	}
	
	//Private instance variables:
	private static int maxNum=SENTINEL, minNum=SENTINEL;
}




Problem 3: Hailstone (Hailstone.java)
 This program is extremely simple. You first take an integer from the user, then,
  • if the number is odd, multiply the integer by 3, then add one to the product
  • if the number is even, divide it by two
You then repeat this process until the resulting number is 1. At this point, the program will output the number of steps that the process took.

// File: Hailstone.java
//--------------------
//This program is a stub for the Hailstone problem, which computes
//Hailstone sequence described in Assignment #2.

//A while loop will do...	

import acm.program.*;

public class Hailstone extends ConsoleProgram {


	public void run() {
		int num;
		int count=0 ;//The number of steps it takes
		num=readInt("Enter a number: ");
		
		while (num!=1) {
			if (num%2==0) {
				print (num+" is even so I take half: ");
				num=num/2;
			} else {
				print (num+" is odd, so I make 3n + 1: ");
				num=num*3+1;
			}
			println(num);
			count++;
			
		}
		println("This process took "+ count+ " to reach 1");
	}
}



Problem 4: Target (Target.java)
 For this program, you basically have to draw three filled ovals centered in the screen:

// File: Target.java
// ------------------
//This program is a stub for the Target problem, which displays
//a target by adding concentric circles to the canvas.

//The only thing problem is that the final size might be off by one pixel because
//of rounding

import java.awt.Color;
import acm.graphics.*;
import acm.program.GraphicsProgram;

public class Target extends GraphicsProgram {

	private static final double INCHES_1=1, INCHES_2=0.65, INCHES_3=0.3;// the three radii
	
	public void run() {
		//Specify the radius (in inches) and color for each circle:
		addFilledCricleToCenter (INCHES_1, Color.red);
		addFilledCricleToCenter (INCHES_2, Color.white);
		addFilledCricleToCenter (INCHES_3, Color.red);
	}
	
	//This method adds a filled circle (with specified color and size) to the center of the canvas
	private void addFilledCricleToCenter (double radiusInInches, Color col) {
		int radiusInPixels= convertToPixels(radiusInInches); //convert radius to pixels
		int diameter= radiusInPixels*2; //calculate diameter
		int startX= (getWidth()/2)- radiusInPixels;  //The leftmost x-location of the circle
		int startY= (getHeight()/2)- radiusInPixels; //the topmost y-location of the circle
		
		//create filled circle with the appropriate attributes, and add it to the canvas:
		add(fillOval(startX, startY, diameter, diameter, col));
		
	}
	
	private int convertToPixels (double inches){
		return (int)(Math.round(inches*72));
	}
	
	//This method creates a filled oval with the appropriate color, location and size
	private GOval fillOval (int x, int y, int width, int height, Color col) {
		GOval oval= new GOval(x, y, width, height); //Create oval with the appropriate size and loc.
		oval.setColor(col); //Change colour
		oval.setFillColor (col); //change colour
		oval.setFilled(true); //make it a filled circle
		return oval;
	}
}



Problem 5: GraphicsHierarchy (GraphicsHierarchy.java)
This program should output something similar to the image below:


The diagram should always be centered in the screen regardless of the width and height of the boxes. Also, the texts should be centered in the boxes. This was probably the program that I worked the longest on, for I am pretty slow at centering objects. It also took me quite a while to simplify the code and make it more general. But besides that, there wasn't any complicated logic needed to code this program.
//
// File: GraphicsHierarchy.java
//----------------------------
//This program is a stub for the GraphicsHierarchy problem, which
//draws a partial diagram of the acm.graphics hierarchy.


import acm.program.*;
import acm.graphics.*;

public class GraphicsHierarchy extends GraphicsProgram {
	
	private static final int BOX_HEIGHT=50, BOX_WIDTH=200;
	private static final int VERT_DISTANCE=40, HORI_DISTANCE=50; // The horizontal and vertical distance between any two adjacent boxes
	

	public void run() {
		assignValues(); //Assign values to the variables that hold the coordinates of the boxes
		
		drawBoxes();
		drawLines();
		
		addLabel("Program", centerBoxX, topBoxY);
		addLabel("ConsoleProgram", centerBoxX, bottomBoxY);
		addLabel("GraphicsProgram", centerBoxX-(BOX_WIDTH+HORI_DISTANCE), bottomBoxY);
		addLabel("DialogProgram", centerBoxX+(BOX_WIDTH+HORI_DISTANCE), bottomBoxY);
	}
	
	private void assignValues() {
		//the console window will only be created after the run method is called, and before that, the height and width will both be
		//zero. Therefore, to get the following three variables to have proper values, the values must be assigned in a method.
		topBoxY=getHeight()/2-(BOX_HEIGHT*2+VERT_DISTANCE)/2;
	    bottomBoxY=getHeight()/2+ VERT_DISTANCE/2;
		centerBoxX=(getWidth()-BOX_WIDTH)/2;
	}
	
	//Add the labels. StartX and startY are the coordinates of the top-left corner of the rectangle that they're in
	private void addLabel(String labelText, int startX, int startY) {
		GLabel lab= new GLabel (labelText, startX, startY); //Create label
		lab.move ((BOX_WIDTH-lab.getWidth())/2,(BOX_HEIGHT+lab.getAscent())/2 ); //move to center	
		add(lab); //add to canvas
	}
	
	//Draw the lines
	private void drawLines() {
		//All three lines branch out of one point, and startX and startY are the coordinates of that point
		int startX=getWidth()/2;
		int startY=(int)((getHeight()-VERT_DISTANCE)/2);
		
		//Draw the three lines
		for(int i=-1; i<=1; i++) {
			add(new GLine(startX, startY, startX+i*(BOX_WIDTH+HORI_DISTANCE), startY+VERT_DISTANCE));
		}
		
	}
	
	//Draws the four boxes
	private void drawBoxes () {
		//The box at the top:
		add(new GRect(centerBoxX, topBoxY, BOX_WIDTH, BOX_HEIGHT));
		
		//The boxes at the bottom
		for (int i=-1; i<=1; i++) {
			add(new GRect(centerBoxX+(BOX_WIDTH+HORI_DISTANCE)*i, bottomBoxY, BOX_WIDTH, BOX_HEIGHT));
		}
	}
	
	//Private instance variables:
	//These are the variables that hold the coordinates of the boxes. See "assignValues" method for more info.
	private static int topBoxY;
	private static int bottomBoxY;
	private static int centerBoxX;
}


Problem 6: Pyramid (Pyramid.java)
With the specified brick width, brick height, and number of rows, the program should output a pyramid like the one below, centered in the screen.

// File: Pyramid.java
// ------------------
// This program is a stub for the Pyramid problem, which draws
// a brick pyramid.


import acm.graphics.*;
import acm.program.*;

public class Pyramid extends GraphicsProgram {
	
	private static int BRICK_WIDTH=18;
	private static int BRICK_HEIGHT=10;
	private static int BRICKS_IN_BASE=35;
	
	public void run() {
		
		//Draw the rectangles row by row, from the bottom row to the top row
		for (int i=BRICKS_IN_BASE; i>=1; i--) {
			int yLocation=getHeight()-(BRICKS_IN_BASE-i+1)*BRICK_HEIGHT-1;
			fillRow (yLocation, i);
		}
	}
	
	private void fillRow (int yLocation, int numOfBricks) {
		int startX=(getWidth()- numOfBricks*BRICK_WIDTH)/2; //the x-Location of the leftmost brick
		//Use for loop to draw the bricks
		//!!!Code continued at the bottom because of the syntaxHighlighter's glitch!
This is the rest of the code:
for (int i=0; i<numOfBricks; i++) { add(new GRect(startX+i*BRICK_WIDTH, yLocation, BRICK_WIDTH, BRICK_HEIGHT)); } } }

I Hate Computers...


Arr!! Why do computers have to be riddled with errors, glitches and bad designs!? After I started using the new computer, I began to pay close attention to its various details, trying to fix any problem that I spotted and change any settings that seemed inconvenient or illogical. And I found that I probably spent at least one and a half hour a day finding solutions for these problems!

Five days ago, I spent hours trying get Microsoft Word to work. On the same day, the icons for certain files stopped displaying correctly, and it took me one to two hours to fix that problem. On the next day, I spent one or two hours just to change the colour of the taskbar. Yesterday, I had to to spend one hour before bed to fix a directory problem. And today, I spent nearly three hours to get the video thumbnails to display correctly, and one hour to find a way to edit the properties of certain glitched files!

Really, why couldn't the developers make the interface a bit more user-friendly, and make more effort to ensure that the system worked without glitches? It is just unacceptable that so many problems arose in just a few days! Even worse, all these problems were difficult to fix, and they all had some obscure solution!

I am exhausted by all the Internet-searching, program-downloading, registry-editing, and rebooting needed to fix the problems. Arrrrrgggg!!

Monday, August 29, 2011

I'm Back (again)

For the past four days, I was away from home, for my family went to another city to help my sister get ready for university.

During those days, I did have access to the Internet, for my family actually brought a laptop. However, I didn't get very much time on the Internet— during the day we would be busy doing other things, and during the night my parents would need the computer to look up for various information— so I couldn't update the blog.

Now that I'm back, I'll be updating the blog again. :)

Thursday, August 25, 2011

The Children of Men by P.D. James



The Children of Men by P. D. James was a wonderful book. After reading the first page I was already drawn to the setting— a world with no fertile man, and therefore no children as well.

Because of this lack of posterity, the world was much different. People no longer cared for technological innovations— except for technologies that will bring pleasures or extend people's lives; most students ended their educational career at the undergraduate level; a form of public suicide called the Quietus emerged; and many people began to have dolls and/or cats as substitutes for children. Also, people no longer cared about political reform—the world was going to end soon anyway— and as a result Britain was ruled by a dictator.

Anyway, the main character, Theodore Faron, by chance got involved with a small rebellion group, and later found out that one of the members of the group was pregnant. He then went on a mission to try to protect this woman so that the baby could be delivered before the woman fell into the hands of the dictator.

Problems with Microsoft Word


Yesterday afternoon I finally finished reading The Children of Men by P. D. James, and decided to use the night to update this blog.

Unfortunately, a terrible thing happened which stopped me from doing so— Microsoft Word 2000 stopped working! Every time I tried to open the program, it would freeze when the program license thing was being displayed. In other words, it would stop responding even before a blank document was opened.

Actually, it would be wrong to say that Microsoft Word had stopped working, for I wasn't even sure if it had ever worked... Yes, that's right— the computer was only a few days old and I have never created a word document on it before. And since I wasn't even sure if it had ever worked, it was hard for me to tackle the problem— I couldn't tell whether it was an installation problem, a compatibility problem (Word 2000 on Windows 7), a licensing problem, or some other type of problem.

Monday, August 22, 2011

The Left Hand of Darkness by Ursula le Guin


I was very excited to read The Left Hand of Darkness, which was partly because that I really liked the author's—Ursula's Le Guin's short story The Ones Who Walk Away From Omelas, and partly because the title sounded extremely interesting. Also, the novel had quite a good reputation, so I was sure that I was going to like this book.

But unfortunately, the novel disappointed me— I did not like it very much.

Friday, August 19, 2011

Should I Transfer?


Today it was finally confirmed that my family would be moving. Not to another city or country, just to another location in the city.

So a question arose: Should I transfer to another school because of the change in location? From my new home, it would take me about twenty minutes by bus to get to my current school. That's not bad at all, but it's worse than the twelve-minute walk that the new close-to-home school would require. Also, I should mention that the new close-to-home school is a very good and popular school which you can't get in unless you live nearby, and this adds another incentive for me to transfer.

However, obviously there are still a lot of reasons for me to stay at my current school, and therefore I have decided to make a detailed comparison between the two schools. For the comparison, I shall call the new close-to-home school school B for simplicity.

Wednesday, August 17, 2011

Looking Back at Grade 10 History

Before the start of second semester, I did not look forward to having history at all. Not only did the subject not interest me, the prospect of having tons of essays and other creative assignments was also unpleasant. Furthermore, I had heard that it was very difficult to get a high mark in history class, so this was one more reason for me not to look forward to the class.

Then, second semester started, and my lack of interest soon turned into strong dislike.

I remember how frightened I was after we spent the first two classes just to introduce ourselves to each other, and the third class to do a group presentation (which was unmarked). It was dreadful to think about how future classes would be, because the first three classes were already filled with my top three dislikes about a class—group work, presentation, and wasting time.

Fortunately, things got better very soon. We began to take notes, and interactions between students became a lot less frequent. Sure, the classes were boring—a lot of the time the teacher was answering stupid questions such as "Where is the Atlantic Ocean?"—but at least it was bearable. Also, most of the things that we learned in the class were things that I did not know before, and this made me quite glad.

And, for some reason, we never did the "creative" assignments! We did not have to write a letter and dip it into tea to pretend that it was written sixty years ago, nor did we have to pretend to be women during WWII, trying to create shopping lists. I was extremely relieved that we did not have to do these assignments.

We did, however, have two major group presentations. But surprisingly, I did very well in both of them! I suppose it was because of the amount of time that I was given to prepare, as well as the group members with whom I did the the presentations.

And as expected,

Tuesday, August 16, 2011

The Handmaid's Tale by Margaret Atwood

The Handmaid's Tale is a famous dystopian novel written by Margaret Atwood. The story takes place in the Republic of Gilead, which is a totalitarian theocratic society that was formerly the United States. In this society, there is a large number of females that are sterile, and as a result there is a group of fertile women whose sole role is to reproduce. These women are the Handmaids.

The narrator of the book is herself a Handmaid, and through her accounts, we learn about the lives of Handmaids, which are quite dull and uneventful. We also learn about the other roles in the society, such as the Commanders, the Wives, the Aunts, and the Eyes. Furthermore, through the narration, we learn about the values and beliefs of the society, as well as what the society considers to be unlawful. In short, by reading about the narrator's life, we get to know how her society functions.

Unfortunately, I didn't particularly like this book. It wasn't bad, but it was a bit boring. To me the whole book was unexciting, and it just wasn't suspenseful. So I only finished this book because I was looking forward to some kind of surprise.

Also, for some reason, I just couldn't feel for the main character. I found her to be rather passive and detached, and many of her problems were those that I could not possibly face during my lifetime (for I am a male). In short, I simply didn't feel connected to the story or the characters, and as a result the book didn't leave a big impression on me.

Monday, August 15, 2011

CS106A Programming Methodology Problem Solutions: Assignment 1

EDIT: Source code files now available for download!
For the full assignment problem descriptions, click here.

Assignment one has four problems, and to be honest none of them is hard. Still, it took me quite a long time to complete all of them, for there were such strict restrictions on the operators and programming structures that I could use. For instance, I wasn't even allowed to have variables, do-while loops, or the ! and && operators! As a result, some of the solutions weren't as neat as they could have been.

 Anyway, here are my solutions to the problems:
 Problem 1: Collect Newspaper Karel (CollectNewspaperKarel.java)



This problem is extremely simple. As shown in the image above, you basically have to write a program that will let Karel pick up the beeper and return to his orginial position. The world will always be the same, so there's no need to include any if structure at all. Just a straight-forward program that directly tells Karel what to do.
import stanford.karel.*;

public class CollectNewspaperKarel extends SuperKarel {

 public void run() {
   moveToNewsPaper();
   pickUpNewsPaper();
   returnToStartingPoint();
  
 }
 
 //Karel picks up the newspaper
 private void pickUpNewsPaper() {
  pickBeeper();

 }
  
 //Karel returns to original position
 private void returnToStartingPoint() {
  turnAround();
  for (int i=0; i<3; i++) {     move();   }      turnRight();   move();   turnRight();     }    //Karel exits the room and gets to the newspaper  private void moveToNewsPaper() {   turnRight();   move();   turnLeft();      for (int i=0; i<3; i++) {     move();   }     }  }  


Problem Two: Stone Mason Karel (StoneMasonKarel.java)


This problem is also very straight-forward. You basically have to create a program that will make Karel fill up the columns (i.e., 1,5,9,13...).
import stanford.karel.*;

public class StoneMasonKarel extends SuperKarel {

 public void run() {
  repairCurrentColumn();
  while (frontIsClear()){
   repairNextColumn();
  }
 }

//Pre-condition: Karel is at the upper-end of a column, facing North
//Post-condition: Karel is at the lower-end of a column, facing east
public void backToOriginalPosition(){
  turnAround();
  while(frontIsClear()){
   move();
  }
  turnLeft();
}

//Pre-condition: Karel is at the lower-end of a column that may needs to be repaired, facing east
//Post-condition: Karel is at the same position, and the entire column is repaired
public void repairCurrentColumn (){
  turnLeft();
 
  while (frontIsClear()){
   if (noBeepersPresent()){
    putBeeper();
   }
   move();
  }
  //This is to repair the last bit of the column
  if (noBeepersPresent()){
   putBeeper();
  }
 
  backToOriginalPosition();
 
}

/*Pre-condition: Karel is at the lower-end of a certain column that has already
  been repaired, and there is an unrepaired column to the right
 *Post-condition: Karel is has moved to and repaired the adjacent column that is
  east of that certain column, and is at the lower-end of it
 */
public void repairNextColumn(){
  goToNextColumn();
  repairCurrentColumn();
}

//Pre-condition: Karel is facing east, at the bottom on a column, and there is another
//column to the right
//Post-condition: Karel has moved eastward, onto the next column
public void goToNextColumn(){
  for (int i=0; i<4; i++){
   move();
  }
}
}



Problem 3: Checkerboard Karel (CheckerboardKarel.java)


For this problem, you have to create a checker pattern for any given world (even a 1*1 square). Took me a little while to figure out how to decompose this problem.
import stanford.karel.*;

public class CheckerboardKarel extends SuperKarel {

 public void run() {
  finishRow();
  while (frontIsClear()){ //If there's a next row, then finish that row
   goToNextRow();
   if (frontIsClear()){ //In case that the world is a one column-world
    finishRow();
   }
   
  }
   
 }
 
 //Pre-condition: Karel is at a square where a beeper needs to be in place
 //Post-condition: The whole row that the square is in is now completed.
 public void finishRow(){
  putBeeper();
  
  //Put down a beeper every other step
  while (frontIsClear()){
   move();
   
   //If structure in place to ensure that
   //Karel doesn't run into a wall
   if (frontIsClear()){
    move();
    putBeeper();
   }
  }
  faceNorth();
 }
 
 //Pre-Condition: Karel is facing east or west
 //Post-Condition: Karel is facing north
 public void faceNorth (){
  if (facingEast()){
   turnLeft();
  }
  else{
   if (facingWest()){
    turnRight();
   }
  }
 }
 
  //pre-condition: Karel is facing north, with at least
  //a wall beside it
 
  //Post-Conidtion: Karel is facing east or west, with a wall
  //right behind it
                   
 public void turn (){
  
  //The following assignment
  if (leftIsClear()){
   turnLeft();
  }else{
   turnRight();
  }
 }
   
    
  
 
 
 //Pre-condition: There is at least one row above the row that Karel is currently in
 //Post-condition: Karel has moved onto the next row, to a space that needs a beeper
 //                (Exception: when it is in a one-column world, he may move by two rows
 //                instead)
 
 //How this method works:
 //Suppose Karel is at point K. If there is a beeper at point K, Karel will move to
 //point X. Otherwise, it will move to point Y
 //...........XY
 //............K
 
 public void goToNextRow(){
  if (noBeepersPresent()){
   move();
   turn();
  }
  else{
   move();
   turn();
   
   /*If this condition is not satisfied, it means that the world is only
   one-column wide. In this case, Karel will move onto the next available row
   (if there is one)*/
   if (frontIsClear()) {
    move();
   }
   else{
    //Move onto the next row if there is one
    faceNorth();
    if (frontIsClear()) {
     move();
    }
    
   }
    
  }
 }

}



Problem Four: Midpoint Finding Karel (MidpointFindingKarel.java)


The goal of this program is to be able to let Karel find and stop at the midpoint of any given width. The first time it took me more than 1.5 hours to finish all the coding, so I was beyond miserable when the whole file got accidentally deleted. Fortunately, the second time it only took me about 10 to 15 minutes.
import stanford.karel.*;

public class MidpointFindingKarel extends SuperKarel {
//My algorithm is quite simple. running the program and reading the comment lines
//should be enough for you to understand
 
public void run() {
  layBeepers(); //Put one beeper in each square in the row
  cleanUpBeepers(); //Alternately remove one beeper from each end. This way Karel will
         //be removing the beeper at the middle square last
  putBeeper(); //Put one beeper back in the middle square

}

//Put one beeper in each square of the row
public void layBeepers(){
  putBeeper();
  while (frontIsClear()){
   move();
   putBeeper();
  }
  turnAround(); //Turn around so that Karel is facing the center
}

//Only move if front is clear
public void moveIfSafe(){
  if(frontIsClear()){
   move();
  }
}

//Pre-condition: Karel is facing west or east
//Post-condition: Karel is facing south
public void turnSouth(){
  if(facingEast()){
   turnRight();
  }else{
   turnLeft();
  }
 
}

//Turn around, move one space (if possible), and then pick up the beeper (if possible)
public void turnAroundAndPickBeeper(){
  turnAround();
  moveIfSafe();
  if (beepersPresent()){
   pickBeeper();
  }
}

//The purpose of this method is basically to let Karel pick up a beeper from the opposite end
public void pickUpEndBeeper(){
  while (beepersPresent()){//Karel keeps walking until there isn't a beeper at his
                        //location or until he reaches the wall
   if (frontIsClear()){
    move();
   }
   else{
    pickBeeper();
    turnSouth();//Turning south is a signal for "already picked up a beeper)
   }
  }
 
  if (frontIsClear()){
   turnAroundAndPickBeeper();//Turn around and pick up the beeper located at the end
  }
  else{
   if (facingSouth()) //If Karel has already picked up a beeper, then he will
                   //simply change direction
   {
    faceCenter();
   }
   else{
    turnAroundAndPickBeeper();//If not, he will pick up the beeper at the end
   }
   
  }
  
}

//Let Karel face the center
public void faceCenter(){
  if (rightIsClear()){
   turnRight();
  }else{
   turnLeft();
  }

 
}

//Karel alternately picks up a beeper from each end. Eventually, Karely will stop at the
//middle square
public void cleanUpBeepers(){
  while (notFacingSouth()){
  
   pickUpEndBeeper();
   moveIfSafe();
   if (noBeepersPresent()){//If this is satisfied, it means that all beepers have been
                        //cleared
    //Move back to the middle square:
    turnAround();
    moveIfSafe();
    turnSouth();//Since no variable can be used, facing south is the only way
                //to break out of the while loop
   }
  }
 
}
}

CS106A Programming Methodology

CS106A
About three to four weeks ago I started viewing the videos of the lectures of Stanford computer programming methodology course.
Then, during one of the first lectures, the professor told the class that there was a website that contained all the handouts and assignments of the course. I decided to do the assignments so that I could enhance my programming abilities. Also, I have decided to put my solutions online so that others may compare their answers with me.
And to make the posts easier to access, all their titles will begin with "CS106A Programming Methodology." They should be easy to find, then, if you simply go to the list of posts in alphabetical order.
That's it for this post.

Sunday, August 14, 2011

Blogger Header: Changed

Random Stuff

A month ago I attempted to change the header of this blog to an animated fish image (read the post that I made at the time). However, that ended up as a failure, so my header remained unchanged.

Today, I made another attempt to create a Blogger header image. This time, I was a lot less ambitious. I only added the description "anything that comes to mind..."and tried to use gradients, lines, and sparks to make the header look less plain.

Unfortunately, the lines, gradients, and sparks didn't end up looking very nice, so I had to gave up on all of them. However, I didn't want my final result to be literally unchanged from my original header, so I added a spider to the image. I think the spider does enhance the header a little bit.

In total, I spent about one hour working on this new (simple) header, with most of the time being used on tweaking the image so that it fit better on the page. For example, I had to readjust the size and position of the image very often. Shame, shame, Blogger. Why do you have to make it so difficult for users to change the header images?

Anyway, I hope you'll all like this header better than the original one. :)

Death on Nile by Agatha Christie


To be honest I found the first half of the book to be quite boring. There was no single murder during this part of the book, and yet I already knew who was going to die (for it was revealed on the front flap). As a result, there wasn't really any excitement for me.

However, once the first murder occurred, everything changed. It was a very mysterious and complex case, and every few pages a new discovery was made. Also, there were two subsequent deaths after the first murder, which made this novel very eventful.

My favourite part was, obviously, the last pages of the book. During these pages, Poirot discussed about the suspects one by one, and one by one the suspects were cleared of the murders. This was very thrilling because I never knew when Poirot would finally said "you are the murderer!"

Also, I must mention that the trick in this book was very ingenious. I actually half-guessed the trick after I read about three quarters of the book, but it was nevertheless smart (and I like considering myself smart...). It was simple, yet clever.

Overall, I liked this book. Even though the first half of it was a bit dull, all the excitement in the second half definitely made up for it.

Friday, August 12, 2011

Towards Zero by Agatha Christie

Towards Zero was first published in 1944, and it is one of the many mystery novels written by Agatha Christie.

This novel is different from most other detective novels—there isn't one single murder until the half-way point. Instead of starting the story with a murder, Agatha Christie starts it with the events that lead to the murders, the descriptions of the suspects , as well as the suspects' relationships with each other.

This way of presenting the murder case is not only interesting but also successful—it gave me a entirely new experience of reading a detective novel. For once, not only did I have to guess who the murderer was, I also had to guess who the victim was! This was especially exciting because I felt that almost everyone could be a murderer or a victim, and every moment I had to hope that my favourite character would neither commit a murder nor become a victim of murder.

Furthermore, once again Agatha Christie gave us a dramatic ending. It wasn't until the very end that we learned who the real murderer was, and what the real murder was intended to be. And like in many other works of Agatha Christie, everything was clear once we read about the truth—all the clues came together, and nothing was illogical.

Overall, I liked this book very much. It was unique and suspenseful, and was one of the best detective novels that I have read.

Also, a bit of spoiler:

Dream: A Strange Adventure

Unfortunately this dream had so many components that I couldn't remember all of them.

Okay, I guess I will start with the most vivid part:

I was in some kind of camp, with my mom being the coordinator. There were a lot of adolescents, and most of them were either my age or close to 20 years old. Also, the camp was either in a mountain or in another isolated place. Oh, and I forgot to mention that even though there were a lot of people in the camp, we were made into "groups," with six or seven people in each group. Everyone was together during daytime, but the groups were separated at night.

There were two vicious people in my group. For two days in a row, they had already killed two other people in my group, for some reason that I forgot. Then, for the same reason, they threatened to kill me and my mother the next morning (it was at night when they threatened me).

After they went into their tents and fell asleep, I quickly went into my mom's tent and told her that we must escape. I think she was reluctant to do so because she was the only adult who could take care of the people in the camp. Fortunately, after some time, I finally persuaded her to drive both of us away.

After we arrived home, I was still very worried about the two murderers, and did a lot of things to ensure that they would never find me. For instance,  I went onto the Internet and made sure that they wouldn't be able to find my picture or address on it.

The next day, I went to (summer) school. Apparently there was a huge project due on the day (which I didn't finish), but fortunately my teacher wasn't there. And since there was only the supply teacher, the students, including me, talked a lot (even during class time).  There was this new girl whom I have never seen, but after talking to her, she seemed quite nice.

Then, after some events, the girl announced that she was actually a ghost! She said that she was also in the camp that I went to, and died because my mother wasn't there and a terrible thing happened. Most other people in the camp died too.

The next thing I knew, I was with my parents, my sister, and my cousin's family. We were in the place where my camp was! Also, one of the murderers was there, but he didn't seem evil or aggressive.

We began to live there. Somehow a house emerged and we didn't really need to worry about not having enough food. But I think there was something that we were worried about. Oh, I think the parents were worried about the children's education. Since the place was isolated, there wasn't any school nearby, and it was hard for us to receive education. I am not sure what the parents' solution was...

 Anyway, for the rest of the dream I think I was basically exploring the house (which was quite normal). Also, I remember how another family moved to the place and opened a coffee shop...

Thursday, August 11, 2011

The Lightning Thief by Rick Riordan


In this book, the narrator, Percy Jackson, finds out that his father is actually the sea god Poseidon. Then, he learns that there is a conflict between Poseidon and Zeus because Zeus believes that Poseidon has stolen his master weapon—the lightning bolt. The narrator must retrieve the lightning bolt for Zeus in order to resolve this conflict, or else the world would turn into chaos. Then, for the rest of the book the narrator describes his quest to finding the lightning bolt.

Tuesday, August 9, 2011

The Hitchhiker's Guide to the Galaxy Douglas Adams

Usually, I would choose whether or not to read a book based on its cover and title— I would only read a book if I like its title and/or cover. And to be honest, I like neither the title nor the cover of The Hitchhiker's Guide to the Galaxy. However, because this book was ranked fourth on a Top 100 Sci-Fi Book List, I decided to read it anyway, just in case that I had misjudged it.

 I hadn't. 

From the very beginning, I just didn't find this book interesting. The style, the plot, the characters—everything. Also, I simply disliked the author's "humor." I feel that there were parts that were supposed to be funny, yet I just found myself unable to laugh at these parts. In fact, I found them to be quite... pretentious (not sure if it's the right word).

 I didn't like this book. I actually tried to like it, but I just couldn't .

Monday, August 8, 2011

Sophie's Choice by William Styron


I must confess that I did not finish reading this book—I only read 114 pages out of the total of 562 pages.

However, unlike usual, the reason why I did not finish reading this book was not that this book was bad. Instead, it was because this book was so intriguing that I could not wait to know all things that would happen in it. I wanted to know why Nathan had such huge mood swings, what "Sophie's choice" was, and what would happen to the three main characters.

So I went onto the Internet and read the spoiler. I didn't just look up the plot summary—I actually looked up the chapter summaries, which were very detailed. And by reading the chapter summaries, I knew all there was to know about the plot of this novel.

I must say, even reading the chapter summaries was exciting, for there were such dramatic revelations and events. However, once I read the chapter summaries, I lost all my interest in the book, and I stopped reading it.

Saturday, August 6, 2011

Database: Fail


For quite some time I have longed for a database program that would be able to store all the vocabularies that I have studied. Each vocabulary would have attributes such as "definition", "synonyms", "date added" and "source," and this way I would be able to sort them very easily.

So today I finally decided to actually obtain one. However, the process was not nearly as easy as I have imagined.

At first, I tried to use the Java Database program. But who knew that it was going to take thirty minutes to download and three hours to install? Even worse, I couldn't find a way to open the program, even after I searched the Internet for more information! So I had to give up.

Next, I tried to code a simple database myself. But I realized the impossibility of it after one hour of coding. The programming language that I used was simply not powerful enough for a good database.

At last, I tried to find other databases on the Internet to download, but it didn't go well either. I could not find any free and non-online database that was easy to understand and use!

So at the end, I wasted a whole day accomplishing nothing.

Friday, August 5, 2011

Google Dictionary: No Longer Available

I have always relied on Google Dictionary when I came across words that I didn't know. It takes shorter to load than dictionary.com, and the layout is much simpler than all the other dictionary websites.

However, today when I typed the URL of Google Dictionary into the address bar, I saw the message that's in the above screenshot—Google Dictionary is no longer available!

So I began searching the Internet for more information, and this is what I found:
Google Dictionary was recently integrated into Google Web Search. Simply search for "define X" where X is the word you want to look up. Clicking on the "more" link (or on the toolbelt "Dictionary" link on the left) will give you practically the same experience that was available on dictionary.google.com.
We're working hard to make the dictionary experience even better on google.com so it will be easier for our users to get the dictionary experience without the need to go to a separate property.
This is just stupid. By incorporating Google Dictionary into the Google Web search, Google is making the dictionary feature much harder to use. Here are the reasons:

1. Poor Accessibility
It's much harder to access now. In the past, the URL for Google Dictionary was so simple that one could just type it into the address bar. It was google.com/dictionary

Now,the typical URL of a dictionary search page is: http://www.google.ca/search?q=best+dystopian+novels&hl=en&safe=off&prmd=ivns&ei=scY0TvPXHMGcgQeX27yEDQ&start=10&sa=N&biw=740&bih=396#sclient=psy&hl=en&safe=off&tbs=dfn:1&source=hp&q=hello&pbx=1&oq=hello&aq=f&aqi=g10&aql=&gs_sm=e&gs_upl=858l107460l2l107610l7l7l1l0l0l0l174l707l2.4l6l0&bav=on.2,or.r_gc.r_pw.&fp=dfa68eb25e59583b&biw=740&bih=396.

See the difference!? Now it'd be impossible to type the URL into the address bar! Instead, one has to go to google.com→ type "define (word)" → press the "search button"→press the "more" link! 

The dictionary has become so much harder to access!

2. Bad Layout
Originally the layout of Google Dictionary was great because the page was extremely simple:
With this layout, you can see the definition(s) and synonyms very easily

However, after it is integrated into Google Web Page, the whole page becomes cramped because of the annoying tool-belt thing on the left:
Click to enlarge image
This may not seem that bad if you view the page at 100% zoom. However, if you view the page at 200% zoom, it would become a huge problem. The page would become too wide, and the synonyms will  come off-screen. At the same time, a huge portion of the page would be occupied the useless tool-belt.
---

Conclusion
Why would Google do such a terrible thing? By doing so, it clearly isn't doing the users any good! Not only does it become harder for the users to actually reach the dictionary page, it also becomes harder for the users to use and view the page! 

Also, why couldn't Google keep the Google Dictionary page even if this new feature was added? Is it because the cost is too high? Or is it because they actually believe that no one will dislike their poor, new feature?

Looking Back at Grade 11 Chemistry

Note: I took this course in grade 10

Overall grade 11 chemistry was an easy course— the marks were mostly based on quizzes and tests, and the course material really wasn't that difficult. As a result, I got a pretty good mark in it.

However, I wish the course was a bit harder and that the teacher covered more material in it.

From my memories, there were about twenty or thirty minutes of free time at the end of almost every chemistry class. In addition, there were probably more than 7 "free study periods," in which we could do whatever we wanted. I feel that we could have accomplished a lot more in the course if the teacher hadn't given us all this free time. Perhaps he could have taught us some of the grade 12 material, or gone deeper into each of the topics.

Nevertheless, I learned quite a lot of stuff in the class. I learned to name the most basic of the organic compounds, to do stoichiometric calculations, as well as to identify the various periodic trends. I also learned more about acids and bases, nuclear reactions, and significant digits. In addition, through the final project at which I failed, I learned about the most common ways in which cancer cells could resist cancer drugs. So it wasn't that I learned nothing from the course, just that I could have learnt a lot more.

Next up: Looking Back at Grade 10 History
Or, go back to intro and a list of all posts in my grade ten reflection series

Thursday, August 4, 2011

Speaker for the Dead by Orson Scott Card

File:Speaker dead cover.jpg
Speaker for the Dead is a novel by Orson Scott Card that is an indirect sequel to Ender's Game. What does this mean? Well, it means that this novel has many elements of Ender's Game (including the character Ender himself), but can still be read even if the reader has not read Ender's Game before.

Personally I have read Ender's Game before, so obviously I had no problems understanding the references made to the book when I read Speaker for the Dead . However, I wouldn't be sure if the readers with no such previous knowledge would be able to handle all the information. This is partly because there's so many things to remember in the book already (e.g., all the characters' names), and partly because there really isn't that much elaborate explanation to all the things that have already been covered in Ender's Game. Also, I feel that people who haven't read the prequel wouldn't know Ender's story as a child, and thus at the beginning they might actually think that he is an evil character (or is this the author's intention?).

Wednesday, August 3, 2011

Eldest by Christopher Paolini

File:Eldest book cover.png
Eldest is the second book in the Inheritance Cycle,  the sequel to Eragon. It mainly focuses on Eragon's training with the elves, but there are also many chapters about Roran (Eragon's Cousin)'s struggles with the Empire.

I found the book to be a bit too long—it had 1000 pages! It was perhaps filled with too many (unimportant) events and too many details of the events, and I have to admit that it could get a bit tiring after about six to seven hundred pages. This was especially true because by the end the chapters involving Roran became incredibly repetitive and boring, to the point where I almost wanted to just skip them.

Nevertheless, it was a great read. I actually enjoyed most parts of the book because the majority of it was about Eragon's magic training, which I found very interesting. Also, I really liked the part where Eragon found out how he actually cursed the girl whom he thought he had blessed. That was very... exhilarating. Furthermore, the revelations at the end were simply astounding (but I wound't want to spoil that for you, would I?).

Overall, I would recommend anyone who hasn't read this book to read it, given that they have read Eragon already. And if one finds this book too long, I would suggest skipping over some pages (or even chapters), as it doesn't really matter if one doesn't read about all the details.

Prefaces and Introductions


Before, I have never bothered to read the prefaces or introductions of novels. I have always thought that these sections were useless, for they had nothing to do with the actual stories.

But I was wrong.

Today, when I started reading The Speaker for the Dead, I noticed its introduction. At first, I was going to skip the section, but for some reason I decided not to.

Anyway, the introduction was about the process in which the author, Orson Scott Card, wrote this novel. In the introduction, he described how he came up with the idea for the novel,  how he came up with the plot and the details of the novel, and many of the difficulties he has faced during the whole process.

For me, this introduction alone was more meaningful than several other novels combined. For one, it was only through reading this introduction that I learned the enormous amount of energy and thoughts that must be put into each novel. For example, before I read this introduction, I have never thought about how character development could be so difficult and complicated! For two, I believe that reading the introduction will help me understand the novel a lot better, for it provided the reason why the author even started writing this novel in the first place.

Furthermore, I feel that this introduction must be very important to the author too. He must have had so many things that he wanted to say about the novel, and without the introduction, how could he have communicated with us readers? I feel that he must have included an introduction because he wanted us to know why certain things in the novel are the way they are, and I am confident that he probably had a lot more to say than what he actually put in the introduction.

Ahh, I feel that I am going nowhere in this post. In short, today I realized that prefaces and introductions are an extremely important part of the novel. They allow the readers to understand how the novel came into being, and why certain things are the way they are. They allow the readers to read and think about the novel in a completely different way.

Dream: Another one About School

Date 2011/08/03
This dream came in two parts.

First Part
I was in summer school, and in the class my teacher was taking up a test. For some reason I had a lot of questions about the test (probably because she took off a lot of marks), so I kept asking her questions. I think I especially questioned her wordings.

Eventually she grew impatient, and finally she said to me, "you are smart, but also annoying."

What happened next, I don't remember. I remember having some conversation with Michael, who apparently was a Martian. I asked him about the characteristics of his planets, as well as his real age. I remember how he said that on Mars, there was a different way of calculating one's age.

Second Part
This was actually related to the first part, but I was sure that it didn't come right after the first part.

Anyway, English class was about to start, and I was complaining to Jordan about the incident that just happened earlier (in summer school). I remember saying how it was the teacher's fault that she worded the questions so strangely, forcing me to ask a lot of questions.

Then, we came into the classroom. I remember the class from one of my recent dreams, for I immediately recognized the teacher, who was a slightly fat old man. Anyway, the teacher told us that we were going to have a test, a test on part of the novel that we were supposed to read.

This was shocking, for I haven't even read a page of the novel! I could actually remember how in the previous dream he told us to read about fifty pages of it, but obviously I didn't read it. Even more scary, he forbade us from the usual last-minute studying, and did not allow anyone to open their book in class.

Extremely worried, I asked the girl beside me to summarize the book for me. She was actually one of my classmates from grade five. Anyway, she did, but obviously she couldn't tell me about all the details and I couldn't even remember the events.

Then the teacher handed us the test.

My thoughts on the dream
The first part of my dream seems to reflect the truth, for when I was in summer school, I did ask the teacher a lot of questions. And even though the teacher didn't show it, I would imagine her to be quite annoyed by me.

I found the second part far more interesting, for it was actually continued from one of the dreams that I had before! Now that I think of it, Jordan was also in the English class of the previous dream! Also, I should note that I have had a similar dream before, in which I forgot to do a project.

Tuesday, August 2, 2011

Grade 11 Timetable

I have always thought that I wouldn't be able to see my grade eleven timetable until September, the reason being that during the summer it would be impossible for me to obtain a copy of it from my school.

And yesterday, I was complaining to my friends about how the school should set up a system where students could view their timetables online. I was looking at some information about online courses, and thought if the school board could have a working system of online learning, then implementing a timetable-viewing system shouldn't be hard either.

Surprisingly, just one day after my complaint, another friend told me that a similar system was indeed in place! He gave a list of instructions as to how to navigate through the complicated website, and after following the instructions, I was able to see my timetable! This was probably the most exciting moment during the summer so far, because I have been wanting to know my schedule since I the day that I chose my courses. 

Anyway, without further ado, here's my schedule:

1st Semester
2nd Semester
Chemistry (12)
Advanced Functions (12)
Functions (11)
Data Management (12)
English (11)
Physics (11)
Financial Accounting (11)
Biology (11)


The classes are all in order (i.e., I will have chemistry first in the morning, functions second, etc), except that the third and fourth classes will alternate everyday. Also, if I am fortunate enough, I am likely to drop accounting and take philosophy instead.

Overall, I am quite content about the schedule. There is one grade twelve course in the first semester and two in the second, making the schedule quite balanced. Also, I am glad that I have English in first Semester, as this will give me the advantage of working on projects over the winter break. I am also happy that all my math courses are in the morning, when my brain is clearer and when I am able to concentrate better.

Hiding Contents in Blogger

Sometimes there are just things in a blog post that you want to keep to yourself. For example, occasionally in a post I would want to make an snide comment, and I wouldn't want the readers to see that comment for fears that they may get offended by it. At the same time, however, I would still want to be able to see the comment myself, for it may be needed for future references or other purposes.

Unfortunately, Blogger does not have a feature where you can make certain parts of a post viewable only to yourself, and as a result hiding contents in a post is not as easy and convenient as it could be.

Fortunately, however, I have come up with two methods to accomplish this task. And in the rest of this post I will describe them in detail.

Saving as a Draft
The easiest way to do this would be to create two separate posts: one will contain only the things you want others to see, and the other would contain everything you want to see. Then, you can simply publish the first post and save the second as a draft. The others will be able to read the published post, and only you would be able to see the contents of the draft.

One huge disadvantage of this method is that it would be very inconvenient if you want to edit your post later on. Every time you want to make a change, you would have to go through the two copies and edit them separately, and this could be a long and boring process. Of course, if the changes are minor, you may decide to just edit the published post.

Using certain HTML tags
Contents in between certain HTML tags would not show on the page. For example, if you add the below HTML code into your blog post (edit HTML), it would appear as if nothing has changed:



You could therefore use this to your advantage—you can use the above code as a content-hider! To do this, simply copy and paste the HTML code into the HTML editor of your post, then change the content in between the squiggly brackets. Alternatively, instead of using the squiggly brackets, you can use an end tag, like this:



Be careful though: if you use this method, it is still possible for the readers to see the hidden content. They simply have to view the page source of the blogger post, and they will see all the HTML code of your post, including the hidden content. So do not use this method if you think your readers are likely to view the page source of your blog.

Monday, August 1, 2011

Looking Back at Grade 10 Civics

I don't really have a lot to say about my civics class, as I don't have much memory about it. This is partly because it was a half-credit class (so I only took it for half a semester), and partly because everything moved on quite smoothly.

Civics class was very easy. I had few assignments, and the assignments that we did have were all very easy, save for the final project. As for quizzes and tests, I only had a few, and they were all so easy that studying for fifteen minutes would be enough

This is not to suggest, however, that I learned nothing from the class. In fact, I believe that I learned much more in civics class than in careers class. In civics, I learned about the brief history of governments and democracy, the different types of government, and the various government roles in Canada. I also learned about the major political parties of Canada as well as their political platforms. In short, I learned many new things in civics class during the short period of time.

The only thing that I didn't quite like about the class was the final project. It was a project where students had to make a presentation about a charity, and its goal was to make students become more active citizens. I never liked this kind of sanctimonious stuff, and obviously I didn't like the project.

Finally, the reason why I quite liked the class was that I got a very good mark in it. Yes, even though I said that it was an easy course, I didn't do that well in the presentations (we had three of them) and was expecting a  final mark of about 94. However, to my surprise, I got a 97! To date, I still can't understand why I got such a high final mark, especially when most of my marks were between 94 and 96. Hopefully it wasn't because the teacher entered the marks wrong...

Next up: Looking Back at Grade 11 Chemistry
Or, Go back to intro and a list of all posts in my grade ten reflection series