У вас очень простая ошибка индексации: k
не может достичь N
, поэтому сделайте это k < N
.
Вот вывод, как только вы исправите это:
R> Rcpp::sourceCpp("/tmp/so53936159.cpp")
R> n <- 9
R> odds <- matrix(1:n,ncol=3)
R> my_combs <- generateCombinations(odds)
R> my_combs
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 1 4 8
[3,] 1 4 9
[4,] 1 5 7
[5,] 1 5 8
[6,] 1 5 9
[7,] 1 6 7
[8,] 1 6 8
[9,] 1 6 9
[10,] 2 4 7
[11,] 2 4 8
[12,] 2 4 9
[13,] 2 5 7
[14,] 2 5 8
[15,] 2 5 9
[16,] 2 6 7
[17,] 2 6 8
[18,] 2 6 9
[19,] 3 4 7
[20,] 3 4 8
[21,] 3 4 9
[22,] 3 5 7
[23,] 3 5 8
[24,] 3 5 9
[25,] 3 6 7
[26,] 3 6 8
[27,] 3 6 9
R>
Исправленный код с помощью приведенного ниже примера R.
#include <Rcpp.h>
// [[Rcpp::plugins("cpp11")]]
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix generateCombinations(const NumericMatrix& odds) {
int n = odds.rows();
int N = n*n*n;
IntegerVector v1(n);
std::iota(v1.begin(), v1.end(), 0);
IntegerVector v2(n*n);
v2 = rep_each(v1,n);
NumericVector col0(N);
NumericVector col1(N);
NumericVector col2(N);
for(int k = 0; k < N; ++k) {
int ind0 = k / (n*n);
int ind1 = k % (n*n);
ind1 = v2[ind1];
int ind2 = k % n;
col0[k] = odds(ind0,0);
col1[k] = odds(ind1,1);
col2[k] = odds(ind2,2);
}
NumericMatrix out(N,3);
out(_,0) = col0;
out(_,1) = col1;
out(_,2) = col2;
return out;
}
/*** R
n <- 9
odds <- matrix(1:n,ncol=3)
my_combs <- generateCombinations(odds)
*/