MATLAB Answers

Help Converting C++ to MATLAB.

1 view (last 30 days)
Peeraphol praphaichai
Peeraphol praphaichai on 29 Oct 2020
Help Converting C++ to MATLAB.
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int N = 20;
vector<pii> v;
void recur(int curr,int val,int vis,int t){
if(curr > N){
return;
}
v.push_back({val,vis});
recur(curr+1,val+t,vis|1<<curr,t*3);
recur(curr+1,val,vis,t*3);
}
int bs(int l,int r,int val){
if(l>r){
return -1;
}
int mid = (l+r)/2;
if(v[mid].first == val){
return mid;
}
if(v[mid].first < val){
return bs(mid+1,r,val);
}else{
return bs(l,mid-1,val);
}
}
int main(){
int n;
scanf("%d",&n);
recur(0,0,0,1);
sort(v.begin(),v.end());
v.resize(unique(v.begin(),v.end())-v.begin());
int sv = v.size()-1;
for(auto curr:v){
int val = curr.first+n;
int p = bs(0,sv,val);
if(p == -1){
continue;
}
bool pass = false;
int n1=0,n2=0;
for(int i=0;i<N;++i){
if(1<<i&curr.second == true && 1<<i&v[p].second == true){
pass = true;
break;
}
if(1<<i&curr.second){
n1++;
}
if(1<<i&v[p].second){
n2++;
}
}
if(pass){
continue;
}
printf("%d %d",n1+n2,val);
break;
}
return 0;
}

Answers (1)

Sripranav Mannepalli
Sripranav Mannepalli on 13 Jul 2021
Hi,
You can call C++ code directly from MATLAB, as shown here.
Alternately, to get started with MATLAB programming, you can start with the MATLAB Onramp Course. After completing it, to get some more knowledge on MATLAB you can go for the MATLAB Fundamentals Course.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!