Karel Top — Codehs All Answers
Karel is patient, but the autograder is not. If Karel spins in circles forever, your browser freezes.
Problem: The world is filled with balls. Remove all of them. Solution:
function main()
while (leftIsClear())
cleanRow();
moveUpAndReverse();
cleanRow();
function cleanRow()
while (frontIsClear())
safeTakeBall();
move();
safeTakeBall();
function moveUpAndReverse()
turnLeft();
move();
turnLeft();
Problem: Karel starts at the bottom of a staircase with 5 steps. Write a program to make Karel climb the staircase.
Solution:
function start()
var i;
for (i = 0; i < 5; i++)
move();
turnLeft();
move();
turnRight();
Task: Define a start() function to stack pancakes. codehs all answers karel top
def start():
move()
make_pancakes()
move()
def make_pancakes():
putBall()
putBall()
putBall()
The Goal: Karel builds "hospitals" (rectangles of balls) over piles of supplies.
Solution:
public class HospitalKarel extends Karel public void run() while(frontIsClear()) if(ballsPresent()) makeHospital(); move(); // Check the last corner if(ballsPresent()) makeHospital();private void makeHospital() // Logic to build the hospital structure turnLeft(); move(); putBall(); turnRight(); move(); putBall(); turnRight(); move(); putBall(); turnAround(); move(); move(); turnLeft();
Problem: Make Karel move forward 10 times.
Solution:
function start()
for (var i = 0; i < 10; i++)
move();
Before diving into specific answers, you must master these 5 helper functions. They appear in every "top" solution.
// Standard movement function moveToWall() while (frontIsClear()) move();// The classic turnaround function turnAround() turnLeft(); turnLeft(); Karel is patient, but the autograder is not
// Right turn (CodeHS doesn't have turnRight by default) function turnRight() turnLeft(); turnLeft(); turnLeft();
// Put a ball if none exists function safePutBall() if (noBallsPresent()) putBall();
// Safe pick up function safeTakeBall() if (ballsPresent()) takeBall();