Stanford CS106a Assignment 1 Solution

Standard

The first assignment consists of four problems, none of them too complicated if you paid attention to the lectures and read through the Karel the Robot Learns Java book. After lecture 2, you should be able to solve the first to problems in assignment 1. problem 3 and 4 may be worth waiting with until you have watched lecture 3. ┬áRemember; in this first assignment you are only allowed to use what have been introduced in the lectures or through the Karel book, so it doesn’t really help you a whole lot if you know some Java beforehand…

PROBLEM #1 – CollectNewspaperKarel

This problem was pretty straight forward and provided a nice and easy introduction to the programming world. The program does only need to work in the world provided, so you can more or less program Karel step for step. The decomposition is nice and easy as well and are provided in the problem text, so I just used the one provided there. Here’s the problem:

I did this pretty straight forward and did only use one loop, a for-loop, when Karel is returning to his house. Feels good to get started writing programs! Here is my code.

import stanford.karel.*;

public class CollectNewspaperKarel extends Karel {
	public void run(){
		moveToNewspaper();
		pickUpNewspaper();
		returnToStartPoint();
	}

	//Makes Karel move to the door
	private void moveToNewspaper(){
		move();
		move();
		turnRight();
		move();
		turnLeft();
		move();

	}

	// Makes Karel pick up beeper and turn 180 deg
	private void pickUpNewspaper(){
		pickBeeper();
		turnAround();
	}

	// Mkes Karel return to initial position.
	// Start cond: facing West. End cond: facing East
	private void returnToStartPoint(){
		for (int i=0; i<3; i++){
			move();
		}
		turnRight();
		move();
		turnRight();
	}

	// Makes Karel turn right 90 degrees
	private void turnRight(){
		turnLeft();
		turnLeft();
		turnLeft();
	}

	//Makes Karel turn 180 degrees
	private void turnAround(){
		turnLeft();
		turnLeft();
	}
}

LINKS

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s