2013-11-27 41 views
0

我需要針對此問題的模擬:2D運動仿真中的R

兩臺機器人A和B被放置在二維座標平面中,A被放置在座標(0,0)和B被放置在(10,0)上。他們可以以相同的概率向上,向下,向左或向右步進。他們在同一時間開始行動,我需要找到他們會遇到多少步驟。如果他們超過15000步,就認爲他們已經失去了,永遠不會見面。 (0,0) - (1,0);(0,0) - (0,0);(0,0) - (1,1)的情況下,機器人遇到了與邊1相同的正方形))

現在我需要進行圖形模擬和計數步驟,直到他們在R統計軟件中見面。我有一些想法如何計算步驟,但我真的被圖形模擬困住了。

+4

看起來像功課。你試過什麼了? –

+0

@BenBolker是的,它是家庭作業,我們有一些R的手冊,但它只包含幾個繪製圖形的命令,我正在跳躍,有一些簡單的命令,可以讓我繪製距離爲1的小線條。 –

+0

我刪除了Rcpp標籤,因爲與我可以說最好的沒有任何關係。 –

回答

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) 
+0

這是接近我想要的。機器人只需在每次迭代中向上,向下,向左或向右移動,但我可以修復該問題。我的問題是如何在機器人移動時獲取連接線而不是字母? 有沒有什麼方法可以加快模擬速度,因爲15000步需要很長時間,而且我必須進行1000次模擬(沒有繪圖):( –

+1

@LeetzMKD:你想讓線連接每個機器人正在使用的路徑?但是,如果機器人的移動方向與之前的移動方向相反,那麼您將失去部分路徑。另外,如果您刪除了'Sys.sleep',它將加速。如果您運行這個模擬,您將看到 –

+0

它是通過路徑創建字母,我希望用字母來代替線條,如果機器人向相反的方向移動,它不會重疊並且不會消失? –

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) 
} 

它不是完美的,但應該給一個想法......我不認爲任何人得到了觀看機器人,直到時間他們見面。這將需要年齡...