我需要对此问题进行模拟:
两个机器人A和B放置在2D坐标平面上,A放在坐标(0,0)上,B放在(10,0)上。他们可以以相同的概率向上,向下,向左或向右步进。他们同时开始行动,我需要找到他们会遇到多少步骤。如果它们超过15000步,则认为它们已经丢失并且永远不会满足。如果机器人与第1侧在同一个方格中(例如坐标(0,0) - (1,0);(0,0) - (0,0);(0,0) - (1,1) ))
现在我需要进行图形模拟和计数步骤,直到它们在R统计软件中相遇。我知道如何计算步数,但我真的很难接受图形模拟。
答案 0 :(得分:1)
也许这样的事情有帮助吗? :
#basic plot
plot(NULL, ann = F, xlim = c(-10,20), ylim = c(-10,20))
abline(h = -10:20, col = grey(0.75), lty = 2)
abline(v = -10:20, col = grey(0.75), lty = 2)
#starting coordinates
A_coords = c(0,0)
B_coords = c(10,0)
text(A_coords[1], A_coords[2], "A", col = "red")
text(B_coords[1], B_coords[2], "B", col = "blue")
for(i in 1:15000)
{
Sys.sleep(1)
text(A_coords[1], A_coords[2], "A", col = "white")
text(B_coords[1], B_coords[2], "B", col = "white")
#used jonas's idea
A <- A_coords + unlist(sample(list(c(0, 1), c(1, 0), c(-1, 0), c(0, -1)), 1))
B <- B_coords + unlist(sample(list(c(0, 1), c(1, 0), c(-1, 0), c(0, -1)), 1))
lines(c(A_coords[1], A[1]), c(A_coords[2], A[2]), col = "red")
lines(c(B_coords[1], B[1]), c(B_coords[2], B[2]), col = "blue")
A_coords <- A
B_coords <- B
text(A_coords[1], A_coords[2], "A", col = "red")
text(B_coords[1], B_coords[2], "B", col = "blue")
if(all(abs(A_coords - B_coords) <= 1)) break
}
list(steps = i, A_coordinates = A_coords, B_coordinates = B_coords)
答案 1 :(得分:1)
我会尝试这样的事情:
plot_robots <- function(rob1, rob2){
plot(1, xlim = c(-20, 20), ylim =c(-20, 20), type = "n", xaxs = "i", yaxs = "i")
abline(h =-20:20, v = -20:20)
points(c(rob1[1], rob2[1]), c(rob2[2], rob2[2]), pch = 21, cex = 2, bg = c("red", "blue"))
}
rob1 <- c(0, 0)
rob2 <- c(10, 0)
plot_robots(rob1, rob2)
for(i in 1:15000){
rob1 <- rob1 + sample(list(c(0, 1), c(1, 0), c(-1, 0), c(0, -1)), 1)[[1]]
rob2 <- rob2 + sample(list(c(0, 1), c(1, 0), c(-1, 0), c(0, -1)), 1)[[1]]
plot_robots(rob1, rob2)
Sys.sleep(.1)
}
这不完美,但应该提出一个想法......我认为没有人有时间观看机器人,直到他们见面为止。这需要很长时间......