Thursday, 10 September 2026

Code Solutions

/* This program should clean up all the balls in any size world. */
function main() {
    while (leftIsClear()) {
        cleanRow();
        comeBack();
        moveUp();
    }
    cleanRow();
    comeBack();
    
    if (leftIsBlocked()) {
        returnHome();
    }
}

/* Karel moves up to the next row.
 * Precondition: Karel is at the start of a just cleaned row.
 * Postcondition: Karel is at the start of the next row to
 * be cleaned, facing east. */
function moveUp() {
    turnLeft();
    move();
    turnRight();
}


/* This brings Karel back to the starting position on the row.
 * Precondition: Karel is at the end of the row, facing a wall.
 * Postcondition: Karel is at the start of the same row, facing
 * east.
 */
function comeBack() {
    turnAround();
    while (frontIsClear()) {
        move();
    }
    turnAround();
}

/* This cleans one row of Karel's world.
 * Precondition: Karel is in the first column, facing east
 * Postcondition: Karel is at the end of the row, facing
 * east, and all balls in the row have been picked up.
 */
function cleanRow() {
    while (frontIsClear()) {
        cleanSpot();
        move();
    }
    cleanSpot();
}

/* This picks up a tennis ball, but only if it is there. */
function cleanSpot() {
    if (ballsPresent()) {
        takeBall();
    }
}

/* This brings Karel back to the starting position, facing east.
 * Precondition: Karel is at the end of the clean up.
 * Postcondition: Karel is back to (1,1), facing east.
 */
function returnHome(){
    turnRight();
    while (frontIsClear()) {
        move();
    }
    turnLeft();
}

main();

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thanks for sharing these code solutions! They're well-organized and easy to follow—great for learners who need quick, reliable references. It's always helpful to see clean and simple examples like these. Keep up the great work!

    Epicforce Tech

    ReplyDelete
  3. I like your technical knowledgeable blogs love and thanks for live share informatic information.

    Best Fine art Institute in Delhi
    Best Computer Institute in Delhi

    ReplyDelete
  4. This Code Solutions article offers valuable guidance for streamlining development and enhancing project efficiency. Clear coding practices always lead to better outcomes. For polished interfaces and smoother user experiences, many teams prefer to Hire Frontend Developers specialists who deliver high-quality front-end results.

    ReplyDelete