Convert C++ to Matlab Code
이전 댓글 표시
Can anyone help me convert the C++ code below to Matlab code?
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 8;
const int L = 3;
const int C = 150;
const int MULTIPLIER = 10;
int profit[N + 1][C + 1];
int PV[N + 1][L + 1];
int benefit[N + 1][L + 1];
int calculate(int index, int capacity){
if(index == 0 || capacity == 0) return 0;
if(profit[index][capacity] != -1) return profit[index][capacity];
int ans = 0;
ans = max(ans, calculate(index - 1, capacity));
if(PV[index][1] < capacity) {
ans = max(ans, calculate(index - 1, capacity - PV[index][1]) + benefit[index][1]);
}
if(PV[index][2] < capacity) {
ans = max(ans, calculate(index - 1, capacity - PV[index][2]) + benefit[index][2]);
}
if(PV[index][3] < capacity) {
ans = max(ans, calculate(index - 1, capacity - PV[index][3]) + benefit[index][3]);
}
profit[index][capacity] = ans;
return profit[index][capacity];
}
int n, true_cap;
int main(){
memset(profit, -1, sizeof profit);
scanf("%d%d", &n, &true_cap);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= L; ++j){
double pv;
scanf("%lf%d", &pv, &benefit[i][j]);
PV[i][j] = int(pv * MULTIPLIER);
}
}
int cap = true_cap * MULTIPLIER;
printf("Profit Maksimum: %d\n", calculate(n, cap));
return 0;
}
댓글 수: 1
Guillaume
2019년 3월 11일
Which part of the C++ code don't you understand? Don't you have documentation for the code that tells you what it does?
More importantly, does this code actually work? I can already see that it has no check for buffer overflows so if the user specify too large a n (anything greater than 7!) the program will at best crash, at worse be very nefarious. In addition, depending on the capacity input, the complexity of calculate could be O(e^n), spending much of that time calculating values that would not be used. It does not look to me that this code has been thought out properly.
답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!