Sunday, 1 February 2026

Code Solutions

/* This program will have Karel run around the racetrack
 * 8 times. */
function main() {
 	for (let i = 0; i < 8; i++) {
		runLap();
	}
}

// This function has Karel run once around the track
function runLap() {
	for (let i = 0; i < 4; i++) {
		runSide();
	}
}

// Karel runs one leg of the track and puts down a ball
function runSide() {
	while (frontIsClear()) {
		move();
	}
	putBall();
	turnLeft();
}

main();

// Answers may vary, especially on how the student moves
// Karel forward.

/* This program will have Karel build a tower on
 * every odd column. A tower consists of 3 tennis balls
 * stacked on top of each other. */
function main() {
    buildTower();
    while (frontIsClear()) {
        move();
        if (frontIsClear()) {
            move();
            buildTower();
        }
    }
}

/* This function has Karel build a tower that is three balls high.
 * Precondition: Karel is facing east at the location to build the tower.
 * Postcondition: Karel has built the tower, and is back at the base
 *                facing east.
 */
function buildTower() {
    turnLeft();
    for (let i = 0; i < 3; i++) {
        putBall();
        move();
    }
    turnAround();
    goDown();
    turnLeft();
}

/* This function moves Karel to the wall. */
function goDown(){
    while (frontIsClear()) {
        move();
    }
}

main();

No comments:

Post a Comment