Stair-climbing puzzle: Difference between revisions

Content added Content deleted
(Added Arturo implementation)
m (syntax highlighting fixup automation)
Line 35: Line 35:


=== Iterative ===
=== Iterative ===
<lang 11l>F step_up1()
<syntaxhighlight lang="11l">F step_up1()
V deficit = 1
V deficit = 1
L deficit > 0
L deficit > 0
Line 41: Line 41:
deficit--
deficit--
E
E
deficit++</lang>
deficit++</syntaxhighlight>


=== Recursive ===
=== Recursive ===
<lang 11l>F step_up2()
<syntaxhighlight lang="11l">F step_up2()
L !step()
L !step()
step_up2()</lang>
step_up2()</syntaxhighlight>


=={{header|ActionScript}}==
=={{header|ActionScript}}==
===Iterative===
===Iterative===
<lang ActionScript>function stepUp()
<syntaxhighlight lang="actionscript">function stepUp()
{
{
var i:int = 0;
var i:int = 0;
Line 56: Line 56:
if(step())i++;
if(step())i++;
else i--;
else i--;
}</lang>
}</syntaxhighlight>
===Recursive===
===Recursive===
<lang ActionScript>function stepUp()
<syntaxhighlight lang="actionscript">function stepUp()
{
{
if(!step())
if(!step())
Line 65: Line 65:
stepUp();
stepUp();
}
}
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>procedure Step_Up is
<syntaxhighlight lang="ada">procedure Step_Up is
begin
begin
while not Step loop
while not Step loop
Step_Up;
Step_Up;
end loop;
end loop;
end Step_Up;</lang>
end Step_Up;</syntaxhighlight>
The following is a test program simulating Step:
The following is a test program simulating Step:
<lang Ada>with Ada.Numerics.Discrete_Random;
<syntaxhighlight lang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
with Ada.Text_IO;


Line 106: Line 106:
Reset (Dice);
Reset (Dice);
Step_Up;
Step_Up;
end Scaffolding;</lang>
end Scaffolding;</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Line 122: Line 122:
=={{header|Aime}}==
=={{header|Aime}}==
{{trans|C}}
{{trans|C}}
<lang aime>void step_up(void)
<syntaxhighlight lang="aime">void step_up(void)
{
{
while (!step()) {
while (!step()) {
step_up();
step_up();
}
}
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 137: Line 137:


{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8.8d.fc9.i386]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8.8d.fc9.i386]}}
<lang Algol68> PROC step up = VOID:
<syntaxhighlight lang="algol68"> PROC step up = VOID:
BEGIN
BEGIN
WHILE NOT step DO
WHILE NOT step DO
step up
step up
OD
OD
END # step up #;</lang>The following is a test program simulating step: <lang Algol68>
END # step up #;</syntaxhighlight>The following is a test program simulating step: <syntaxhighlight lang="algol68">
PROC scaffolding = VOID:
PROC scaffolding = VOID:
BEGIN
BEGIN
Line 170: Line 170:
END # scaffolding #;
END # scaffolding #;


scaffolding</lang>
scaffolding</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Line 182: Line 182:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>Position: 0
<syntaxhighlight lang="rebol">Position: 0


stepUp: function [].export:[Position][
stepUp: function [].export:[Position][
Line 203: Line 203:
]
]


stepUp</lang>
stepUp</syntaxhighlight>


{{out}}
{{out}}
Line 219: Line 219:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Recursive solution:
Recursive solution:
<lang AutoHotkey>step_up()
<syntaxhighlight lang="autohotkey">step_up()
{
{
While !step()
While !step()
step_up()
step_up()
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
function step_up() {
function step_up() {
while (!step()) { step_up() }
while (!step()) { step_up() }
}
}
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 238: Line 238:
For many (most?) BASICs, <code>STEP</code> is a (case-insensitive) keyword, therefore the "step" function would need a different name -- in this example, "step1". (Also, for some BASICs -- notably those influenced by [[Microsoft]]'s [[QuickBASIC]] -- the underscore character ("'''_'''") is invalid inside subroutine names.)
For many (most?) BASICs, <code>STEP</code> is a (case-insensitive) keyword, therefore the "step" function would need a different name -- in this example, "step1". (Also, for some BASICs -- notably those influenced by [[Microsoft]]'s [[QuickBASIC]] -- the underscore character ("'''_'''") is invalid inside subroutine names.)


<lang qbasic>SUB stepup
<syntaxhighlight lang="qbasic">SUB stepup
IF NOT step1 THEN stepup: stepup
IF NOT step1 THEN stepup: stepup
END SUB</lang>
END SUB</syntaxhighlight>


See also: [[#BBC BASIC|BBC BASIC]], [[#Liberty BASIC|Liberty BASIC]], [[#PureBasic|PureBasic]], [[#TI-83 BASIC|TI-83 BASIC]]
See also: [[#BBC BASIC|BBC BASIC]], [[#Liberty BASIC|Liberty BASIC]], [[#PureBasic|PureBasic]], [[#TI-83 BASIC|TI-83 BASIC]]
Line 246: Line 246:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
Recursive solution:
Recursive solution:
<lang bbcbasic> DEF PROCstepup
<syntaxhighlight lang="bbcbasic"> DEF PROCstepup
IF NOT FNstep PROCstepup : PROCstepup
IF NOT FNstep PROCstepup : PROCstepup
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>void step_up(void)
<syntaxhighlight lang="c">void step_up(void)
{
{
while (!step()) {
while (!step()) {
step_up();
step_up();
}
}
}</lang>
}</syntaxhighlight>


The following uses a variable and is a bit longer, but avoids a possible stack overflow by risking a probably less likely integer overflow instead:
The following uses a variable and is a bit longer, but avoids a possible stack overflow by risking a probably less likely integer overflow instead:
<lang c>void step_up(void)
<syntaxhighlight lang="c">void step_up(void)
{
{
int i = 0;
int i = 0;
Line 270: Line 270:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>void step_up() {
<syntaxhighlight lang="csharp">void step_up() {
while (!step()) step_up();
while (!step()) step_up();
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>void step_up()
<syntaxhighlight lang="cpp">void step_up()
{
{
while (!step()) step_up();
while (!step()) step_up();
}</lang>
}</syntaxhighlight>


The following uses a variable and is a bit longer, but avoids a possible stack overflow:
The following uses a variable and is a bit longer, but avoids a possible stack overflow:
<lang cpp>void step_up()
<syntaxhighlight lang="cpp">void step_up()
{
{
for (int i = 0; i < 1; step()? ++i : --i);
for (int i = 0; i < 1; step()? ++i : --i);
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
First, some boilerplate.
First, some boilerplate.


<lang lisp>;; the initial level
<syntaxhighlight lang="lisp">;; the initial level
(def level (atom 41))
(def level (atom 41))


Line 303: Line 303:
(let [success (< (rand) prob)]
(let [success (< (rand) prob)]
(swap! level (if success inc dec))
(swap! level (if success inc dec))
success) )</lang>
success) )</syntaxhighlight>


=== Tail-recursive ===
=== Tail-recursive ===
The internal recursion uses a counter; see the function documentation.
The internal recursion uses a counter; see the function documentation.


<lang lisp>(defn step-up1
<syntaxhighlight lang="lisp">(defn step-up1
"Straightforward implementation: keep track of how many level we
"Straightforward implementation: keep track of how many level we
need to ascend, and stop when this count is zero."
need to ascend, and stop when this count is zero."
Line 315: Line 315:
(or (zero? deficit)
(or (zero? deficit)
(recur (if (step) (dec deficit)
(recur (if (step) (dec deficit)
(inc deficit)))) ) )</lang>
(inc deficit)))) ) )</syntaxhighlight>


=== Recursive ===
=== Recursive ===
Line 321: Line 321:
''p'' approaches 0.5.
''p'' approaches 0.5.


<lang lisp>(defn step-up2
<syntaxhighlight lang="lisp">(defn step-up2
"Non-tail-recursive. No numbers."
"Non-tail-recursive. No numbers."
[]
[]
Line 328: Line 328:
(step-up2) ;; try again
(step-up2) ;; try again
)
)
true))</lang>
true))</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun step-up ()
<syntaxhighlight lang="lisp">(defun step-up ()
(unless (step) (step-up) (step-up)))</lang>
(unless (step) (step-up) (step-up)))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
The recursive version (note that "step_up" is equivalent to "step_up()" in D):
The recursive version (note that "step_up" is equivalent to "step_up()" in D):
<lang d>void step_up()
<syntaxhighlight lang="d">void step_up()
{
{
while(!step)
while(!step)
step_up;
step_up;
}</lang>
}</syntaxhighlight>
The non-recursive version, using 1 variable:
The non-recursive version, using 1 variable:
<lang d>void step_up_nr()
<syntaxhighlight lang="d">void step_up_nr()
{
{
for(uint i = 0; i < 1; step ? ++i : --i) {};
for(uint i = 0; i < 1; step ? ++i : --i) {};
}</lang>
}</syntaxhighlight>
Test program:
Test program:
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;
import std.random;
import std.random;


Line 371: Line 371:
rand_seed(0, 0); // to make it somewhat repeatable
rand_seed(0, 0); // to make it somewhat repeatable
step_up;
step_up;
}</lang>
}</syntaxhighlight>
Sample output:
Sample output:
<pre>Fell down to -1
<pre>Fell down to -1
Line 391: Line 391:
The problem framework:
The problem framework:


<lang e>var level := 41
<syntaxhighlight lang="e">var level := 41
var prob := 0.5001
var prob := 0.5001


Line 398: Line 398:
level += success.pick(1, -1)
level += success.pick(1, -1)
return success
return success
}</lang>
}</syntaxhighlight>


Counting solution:
Counting solution:


<lang e>def stepUpCounting() {
<syntaxhighlight lang="e">def stepUpCounting() {
var deficit := 1
var deficit := 1
while (deficit > 0) {
while (deficit > 0) {
deficit += step().pick(-1, 1)
deficit += step().pick(-1, 1)
}
}
}</lang>
}</syntaxhighlight>


Ordinary recursive solution:
Ordinary recursive solution:
<lang e>def stepUpRecur() {
<syntaxhighlight lang="e">def stepUpRecur() {
if (!step()) {
if (!step()) {
stepUpRecur()
stepUpRecur()
stepUpRecur()
stepUpRecur()
}
}
}</lang>
}</syntaxhighlight>


Eventual-recursive solution. This executes on the vat ''queue'' rather than the stack, so while it has the same space usage properties as the stack-recursive version it does not use the stack which is often significantly smaller than the heap. Its return value resolves when it has completed its task.
Eventual-recursive solution. This executes on the vat ''queue'' rather than the stack, so while it has the same space usage properties as the stack-recursive version it does not use the stack which is often significantly smaller than the heap. Its return value resolves when it has completed its task.


<lang e>def stepUpEventualRecur() {
<syntaxhighlight lang="e">def stepUpEventualRecur() {
if (!step()) {
if (!step()) {
return when (stepUpEventualRecur <- (),
return when (stepUpEventualRecur <- (),
stepUpEventualRecur <- ()) -> {}
stepUpEventualRecur <- ()) -> {}
}
}
}</lang>
}</syntaxhighlight>


Fully eventual counting solution. This would be appropriate for controlling an actual robot, where the climb operation is non-instantaneous (and therefore eventual):
Fully eventual counting solution. This would be appropriate for controlling an actual robot, where the climb operation is non-instantaneous (and therefore eventual):


[[Category:E examples needing attention]]
[[Category:E examples needing attention]]
<lang e>def stepUpEventual() {
<syntaxhighlight lang="e">def stepUpEventual() {
# This general structure (tail-recursive def{if{when}}) is rather common
# This general structure (tail-recursive def{if{when}}) is rather common
# and probably ought to be defined in a library.
# and probably ought to be defined in a library.
Line 441: Line 441:
}
}
return loop(1)
return loop(1)
}</lang>
}</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define (step-up) (while (not (step)) (step-up)))
(define (step-up) (while (not (step)) (step-up)))
;; checking this is tail-recusive :
;; checking this is tail-recusive :
Line 466: Line 466:
(climb stairs)
(climb stairs)
(writeln 'stairs stairs 'probability success 'steps STEPS)))
(writeln 'stairs stairs 'probability success 'steps STEPS)))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 496: Line 496:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule Stair_climbing do
<syntaxhighlight lang="elixir">defmodule Stair_climbing do
defp step, do: 1 == :rand.uniform(2)
defp step, do: 1 == :rand.uniform(2)
Line 508: Line 508:
end
end


IO.inspect Stair_climbing.step_up</lang>
IO.inspect Stair_climbing.step_up</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>
<syntaxhighlight lang="erlang">
-module(stair).
-module(stair).
-compile(export_all).
-compile(export_all).
Line 526: Line 526:
step_up() ->
step_up() ->
step_up(step()).
step_up(step()).
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>procedure step_up()
<syntaxhighlight lang="euphoria">procedure step_up()
if not step() then
if not step() then
step_up()
step_up()
step_up()
step_up()
end if
end if
end procedure</lang>
end procedure</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>: step-up ( -- ) step [ step-up step-up ] unless ;</lang>
<syntaxhighlight lang="factor">: step-up ( -- ) step [ step-up step-up ] unless ;</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
Recursive. May exceed return stack unless compiler optimizes tail calls.
Recursive. May exceed return stack unless compiler optimizes tail calls.
<lang forth>: step-up begin step 0= while recurse repeat ;</lang>
<syntaxhighlight lang="forth">: step-up begin step 0= while recurse repeat ;</syntaxhighlight>
Counting. Avoids using a named variable.
Counting. Avoids using a named variable.
<lang forth>: step-up -1 begin step if 1+ else 1- then ?dup 0= until ;</lang>
<syntaxhighlight lang="forth">: step-up -1 begin step if 1+ else 1- then ?dup 0= until ;</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 549: Line 549:


{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>module StairRobot
<syntaxhighlight lang="fortran">module StairRobot
implicit none
implicit none


Line 576: Line 576:
end subroutine step_up_iter
end subroutine step_up_iter


end module StairRobot</lang>
end module StairRobot</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Line 582: Line 582:


Iterative version using one variable.
Iterative version using one variable.
<lang FreeBASIC>Sub step_up()
<syntaxhighlight lang="freebasic">Sub step_up()
Dim As Integer i
Dim As Integer i
Do
Do
Line 591: Line 591:
End If
End If
Loop Until i = 1
Loop Until i = 1
End Sub</lang>
End Sub</syntaxhighlight>


Recursive version.
Recursive version.
<lang FreeBASIC>Sub step_up()
<syntaxhighlight lang="freebasic">Sub step_up()
While Not step_()
While Not step_()
step_up()
step_up()
Wend
Wend
End Sub</lang>
End Sub</syntaxhighlight>


Demonstration program.
Demonstration program.
<lang FreeBASIC>Function step_() As Boolean
<syntaxhighlight lang="freebasic">Function step_() As Boolean
If Int((Rnd * 2)) Then
If Int((Rnd * 2)) Then
Print "Robot sube"
Print "Robot sube"
Line 619: Line 619:


step_up
step_up
Sleep</lang>
Sleep</syntaxhighlight>




=={{header|Go}}==
=={{header|Go}}==
38 bytes, no variables, no numbers.
38 bytes, no variables, no numbers.
<lang go>func step_up(){for !step(){step_up()}}</lang>
<syntaxhighlight lang="go">func step_up(){for !step(){step_up()}}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<syntaxhighlight lang="grovy">
<lang Grovy>
class Stair_climbing{
class Stair_climbing{
static void main(String[] args){
static void main(String[] args){
Line 638: Line 638:


}
}
</syntaxhighlight>
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 644: Line 644:
In Haskell, stateful computation is only allowed in a monad. Then suppose we have a monad <code>Robot</code> with an action <code>step :: Robot Bool</code>. We can implement <code>stepUp</code> like this:
In Haskell, stateful computation is only allowed in a monad. Then suppose we have a monad <code>Robot</code> with an action <code>step :: Robot Bool</code>. We can implement <code>stepUp</code> like this:


<lang haskell>stepUp :: Robot ()
<syntaxhighlight lang="haskell">stepUp :: Robot ()
stepUp = untilM step stepUp
stepUp = untilM step stepUp


Line 650: Line 650:
untilM test action = do
untilM test action = do
result <- test
result <- test
if result then return () else action >> untilM test action</lang>
if result then return () else action >> untilM test action</syntaxhighlight>


Here's an example implementation of <code>Robot</code> and <code>step</code>, as well as a <code>main</code> with which to test <code>stepUp</code>.
Here's an example implementation of <code>Robot</code> and <code>step</code>, as well as a <code>main</code> with which to test <code>stepUp</code>.


<lang haskell>import Control.Monad.State
<syntaxhighlight lang="haskell">import Control.Monad.State
import System.Random (StdGen, getStdGen, random)
import System.Random (StdGen, getStdGen, random)


Line 672: Line 672:
putStrLn $ "The robot is at step #" ++ show startingPos ++ "."
putStrLn $ "The robot is at step #" ++ show startingPos ++ "."
let (endingPos, _) = execState stepUp (startingPos, g)
let (endingPos, _) = execState stepUp (startingPos, g)
putStrLn $ "The robot is at step #" ++ show endingPos ++ "."</lang>
putStrLn $ "The robot is at step #" ++ show endingPos ++ "."</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 681: Line 681:
is implemented in Icon (or Unicon) and fails only when the implementation in
is implemented in Icon (or Unicon) and fails only when the implementation in
another language returns <tt>false</tt>, then:
another language returns <tt>false</tt>, then:
<lang unicon>procedure step_up()
<syntaxhighlight lang="unicon">procedure step_up()
return step() | (step_up(),step_up())
return step() | (step_up(),step_up())
end</lang>
end</syntaxhighlight>


You can subtract a few more characters (and multiply the difficulty
You can subtract a few more characters (and multiply the difficulty
of understanding) with:
of understanding) with:
<lang unicon>procedure step_up()
<syntaxhighlight lang="unicon">procedure step_up()
(|not step(), step_up())
(|not step(), step_up())
end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
'''Solution (Tacit):'''
'''Solution (Tacit):'''
<lang j>step =: 0.6 > ?@0:
<syntaxhighlight lang="j">step =: 0.6 > ?@0:
attemptClimb =: [: <:`>:@.step 0:
attemptClimb =: [: <:`>:@.step 0:
isNotUpOne =: -.@(+/@])
isNotUpOne =: -.@(+/@])


step_up=: (] , attemptClimb)^:isNotUpOne^:_</lang>
step_up=: (] , attemptClimb)^:isNotUpOne^:_</syntaxhighlight>
Note that <code>0:</code> is not a number but a verb (function) that returns the number zero irrespective of its argument(s). And, arguably, infinity is not any specific number. And, finally, <code>step</code> is presumed to pre-exist in the task description. Therefore the above solution for <code>step_up</code> could validly be said to meet the restrictions of no variables or numbers.
Note that <code>0:</code> is not a number but a verb (function) that returns the number zero irrespective of its argument(s). And, arguably, infinity is not any specific number. And, finally, <code>step</code> is presumed to pre-exist in the task description. Therefore the above solution for <code>step_up</code> could validly be said to meet the restrictions of no variables or numbers.


Line 703: Line 703:


'''Solution (Explicit):'''
'''Solution (Explicit):'''
<lang j>step_upX=: monad define NB. iterative
<syntaxhighlight lang="j">step_upX=: monad define NB. iterative
while. -. +/y do. y=. y , _1 1 {~ step 0 end.
while. -. +/y do. y=. y , _1 1 {~ step 0 end.
)
)
Line 709: Line 709:
step_upR=: monad define NB. recursive (stack overflow possible!)
step_upR=: monad define NB. recursive (stack overflow possible!)
while. -. step'' do. step_upR'' end.
while. -. step'' do. step_upR'' end.
)</lang>
)</syntaxhighlight>


'''Example usage:'''
'''Example usage:'''
<lang j> step_up '' NB. output is sequence of falls & climbs required to climb one step.
<syntaxhighlight lang="j"> step_up '' NB. output is sequence of falls & climbs required to climb one step.
_1 1 _1 _1 1 1 1
_1 1 _1 _1 1 1 1
+/\ _1 1 _1 _1 1 1 1 NB. running sum of output (current step relative to start)
+/\ _1 1 _1 _1 1 1 1 NB. running sum of output (current step relative to start)
_1 0 _1 _2 _1 0 1
_1 0 _1 _2 _1 0 1
+/\ step_up '' NB. another example
+/\ step_up '' NB. another example
_1 _2 _3 _2 _3 _2 _1 _2 _3 _4 _3 _2 _3 _2 _3 _2 _3 _2 _1 _2 _1 _2 _1 0 1</lang>
_1 _2 _3 _2 _3 _2 _1 _2 _3 _4 _3 _2 _3 _2 _3 _2 _3 _2 _1 _2 _1 _2 _1 0 1</syntaxhighlight>




Another approach might be:
Another approach might be:


<lang J>keepTrying=: (, {: - _1 ^ step)^:({. >: {:)^:_</lang>
<syntaxhighlight lang="j">keepTrying=: (, {: - _1 ^ step)^:({. >: {:)^:_</syntaxhighlight>


Here, the argument is the number of the starting step and the result is a list of the numbers of each visited step including the initial and final steps. For example:
Here, the argument is the number of the starting step and the result is a list of the numbers of each visited step including the initial and final steps. For example:


<lang J> keepTrying 2
<syntaxhighlight lang="j"> keepTrying 2
2 1 0 1 2 3
2 1 0 1 2 3
keepTrying 3
keepTrying 3
3 2 3 2 3 2 3 4
3 2 3 2 3 2 3 4
keepTrying 4
keepTrying 4
4 5</lang>
4 5</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{trans|C++}}
{{trans|C++}}
<lang java>public void stepUp() {
<syntaxhighlight lang="java">public void stepUp() {
while (!step()) stepUp();
while (!step()) stepUp();
}</lang>
}</syntaxhighlight>
The following uses a variable and is a bit longer, but avoids a possible stack overflow:
The following uses a variable and is a bit longer, but avoids a possible stack overflow:
<lang java>public void stepUp(){
<syntaxhighlight lang="java">public void stepUp(){
for (int i = 0; i < 1; step() ? ++i : --i);
for (int i = 0; i < 1; step() ? ++i : --i);
}</lang>
}</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 747: Line 747:


Since jq is a purely functional language, we need to keep track of time explicitly. This can be done using a clock that ticks the time:
Since jq is a purely functional language, we need to keep track of time explicitly. This can be done using a clock that ticks the time:
<lang jq>def tick: .+1;</lang>
<syntaxhighlight lang="jq">def tick: .+1;</syntaxhighlight>
To model the robot's success and failure, we shall assume a sufficiently large array of 0/1 values is available.
To model the robot's success and failure, we shall assume a sufficiently large array of 0/1 values is available.
To avoid problems with modeling infinite time, we will pad the array with 1s if necessary.
To avoid problems with modeling infinite time, we will pad the array with 1s if necessary.
<lang jq>def random: [0, 0, 0, 1, 0, 1, 1, 0];</lang>
<syntaxhighlight lang="jq">def random: [0, 0, 0, 1, 0, 1, 1, 0];</syntaxhighlight>


"step" returns true or false based on the current time (the input) and the value of "random":
"step" returns true or false based on the current time (the input) and the value of "random":
<lang jq>def step:
<syntaxhighlight lang="jq">def step:
random as $r
random as $r
| if . >= ($r|length) then true else ($r[.] == 1) end ;</lang>
| if . >= ($r|length) then true else ($r[.] == 1) end ;</syntaxhighlight>


We can now define step_up:
We can now define step_up:
<lang jq>def step_up:
<syntaxhighlight lang="jq">def step_up:
if step then tick
if step then tick
else tick | step_up | step_up
else tick | step_up | step_up
end;</lang>
end;</syntaxhighlight>
Now we can start the simulation at time 0; step_up will then emit the number of "step" attempts that have been made to achieve success:
Now we can start the simulation at time 0; step_up will then emit the number of "step" attempts that have been made to achieve success:
<lang jq>0 | step_up</lang>
<syntaxhighlight lang="jq">0 | step_up</syntaxhighlight>
{{out}}
{{out}}
<lang sh>$ jq -n -f stair-climbing_puzzle.jq
<syntaxhighlight lang="sh">$ jq -n -f stair-climbing_puzzle.jq
11</lang>
11</syntaxhighlight>
===Tail Call Optimization===
===Tail Call Optimization===
To take advantage of jq's TCO (available in versions of jq after the release of Version 1.4), the step_up
To take advantage of jq's TCO (available in versions of jq after the release of Version 1.4), the step_up
function must be tail-recursive and have arity 0. This can be
function must be tail-recursive and have arity 0. This can be
achieved by providing [time, goal] as the input as follows:
achieved by providing [time, goal] as the input as follows:
<lang jq>def tco_step_up:
<syntaxhighlight lang="jq">def tco_step_up:
.[0] as $time | .[1] as $goal
.[0] as $time | .[1] as $goal
| if $goal == 0 then $time
| if $goal == 0 then $time
Line 777: Line 777:
if $time|step then $goal - 1 else $goal + 1 end
if $time|step then $goal - 1 else $goal + 1 end
| [ ($time|tick), .] | tco_step_up
| [ ($time|tick), .] | tco_step_up
end ;</lang>
end ;</syntaxhighlight>
The simulation can then be started as follows:
The simulation can then be started as follows:
<lang jq>[0,1] | tco_step_up</lang>
<syntaxhighlight lang="jq">[0,1] | tco_step_up</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
As specified, shorter and fewer numbers preferred. It may be supposed that the robot would reach the bottom of any steps well before blowing the stack to reboot.
As specified, shorter and fewer numbers preferred. It may be supposed that the robot would reach the bottom of any steps well before blowing the stack to reboot.
<lang julia>
<syntaxhighlight lang="julia">
step_up() = while !step() step_up() end
step_up() = while !step() step_up() end
</syntaxhighlight>
</lang>
Here is an example to test the code with a step that has a 1/3 failure rate:
Here is an example to test the code with a step that has a 1/3 failure rate:
<lang julia>
<syntaxhighlight lang="julia">
step() = (b = rand([true,true,false]); println(b); b)
step() = (b = rand([true,true,false]); println(b); b)
step_up()
step_up()
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>
<pre>
Line 807: Line 807:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|D}}
{{trans|D}}
<lang scala>// version 1.2.0
<syntaxhighlight lang="scala">// version 1.2.0


import java.util.Random
import java.util.Random
Line 829: Line 829:
fun main(args: Array<String>) {
fun main(args: Array<String>) {
stepUp()
stepUp()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 845: Line 845:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>'This demo will try to get the robot to step up
<syntaxhighlight lang="lb">'This demo will try to get the robot to step up
'Run it several times to see the differences; sometimes the robot falls
'Run it several times to see the differences; sometimes the robot falls
'quite a ways before making it to the next step up, but sometimes he makes it
'quite a ways before making it to the next step up, but sometimes he makes it
Line 865: Line 865:
Print "Robot fell down"
Print "Robot fell down"
End If
End If
End Function</lang>
End Function</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
Recursive.
Recursive.
<lang logo>to step.up
<syntaxhighlight lang="logo">to step.up
if not step [step.up step.up]
if not step [step.up step.up]
end</lang>
end</syntaxhighlight>
Constant space (fully tail-recursive).
Constant space (fully tail-recursive).
<lang logo>to step.up [:n 1]
<syntaxhighlight lang="logo">to step.up [:n 1]
if :n=0 [stop]
if :n=0 [stop]
(step.up ifelse step [:n-1] [:n+1])
(step.up ifelse step [:n-1] [:n+1])
end</lang>
end</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==


<syntaxhighlight lang="lua">
<lang Lua>
function step_up()
function step_up()
while not step() do step_up() end
while not step() do step_up() end
end
end
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>StepUp[] := If[!Step[], StepUp[]; StepUp[]]</lang>
<syntaxhighlight lang="mathematica">StepUp[] := If[!Step[], StepUp[]; StepUp[]]</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang MATLAB>function step_up()
<syntaxhighlight lang="matlab">function step_up()
while ~step()
while ~step()
step_up();
step_up();
end</lang>
end</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
One liner (yes it is possible in Nim).
One liner (yes it is possible in Nim).
<lang nim>proc stepUp = (while not step(): stepUp())</lang>
<syntaxhighlight lang="nim">proc stepUp = (while not step(): stepUp())</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let rec step_up() =
<syntaxhighlight lang="ocaml">let rec step_up() =
while not(step()) do
while not(step()) do
step_up()
step_up()
done
done
;;</lang>
;;</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
Recursive solution:
Recursive solution:
<lang oz>proc {StepUp}
<syntaxhighlight lang="oz">proc {StepUp}
if {Not {Step}} then
if {Not {Step}} then
{StepUp} %% make up for the fall
{StepUp} %% make up for the fall
{StepUp} %% repeat original attempt
{StepUp} %% repeat original attempt
end
end
end</lang>
end</syntaxhighlight>
Might lead to a stack overflow because the first call to <code>StepUp</code> is not in tail position.
Might lead to a stack overflow because the first call to <code>StepUp</code> is not in tail position.


Iterative solution:
Iterative solution:
<lang oz>proc {StepUp}
<syntaxhighlight lang="oz">proc {StepUp}
Level = {NewCell 0}
Level = {NewCell 0}
in
in
Line 926: Line 926:
end
end
end
end
</syntaxhighlight>
</lang>
Oz has arbitrary large integers. So if the robot is very unlucky, the contents of the <code>Level</code> variable will fill up all the memory and the program will fail. I believe this problem needs infinite memory to be solved for all cases.
Oz has arbitrary large integers. So if the robot is very unlucky, the contents of the <code>Level</code> variable will fill up all the memory and the program will fail. I believe this problem needs infinite memory to be solved for all cases.


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>step_up()=while(!step(),step_up())</lang>
<syntaxhighlight lang="parigp">step_up()=while(!step(),step_up())</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Recursive solution:
Recursive solution:
<lang pascal>procedure stepUp;
<syntaxhighlight lang="pascal">procedure stepUp;
begin
begin
while not step do
while not step do
stepUp;
stepUp;
end;</lang>
end;</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub step_up { step_up until step; }</lang>
<syntaxhighlight lang="perl">sub step_up { step_up until step; }</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">step_up</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">step_up</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">while</span> <span style="color: #008080;">not</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">do</span> <span style="color: #000000;">step_up</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">while</span> <span style="color: #008080;">not</span> <span style="color: #000000;">step</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">do</span> <span style="color: #000000;">step_up</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de stepUp ()
<syntaxhighlight lang="picolisp">(de stepUp ()
(until (step1) # ('step1', because 'step' is a system function)
(until (step1) # ('step1', because 'step' is a system function)
(stepUp) ) )</lang>
(stepUp) ) )</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>function StepUp
<syntaxhighlight lang="powershell">function StepUp
{
{
If ( -not ( Step ) )
If ( -not ( Step ) )
Line 983: Line 983:
# Test
# Test
$VerbosePreference = 'Continue'
$VerbosePreference = 'Continue'
StepUp</lang>
StepUp</syntaxhighlight>
{{out}}
{{out}}
<pre>VERBOSE: Fell one step
<pre>VERBOSE: Fell one step
Line 999: Line 999:
=={{header|Prolog}}==
=={{header|Prolog}}==
The robot code is very short
The robot code is very short
<lang Prolog>step_up :- \+ step, step_up, step_up.</lang>
<syntaxhighlight lang="prolog">step_up :- \+ step, step_up, step_up.</syntaxhighlight>
The test program keeps track of the level in a dynamic predicate.
The test program keeps track of the level in a dynamic predicate.
<lang Prolog>:- dynamic level/1.
<syntaxhighlight lang="prolog">:- dynamic level/1.
setup :-
setup :-
Line 1,019: Line 1,019:
retractall(level(Level)),
retractall(level(Level)),
assert(level(NewLevel)),
assert(level(NewLevel)),
N > 0. % Fail if 0 because that is a non step up.</lang>
N > 0. % Fail if 0 because that is a non step up.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,043: Line 1,043:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
Iterative version using one variable.
Iterative version using one variable.
<lang PureBasic>Procedure step_up()
<syntaxhighlight lang="purebasic">Procedure step_up()
Protected i
Protected i
Repeat: If _step(): i + 1: Else: i - 1: EndIf: Until i = 1
Repeat: If _step(): i + 1: Else: i - 1: EndIf: Until i = 1
EndProcedure</lang>
EndProcedure</syntaxhighlight>
Recursive version. Stack may overflow as probability of a fall approaches or exceeds 50%.
Recursive version. Stack may overflow as probability of a fall approaches or exceeds 50%.
<lang PureBasic>Procedure step_up()
<syntaxhighlight lang="purebasic">Procedure step_up()
While Not _step()
While Not _step()
step_up()
step_up()
Wend
Wend
EndProcedure</lang>
EndProcedure</syntaxhighlight>
Demonstration program.
Demonstration program.
<lang PureBasic>Global level
<syntaxhighlight lang="purebasic">Global level


Procedure _step()
Procedure _step()
Line 1,083: Line 1,083:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
Sample output:
Sample output:
<pre>Begin at level: 0
<pre>Begin at level: 0
Line 1,096: Line 1,096:


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


=== Recursive ===
=== Recursive ===
Line 1,110: Line 1,110:
''p'' approaches 0.5.
''p'' approaches 0.5.


<lang python>def step_up2():
<syntaxhighlight lang="python">def step_up2():
"No numbers."
"No numbers."
while not step():
while not step():
step_up2() # undo the fall</lang>
step_up2() # undo the fall</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery>[ step if done recurse again ] is step-up</lang>
<syntaxhighlight lang="quackery">[ step if done recurse again ] is step-up</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
Line 1,123: Line 1,123:
The step() function described would not be idiomatic R, since it would
The step() function described would not be idiomatic R, since it would
require using the global assignment operator to get the side effect.
require using the global assignment operator to get the side effect.
<lang R>step <- function() {
<syntaxhighlight lang="r">step <- function() {
success <- runif(1) > p
success <- runif(1) > p
## Requires that the "robot" is a variable named "level"
## Requires that the "robot" is a variable named "level"
level <<- level - 1 + (2 * success)
level <<- level - 1 + (2 * success)
success
success
}</lang>
}</syntaxhighlight>


===Recursive Solution===
===Recursive Solution===


<lang R>stepUp <- function() {
<syntaxhighlight lang="r">stepUp <- function() {
while(! step()) {
while(! step()) {
stepUp()
stepUp()
}
}
}</lang>
}</syntaxhighlight>


===Iterative Solution===
===Iterative Solution===


<lang R>stepUpIter <- function() {
<syntaxhighlight lang="r">stepUpIter <- function() {
i <- 0
i <- 0
while ( ! i) {
while ( ! i) {
i <- i - 1 + (2 * step())
i <- i - 1 + (2 * step())
}
}
}</lang>
}</syntaxhighlight>


Example output:
Example output:
Line 1,162: Line 1,162:


=={{header|Racket}}==
=={{header|Racket}}==
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define p 0.5001)
(define p 0.5001)
(define (step)
(define (step)
Line 1,172: Line 1,172:
(else (step-up (add1 n)))))
(else (step-up (add1 n)))))


(step-up 1)</lang>
(step-up 1)</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>sub step_up { step_up until step; }</lang>
<syntaxhighlight lang="raku" line>sub step_up { step_up until step; }</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Stair Climber"
Title: "Stair Climber"
URL: http://rosettacode.org/wiki/Stair_Climbing
URL: http://rosettacode.org/wiki/Stair_Climbing
Line 1,217: Line 1,217:
step_upt: does [if not step [step_upt step_upt]]
step_upt: does [if not step [step_upt step_upt]]


step_upt print "Success!"</lang>
step_upt print "Success!"</syntaxhighlight>


Output:
Output:
Line 1,232: Line 1,232:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>step_up: do while \step(); call step_up
<syntaxhighlight lang="rexx">step_up: do while \step(); call step_up
end
end
return</lang>
return</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
stepup()
stepup()


Line 1,249: Line 1,249:
func stp
func stp
return 0
return 0
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def step_up
<syntaxhighlight lang="ruby">def step_up
start_position = $position
start_position = $position
step until ($position == start_position + 1)
step until ($position == start_position + 1)
Line 1,273: Line 1,273:


$position = 0
$position = 0
step_up</lang>
step_up</syntaxhighlight>
Sample run:
Sample run:
<pre>$ ruby -d stair.climbing.rb
<pre>$ ruby -d stair.climbing.rb
Line 1,287: Line 1,287:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>
<syntaxhighlight lang="runbasic">
result = stepUp()
result = stepUp()
Line 1,300: Line 1,300:
print "Robot stepped "+word$("up down",stepp+1)
print "Robot stepped "+word$("up down",stepp+1)
End Function
End Function
</syntaxhighlight>
</lang>


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>fn step_up() {
<syntaxhighlight lang="rust">fn step_up() {
while !step() {
while !step() {
step_up();
step_up();
}
}
}</lang>
}</syntaxhighlight>


=={{header|SAS}}==
=={{header|SAS}}==


<syntaxhighlight lang="sas">
<lang SAS>
%macro step();
%macro step();
%sysfunc(round(%sysfunc(ranuni(0))))
%sysfunc(round(%sysfunc(ranuni(0))))
%mend step;
%mend step;
</syntaxhighlight>
</lang>


===Recursive===
===Recursive===
<syntaxhighlight lang="sas">
<lang SAS>
%macro step_up();
%macro step_up();


Line 1,331: Line 1,331:


%step_up;
%step_up;
</syntaxhighlight>
</lang>


===Iterative===
===Iterative===
<syntaxhighlight lang="sas">
<lang SAS>
%macro step_up();
%macro step_up();


Line 1,344: Line 1,344:


%mend step_up;
%mend step_up;
</syntaxhighlight>
</lang>




Line 1,366: Line 1,366:
Simple recursive solution:
Simple recursive solution:


<lang scala>def stepUp { while (! step) stepUp }</lang>
<syntaxhighlight lang="scala">def stepUp { while (! step) stepUp }</syntaxhighlight>


Non-recursive solution which almost gets away with not having named variables:
Non-recursive solution which almost gets away with not having named variables:


<lang scala>def stepUp {
<syntaxhighlight lang="scala">def stepUp {
def rec: List[Boolean] => Boolean = step :: (_: List[Boolean]) match {
def rec: List[Boolean] => Boolean = step :: (_: List[Boolean]) match {
case true :: Nil => true
case true :: Nil => true
Line 1,377: Line 1,377:
}
}
rec(Nil)
rec(Nil)
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (step-up n-steps)
<syntaxhighlight lang="scheme">(define (step-up n-steps)
(cond ((zero? n-steps) 'done)
(cond ((zero? n-steps) 'done)
((step) (step-up (- n-steps 1)))
((step) (step-up (- n-steps 1)))
(else (step-up (+ n-steps 1)))))</lang>
(else (step-up (+ n-steps 1)))))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>const proc: step_up is func
<syntaxhighlight lang="seed7">const proc: step_up is func
begin
begin
while not doStep do
while not doStep do
step_up;
step_up;
end while;
end while;
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func step_up() {
<syntaxhighlight lang="ruby">func step_up() {
while (!step()) {
while (!step()) {
step_up();
step_up();
}
}
}</lang>
}</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 1,404: Line 1,404:


The following uses a block closure and the recursive solution which consumes stack until successful.
The following uses a block closure and the recursive solution which consumes stack until successful.
<lang smalltalk>Smalltalk at: #stepUp put: 0.
<syntaxhighlight lang="smalltalk">Smalltalk at: #stepUp put: 0.
stepUp := [ [ step value ] whileFalse: [ stepUp value ] ].</lang>
stepUp := [ [ step value ] whileFalse: [ stepUp value ] ].</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
<lang Standard ML>
(*
(*
* val step : unit -> bool
* val step : unit -> bool
Line 1,419: Line 1,419:
*)
*)
fun step_up() = step() orelse (step_up() andalso step_up())
fun step_up() = step() orelse (step_up() andalso step_up())
</syntaxhighlight>
</lang>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>func step_up() {
<syntaxhighlight lang="swift">func step_up() {
while !step() {
while !step() {
step_up()
step_up()
}
}
}</lang>
}</syntaxhighlight>


The following uses a variable and is a bit longer, but avoids a possible stack overflow:
The following uses a variable and is a bit longer, but avoids a possible stack overflow:
<lang swift>func step_up() {
<syntaxhighlight lang="swift">func step_up() {
for var i = 0; i < 1; step()? ++i : --i { }
for var i = 0; i < 1; step()? ++i : --i { }
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
The setup (note that <code>level</code> and <code>steps</code> are not used elsewhere, but are great for testing…)
The setup (note that <code>level</code> and <code>steps</code> are not used elsewhere, but are great for testing…)
<lang tcl>set level 41
<syntaxhighlight lang="tcl">set level 41
set prob 0.5001
set prob 0.5001
proc step {} {
proc step {} {
Line 1,447: Line 1,447:
return 0
return 0
}
}
}</lang>
}</syntaxhighlight>
===Iterative Solution===
===Iterative Solution===
All iterative solutions require a counter variable, but at least we can avoid any literal digits...
All iterative solutions require a counter variable, but at least we can avoid any literal digits...
<lang tcl>proc step-up-iter {} {
<syntaxhighlight lang="tcl">proc step-up-iter {} {
for {incr d} {$d} {incr d} {
for {incr d} {$d} {incr d} {
incr d [set s -[step]]; incr d $s
incr d [set s -[step]]; incr d $s
}
}
}</lang>
}</syntaxhighlight>
===Recursive Solution===
===Recursive Solution===
This is the simplest possible recursive solution:
This is the simplest possible recursive solution:
<lang tcl>proc step-up-rec {} {
<syntaxhighlight lang="tcl">proc step-up-rec {} {
while {![step]} step-up-rec
while {![step]} step-up-rec
}</lang>
}</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Line 1,465: Line 1,465:


<code>prgmSTEP</code>:
<code>prgmSTEP</code>:
<lang ti83b>If rand>.5:Then
<syntaxhighlight lang="ti83b">If rand>.5:Then
0→C
0→C
Disp "FALL"
Disp "FALL"
Line 1,481: Line 1,481:
End
End
If B=1
If B=1
Pause</lang>
Pause</syntaxhighlight>


<code>prgmSTEPUP</code>:
<code>prgmSTEPUP</code>:
<lang ti83b>prgmSTEP
<syntaxhighlight lang="ti83b">prgmSTEP
While C=0
While C=0
prgmSTEPUP
prgmSTEPUP
prgmSTEP
prgmSTEP
End</lang>
End</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "random" for Random
<syntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Conv
import "/fmt" for Conv


Line 1,516: Line 1,516:
}
}


stepUp.call()</lang>
stepUp.call()</syntaxhighlight>


{{out}}
{{out}}
Line 1,530: Line 1,530:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>proc Step_up; \Iterative version
<syntaxhighlight lang="xpl0">proc Step_up; \Iterative version
int I;
int I;
[I:= 0;
[I:= 0;
Line 1,539: Line 1,539:


proc Step_up; \Recursive version
proc Step_up; \Recursive version
while not Step do Step_up;</lang>
while not Step do Step_up;</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
Line 1,545: Line 1,545:


This version consumes stack space proportional to the number of steps it needs to go up, as opposed to the number of steps it attempts. This is a substantial difference if the probability of success is only somewhat greater than or equal to 1/2.
This version consumes stack space proportional to the number of steps it needs to go up, as opposed to the number of steps it attempts. This is a substantial difference if the probability of success is only somewhat greater than or equal to 1/2.
<lang zkl>fcn step{ } // add code to return Bool
<syntaxhighlight lang="zkl">fcn step{ } // add code to return Bool
fcn stepUp{ while(not step()){ self.fcn() } }</lang>
fcn stepUp{ while(not step()){ self.fcn() } }</syntaxhighlight>
You could also use "stepUp" instead of self.fcn, self.fcn seems a little clearer and makes it easier to refactor.
You could also use "stepUp" instead of self.fcn, self.fcn seems a little clearer and makes it easier to refactor.


An example step function:
An example step function:
{{trans|D}}
{{trans|D}}
<lang zkl>var position=0;
<syntaxhighlight lang="zkl">var position=0;
fcn step(){ //-->0|1
fcn step(){ //-->0|1
r:=(0).random(2); // 0 or 1
r:=(0).random(2); // 0 or 1
Line 1,558: Line 1,558:
r
r
}
}
stepUp();</lang>
stepUp();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>