Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

A Function That Searches

As in the Bones Mark the Way exercise, the dog is in a park where paths cross everywhere, and the owner has marked the way with bones. This time, there are four of them: at the first bone, the dog turns left, at the second, right, at the third, right again, and at the fourth, left. Then it walks straight ahead to the goal. The turns are the same on all three maps, but the bones lie at different distances.

On the way to every bone, the dog does the same thing: it walks until it stands on a bone, and then it picks the bone up. That's a dog's favorite game, fetch. Make it a function:

  • Define fetch
    • Repeat while not bone here
      • Move forward
    • Pick up bone

This function doesn't take a fixed number of steps. It searches: it walks on until it finds a bone, however far away the bone is. Each call finds the next one. Between the calls, you only add the turns: fetch, turn left, fetch, turn right, and so on.

That's how programmers use functions: a function hides a small algorithm behind a name. Once fetch works, you don't need to think about how it searches; you just call it. So try the function on its own first: call it once under Start and run the program. The dog should stop on the first bone and pick it up.

Instructions

  1. 1

    Pick up all the bones on all three maps.

  2. 2

    Walk to the goal.

  3. 3

    Use at most 16 blocks.

Back

6/9

  1. 1. Teach the Dog a Trick
  2. 2. A Function in a Loop
  3. 3. A Loop in a Function
  4. 4. Quiz: Calling a Function
  5. 5. Two Functions
  6. 6. A Function That Searches
  7. 7. Fix the Function
  8. 8. Quiz: A Bug in a Function
  9. 9. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.