Please help translate c++ into matlab code!
Mostra commenti meno recenti
Can anyone help me translate this c++ code into matlab code? I can't seem to get the hang of using string in matlab compared to c++, been sitting around it for ages now. Edit: the program I'm trying to do is that it outputs all possibilities to put + or − or nothing between the numbers from 1 to 9 (in ascending order) such that the result is some target number. The target number is entered by the user. Say for target number 100, one of the possibilities is: 1+2+3−4+5+6+78+9=100.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
# include <iomanip>
# include <cmath>
# include <fstream>
# include <cstring>
using namespace std;
int main()
{
int TARGET;
cin >> TARGET;
int i, total;
vector<string> all = { "1" }; // Will hold all 3^8 legitimate combinations as a string
for ( i = 2; i <= 9; i++ ) // Add each following digit with either -, + or nothing
{
char c = (char)( '0' + i );
vector<string> temp;
for ( string s : all ) // For each previous string there will be three new ones
{
temp.push_back( s + '-' + c );
temp.push_back( s + '+' + c );
temp.push_back( s + c );
}
all = temp;
}
// Now evaluate results by stringstreaming +n or -n into integers
vector<string> matches;
for ( string s : all )
{
stringstream ss( s );
ss >> total;
while ( ss >> i ) total += i;
if ( total == TARGET ) matches.push_back( s );
}
// Write results
cout << "There are " << matches.size() << " possibilities:\n";
for ( string s : matches ) cout << s << '\n';
}
1 Commento
Ameer Hamza
il 19 Apr 2020
Instead of pasting the code, it would be much better if you can explain what you are trying to do in this code. Understanding someone else's code requires much more effort. In the end, it will not be a line to line translation anyway. MATLAB will usually be able to do it in a few lines.
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Deploy to C++ Applications Using MATLAB Data API (C++11) in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!