Stair-climbing puzzle: Difference between revisions

From Rosetta Code
Content added Content deleted
(Add Chuhg-chieh Shan's stair-climbing problem)
 
(added python)
Line 50: Line 50:
true))
true))
</lang>
</lang>

=={{header|Python}}==

=== Iterative ===
<lang python>def step_up1()
"Straightforward implementation: keep track of how many level we
need to ascend, and stop when this count is zero."
deficit = 1
while deficit > 0:
if step():
deficit -= 1
else:
deficit += 1</lang>

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

<lang python>def step_up2():
"No numbers."
if not step():
step_up2() # undo the fall
step_up2() # try again</lang>

Revision as of 23:59, 24 October 2009

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>

Python

Iterative

<lang python>def step_up1()

 "Straightforward implementation: keep track of how many level we
  need to ascend, and stop when this count is zero."
 deficit = 1
 while deficit > 0:
   if step():
     deficit -= 1
   else:
     deficit += 1</lang>

Recursive

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

<lang python>def step_up2():

 "No numbers."
 if not step():
   step_up2() # undo the fall
   step_up2() # try again</lang>