C++ 用RCPP在R中实现
我已经用R写了一个蛮力算法,它运行得很好。我想使用Rcpp实现,这样我的代码运行得更快,但我无法让它工作。例如,对于一个简单的示例w=[4 2 3],v=[10 7 4],最大权重w=5,它不会返回正确的值(11)。如果你能帮助我,我非常感激。 Rccp代码:C++ 用RCPP在R中实现,c++,r,C++,R,我已经用R写了一个蛮力算法,它运行得很好。我想使用Rcpp实现,这样我的代码运行得更快,但我无法让它工作。例如,对于一个简单的示例w=[4 2 3],v=[10 7 4],最大权重w=5,它不会返回正确的值(11)。如果你能帮助我,我非常感激。 Rccp代码: #include <Rcpp.h> #include <vector> #include <math.h> using namespace Rcpp; using namespace std; /
#include <Rcpp.h>
#include <vector>
#include <math.h>
using namespace Rcpp;
using namespace std;
//[[Rcpp::export]]
List brute_force(IntegerVector w, NumericVector v ,int W) {
int n=sizeof(w);
NumericVector result(0);
int allCase = static_cast<int>(pow(2, n));
int maxValue = 0;
for (int i = 0; i < allCase; i++) {
NumericVector temp(0);
int currentCase = i, currentWeight = 0, currentValue = 0;
for(int j=0;j<n;j++){
if(currentCase&1){
currentWeight+=w[j];
currentValue+=v[j];
temp.push_back(j+1);
}
if(currentWeight>W){
break;
}
currentCase=currentCase>>1;
if(currentWeight<=W&¤tValue>maxValue){
maxValue=currentValue;
result=temp;
}
}
}
List L=List::create(Named("value")=maxValue,Named("element")=result);
return L;
}
#包括
#包括
#包括
使用名称空间Rcpp;
使用名称空间std;
//[[Rcpp::导出]]
列出蛮力(整数向量w,数值向量v,整数向量w){
int n=sizeof(w);
数值向量结果(0);
int allCase=静态施法(功率(2,n));
int maxValue=0;
for(int i=0;i>1;
if(currentWeightmaxValue){
最大值=当前值;
结果=温度;
}
}
}
List L=List::create(命名(“值”)=maxValue,命名(“元素”)=result);
返回L;
}
价值观
二十
元素
2 3 11 12 13
正确答案应该是
价值11
要素2 3
我的原始R代码是:
brute_force_knapsack= function(x,W){
stopifnot(is.data.frame(x), apply(x, c(1,2), is.numeric), is.numeric(W), W>=0, colnames(x)==c("w","v"))
n=length(x$w)
w=x$w
v=x$v
result_elements=c()
result_value=0
range=1:2^(n) - 1
for(j in range){
element=which(intToBits(j)==01)
total_weights=sum(w[element])
total_value=sum(v[element])
if(total_value > result_value && total_weights <= W){
result_elements=element
result_value=total_value
}
}
result=list("value"=(result_value),"elements"=result_elements)
print(lengths(result))
return (result)
}
brute\u force\u背包=函数(x,W){
stopifnot(is.data.frame(x),apply(x,c(1,2),is.numeric(W),W>=0,colnames(x)=c(“W”,“v”))
n=长度(x$w)
w=x$w
v=x$v
结果_元素=c()
结果_值=0
范围=1:2^(n)-1
用于(范围内的j){
元素=其中(intToBits(j)==01)
总权重=总和(w[元素])
总值=总和(v[元素])
如果(总值>结果值和总权重行
int n=sizeof(w);
是不好的,因为sizeof
不是用于获取元素数,而是用于获取内存中占用的字节数
应该是
int n=w.length();