生成 4 个方向随机游动的 RCPP 函数

RCPP Function for Generation Random Walk in 4 Directions

我正在尝试生成一个名为 StepstoShop 的函数,它将生成一个 n*2 矩阵,表示 x 和 y 坐标。允许的方向只有北、南、东和西(不允许对角线移动)

这是我目前开发的代码

#include <RcppArmadilloExtensions/sample.h>
#include <cstdlib>
#include <ctime>
using namespace Rcpp;

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]


NumericMatrix StepstoShop(double Steps){

    NumericMatrix SampleGen(Steps,2);
    int n=SampleGen.size();
    int colnum= rand()%1;



for( int i=0; i<n; i++)
      { SampleGen(i,colnum)=(rand()%3)-1;
      }

return SampleGen;
}

我试图通过行在 for 循环中将 0 和 1 之间的随机数分配索引到列,以获得 4 个方向的期望结果 (0,1) (1,0) (-1,0) (0,-1),但是我得到了 8 个方向的混合物。

任何指导,将不胜感激

谢谢

我回顾性地包含了 R 代码来说明我试图重新创建的内容

  # compute path
  n <- 1000
  rw <- matrix(0, ncol = 2, nrow = n)
  # generate the indices to set the deltas
  indx <- cbind(seq(n), sample(c(1, 2), n, TRUE))

  # now set the values
  rw[indx] <- sample(c(-1, 1), n, TRUE)
  # cumsum the columns
  rw[,1] <- cumsum(rw[, 1])
  rw[, 2] <- cumsum(rw[, 2])

  plot(0,type="n",xlab="x",ylab="y",main="Random Walk Simulation In Two 
  Dimensions",col=1:10,xlim=range(-10,15),ylim=range(-40,40))

  # use 'segments' to color each path
  segments(head(rw[, 1], -1)
  , head(rw[, 2], -1)
  , tail(rw[, 1], -1)
  , tail(rw[, 2], -1)
  , col = rainbow(nrow(rw) -1)  # a range of colors
  )

  end<-cbind(-10,30)
  start<-cbind(0,0)

  points(start,pch=16,col="green", cex = 3)
  points(end,pch=16,col="red", cex = 3)

思路是将这段代码迭代100,000次,计算到达终点的概率

谢谢

我会用

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerMatrix StepstoShop(double Steps){

  IntegerVector possible_x = IntegerVector::create(0, 1, -1, 0);
  IntegerVector possible_y = IntegerVector::create(1, 0, 0, -1);
  IntegerMatrix SampleGen(Steps, 2);
  int ind;

  for (int i = 0; i < Steps; i++) {
    ind = R::runif(0, 4);
    SampleGen(i, 0) = possible_x[ind];
    SampleGen(i, 1) = possible_y[ind];
  }

  return SampleGen;
}