[英]Implementation in R with RCPP
我在 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;
//[[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;
}
值 20
元素 2 3 11 12 13
正確答案應該是 Value 11 element 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)
}
線
int n=sizeof(w);
不好,因為sizeof
不是用於獲取元素數,而是用於獲取 memory 上占用的字節數。
它應該是
int n=w.length();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.