Jump to content

Stair-climbing puzzle: Difference between revisions

no edit summary
(Logo)
No edit summary
Line 357:
while not step():
step_up2() # undo the fall</lang>
 
=={{header|R}}==
 
The step() function described would not be idiomatic R, since it would
require using the global assignment operator to get the side effect.
<lang R>
step <- function() {
success <- runif(1) > p
## Requires that the "robot" is a variable named "level"
level <<- level - 1 + (2 * success)
success
}
</lang>
 
== Recursive Solution ==
 
<lang R>
stepUp <- function() {
while(! step()) {
stepUp()
}
}
</lang>
 
== Iterative Solution ==
 
<lang R>
stepUpIter <- function() {
i <- 0
while ( ! i) {
i <- i - 1 + (2 * step())
}
}
</lang>
 
Example output:
<pre>
> p <- 0.25
> level <- 1
> print(level)
[1] 1
> stepUp()
> print(level)
[1] 2
> stepUpIter()
> print(level)
[1] 3
</pre>
 
 
 
=={{header|Smalltalk}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.