Stair-climbing puzzle

From Rosetta Code
Revision as of 22:56, 24 October 2009 by rosettacode>Hircus (Add Chuhg-chieh Shan's stair-climbing problem)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Stair-climbing puzzle
You are encouraged to solve this task according to the task description, using any language you may know.

From Chung-Chieh Shan (LtU):

Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure. Write a function "step_up" that climbs one step up (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?

Clojure

First, some boilerplate.

<lang clojure>

the initial level

(def level (atom 41))

the probability of success

(def prob 0.5001)


(defn step

 []
 (let [success (< (rand) prob)]
   (swap! level (if success inc dec))
   success) )

</lang>

Tail-recursive

The internal recursion uses a counter; see the function documentation.

<lang clojure> (defn step-up1

 "Straightforward implementation: keep track of how many level we
  need to ascend, and stop when this count is zero."
 []
 (loop [deficit 1]
   (or (zero? deficit)

(recur (if (step) (dec deficit) (inc deficit)))) ) ) </lang>

Recursive

This satisfies Chung-chieh's challenge to avoid using numbers. Might blow the stack as p approaches 0.5.

<lang clojure> (defn step-up2

 "Non-tail-recursive. No numbers."
 []
 (if (not (step))
   (do (step-up2) ;; undo the fall

(step-up2) ;; try again )

   true))

</lang>