在r中创建一维沙堆模型
我试图在r中创建一个沙堆模型。它是一维的 规则如下:在r中创建一维沙堆模型,r,R,我试图在r中创建一个沙堆模型。它是一维的 规则如下: 有10个空间 选择一个随机空间。撒一粒沙子 a。如果空间中有0粒沙子,则添加1粒沙子,总共1粒。 B如果它有一粒沙子,那么它现在有两粒,并且这堆沙子会坍塌。将这些谷物中的一种分配给每个邻居。如果邻居有0粒沙子,添加一粒。如果它有两粒沙子,则将其中一粒分配给每个邻居。继续,直到没有更多的空间具有超过1个颗粒。晶粒在0和11处从边缘脱落 现在我写了一些代码。当然,生成初始状态本身很容易: sandpile <- c(0,0,0,0,0,0,
sandpile <- c(0,0,0,0,0,0,0,0,0,0)
沙堆#10个空格
沙堆谢谢!更新它使它更清晰。谢谢,这似乎是工作!还有一个问题。。。你知道我怎么能记录下每圈移动的沙粒数量吗?@TheCurlyManlifes很高兴它能起作用!我对你的问题投了赞成票。我一开始用了很多if
语句,但很快就明白了这是一个棘手的问题,所以我切换到while
。关于后续问题——不是随便问的,但是如果你再问一个问题,那么我会在早上再做。如果你还有兴趣看的话,我现在就发布了这个问题。
drop <- sample (1:10, 1)
sandpile[drop] <- sandpile[drop]+1
if(sandpile[drop] > 1) { (sandpile[drop-1] <- sandpile[drop-1]+1)
if(sandpile[drop] > 1 ) { (sandpile[drop+1] <- sandpile[drop+1]+1)
if(sandpile[drop] > 1) {sandpile[drop] <- sandpile[drop]-2
# 10 spaces
sandpile <- c(1,1,1,1,1,1,1,0,1,1)
# Pick a random space
drop <- sample (1:10, 1)
# If the space has 0 grains of sand, add 1 grain of sand.
if(sandpile[drop]==0){
sandpile[drop] <- 1
cat("done")
# If it has 1, distribute one to each neighbor and so on
} else if(sandpile[drop]==1){
# Left neighbor(s)
i <- drop-1
while(sandpile[i] > 0 & i > 1){
if(i > 1){i <- i -1
} else if (i == 1 & sandpile[i] > 0){
break # it fell off
}else if (i == 1 & sandpile[i] == 0){
sandpile[i] <- 1
break
}
}
if(sandpile[i]==0) sandpile[i] <- 1
# Right neighbor(s)
i <- drop+1
while(sandpile[i] > 0 & i < 10){
if(i > 1){i <- i +1
} else if (i == 10 & sandpile[i] > 0){
break # it fell off
}else if (i == 10 & sandpile[i] == 0){
sandpile[i] <- 1
break
}
}
if(sandpile[i]==0) sandpile[i] <- 1
cat("done")
}