There are three rods (rod A, rod B, and rod C) and 20 disks of different sizes, which can slide onto any rod. The 20 disks are placed in ascending order of size on rod A, while the smallest at the top, and the largest at the bottom.
Question: Please calculate the minimum number of steps required to move the 20 disks from rod A to rod C, obeying the following rules: 1. Only one disk can be moved in a step. 2. No larger disk can be placed on top of a smaller disk. 3. Please answer this question with a recursive function.
hanoi_tower <- function(n) {
# by the pattern, the largest disc will be move with 1 step, the rest are in 2 steps
if (n == 1) {
cat("move disc(1)\n")
return(1)
} else {
cat("move disc(", n, ")\n", sep = "")
return(1+2*hanoi_tower(n-1)) -0.5
}
}
hanoi_tower(20)
## move disc(20)
## move disc(19)
## move disc(18)
## move disc(17)
## move disc(16)
## move disc(15)
## move disc(14)
## move disc(13)
## move disc(12)
## move disc(11)
## move disc(10)
## move disc(9)
## move disc(8)
## move disc(7)
## move disc(6)
## move disc(5)
## move disc(4)
## move disc(3)
## move disc(2)
## move disc(1)
## [1] 1048575
Please use the “apply” command to calculate the medians, maximums, and minimums, of each row and each column. Missing values could be ignored.
matrix <- matrix(
c(3600, 5000, 12000, NA, 1000, 2000, 600, 7500, 1800, 9000,
3600, 4500, 10000, 8500, 3000, 10000, 1000, NA, 1200, 10000,
3800, 5500, 9000, 6000, 6600, 3000, 9600, 6500, 8200, 8000,
5000, 6600, 13000, 4500, 5000, NA, 10600, 9500, 7600, 6000,
6600, 8000, 17000, 3000, 7000, 1000, 12600, 8500, 6000, NA),
5,10, byrow = TRUE)
# by row
apply(matrix,1,median, na.rm = T)
## [1] 3600 4500 6550 6600 7000
apply(matrix,1,max, na.rm = T)
## [1] 12000 10000 9600 13000 17000
apply(matrix,1,min, na.rm = T)
## [1] 600 1000 3000 4500 1000
# by col
apply(matrix,2,median, na.rm = T)
## [1] 3800 5500 12000 5250 5000 2500 9600 8000 6000 8500
apply(matrix,2,max, na.rm = T)
## [1] 6600 8000 17000 8500 7000 10000 12600 9500 8200 10000
apply(matrix,2,min, na.rm = T)
## [1] 3600 4500 9000 3000 1000 1000 600 6500 1200 6000
Please find x, y, and z to satisfy
Please first build a matrix and use the “solve” command.
x <- matrix(c(1,-3,1,1,-2,3,1,-1,1),3,3,byrow = T)
y <- c(4,6,4)
(sol <- solve(x,y))
## [1] 3 0 1
# x %*% sol