为了减少代码的运行时间,我需要使用Rcpp在C ++中实现背包解算器功能。当我从R调用C ++函数时,它会在前几次运行,但如果我反复调用它R(studio)崩溃(在我调用函数的前3到10次内)。我有3年的R经验,但没有C ++的经验。背包解算器功能如下:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
// A function that returns maximum of two integers
int max(int a, int b) { return (a > b)? a : b; }
// Returns the solution of the Knapsack problem
// [[Rcpp::export]]
IntegerVector knapSack(int nItems, int size, NumericVector weights, NumericVector values){
NumericMatrix matrix(nItems,size);
NumericMatrix picks(nItems,size);
IntegerVector chosen(nItems);
int i,j;
for (i=1;i<=nItems;i++){
for (j=0;j<=size;j++){
if (weights(i-1)<=j){
matrix(i,j) = max(matrix(i-1,j),values(i-1)+matrix(i-1,j-weights(i-1)));
if (values(i-1)+matrix(i-1,j-weights(i-1))>matrix(i-1,j))
picks(i,j)=1;
else
picks(i,j)=-1;
}
else{
picks(i,j) = -1;
matrix(i,j) = matrix(i-1,j);
}
}
}
while (nItems>0){
if (picks(nItems,size)==1){
nItems--;
chosen(nItems)=1;
size -= weights(nItems);
}
else{
nItems--;
}
}
return chosen;
}
我使用以下命令在我的主R脚本中编译函数:
library(Rcpp)
sourceCpp('<path>/Cfunction.cpp')
然后我生成以下数据:
nrRespondents <- 1000
nrComponents <- 30
prices <- matrix(sample(0:100, (nrRespondents*nrComponents), replace=T),nrow=nrRespondents, ncol=nrComponents)
budgets <- matrix(sample(300:500, nrRespondents, replace=T),nrow=nrRespondents, ncol=1)
utilities <- matrix(sample(0:100, nrRespondents*nrComponents, replace=T),nrow=nrRespondents, ncol=nrComponents)
i <- sample(100,1)
b <- budgets[i] #size
p <- prices[i,] #weights
mu <- utilities[i,]
v <- mu-p #values
最后我调用了函数:
knapSack(nrComponents,b,p,v)
我的操作系统是Windows 7,我有R版本3.2.0和Rstudio 0.98.1102。在此先感谢您的帮助。