forked from cardiomoon/RLecture2018
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tower_of_hanoi.R
64 lines (59 loc) · 2.1 KB
/
tower_of_hanoi.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#' Demonstrate the Tower of Hanoi puzzle in R
#'
#' This function uses the recursive algorithm to solve the Tower of Hanoi
#' puzzle, and demonstrates the game in animation.
#'
#' This function was written by Linlin Yan <linlin.yan@@cos.name> in a Chinese
#' forum (See 'References') to show the usage of recursive algorithm.
#' @param n an integer indicating the number of disks on the rot.
#' @seealso \code{\link[graphics]{barplot}}
#' @references Original code: \url{http://cos.name/cn/topic/101199}
#'
#' About the Tower of Hanoi: \url{http://en.wikipedia.org/wiki/Tower_of_Hanoi}
#' @author Linlin Yan <\email{linlin.yan@@cos.name}>
#' @export
#' @examples
#' \dontrun{
#' tower_of_hanoi(7)
#' }
tower_of_hanoi <- function(n = 7) {
if (!interactive()) return()
tower <- list(1:n, NULL, NULL)
color <- rainbow(n)
par(mfrow = c(1, 3), mar = rep(0, 4), ann = FALSE)
bgcolor <- par("bg")
if (bgcolor == "transparent") bgcolor <- "white"
draw.hanoi <- function() {
for (i in 1:3) {
plot(c(-n, n), c(0, n + 2), type = "n", xlab = "",
ylab = "", axes = FALSE)
rect(-n, 0, n, n + 2, border = bgcolor, col = bgcolor)
if (length(tower[[i]]) > 0) {
barplot(rev(tower[[i]]), add = TRUE, horiz = TRUE,
col = color[rev(tower[[i]])])
barplot(-rev(tower[[i]]), add = TRUE, horiz = TRUE,
col = color[rev(tower[[i]])])
}
}
}
move.hanoi <- function(k, from, to, via) {
if (k > 1) {
move.hanoi(k - 1, from, via, to)
move.hanoi(1, from, to, via)
move.hanoi(k - 1, via, to, from)
}
else {
cat("Move ", tower[[from]][1], " from ", LETTERS[from],
" to ", LETTERS[to], "\n")
#print(tower)
tower[[to]] <<- c(tower[[from]][1], tower[[to]])
tower[[from]] <<- tower[[from]][-1]
draw.hanoi()
Sys.sleep(0.5)
}
}
draw.hanoi()
move.hanoi(n, 1, 2, 3)
par(mfrow = c(1, 1))
}
tower_of_hanoi(3)