Stair-climbing puzzle: Difference between revisions

Realize in F#
m (minor fix to reporting in Prolog implementation)
(Realize in F#)
(19 intermediate revisions by 13 users not shown)
Line 30:
}
</pre>
 
=={{header|11l}}==
{{trans|Python}}
 
=== Iterative ===
<syntaxhighlight lang="11l">F step_up1()
V deficit = 1
L deficit > 0
I step()
deficit--
E
deficit++</syntaxhighlight>
 
=== Recursive ===
<syntaxhighlight lang="11l">F step_up2()
L !step()
step_up2()</syntaxhighlight>
 
=={{header|ActionScript}}==
===Iterative===
<langsyntaxhighlight ActionScriptlang="actionscript">function stepUp()
{
var i:int = 0;
Line 39 ⟶ 56:
if(step())i++;
else i--;
}</langsyntaxhighlight>
===Recursive===
<langsyntaxhighlight ActionScriptlang="actionscript">function stepUp()
{
if(!step())
Line 48 ⟶ 65:
stepUp();
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">procedure Step_Up is
begin
while not Step loop
Step_Up;
end loop;
end Step_Up;</langsyntaxhighlight>
The following is a test program simulating Step:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
 
Line 89 ⟶ 106:
Reset (Dice);
Step_Up;
end Scaffolding;</langsyntaxhighlight>
Sample output:
<pre>
Line 105 ⟶ 122:
=={{header|Aime}}==
{{trans|C}}
<langsyntaxhighlight lang="aime">void step_up(void)
{
while (!step()) {
step_up();
}
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 120 ⟶ 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]}}
<langsyntaxhighlight Algol68lang="algol68"> PROC step up = VOID:
BEGIN
WHILE NOT step DO
step up
OD
END # step up #;</langsyntaxhighlight>The following is a test program simulating step: <langsyntaxhighlight Algol68lang="algol68">
PROC scaffolding = VOID:
BEGIN
Line 153 ⟶ 170:
END # scaffolding #;
 
scaffolding</langsyntaxhighlight>
Sample output:
<pre>
Line 162 ⟶ 179:
Climbed up to +1
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">Position: 0
 
stepUp: function [].export:[Position][
startPos: Position
until -> step [
Position = startPos + 1
]
]
 
step: function [].export:[Position][
(0.5 > random 0 1.0)? [
Position: Position - 1
print ~"fall (|Position|)"
false
][
Position: Position + 1
print ~"rise (|Position|)"
true
]
]
 
stepUp</syntaxhighlight>
 
{{out}}
 
<pre>fall (-1)
fall (-2)
rise (-1)
rise (0)
fall (-1)
fall (-2)
rise (-1)
rise (0)
rise (1)</pre>
 
=={{header|AutoHotkey}}==
Recursive solution:
<langsyntaxhighlight AutoHotkeylang="autohotkey">step_up()
{
While !step()
step_up()
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
function step_up() {
while (!step()) { step_up() }
}
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
Line 183 ⟶ 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.)
 
<langsyntaxhighlight lang="qbasic">SUB stepup
IF NOT step1 THEN stepup: stepup
END SUB</langsyntaxhighlight>
 
See also: [[#BBC BASIC|BBC BASIC]], [[#Liberty BASIC|Liberty BASIC]], [[#PureBasic|PureBasic]], [[#TI-83 BASIC|TI-83 BASIC]]
Line 191 ⟶ 246:
=={{header|BBC BASIC}}==
Recursive solution:
<langsyntaxhighlight lang="bbcbasic"> DEF PROCstepup
IF NOT FNstep PROCstepup : PROCstepup
ENDPROC</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">void step_up(void)
{
while (!step()) {
step_up();
}
}</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="c">void step_up(void)
{
int i = 0;
Line 215 ⟶ 270:
}
}
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">void step_up() {
while (!step()) step_up();
}</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">void step_up()
{
while (!step()) step_up();
}</langsyntaxhighlight>
 
The following uses a variable and is a bit longer, but avoids a possible stack overflow:
<langsyntaxhighlight lang="cpp">void step_up()
{
for (int i = 0; i < 1; step()? ++i : --i);
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<lang csharp>void step_up() {
while (!step()) step_up();
}</lang>
 
=={{header|Clojure}}==
First, some boilerplate.
 
<langsyntaxhighlight lang="lisp">;; the initial level
(def level (atom 41))
 
Line 248 ⟶ 303:
(let [success (< (rand) prob)]
(swap! level (if success inc dec))
success) )</langsyntaxhighlight>
 
=== Tail-recursive ===
The internal recursion uses a counter; see the function documentation.
 
<langsyntaxhighlight lang="lisp">(defn step-up1
"Straightforward implementation: keep track of how many level we
need to ascend, and stop when this count is zero."
Line 260 ⟶ 315:
(or (zero? deficit)
(recur (if (step) (dec deficit)
(inc deficit)))) ) )</langsyntaxhighlight>
 
=== Recursive ===
Line 266 ⟶ 321:
''p'' approaches 0.5.
 
<langsyntaxhighlight lang="lisp">(defn step-up2
"Non-tail-recursive. No numbers."
[]
Line 273 ⟶ 328:
(step-up2) ;; try again
)
true))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun step-up ()
(unless (step) (step-up) (step-up)))</langsyntaxhighlight>
 
=={{header|D}}==
The recursive version (note that "step_up" is equivalent to "step_up()" in D):
<langsyntaxhighlight lang="d">void step_up()
{
while(!step)
step_up;
}</langsyntaxhighlight>
The non-recursive version, using 1 variable:
<langsyntaxhighlight lang="d">void step_up_nr()
{
for(uint i = 0; i < 1; step ? ++i : --i) {};
}</langsyntaxhighlight>
Test program:
<langsyntaxhighlight lang="d">import std.stdio;
import std.random;
 
Line 315 ⟶ 371:
rand_seed(0, 0); // to make it somewhat repeatable
step_up;
}</langsyntaxhighlight>
Sample output:
<pre>Fell down to -1
Line 328 ⟶ 384:
Climbed up to 0
Climbed up to 1</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
Recursive version using no variables other than the Boolean returned by "Step"
 
<syntaxhighlight lang="Delphi">
 
{Recursive version}
 
procedure Step_Up;
begin
while not Step do Step_Up;
end;
 
</syntaxhighlight>
 
Iterative versions using one variable.
 
<syntaxhighlight lang="Delphi">
 
{Iterative version}
 
procedure Step_Up;
var I: integer;
begin
while I<1 do
if Step then Inc(I) else Dec(I);
end;
</syntaxhighlight>
 
Functional example program
 
<syntaxhighlight lang="Delphi">
var Position: integer;
 
function Step(Memo: TMemo): boolean;
begin
Result:=Random(2)=1;
if Result then Inc(Position)
else Dec(Position);
If Result then Memo.Lines.Add(Format('Climbed up to %d', [Position]))
else Memo.Lines.Add(Format('Fell down to %d', [Position]));
end;
 
 
procedure StepUp(Memo: TMemo);
begin
while not Step(Memo) do StepUp(Memo);
end;
 
 
procedure ShowStairClimb(Memo: TMemo);
begin
Position:=0;
Randomize;
StepUp(Memo);
end;
 
</syntaxhighlight>
{{out}}
<pre>
Fell down to -1
Climbed up to 0
Fell down to -1
Climbed up to 0
Climbed up to 1
Elapsed Time: 4.600 ms.
 
</pre>
 
=={{header|E}}==
Line 335 ⟶ 462:
The problem framework:
 
<langsyntaxhighlight lang="e">var level := 41
var prob := 0.5001
 
Line 342 ⟶ 469:
level += success.pick(1, -1)
return success
}</langsyntaxhighlight>
 
Counting solution:
 
<langsyntaxhighlight lang="e">def stepUpCounting() {
var deficit := 1
while (deficit > 0) {
deficit += step().pick(-1, 1)
}
}</langsyntaxhighlight>
 
Ordinary recursive solution:
<langsyntaxhighlight lang="e">def stepUpRecur() {
if (!step()) {
stepUpRecur()
stepUpRecur()
}
}</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="e">def stepUpEventualRecur() {
if (!step()) {
return when (stepUpEventualRecur <- (),
stepUpEventualRecur <- ()) -> {}
}
}</langsyntaxhighlight>
 
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]]
<langsyntaxhighlight lang="e">def stepUpEventual() {
# This general structure (tail-recursive def{if{when}}) is rather common
# and probably ought to be defined in a library.
Line 385 ⟶ 512:
}
return loop(1)
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define (step-up) (while (not (step)) (step-up)))
;; checking this is tail-recusive :
Line 410 ⟶ 537:
(climb stairs)
(writeln 'stairs stairs 'probability success 'steps STEPS)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 440 ⟶ 567:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Stair_climbing do
defp step, do: 1 == :rand.uniform(2)
Line 452 ⟶ 579:
end
 
IO.inspect Stair_climbing.step_up</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(stair).
-compile(export_all).
Line 470 ⟶ 597:
step_up() ->
step_up(step()).
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">procedure step_up()
if not step() then
step_up()
step_up()
end if
end procedure</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
let rec step_up() = while not(step()) do step_up()
</syntaxhighlight>
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: step-up ( -- ) step [ step-up step-up ] unless ;</langsyntaxhighlight>
 
=={{header|Forth}}==
Recursive. May exceed return stack unless compiler optimizes tail calls.
<langsyntaxhighlight lang="forth">: step-up begin step 0= while recurse repeat ;</langsyntaxhighlight>
Counting. Avoids using a named variable.
<langsyntaxhighlight lang="forth">: step-up -1 begin step if 1+ else 1- then ?dup 0= until ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 493 ⟶ 624:
 
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">module StairRobot
implicit none
 
Line 520 ⟶ 651:
end subroutine step_up_iter
 
end module StairRobot</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Since step is a statement modifier in FreeBASIC, we will use step_
 
Iterative version using one variable.
<syntaxhighlight lang="freebasic">Sub step_up()
Dim As Integer i
Do
If step_() Then
i += 1
Else
i -= 1
End If
Loop Until i = 1
End Sub</syntaxhighlight>
 
Recursive version.
<syntaxhighlight lang="freebasic">Sub step_up()
While Not step_()
step_up()
Wend
End Sub</syntaxhighlight>
 
Demonstration program.
<syntaxhighlight lang="freebasic">Function step_() As Boolean
If Int((Rnd * 2)) Then
Print "Robot sube"
Return True
Else
Print "Robot se cae"
Return False
End If
End Function
'recursive
Sub step_up()
While Not step_()
step_up()
Wend
End Sub
 
step_up
Sleep</syntaxhighlight>
 
 
=={{header|Go}}==
38 bytes, no variables, no numbers.
<langsyntaxhighlight lang="go">func step_up(){for !step(){step_up()}}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<syntaxhighlight lang="grovy">
<lang Grovy>
class Stair_climbing{
static void main(String[] args){
Line 538 ⟶ 713:
 
}
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
Line 544 ⟶ 719:
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:
 
<langsyntaxhighlight lang="haskell">stepUp :: Robot ()
stepUp = untilM step stepUp
 
Line 550 ⟶ 725:
untilM test action = do
result <- test
if result then return () else action >> untilM test action</langsyntaxhighlight>
 
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>.
 
<langsyntaxhighlight lang="haskell">import Control.Monad.State
import System.Random (StdGen, getStdGen, random)
 
Line 572 ⟶ 747:
putStrLn $ "The robot is at step #" ++ show startingPos ++ "."
let (endingPos, _) = execState stepUp (startingPos, g)
putStrLn $ "The robot is at step #" ++ show endingPos ++ "."</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 581 ⟶ 756:
is implemented in Icon (or Unicon) and fails only when the implementation in
another language returns <tt>false</tt>, then:
<langsyntaxhighlight lang="unicon">procedure step_up()
return step() | (step_up(),step_up())
end</langsyntaxhighlight>
 
You can subtract a few more characters (and multiply the difficulty
of understanding) with:
<langsyntaxhighlight lang="unicon">procedure step_up()
(|not step(), step_up())
end</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution (Tacit):'''
<langsyntaxhighlight lang="j">step =: 0.6 > ?@0:
attemptClimb =: [: <:`>:@.step 0:
isNotUpOne =: -.@(+/@])
 
step_up=: (] , attemptClimb)^:isNotUpOne^:_</langsyntaxhighlight>
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 603 ⟶ 778:
 
'''Solution (Explicit):'''
<langsyntaxhighlight lang="j">step_upX=: monad define NB. iterative
while. -. +/y do. y=. y , _1 1 {~ step 0 end.
)
Line 609 ⟶ 784:
step_upR=: monad define NB. recursive (stack overflow possible!)
while. -. step'' do. step_upR'' end.
)</langsyntaxhighlight>
 
'''Example usage:'''
<langsyntaxhighlight 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 NB. running sum of output (current step relative to start)
_1 0 _1 _2 _1 0 1
+/\ 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</langsyntaxhighlight>
 
 
Another approach might be:
 
<langsyntaxhighlight Jlang="j">keepTrying=: (, {: - _1 ^ step)^:({. >: {:)^:_</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight Jlang="j"> keepTrying 2
2 1 0 1 2 3
keepTrying 3
3 2 3 2 3 2 3 4
keepTrying 4
4 5</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|C++}}
<langsyntaxhighlight lang="java">public void stepUp() {
while (!step()) stepUp();
}</langsyntaxhighlight>
The following uses a variable and is a bit longer, but avoids a possible stack overflow:
<langsyntaxhighlight lang="java">public void stepUp(){
for (int i = 0; i < 1; step() ? ++i : --i);
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 647 ⟶ 822:
 
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:
<syntaxhighlight lang ="jq">def tick: .+1;</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="jq">def random: [0, 0, 0, 1, 0, 1, 1, 0];</langsyntaxhighlight>
 
"step" returns true or false based on the current time (the input) and the value of "random":
<langsyntaxhighlight lang="jq">def step:
random as $r
| if . >= ($r|length) then true else ($r[.] == 1) end ;</langsyntaxhighlight>
 
We can now define step_up:
<langsyntaxhighlight lang="jq">def step_up:
if step then tick
else tick | step_up | step_up
end;</langsyntaxhighlight>
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:
<syntaxhighlight lang ="jq">0 | step_up</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -f stair-climbing_puzzle.jq
11</langsyntaxhighlight>
===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
function must be tail-recursive and have arity 0. This can be
achieved by providing [time, goal] as the input as follows:
<langsyntaxhighlight lang="jq">def tco_step_up:
.[0] as $time | .[1] as $goal
| if $goal == 0 then $time
Line 677 ⟶ 852:
if $time|step then $goal - 1 else $goal + 1 end
| [ ($time|tick), .] | tco_step_up
end ;</langsyntaxhighlight>
The simulation can then be started as follows:
<syntaxhighlight lang ="jq">[0,1] | tco_step_up</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="julia">
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:
<langsyntaxhighlight lang="julia">
step() = (b = rand([true,true,false]); println(b); b)
step_up()
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 707 ⟶ 882:
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">// version 1.2.0
 
import java.util.Random
Line 729 ⟶ 904:
fun main(args: Array<String>) {
stepUp()
}</langsyntaxhighlight>
 
{{out}}
Line 745 ⟶ 920:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight 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
'quite a ways before making it to the next step up, but sometimes he makes it
Line 765 ⟶ 940:
Print "Robot fell down"
End If
End Function</langsyntaxhighlight>
 
=={{header|Logo}}==
Recursive.
<langsyntaxhighlight lang="logo">to step.up
if not step [step.up step.up]
end</langsyntaxhighlight>
Constant space (fully tail-recursive).
<langsyntaxhighlight lang="logo">to step.up [:n 1]
if :n=0 [stop]
(step.up ifelse step [:n-1] [:n+1])
end</langsyntaxhighlight>
 
=={{header|Lua}}==
 
<syntaxhighlight lang="lua">
<lang Lua>
function step_up()
while not step() do step_up() end
end
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">StepUp[] := If[!Step[], StepUp[]; StepUp[]]</syntaxhighlight>
 
<lang Mathematica>StepUp[] := If[!Step[], StepUp[]; StepUp[]]</lang>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function step_up()
while ~step()
step_up();
end</langsyntaxhighlight>
 
=={{header|Nim}}==
One liner (yes it is possible in Nim).
<lang nim>proc stepUp1 =
<syntaxhighlight lang="nim">proc stepUp = (while not step(): stepUp())</syntaxhighlight>
var deficit = 1
while deficit > 0:
if step():
dec deficit
else:
inc deficit
 
proc stepUp2 =
while not step():
stepUp2()</lang>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec step_up() =
while not(step()) do
step_up()
done
;;</langsyntaxhighlight>
 
=={{header|Oz}}==
Recursive solution:
<langsyntaxhighlight lang="oz">proc {StepUp}
if {Not {Step}} then
{StepUp} %% make up for the fall
{StepUp} %% repeat original attempt
end
end</langsyntaxhighlight>
Might lead to a stack overflow because the first call to <code>StepUp</code> is not in tail position.
 
Iterative solution:
<langsyntaxhighlight lang="oz">proc {StepUp}
Level = {NewCell 0}
in
Line 836 ⟶ 1,001:
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.
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">step_up()=while(!step(),step_up())</langsyntaxhighlight>
 
=={{header|Pascal}}==
Recursive solution:
<langsyntaxhighlight lang="pascal">procedure stepUp;
begin
while not step do
stepUp;
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub step_up { step_up until step; }</langsyntaxhighlight>
 
=={{header|Perl 6}}==
<lang perl6>sub step_up { step_up until step; }</lang>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>procedure step_up()
<span style="color: #008080;">procedure</span> <span style="color: #000000;">step_up</span><span style="color: #0000FF;">()</span>
while not step() do step_up() end while
<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>
end procedure</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de stepUp ()
(until (step1) # ('step1', because 'step' is a system function)
(stepUp) ) )</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function StepUp
{
If ( -not ( Step ) )
Line 894 ⟶ 1,058:
# Test
$VerbosePreference = 'Continue'
StepUp</langsyntaxhighlight>
{{out}}
<pre>VERBOSE: Fell one step
Line 910 ⟶ 1,074:
=={{header|Prolog}}==
The robot code is very short
<syntaxhighlight lang="prolog">step_up :- \+ step, step_up, step_up.</syntaxhighlight>
<lang Prolog>step_robot :- repeat, step, fail.</lang>
The test program uses a global variable to store the current level and then implements the step behaviour which determines and reports the success of the step and updates the level.
 
This is capped at 20 steps but removing the last line will enable the program to run forever.
<lang Prolog>test_step_robot :-
nb_setval(level, 1),
step_robot.
The test program keeps track of the level in a dynamic predicate.
<syntaxhighlight lang="prolog">:- dynamic level/1.
setup :-
retractall(level(_)),
assert(level(1)).
step :-
nb_getval(level, (Level),
random_between(0,3,N),
(
Line 928 ⟶ 1,092:
succ(NewLevel, Level), format('Fell down to ~d~n', NewLevel)
),
nb_setvalretractall(level, NewLevel(Level)),
assert(level(NewLevel)),
NewLevel >= 20 -> abort.</lang>
N > 0. % Fail if 0 because that is a non step up.</syntaxhighlight>
{{out}}
<pre>
?- setup, between(1,10,_), step_up, fail.
?- test_step_robot.
Climbed up to 2
Climbed up to 3
Line 939 ⟶ 1,104:
Fell down to 4
Climbed up to 5
Climbed up to 6
Fell down to 5
Climbed up to 6
Climbed up to 7
Climbed up to 8
ClimbedFell updown to 97
Climbed up to 108
false.
Fell down to 9
 
Climbed up to 10
Climbed up to 11
Climbed up to 12
Climbed up to 13
Climbed up to 14
Climbed up to 15
Climbed up to 16
Climbed up to 17
Climbed up to 18
Fell down to 17
Climbed up to 18
Climbed up to 19
Climbed up to 20
% Execution Aborted
?-
</pre>
Line 964 ⟶ 1,118:
=={{header|PureBasic}}==
Iterative version using one variable.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure step_up()
Protected i
Repeat: If _step(): i + 1: Else: i - 1: EndIf: Until i = 1
EndProcedure</langsyntaxhighlight>
Recursive version. Stack may overflow as probability of a fall approaches or exceeds 50%.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure step_up()
While Not _step()
step_up()
Wend
EndProcedure</langsyntaxhighlight>
Demonstration program.
<langsyntaxhighlight PureBasiclang="purebasic">Global level
 
Procedure _step()
Line 1,004 ⟶ 1,158:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>Begin at level: 0
Line 1,017 ⟶ 1,171:
 
=== Iterative ===
<langsyntaxhighlight 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:
Line 1,025 ⟶ 1,179:
deficit -= 1
else:
deficit += 1</langsyntaxhighlight>
 
=== Recursive ===
Line 1,031 ⟶ 1,185:
''p'' approaches 0.5.
 
<langsyntaxhighlight lang="python">def step_up2():
"No numbers."
while not step():
step_up2() # undo the fall</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery">[ step if done recurse again ] is step-up</syntaxhighlight>
 
=={{header|R}}==
Line 1,040 ⟶ 1,198:
The step() function described would not be idiomatic R, since it would
require using the global assignment operator to get the side effect.
<langsyntaxhighlight Rlang="r">step <- function() {
success <- runif(1) > p
## Requires that the "robot" is a variable named "level"
level <<- level - 1 + (2 * success)
success
}</langsyntaxhighlight>
 
===Recursive Solution===
 
<langsyntaxhighlight Rlang="r">stepUp <- function() {
while(! step()) {
stepUp()
}
}</langsyntaxhighlight>
 
===Iterative Solution===
 
<langsyntaxhighlight Rlang="r">stepUpIter <- function() {
i <- 0
while ( ! i) {
i <- i - 1 + (2 * step())
}
}</langsyntaxhighlight>
 
Example output:
Line 1,079 ⟶ 1,237:
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define p 0.5001)
(define (step)
Line 1,089 ⟶ 1,247:
(else (step-up (add1 n)))))
 
(step-up 1)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub step_up { step_up until step; }</syntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Stair Climber"
URL: http://rosettacode.org/wiki/Stair_Climbing
Line 1,130 ⟶ 1,292:
step_upt: does [if not step [step_upt step_upt]]
 
step_upt print "Success!"</langsyntaxhighlight>
 
Output:
Line 1,145 ⟶ 1,307:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">step_up: do while \step(); call step_up
end
return</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
stepup()
 
Line 1,162 ⟶ 1,324:
func stp
return 0
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<lang runbasic>
result = stepUp()
Function stepUp()
While Not(stepp())
result = stepUp()
Wend
End Function
Function stepp()
stepp = int((Rnd(1) * 2))
print "Robot stepped "+word$("up down",stepp+1)
End Function
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def step_up
start_position = $position
step until ($position == start_position + 1)
Line 1,202 ⟶ 1,348:
 
$position = 0
step_up</langsyntaxhighlight>
Sample run:
<pre>$ ruby -d stair.climbing.rb
Line 1,214 ⟶ 1,360:
"rise (0)"
"rise (1)"</pre>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">
result = stepUp()
Function stepUp()
While Not(stepp())
result = stepUp()
Wend
End Function
Function stepp()
stepp = int((Rnd(1) * 2))
print "Robot stepped "+word$("up down",stepp+1)
End Function
</syntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn step_up() {
while !step() {
step_up();
}
}</syntaxhighlight>
 
=={{header|SAS}}==
 
<syntaxhighlight lang="sas">
<lang SAS>
%macro step();
%sysfunc(round(%sysfunc(ranuni(0))))
%mend step;
</syntaxhighlight>
</lang>
 
===Recursive===
<syntaxhighlight lang="sas">
<lang SAS>
%macro step_up();
 
Line 1,237 ⟶ 1,406:
 
%step_up;
</syntaxhighlight>
</lang>
 
===Iterative===
<syntaxhighlight lang="sas">
<lang SAS>
%macro step_up();
 
Line 1,250 ⟶ 1,419:
 
%mend step_up;
</syntaxhighlight>
</lang>
 
 
Line 1,272 ⟶ 1,441:
Simple recursive solution:
 
<langsyntaxhighlight lang="scala">def stepUp { while (! step) stepUp }</langsyntaxhighlight>
 
Non-recursive solution which almost gets away with not having named variables:
 
<langsyntaxhighlight lang="scala">def stepUp {
def rec: List[Boolean] => Boolean = step :: (_: List[Boolean]) match {
case true :: Nil => true
Line 1,283 ⟶ 1,452:
}
rec(Nil)
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (step-up n-steps)
(cond ((zero? n-steps) 'done)
((step) (step-up (- n-steps 1)))
(else (step-up (+ n-steps 1)))))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const proc: step_up is func
begin
while not doStep do
step_up;
end while;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func step_up() {
while (!step()) {
step_up();
}
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 1,310 ⟶ 1,479:
 
The following uses a block closure and the recursive solution which consumes stack until successful.
<langsyntaxhighlight lang="smalltalk">Smalltalk at: #stepUp put: 0.
stepUp := [ [ step value ] whileFalse: [ stepUp value ] ].</langsyntaxhighlight>
 
=={{header|Standard ML}}==
 
<lang Standard ML>
<syntaxhighlight lang="sml">
(*
* val step : unit -> bool
Line 1,325 ⟶ 1,495:
*)
fun step_up() = step() orelse (step_up() andalso step_up())
</syntaxhighlight>
</lang>
 
Alternate version:
<syntaxhighlight lang="sml">fun step() = true
 
fun step_up() = while step() = false do step_up()
</syntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func step_up() {
while !step() {
step_up()
}
}</langsyntaxhighlight>
 
The following uses a variable and is a bit longer, but avoids a possible stack overflow:
<langsyntaxhighlight lang="swift">func step_up() {
for var i = 0; i < 1; step()? ++i : --i { }
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
The setup (note that <code>level</code> and <code>steps</code> are not used elsewhere, but are great for testing…)
<langsyntaxhighlight lang="tcl">set level 41
set prob 0.5001
proc step {} {
Line 1,353 ⟶ 1,529:
return 0
}
}</langsyntaxhighlight>
===Iterative Solution===
All iterative solutions require a counter variable, but at least we can avoid any literal digits...
<langsyntaxhighlight lang="tcl">proc step-up-iter {} {
for {incr d} {$d} {incr d} {
incr d [set s -[step]]; incr d $s
}
}</langsyntaxhighlight>
===Recursive Solution===
This is the simplest possible recursive solution:
<langsyntaxhighlight lang="tcl">proc step-up-rec {} {
while {![step]} step-up-rec
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 1,371 ⟶ 1,547:
 
<code>prgmSTEP</code>:
<langsyntaxhighlight lang="ti83b">If rand>.5:Then
0→C
Disp "FALL"
Line 1,387 ⟶ 1,563:
End
If B=1
Pause</langsyntaxhighlight>
 
<code>prgmSTEPUP</code>:
<langsyntaxhighlight lang="ti83b">prgmSTEP
While C=0
prgmSTEPUP
prgmSTEP
End</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "random" for Random
import "./fmt" for Conv
 
var rand = Random.new(1268) // generates short repeatable sequence
var position = 0
 
var step = Fn.new {
var r = Conv.itob(rand.int(2))
if (r) {
position = position + 1
System.print("Climbed up to %(position)")
} else {
position = position - 1
System.print("Fell down to %(position)")
}
return r
}
 
var stepUp // recursive
stepUp = Fn.new {
while (!step.call()) stepUp.call()
}
 
stepUp.call()</syntaxhighlight>
 
{{out}}
<pre>
Fell down to -1
Fell down to -2
Climbed up to -1
Climbed up to 0
Fell down to -1
Climbed up to 0
Climbed up to 1
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">proc Step_up; \Iterative version
int I;
[I:= 0;
Line 1,406 ⟶ 1,621:
 
proc Step_up; \Recursive version
while not Step do Step_up;</langsyntaxhighlight>
 
=={{header|zkl}}==
Line 1,412 ⟶ 1,627:
 
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.
<langsyntaxhighlight lang="zkl">fcn step{ } // add code to return Bool
fcn stepUp{ while(not step()){ self.fcn() } }</langsyntaxhighlight>
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:
{{trans|D}}
<langsyntaxhighlight lang="zkl">var position=0;
fcn step(){ //-->0|1
r:=(0).random(2); // 0 or 1
Line 1,425 ⟶ 1,640:
r
}
stepUp();</langsyntaxhighlight>
{{out}}
<pre>
2,172

edits