Stair-climbing puzzle: Difference between revisions

Added D code
m (→‎{{header|Scala}}: identation)
(Added D code)
Line 194:
)
true))</lang>
 
=={{header|D}}==
The recursive version (note that "step_up" is equivalent to "step_up()" in D):
<lang d>void step_up()
{
while(!step)
step_up;
}</lang>
The non-recursive version, using 1 variable:
<lang d>void step_up_nr()
{
for(uint i = 0; i < 1; step ? ++i : --i) {};
}</lang>
Test program:
<lang d>import std.stdio;
import std.random;
 
int position;
bool step()
{
bool r = rand() > (uint.max / 2);
if(r)
writefln("Climbed up to %d", ++position);
else
writefln("Fell down to %d", --position);
return r;
}
 
void step_up()
{
while(!step)
step_up;
}
 
void main()
{
rand_seed(0, 0); // to make it somewhat repeatable
step_up;
}</lang>
Sample output:
<pre>Fell down to -1
Fell down to -2
Fell down to -3
Fell down to -4
Climbed up to -3
Fell down to -4
Climbed up to -3
Climbed up to -2
Climbed up to -1
Climbed up to 0
Climbed up to 1</pre>
 
=={{header|E}}==