Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a functionally identical C++ code for the snippet given in VB.
Sub magicsquare() Const n = 9 Dim i As Integer, j As Integer, v As Integer Debug.Print "The square order is: " & n For i = 1 To n For j = 1 To n Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1 Next j Next i Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2 End Sub
#include <iostream> #include <sstream> #include <iomanip> #include <cassert> #include <vector> using namespace std; class MagicSquare { public: MagicSquare(int d) : sqr(d*d,0), sz(d) { assert(d&1); fillSqr(); } void display() { cout << "Odd Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) cout << setw( l + 2 ) << sqr[yy + x]; cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { int sx = sz / 2, sy = 0, c = 0; while( c < sz * sz ) { if( !sqr[sx + sy * sz] ) { sqr[sx + sy * sz]= c + 1; inc( sx ); dec( sy ); c++; } else { dec( sx ); inc( sy ); inc( sy ); } } } int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } vector<int> sqr; int sz; }; int main() { MagicSquare s(7); s.display(); return 0; }
Write the same code in C++ as shown below in VB.
Sub BenfordLaw() Dim BenResult(1 To 9) As Long BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%" For Each c In Selection.Cells If InStr(1, "-0123456789", Left(c, 1)) > 0 Then For i = 1 To 9 If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For Next End If Next Total= Application.Sum(BenResult) biggest= Len(CStr(BenResult(1))) txt = "# | Values | Real | Expected " & vbCrLf For i = 1 To 9 If BenResult(i) > 0 Then txt = txt & "#" & i & " | " & vbTab txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab txt = txt & Format(Split(BENref, "|")(i - 1), " ##0.0%") & vbCrLf End If Next MsgBox txt, vbOKOnly, "Finish" End Sub }
#include <cln/integer.h> #include <cln/integer_io.h> #include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <sstream> #include <string> #include <cstdlib> #include <cmath> #include <map> using namespace cln ; class NextNum { public : NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { } cl_I operator( )( ) { cl_I result = first + second ; first = second ; second = result ; return result ; } private : cl_I first ; cl_I second ; } ; void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) { for ( cl_I bignumber : fibos ) { std::ostringstream os ; fprintdecimal ( os , bignumber ) ; int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ; auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ; if ( ! result.second ) numberfrequencies[ firstdigit ]++ ; } } int main( ) { std::vector<cl_I> fibonaccis( 1000 ) ; fibonaccis[ 0 ] = 0 ; fibonaccis[ 1 ] = 1 ; cl_I a = 0 ; cl_I b = 1 ; std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ; std::cout << std::endl ; std::map<int , int> frequencies ; findFrequencies( fibonaccis , frequencies ) ; std::cout << " found expected\n" ; for ( int i = 1 ; i < 10 ; i++ ) { double found = static_cast<double>( frequencies[ i ] ) / 1000 ; double expected = std::log10( 1 + 1 / static_cast<double>( i )) ; std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ; std::cout.precision( 3 ) ; std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ; } return 0 ; }
Port the provided VB code into C++ while preserving the original functionality.
Sub BenfordLaw() Dim BenResult(1 To 9) As Long BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%" For Each c In Selection.Cells If InStr(1, "-0123456789", Left(c, 1)) > 0 Then For i = 1 To 9 If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For Next End If Next Total= Application.Sum(BenResult) biggest= Len(CStr(BenResult(1))) txt = "# | Values | Real | Expected " & vbCrLf For i = 1 To 9 If BenResult(i) > 0 Then txt = txt & "#" & i & " | " & vbTab txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab txt = txt & Format(Split(BENref, "|")(i - 1), " ##0.0%") & vbCrLf End If Next MsgBox txt, vbOKOnly, "Finish" End Sub }
#include <cln/integer.h> #include <cln/integer_io.h> #include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <sstream> #include <string> #include <cstdlib> #include <cmath> #include <map> using namespace cln ; class NextNum { public : NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { } cl_I operator( )( ) { cl_I result = first + second ; first = second ; second = result ; return result ; } private : cl_I first ; cl_I second ; } ; void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) { for ( cl_I bignumber : fibos ) { std::ostringstream os ; fprintdecimal ( os , bignumber ) ; int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ; auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ; if ( ! result.second ) numberfrequencies[ firstdigit ]++ ; } } int main( ) { std::vector<cl_I> fibonaccis( 1000 ) ; fibonaccis[ 0 ] = 0 ; fibonaccis[ 1 ] = 1 ; cl_I a = 0 ; cl_I b = 1 ; std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ; std::cout << std::endl ; std::map<int , int> frequencies ; findFrequencies( fibonaccis , frequencies ) ; std::cout << " found expected\n" ; for ( int i = 1 ; i < 10 ; i++ ) { double found = static_cast<double>( frequencies[ i ] ) / 1000 ; double expected = std::log10( 1 + 1 / static_cast<double>( i )) ; std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ; std::cout.precision( 3 ) ; std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ; } return 0 ; }
Transform the following VB implementation into C++, maintaining the same output and logic.
Sub Main() Debug.Print F(-10) Debug.Print F(10) End Sub Private Function F(N As Long) As Variant If N < 0 Then F = "Error. Negative argument" ElseIf N <= 1 Then F = N Else F = F(N - 1) + F(N - 2) End If End Function
double fib(double n) { if(n < 0) { throw "Invalid argument passed to fib"; } else { struct actual_fib { static double calc(double n) { if(n < 2) { return n; } else { return calc(n-1) + calc(n-2); } } }; return actual_fib::calc(n); } }
Convert the following code from VB to C++, ensuring the logic remains intact.
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
#include <string> #include <iostream> int main( ) { std::string word( "Premier League" ) ; std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ; std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ; std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ; return 0 ; }
Convert the following code from VB to C++, ensuring the logic remains intact.
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
#include <string> #include <iostream> int main( ) { std::string word( "Premier League" ) ; std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ; std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ; std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ; return 0 ; }
Write a version of this VB function in C++ with identical behavior.
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
#include <string> #include <iostream> int main( ) { std::string word( "Premier League" ) ; std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ; std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ; std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ; return 0 ; }
Keep all operations the same but rewrite the snippet in C++.
Set objfso = CreateObject("Scripting.FileSystemObject") Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\input.txt",1) list = "" previous_line = "" l = Len(previous_line) Do Until objfile.AtEndOfStream current_line = objfile.ReadLine If Mid(current_line,l+1,1) <> "" Then list = current_line & vbCrLf previous_line = current_line l = Len(previous_line) ElseIf Mid(current_line,l,1) <> "" And Mid(current_line,(l+1),1) = "" Then list = list & current_line & vbCrLf End If Loop WScript.Echo list objfile.Close Set objfso = Nothing
#include <iostream> #include <string.h> int main() { std::string longLine, longestLines, newLine; while (std::cin >> newLine) { auto isNewLineShorter = longLine.c_str(); auto isLongLineShorter = newLine.c_str(); while (*isNewLineShorter && *isLongLineShorter) { isNewLineShorter = &isNewLineShorter[1]; isLongLineShorter = &isLongLineShorter[1]; } if(*isNewLineShorter) continue; if(*isLongLineShorter) { longLine = newLine; longestLines = newLine; } else { longestLines+=newLine; } longestLines+="\n"; } std::cout << "\nLongest string:\n" << longestLines; }
Write the same code in C++ as shown below in VB.
Option Base 1 Public Enum sett name_ = 1 initState endState blank rules End Enum Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant Private Sub init() incrementer = Array("Simple incrementer", _ "q0", _ "qf", _ "B", _ Array( _ Array("q0", "1", "1", "right", "q0"), _ Array("q0", "B", "1", "stay", "qf"))) threeStateBB = Array("Three-state busy beaver", _ "a", _ "halt", _ "0", _ Array( _ Array("a", "0", "1", "right", "b"), _ Array("a", "1", "1", "left", "c"), _ Array("b", "0", "1", "left", "a"), _ Array("b", "1", "1", "right", "b"), _ Array("c", "0", "1", "left", "b"), _ Array("c", "1", "1", "stay", "halt"))) fiveStateBB = Array("Five-state busy beaver", _ "A", _ "H", _ "0", _ Array( _ Array("A", "0", "1", "right", "B"), _ Array("A", "1", "1", "left", "C"), _ Array("B", "0", "1", "right", "C"), _ Array("B", "1", "1", "right", "B"), _ Array("C", "0", "1", "right", "D"), _ Array("C", "1", "0", "left", "E"), _ Array("D", "0", "1", "left", "A"), _ Array("D", "1", "1", "left", "D"), _ Array("E", "0", "1", "stay", "H"), _ Array("E", "1", "0", "left", "A"))) End Sub Private Sub show(state As String, headpos As Long, tape As Collection) Debug.Print " "; state; String$(7 - Len(state), " "); "| "; For p = 1 To tape.Count Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " "); Next p Debug.Print End Sub Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0) Dim state As String: state = machine(initState) Dim headpos As Long: headpos = 1 Dim counter As Long, rule As Variant Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=") If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------" Do While True If headpos > tape.Count Then tape.Add machine(blank) Else If headpos < 1 Then tape.Add machine(blank), Before:=1 headpos = 1 End If End If If Not countOnly Then show state, headpos, tape For i = LBound(machine(rules)) To UBound(machine(rules)) rule = machine(rules)(i) If rule(1) = state And rule(2) = tape(headpos) Then tape.Remove headpos If headpos > tape.Count Then tape.Add rule(3) Else tape.Add rule(3), Before:=headpos End If If rule(4) = "left" Then headpos = headpos - 1 If rule(4) = "right" Then headpos = headpos + 1 state = rule(5) Exit For End If Next i counter = counter + 1 If counter Mod 100000 = 0 Then Debug.Print counter DoEvents DoEvents End If If state = machine(endState) Then Exit Do Loop DoEvents If countOnly Then Debug.Print "Steps taken: ", counter Else show state, headpos, tape Debug.Print End If End Sub Public Sub main() init Dim tap As New Collection tap.Add "1": tap.Add "1": tap.Add "1" UTM incrementer, tap Set tap = New Collection UTM threeStateBB, tap Set tap = New Collection UTM fiveStateBB, tap, countOnly:=-1 End Sub
#include <vector> #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <iomanip> typedef unsigned int uint; using namespace std; const uint TAPE_MAX_LEN = 49152; struct action { char write, direction; }; class tape { public: tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); } void reset() { clear( '0' ); headPos = _sp; } char read(){ return _t[headPos]; } void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; } void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); } void action( const action* a ) { write( a->write ); move( a->direction ); } void print( int c = 10 ) { int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx; for( int x = st; x < ed; x++ ) { tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } cout << endl << setw( c + 1 ) << "^" << endl; } private: void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; } void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } } string _t; uint headPos, _sp; char blk; const uint MAX_LEN; }; class state { public: bool operator ==( const string o ) { return o == name; } string name, next; char symbol, write, direction; }; class actionTable { public: bool loadTable( string file ) { reset(); ifstream mf; mf.open( file.c_str() ); if( mf.is_open() ) { string str; state stt; while( mf.good() ) { getline( mf, str ); if( str[0] == '\'' ) break; parseState( str, stt ); states.push_back( stt ); } while( mf.good() ) { getline( mf, str ); if( str == "" ) continue; if( str[0] == '!' ) blank = str.erase( 0, 1 )[0]; if( str[0] == '^' ) curState = str.erase( 0, 1 ); if( str[0] == '>' ) input = str.erase( 0, 1 ); } mf.close(); return true; } cout << "Could not open " << file << endl; return false; } bool action( char symbol, action& a ) { vector<state>::iterator f = states.begin(); while( true ) { f = find( f, states.end(), curState ); if( f == states.end() ) return false; if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) ) { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; } f++; } return true; } void reset() { states.clear(); blank = '0'; curState = input = ""; } string getInput() { return input; } char getBlank() { return blank; } private: void parseState( string str, state& stt ) { string a[5]; int idx = 0; for( string::iterator si = str.begin(); si != str.end(); si++ ) { if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); } stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4]; } vector<state> states; char blank; string curState, input; }; class utm { public: utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; } void start() { while( true ) { reset(); int t = showMenu(); if( t == 0 ) return; if( !at.loadTable( files[t - 1] ) ) return; startMachine(); } } private: void simulate() { char r; action a; while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); } cout << endl << endl; system( "pause" ); } int showMenu() { int t = -1; while( t < 0 || t > 3 ) { system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit"; cout << endl << endl << "Choose an action "; cin >> t; } return t; } void reset() { tp.reset(); at.reset(); } void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); } tape tp; actionTable at; string files[7]; }; int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
Port the provided VB code into C++ while preserving the original functionality.
Option Base 1 Public Enum sett name_ = 1 initState endState blank rules End Enum Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant Private Sub init() incrementer = Array("Simple incrementer", _ "q0", _ "qf", _ "B", _ Array( _ Array("q0", "1", "1", "right", "q0"), _ Array("q0", "B", "1", "stay", "qf"))) threeStateBB = Array("Three-state busy beaver", _ "a", _ "halt", _ "0", _ Array( _ Array("a", "0", "1", "right", "b"), _ Array("a", "1", "1", "left", "c"), _ Array("b", "0", "1", "left", "a"), _ Array("b", "1", "1", "right", "b"), _ Array("c", "0", "1", "left", "b"), _ Array("c", "1", "1", "stay", "halt"))) fiveStateBB = Array("Five-state busy beaver", _ "A", _ "H", _ "0", _ Array( _ Array("A", "0", "1", "right", "B"), _ Array("A", "1", "1", "left", "C"), _ Array("B", "0", "1", "right", "C"), _ Array("B", "1", "1", "right", "B"), _ Array("C", "0", "1", "right", "D"), _ Array("C", "1", "0", "left", "E"), _ Array("D", "0", "1", "left", "A"), _ Array("D", "1", "1", "left", "D"), _ Array("E", "0", "1", "stay", "H"), _ Array("E", "1", "0", "left", "A"))) End Sub Private Sub show(state As String, headpos As Long, tape As Collection) Debug.Print " "; state; String$(7 - Len(state), " "); "| "; For p = 1 To tape.Count Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " "); Next p Debug.Print End Sub Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0) Dim state As String: state = machine(initState) Dim headpos As Long: headpos = 1 Dim counter As Long, rule As Variant Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=") If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------" Do While True If headpos > tape.Count Then tape.Add machine(blank) Else If headpos < 1 Then tape.Add machine(blank), Before:=1 headpos = 1 End If End If If Not countOnly Then show state, headpos, tape For i = LBound(machine(rules)) To UBound(machine(rules)) rule = machine(rules)(i) If rule(1) = state And rule(2) = tape(headpos) Then tape.Remove headpos If headpos > tape.Count Then tape.Add rule(3) Else tape.Add rule(3), Before:=headpos End If If rule(4) = "left" Then headpos = headpos - 1 If rule(4) = "right" Then headpos = headpos + 1 state = rule(5) Exit For End If Next i counter = counter + 1 If counter Mod 100000 = 0 Then Debug.Print counter DoEvents DoEvents End If If state = machine(endState) Then Exit Do Loop DoEvents If countOnly Then Debug.Print "Steps taken: ", counter Else show state, headpos, tape Debug.Print End If End Sub Public Sub main() init Dim tap As New Collection tap.Add "1": tap.Add "1": tap.Add "1" UTM incrementer, tap Set tap = New Collection UTM threeStateBB, tap Set tap = New Collection UTM fiveStateBB, tap, countOnly:=-1 End Sub
#include <vector> #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <iomanip> typedef unsigned int uint; using namespace std; const uint TAPE_MAX_LEN = 49152; struct action { char write, direction; }; class tape { public: tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); } void reset() { clear( '0' ); headPos = _sp; } char read(){ return _t[headPos]; } void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; } void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); } void action( const action* a ) { write( a->write ); move( a->direction ); } void print( int c = 10 ) { int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx; for( int x = st; x < ed; x++ ) { tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } cout << endl << setw( c + 1 ) << "^" << endl; } private: void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; } void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } } string _t; uint headPos, _sp; char blk; const uint MAX_LEN; }; class state { public: bool operator ==( const string o ) { return o == name; } string name, next; char symbol, write, direction; }; class actionTable { public: bool loadTable( string file ) { reset(); ifstream mf; mf.open( file.c_str() ); if( mf.is_open() ) { string str; state stt; while( mf.good() ) { getline( mf, str ); if( str[0] == '\'' ) break; parseState( str, stt ); states.push_back( stt ); } while( mf.good() ) { getline( mf, str ); if( str == "" ) continue; if( str[0] == '!' ) blank = str.erase( 0, 1 )[0]; if( str[0] == '^' ) curState = str.erase( 0, 1 ); if( str[0] == '>' ) input = str.erase( 0, 1 ); } mf.close(); return true; } cout << "Could not open " << file << endl; return false; } bool action( char symbol, action& a ) { vector<state>::iterator f = states.begin(); while( true ) { f = find( f, states.end(), curState ); if( f == states.end() ) return false; if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) ) { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; } f++; } return true; } void reset() { states.clear(); blank = '0'; curState = input = ""; } string getInput() { return input; } char getBlank() { return blank; } private: void parseState( string str, state& stt ) { string a[5]; int idx = 0; for( string::iterator si = str.begin(); si != str.end(); si++ ) { if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); } stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4]; } vector<state> states; char blank; string curState, input; }; class utm { public: utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; } void start() { while( true ) { reset(); int t = showMenu(); if( t == 0 ) return; if( !at.loadTable( files[t - 1] ) ) return; startMachine(); } } private: void simulate() { char r; action a; while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); } cout << endl << endl; system( "pause" ); } int showMenu() { int t = -1; while( t < 0 || t > 3 ) { system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit"; cout << endl << endl << "Choose an action "; cin >> t; } return t; } void reset() { tp.reset(); at.reset(); } void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); } tape tp; actionTable at; string files[7]; }; int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
Translate the given VB code snippet into C++ without altering its behavior.
Public Sub create_file() Dim FileNumber As Integer FileNumber = FreeFile MkDir "docs" Open "docs\output.txt" For Output As #FreeFile Close #FreeFile MkDir "C:\docs" Open "C:\docs\output.txt" For Output As #FreeFile Close #FreeFile End Sub
#include <direct.h> #include <fstream> int main() { std::fstream f("output.txt", std::ios::out); f.close(); f.open("/output.txt", std::ios::out); f.close(); _mkdir("docs"); _mkdir("/docs"); return 0; }
Keep all operations the same but rewrite the snippet in C++.
b=_ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_ "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_ "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_ "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_ "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_ "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_ "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_ "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_ "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" s="SEQUENCE:" acnt=0:ccnt=0:gcnt=0:tcnt=0 for i=0 to len(b)-1 if (i mod 30)=0 then s = s & vbcrlf & right(" "& i+1,3)&": " if (i mod 5)=0 then s=s& " " m=mid(b,i+1,1) s=s & m select case m case "A":acnt=acnt+1 case "C":ccnt=ccnt+1 case "G":gcnt=gcnt+1 case "T":tcnt=tcnt+1 case else wscript.echo "error at ",i+1, m end select next wscript.echo s & vbcrlf wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"; class DnaBase { public: DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) { for (auto elm : dna) { if (count.find(elm) == count.end()) count[elm] = 0; ++count[elm]; } } void viewGenome() { std::cout << "Sequence:" << std::endl; std::cout << std::endl; int limit = genome.size() / displayWidth; if (genome.size() % displayWidth != 0) ++limit; for (int i = 0; i < limit; ++i) { int beginPos = i * displayWidth; std::cout << std::setw(4) << beginPos << "  :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl; } std::cout << std::endl; std::cout << "Base Count" << std::endl; std::cout << "----------" << std::endl; std::cout << std::endl; int total = 0; for (auto elm : count) { std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl; total += elm.second; } std::cout << std::endl; std::cout << "Total: " << total << std::endl; } private: std::string genome; std::map<char, int> count; int displayWidth; }; int main(void) { auto d = new DnaBase(); d->viewGenome(); delete d; return 0; }
Change the following VB code into C++ without altering its purpose.
b=_ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_ "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_ "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_ "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_ "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_ "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_ "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_ "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_ "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" s="SEQUENCE:" acnt=0:ccnt=0:gcnt=0:tcnt=0 for i=0 to len(b)-1 if (i mod 30)=0 then s = s & vbcrlf & right(" "& i+1,3)&": " if (i mod 5)=0 then s=s& " " m=mid(b,i+1,1) s=s & m select case m case "A":acnt=acnt+1 case "C":ccnt=ccnt+1 case "G":gcnt=gcnt+1 case "T":tcnt=tcnt+1 case else wscript.echo "error at ",i+1, m end select next wscript.echo s & vbcrlf wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"; class DnaBase { public: DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) { for (auto elm : dna) { if (count.find(elm) == count.end()) count[elm] = 0; ++count[elm]; } } void viewGenome() { std::cout << "Sequence:" << std::endl; std::cout << std::endl; int limit = genome.size() / displayWidth; if (genome.size() % displayWidth != 0) ++limit; for (int i = 0; i < limit; ++i) { int beginPos = i * displayWidth; std::cout << std::setw(4) << beginPos << "  :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl; } std::cout << std::endl; std::cout << "Base Count" << std::endl; std::cout << "----------" << std::endl; std::cout << std::endl; int total = 0; for (auto elm : count) { std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl; total += elm.second; } std::cout << std::endl; std::cout << "Total: " << total << std::endl; } private: std::string genome; std::map<char, int> count; int displayWidth; }; int main(void) { auto d = new DnaBase(); d->viewGenome(); delete d; return 0; }
Produce a functionally identical C++ code for the snippet given in VB.
Public Const HOLDON = False Public Const DIJKSTRASOLUTION = True Public Const X = 10 Public Const GETS = 0 Public Const PUTS = 1 Public Const EATS = 2 Public Const THKS = 5 Public Const FRSTFORK = 0 Public Const SCNDFORK = 1 Public Const SPAGHETI = 0 Public Const UNIVERSE = 1 Public Const MAXCOUNT = 100000 Public Const PHILOSOPHERS = 5 Public semaphore(PHILOSOPHERS - 1) As Integer Public positi0n(1, PHILOSOPHERS - 1) As Integer Public programcounter(PHILOSOPHERS - 1) As Long Public statistics(PHILOSOPHERS - 1, 5, 1) As Long Public names As Variant Private Sub init() names = [{"Aquinas","Babbage","Carroll","Derrida","Erasmus"}] For j = 0 To PHILOSOPHERS - 2 positi0n(0, j) = j + 1 positi0n(1, j) = j Next j If DIJKSTRASOLUTION Then positi0n(0, PHILOSOPHERS - 1) = j positi0n(1, PHILOSOPHERS - 1) = 0 Else positi0n(0, PHILOSOPHERS - 1) = 0 positi0n(1, PHILOSOPHERS - 1) = j End If End Sub Private Sub philosopher(subject As Integer, verb As Integer, objekt As Integer) statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1 If verb < 2 Then If semaphore(positi0n(objekt, subject)) <> verb Then If Not HOLDON Then semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt programcounter(subject) = 0 End If Else semaphore(positi0n(objekt, subject)) = 1 - verb programcounter(subject) = (programcounter(subject) + 1) Mod 6 End If Else programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6 End If End Sub Private Sub dine() Dim ph As Integer Do While TC < MAXCOUNT For ph = 0 To PHILOSOPHERS - 1 Select Case programcounter(ph) Case 0: philosopher ph, GETS, FRSTFORK Case 1: philosopher ph, GETS, SCNDFORK Case 2: philosopher ph, EATS, SPAGHETI Case 3: philosopher ph, PUTS, FRSTFORK Case 4: philosopher ph, PUTS, SCNDFORK Case 5: philosopher ph, THKS, UNIVERSE End Select TC = TC + 1 Next ph Loop End Sub Private Sub show() Debug.Print "Stats", "Gets", "Gets", "Eats", "Puts", "Puts", "Thinks" Debug.Print "", "First", "Second", "Spag-", "First", "Second", "About" Debug.Print "", "Fork", "Fork", "hetti", "Fork", "Fork", "Universe" For subject = 0 To PHILOSOPHERS - 1 Debug.Print names(subject + 1), For objekt = 0 To 1 Debug.Print statistics(subject, GETS, objekt), Next objekt Debug.Print statistics(subject, EATS, SPAGHETI), For objekt = 0 To 1 Debug.Print statistics(subject, PUTS, objekt), Next objekt Debug.Print statistics(subject, THKS, UNIVERSE) Next subject End Sub Public Sub main() init dine show End Sub
#include <algorithm> #include <array> #include <chrono> #include <iostream> #include <mutex> #include <random> #include <string> #include <string_view> #include <thread> const int timeScale = 42; void Message(std::string_view message) { static std::mutex cout_mutex; std::scoped_lock cout_lock(cout_mutex); std::cout << message << std::endl; } struct Fork { std::mutex mutex; }; struct Dinner { std::array<Fork, 5> forks; ~Dinner() { Message("Dinner is over"); } }; class Philosopher { std::mt19937 rng{std::random_device {}()}; const std::string name; Fork& left; Fork& right; std::thread worker; void live(); void dine(); void ponder(); public: Philosopher(std::string name_, Fork& l, Fork& r) : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this) {} ~Philosopher() { worker.join(); Message(name + " went to sleep."); } }; void Philosopher::live() { for(;;) { { std::scoped_lock dine_lock(left.mutex, right.mutex); dine(); } ponder(); } } void Philosopher::dine() { Message(name + " started eating."); thread_local std::array<const char*, 3> foods {"chicken", "rice", "soda"}; thread_local std::array<const char*, 3> reactions { "I like this %s!", "This %s is good.", "Mmm, %s..." }; thread_local std::uniform_int_distribution<> dist(1, 6); std::shuffle( foods.begin(), foods.end(), rng); std::shuffle(reactions.begin(), reactions.end(), rng); constexpr size_t buf_size = 64; char buffer[buf_size]; for(int i = 0; i < 3; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale)); snprintf(buffer, buf_size, reactions[i], foods[i]); Message(name + ": " + buffer); } std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale); Message(name + " finished and left."); } void Philosopher::ponder() { static constexpr std::array<const char*, 5> topics {{ "politics", "art", "meaning of life", "source of morality", "how many straws makes a bale" }}; thread_local std::uniform_int_distribution<> wait(1, 6); thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1); while(dist(rng) > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale)); Message(name + " is pondering about " + topics[dist(rng)] + "."); } std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale)); Message(name + " is hungry again!"); } int main() { Dinner dinner; Message("Dinner started!"); std::array<Philosopher, 5> philosophers {{ {"Aristotle", dinner.forks[0], dinner.forks[1]}, {"Democritus", dinner.forks[1], dinner.forks[2]}, {"Plato", dinner.forks[2], dinner.forks[3]}, {"Pythagoras", dinner.forks[3], dinner.forks[4]}, {"Socrates", dinner.forks[4], dinner.forks[0]}, }}; Message("It is dark outside..."); }
Port the provided VB code into C++ while preserving the original functionality.
Dim fact() nn1=9 : nn2=12 lim=1499999 ReDim fact(nn2) fact(0)=1 For i=1 To nn2 fact(i)=fact(i-1)*i Next For base=nn1 To nn2 list="" For i=1 To lim s=0 t=i Do While t<>0 d=t Mod base s=s+fact(d) t=t\base Loop If s=i Then list=list &" "& i Next Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list Next
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return sum == i; } private: ulong f[12]; }; int main() { factorion_t factorion; for (uint b = 9u; b <= 12u; ++b) { std::cout << "factorions for base " << b << ':'; for (uint i = 1u; i < 1500000u; ++i) if (factorion(i, b)) std::cout << ' ' << i; std::cout << std::endl; } return 0; }
Produce a language-to-language conversion: from VB to C++, same semantics.
Dim fact() nn1=9 : nn2=12 lim=1499999 ReDim fact(nn2) fact(0)=1 For i=1 To nn2 fact(i)=fact(i-1)*i Next For base=nn1 To nn2 list="" For i=1 To lim s=0 t=i Do While t<>0 d=t Mod base s=s+fact(d) t=t\base Loop If s=i Then list=list &" "& i Next Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list Next
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return sum == i; } private: ulong f[12]; }; int main() { factorion_t factorion; for (uint b = 9u; b <= 12u; ++b) { std::cout << "factorions for base " << b << ':'; for (uint i = 1u; i < 1500000u; ++i) if (factorion(i, b)) std::cout << ' ' << i; std::cout << std::endl; } return 0; }
Preserve the algorithm and functionality while converting the code from VB to C++.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " commandtable = Split(s, " ") Dim i As Integer For Each word In commandtable If Len(word) > 0 Then i = 1 Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z" i = i + 1 Loop command_table.Add Key:=word, Item:=i - 1 End If Next word For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } size_t get_min_length(const std::string& str) { size_t len = 0, n = str.length(); while (len < n && std::isupper(static_cast<unsigned char>(str[len]))) ++len; return len; } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::vector<command> commands; std::istringstream is(table); std::string word; while (is >> word) { size_t len = get_min_length(word); uppercase(word); commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Generate an equivalent C++ version of this VB code.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " commandtable = Split(s, " ") Dim i As Integer For Each word In commandtable If Len(word) > 0 Then i = 1 Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z" i = i + 1 Loop command_table.Add Key:=word, Item:=i - 1 End If Next word For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } size_t get_min_length(const std::string& str) { size_t len = 0, n = str.length(); while (len < n && std::isupper(static_cast<unsigned char>(str[len]))) ++len; return len; } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::vector<command> commands; std::istringstream is(table); std::string word; while (is >> word) { size_t len = get_min_length(word); uppercase(word); commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Rewrite the snippet below in C++ so it works the same as the original VB code.
Imports System.Text Module Module1 ReadOnly CODES As New Dictionary(Of Char, String) From { {"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"}, {"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"}, {"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"}, {"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"}, {"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"}, {"z", "BBAAB"}, {" ", "BBBAA"} } Function Encode(plainText As String, message As String) As String Dim pt = plainText.ToLower() Dim sb As New StringBuilder() For Each c In pt If "a" <= c AndAlso c <= "z" Then sb.Append(CODES(c)) Else sb.Append(CODES(" ")) End If Next Dim et = sb.ToString() Dim mg = message.ToLower() sb.Length = 0 Dim count = 0 For Each c In mg If "a" <= c AndAlso c <= "z" Then If et(count) = "A" Then sb.Append(c) Else sb.Append(Chr(Asc(c) - 32)) End If count += 1 If count = et.Length Then Exit For End If Else sb.Append(c) End If Next Return sb.ToString() End Function Function Decode(message As String) As String Dim sb As New StringBuilder For Each c In message If "a" <= c AndAlso c <= "z" Then sb.Append("A") ElseIf "A" <= c AndAlso c <= "Z" Then sb.Append("B") End If Next Dim et = sb.ToString() sb.Length = 0 For index = 0 To et.Length - 1 Step 5 Dim quintet = et.Substring(index, 5) Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key sb.Append(key) Next Return sb.ToString() End Function Sub Main() Dim plainText = "the quick brown fox jumps over the lazy dog" Dim message = "bacon "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space." Dim cipherText = Encode(plainText, message) Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText) Dim decodedText = Decode(cipherText) Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText) End Sub End Module
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Translate this program into C++ but keep the logic exactly as in VB.
Imports System.Text Module Module1 ReadOnly CODES As New Dictionary(Of Char, String) From { {"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"}, {"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"}, {"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"}, {"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"}, {"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"}, {"z", "BBAAB"}, {" ", "BBBAA"} } Function Encode(plainText As String, message As String) As String Dim pt = plainText.ToLower() Dim sb As New StringBuilder() For Each c In pt If "a" <= c AndAlso c <= "z" Then sb.Append(CODES(c)) Else sb.Append(CODES(" ")) End If Next Dim et = sb.ToString() Dim mg = message.ToLower() sb.Length = 0 Dim count = 0 For Each c In mg If "a" <= c AndAlso c <= "z" Then If et(count) = "A" Then sb.Append(c) Else sb.Append(Chr(Asc(c) - 32)) End If count += 1 If count = et.Length Then Exit For End If Else sb.Append(c) End If Next Return sb.ToString() End Function Function Decode(message As String) As String Dim sb As New StringBuilder For Each c In message If "a" <= c AndAlso c <= "z" Then sb.Append("A") ElseIf "A" <= c AndAlso c <= "Z" Then sb.Append("B") End If Next Dim et = sb.ToString() sb.Length = 0 For index = 0 To et.Length - 1 Step 5 Dim quintet = et.Substring(index, 5) Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key sb.Append(key) Next Return sb.ToString() End Function Sub Main() Dim plainText = "the quick brown fox jumps over the lazy dog" Dim message = "bacon "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space." Dim cipherText = Encode(plainText, message) Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText) Dim decodedText = Decode(cipherText) Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText) End Sub End Module
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Write the same algorithm in C++ as shown in this VB implementation.
Function build_spiral(n) botcol = 0 : topcol = n - 1 botrow = 0 : toprow = n - 1 Dim matrix() ReDim matrix(topcol,toprow) dir = 0 : col = 0 : row = 0 For i = 0 To n*n-1 matrix(col,row) = i Select Case dir Case 0 If col < topcol Then col = col + 1 Else dir = 1 : row = row + 1 : botrow = botrow + 1 End If Case 1 If row < toprow Then row = row + 1 Else dir = 2 : col = col - 1 : topcol = topcol - 1 End If Case 2 If col > botcol Then col = col - 1 Else dir = 3 : row = row - 1 : toprow = toprow - 1 End If Case 3 If row > botrow Then row = row - 1 Else dir = 0 : col = col + 1 : botcol = botcol + 1 End If End Select Next For y = 0 To n-1 For x = 0 To n-1 WScript.StdOut.Write matrix(x,y) & vbTab Next WScript.StdOut.WriteLine Next End Function build_spiral(CInt(WScript.Arguments(0)))
#include <vector> #include <memory> #include <cmath> #include <iostream> #include <iomanip> using namespace std; typedef vector< int > IntRow; typedef vector< IntRow > IntTable; auto_ptr< IntTable > getSpiralArray( int dimension ) { auto_ptr< IntTable > spiralArrayPtr( new IntTable( dimension, IntRow( dimension ) ) ); int numConcentricSquares = static_cast< int >( ceil( static_cast< double >( dimension ) / 2.0 ) ); int j; int sideLen = dimension; int currNum = 0; for ( int i = 0; i < numConcentricSquares; i++ ) { for ( j = 0; j < sideLen; j++ ) ( *spiralArrayPtr )[ i ][ i + j ] = currNum++; for ( j = 1; j < sideLen; j++ ) ( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++; for ( j = sideLen - 2; j > -1; j-- ) ( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++; for ( j = sideLen - 2; j > 0; j-- ) ( *spiralArrayPtr )[ i + j ][ i ] = currNum++; sideLen -= 2; } return spiralArrayPtr; } void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr ) { size_t dimension = spiralArrayPtr->size(); int fieldWidth = static_cast< int >( floor( log10( static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; size_t col; for ( size_t row = 0; row < dimension; row++ ) { for ( col = 0; col < dimension; col++ ) cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ]; cout << endl; } } int main() { printSpiralArray( getSpiralArray( 5 ) ); }
Write a version of this VB function in C++ with identical behavior.
Private Sub optional_parameters(theRange As String, _ Optional ordering As Integer = 0, _ Optional column As Integer = 1, _ Optional reverse As Integer = 1) ActiveSheet.Sort.SortFields.Clear ActiveSheet.Sort.SortFields.Add _ Key:=Range(theRange).Columns(column), _ SortOn:=SortOnValues, _ Order:=reverse, _ DataOption:=ordering With ActiveSheet.Sort .SetRange Range(theRange) .Header = xlGuess .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub Public Sub main() optional_parameters theRange:="A1:C4", ordering:=1, column:=2, reverse:=1 End Sub
#include <vector> #include <algorithm> #include <string> template <class T> struct sort_table_functor { typedef bool (*CompFun)(const T &, const T &); const CompFun ordering; const int column; const bool reverse; sort_table_functor(CompFun o, int c, bool r) : ordering(o), column(c), reverse(r) { } bool operator()(const std::vector<T> &x, const std::vector<T> &y) const { const T &a = x[column], &b = y[column]; return reverse ? ordering(b, a) : ordering(a, b); } }; template <class T> bool myLess(const T &x, const T &y) { return x < y; } template <class T> void sort_table(std::vector<std::vector<T> > &table, int column = 0, bool reverse = false, bool (*ordering)(const T &, const T &) = myLess) { std::sort(table.begin(), table.end(), sort_table_functor<T>(ordering, column, reverse)); } #include <iostream> template <class T> void print_matrix(std::vector<std::vector<T> > &data) { for () { for (int j = 0; j < 3; j++) std::cout << data[i][j] << "\t"; std::cout << std::endl; } } bool desc_len_comparator(const std::string &x, const std::string &y) { return x.length() > y.length(); } int main() { std::string data_array[3][3] = { {"a", "b", "c"}, {"", "q", "z"}, {"zap", "zip", "Zot"} }; std::vector<std::vector<std::string> > data_orig; for (int i = 0; i < 3; i++) { std::vector<std::string> row; for (int j = 0; j < 3; j++) row.push_back(data_array[i][j]); data_orig.push_back(row); } print_matrix(data_orig); std::vector<std::vector<std::string> > data = data_orig; sort_table(data); print_matrix(data); data = data_orig; sort_table(data, 2); print_matrix(data); data = data_orig; sort_table(data, 1); print_matrix(data); data = data_orig; sort_table(data, 1, true); print_matrix(data); data = data_orig; sort_table(data, 0, false, desc_len_comparator); print_matrix(data); return 0; }
Convert this VB block to C++, preserving its control flow and logic.
Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _ CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _ overlapped As Ptr) As Boolean Declare Function GetLastError Lib "Kernel32" () As Integer Declare Function CloseHandle Lib "kernel32" (hObject As Integer) As Boolean Const FILE_SHARE_READ = &h00000001 Const FILE_SHARE_WRITE = &h00000002 Const OPEN_EXISTING = 3 Dim fHandle As Integer = CreateFileW("C:\foo.txt", 0, FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0) If fHandle > 0 Then Dim mb As MemoryBlock = "Hello, World!" Dim bytesWritten As Integer If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then MsgBox("Error Number: " + Str(GetLastError)) End If Call CloseHandle(fHandle) Else MsgBox("Error Number: " + Str(GetLastError)) End If
FUNCTION MULTIPLY(X, Y) DOUBLE PRECISION MULTIPLY, X, Y
Port the following code from VB to C++ with equivalent syntax and logic.
Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _ CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _ overlapped As Ptr) As Boolean Declare Function GetLastError Lib "Kernel32" () As Integer Declare Function CloseHandle Lib "kernel32" (hObject As Integer) As Boolean Const FILE_SHARE_READ = &h00000001 Const FILE_SHARE_WRITE = &h00000002 Const OPEN_EXISTING = 3 Dim fHandle As Integer = CreateFileW("C:\foo.txt", 0, FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0) If fHandle > 0 Then Dim mb As MemoryBlock = "Hello, World!" Dim bytesWritten As Integer If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then MsgBox("Error Number: " + Str(GetLastError)) End If Call CloseHandle(fHandle) Else MsgBox("Error Number: " + Str(GetLastError)) End If
FUNCTION MULTIPLY(X, Y) DOUBLE PRECISION MULTIPLY, X, Y
Produce a functionally identical C++ code for the snippet given in VB.
Module Module1 Class Frac Private ReadOnly num As Long Private ReadOnly denom As Long Public Shared ReadOnly ZERO = New Frac(0, 1) Public Shared ReadOnly ONE = New Frac(1, 1) Public Sub New(n As Long, d As Long) If d = 0 Then Throw New ArgumentException("d must not be zero") End If Dim nn = n Dim dd = d If nn = 0 Then dd = 1 ElseIf dd < 0 Then nn = -nn dd = -dd End If Dim g = Math.Abs(Gcd(nn, dd)) If g > 1 Then nn /= g dd /= g End If num = nn denom = dd End Sub Private Shared Function Gcd(a As Long, b As Long) As Long If b = 0 Then Return a Else Return Gcd(b, a Mod b) End If End Function Public Shared Operator -(self As Frac) As Frac Return New Frac(-self.num, self.denom) End Operator Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom) End Operator Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac Return lhs + -rhs End Operator Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom) End Operator Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x < y End Operator Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x > y End Operator Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom End Operator Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom End Operator Public Overrides Function ToString() As String If denom = 1 Then Return num.ToString Else Return String.Format("{0}/{1}", num, denom) End If End Function Public Overrides Function Equals(obj As Object) As Boolean Dim frac = CType(obj, Frac) Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom End Function End Class Function Bernoulli(n As Integer) As Frac If n < 0 Then Throw New ArgumentException("n may not be negative or zero") End If Dim a(n + 1) As Frac For m = 0 To n a(m) = New Frac(1, m + 1) For j = m To 1 Step -1 a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1) Next Next If n <> 1 Then Return a(0) Else Return -a(0) End If End Function Function Binomial(n As Integer, k As Integer) As Integer If n < 0 OrElse k < 0 OrElse n < k Then Throw New ArgumentException() End If If n = 0 OrElse k = 0 Then Return 1 End If Dim num = 1 For i = k + 1 To n num *= i Next Dim denom = 1 For i = 2 To n - k denom *= i Next Return num \ denom End Function Function FaulhaberTriangle(p As Integer) As Frac() Dim coeffs(p + 1) As Frac For i = 1 To p + 1 coeffs(i - 1) = Frac.ZERO Next Dim q As New Frac(1, p + 1) Dim sign = -1 For j = 0 To p sign *= -1 coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j) Next Return coeffs End Function Sub Main() For i = 1 To 10 Dim coeffs = FaulhaberTriangle(i - 1) For Each coeff In coeffs Console.Write("{0,5} ", coeff) Next Console.WriteLine() Next End Sub End Module
#include <exception> #include <iomanip> #include <iostream> #include <numeric> #include <sstream> #include <vector> class Frac { public: Frac() : num(0), denom(1) {} Frac(int n, int d) { if (d == 0) { throw std::runtime_error("d must not be zero"); } int sign_of_d = d < 0 ? -1 : 1; int g = std::gcd(n, d); num = sign_of_d * n / g; denom = sign_of_d * d / g; } Frac operator-() const { return Frac(-num, denom); } Frac operator+(const Frac& rhs) const { return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom); } Frac operator-(const Frac& rhs) const { return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom); } Frac operator*(const Frac& rhs) const { return Frac(num*rhs.num, denom*rhs.denom); } Frac operator*(int rhs) const { return Frac(num * rhs, denom); } friend std::ostream& operator<<(std::ostream&, const Frac&); private: int num; int denom; }; std::ostream & operator<<(std::ostream & os, const Frac &f) { if (f.num == 0 || f.denom == 1) { return os << f.num; } std::stringstream ss; ss << f.num << "/" << f.denom; return os << ss.str(); } Frac bernoulli(int n) { if (n < 0) { throw std::runtime_error("n may not be negative or zero"); } std::vector<Frac> a; for (int m = 0; m <= n; m++) { a.push_back(Frac(1, m + 1)); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * j; } } if (n != 1) return a[0]; return -a[0]; } int binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw std::runtime_error("parameters are invalid"); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num *= i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom *= i; } return num / denom; } std::vector<Frac> faulhaberTraingle(int p) { std::vector<Frac> coeffs(p + 1); Frac q{ 1, p + 1 }; int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j); } return coeffs; } int main() { for (int i = 0; i < 10; i++) { std::vector<Frac> coeffs = faulhaberTraingle(i); for (auto frac : coeffs) { std::cout << std::right << std::setw(5) << frac << " "; } std::cout << std::endl; } return 0; }
Rewrite the snippet below in C++ so it works the same as the original VB code.
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl; return 0; }
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl; return 0; }
Produce a functionally identical C++ code for the snippet given in VB.
Const wheel="ndeokgelw" Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub Dim oDic Set oDic = WScript.CreateObject("scripting.dictionary") Dim cnt(127) Dim fso Set fso = WScript.CreateObject("Scripting.Filesystemobject") Set ff=fso.OpenTextFile("unixdict.txt") i=0 print "reading words of 3 or more letters" While Not ff.AtEndOfStream x=LCase(ff.ReadLine) If Len(x)>=3 Then If Not odic.exists(x) Then oDic.Add x,0 End If Wend print "remaining words: "& oDic.Count & vbcrlf ff.Close Set ff=Nothing Set fso=Nothing Set re=New RegExp print "removing words with chars not in the wheel" re.pattern="[^"& wheel &"]" For Each w In oDic.Keys If re.test(w) Then oDic.remove(w) Next print "remaining words: "& oDic.Count & vbcrlf print "ensuring the mandatory letter "& Mid(wheel,5,1) & " is present" re.Pattern=Mid(wheel,5,1) For Each w In oDic.Keys If Not re.test(w) Then oDic.remove(w) Next print "remaining words: "& oDic.Count & vbcrlf print "checking number of chars" Dim nDic Set nDic = WScript.CreateObject("scripting.dictionary") For i=1 To Len(wheel) x=Mid(wheel,i,1) If nDic.Exists(x) Then a=nDic(x) nDic(x)=Array(a(0)+1,0) Else nDic.add x,Array(1,0) End If Next For Each w In oDic.Keys For Each c In nDic.Keys ndic(c)=Array(nDic(c)(0),0) Next For ii = 1 To len(w) c=Mid(w,ii,1) a=nDic(c) If (a(0)=a(1)) Then oDic.Remove(w):Exit For End If nDic(c)=Array(a(0),a(1)+1) Next Next print "Remaining words "& oDic.count For Each w In oDic.Keys print w Next
#include <array> #include <iostream> #include <fstream> #include <map> #include <string> #include <vector> #include <boost/program_options.hpp> class letterset { public: letterset() { count_.fill(0); } explicit letterset(const std::string& str) { count_.fill(0); for (char c : str) add(c); } bool contains(const letterset& set) const { for (size_t i = 0; i < count_.size(); ++i) { if (set.count_[i] > count_[i]) return false; } return true; } unsigned int count(char c) const { return count_[index(c)]; } bool is_valid() const { return count_[0] == 0; } void add(char c) { ++count_[index(c)]; } private: static bool is_letter(char c) { return c >= 'a' && c <= 'z'; } static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; } std::array<unsigned int, 27> count_; }; template <typename iterator, typename separator> std::string join(iterator begin, iterator end, separator sep) { std::string result; if (begin != end) { result += *begin++; for (; begin != end; ++begin) { result += sep; result += *begin; } } return result; } using dictionary = std::vector<std::pair<std::string, letterset>>; dictionary load_dictionary(const std::string& filename, int min_length, int max_length) { std::ifstream in(filename); if (!in) throw std::runtime_error("Cannot open file " + filename); std::string word; dictionary result; while (getline(in, word)) { if (word.size() < min_length) continue; if (word.size() > max_length) continue; letterset set(word); if (set.is_valid()) result.emplace_back(word, set); } return result; } void word_wheel(const dictionary& dict, const std::string& letters, char central_letter) { letterset set(letters); if (central_letter == 0 && !letters.empty()) central_letter = letters.at(letters.size()/2); std::map<size_t, std::vector<std::string>> words; for (const auto& pair : dict) { const auto& word = pair.first; const auto& subset = pair.second; if (subset.count(central_letter) > 0 && set.contains(subset)) words[word.size()].push_back(word); } size_t total = 0; for (const auto& p : words) { const auto& v = p.second; auto n = v.size(); total += n; std::cout << "Found " << n << " " << (n == 1 ? "word" : "words") << " of length " << p.first << ": " << join(v.begin(), v.end(), ", ") << '\n'; } std::cout << "Number of words found: " << total << '\n'; } void find_max_word_count(const dictionary& dict, int word_length) { size_t max_count = 0; std::vector<std::pair<std::string, char>> max_words; for (const auto& pair : dict) { const auto& word = pair.first; if (word.size() != word_length) continue; const auto& set = pair.second; dictionary subsets; for (const auto& p : dict) { if (set.contains(p.second)) subsets.push_back(p); } letterset done; for (size_t index = 0; index < word_length; ++index) { char central_letter = word[index]; if (done.count(central_letter) > 0) continue; done.add(central_letter); size_t count = 0; for (const auto& p : subsets) { const auto& subset = p.second; if (subset.count(central_letter) > 0) ++count; } if (count > max_count) { max_words.clear(); max_count = count; } if (count == max_count) max_words.emplace_back(word, central_letter); } } std::cout << "Maximum word count: " << max_count << '\n'; std::cout << "Words of " << word_length << " letters producing this count:\n"; for (const auto& pair : max_words) std::cout << pair.first << " with central letter " << pair.second << '\n'; } constexpr const char* option_filename = "filename"; constexpr const char* option_wheel = "wheel"; constexpr const char* option_central = "central"; constexpr const char* option_min_length = "min-length"; constexpr const char* option_part2 = "part2"; int main(int argc, char** argv) { const int word_length = 9; int min_length = 3; std::string letters = "ndeokgelw"; std::string filename = "unixdict.txt"; char central_letter = 0; bool do_part2 = false; namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() (option_filename, po::value<std::string>(), "name of dictionary file") (option_wheel, po::value<std::string>(), "word wheel letters") (option_central, po::value<char>(), "central letter (defaults to middle letter of word)") (option_min_length, po::value<int>(), "minimum word length") (option_part2, "include part 2"); try { po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count(option_filename)) filename = vm[option_filename].as<std::string>(); if (vm.count(option_wheel)) letters = vm[option_wheel].as<std::string>(); if (vm.count(option_central)) central_letter = vm[option_central].as<char>(); if (vm.count(option_min_length)) min_length = vm[option_min_length].as<int>(); if (vm.count(option_part2)) do_part2 = true; auto dict = load_dictionary(filename, min_length, word_length); word_wheel(dict, letters, central_letter); if (do_part2) { std::cout << '\n'; find_max_word_count(dict, word_length); } } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Port the provided VB code into C++ while preserving the original functionality.
DEFINT A(1 to 4) = {1, 2, 3, 4} DEFINT B(1 to 4) = {10, 20, 30, 40} Redim A(1 to 8) as integer MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
#include <vector> #include <iostream> int main() { std::vector<int> a(3), b(4); a[0] = 11; a[1] = 12; a[2] = 13; b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24; a.insert(a.end(), b.begin(), b.end()); for (int i = 0; i < a.size(); ++i) std::cout << "a[" << i << "] = " << a[i] << "\n"; }
Maintain the same structure and functionality when rewriting this code in C++.
Public Sub text() Debug.Print InputBox("Input a string") Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long") End Sub
#include <iostream> #include <string> using namespace std; int main() { long int integer_input; string string_input; cout << "Enter an integer: "; cin >> integer_input; cout << "Enter a string: "; cin >> string_input; return 0; }
Generate an equivalent C++ version of this VB code.
Public Sub text() Debug.Print InputBox("Input a string") Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long") End Sub
#include <iostream> #include <string> using namespace std; int main() { long int integer_input; string string_input; cout << "Enter an integer: "; cin >> integer_input; cout << "Enter a string: "; cin >> string_input; return 0; }
Convert the following code from VB to C++, ensuring the logic remains intact.
Option Explicit Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) { std::cout << "Error opening MIDI Output..." << std::endl; device = 0; } } ~midi() { midiOutReset( device ); midiOutClose( device ); } bool isOpen() { return device != 0; } void setInstrument( byte i ) { message.data[0] = 0xc0; message.data[1] = i; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void playNote( byte n, unsigned i ) { playNote( n ); Sleep( i ); stopNote( n ); } private: void playNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 127; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void stopNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } HMIDIOUT device; midi_msg message; }; int main( int argc, char* argv[] ) { midi m; if( m.isOpen() ) { byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 }; m.setInstrument( 42 ); for( int x = 0; x < 8; x++ ) m.playNote( notes[x], rand() % 100 + 158 ); Sleep( 1000 ); } return 0; }
Translate this program into C++ but keep the logic exactly as in VB.
Option Explicit Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) { std::cout << "Error opening MIDI Output..." << std::endl; device = 0; } } ~midi() { midiOutReset( device ); midiOutClose( device ); } bool isOpen() { return device != 0; } void setInstrument( byte i ) { message.data[0] = 0xc0; message.data[1] = i; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void playNote( byte n, unsigned i ) { playNote( n ); Sleep( i ); stopNote( n ); } private: void playNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 127; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void stopNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } HMIDIOUT device; midi_msg message; }; int main( int argc, char* argv[] ) { midi m; if( m.isOpen() ) { byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 }; m.setInstrument( 42 ); for( int x = 0; x < 8; x++ ) m.playNote( notes[x], rand() % 100 + 158 ); Sleep( 1000 ); } return 0; }
Preserve the algorithm and functionality while converting the code from VB to C++.
Option Explicit Const maxWeight = 400 Dim DataList As Variant Dim xList(64, 3) As Variant Dim nItems As Integer Dim s As String, xss As String Dim xwei As Integer, xval As Integer, nn As Integer Sub Main() Dim i As Integer, j As Integer DataList = Array("map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160, _ "glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40, _ "cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30, _ "T-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10, _ "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _ "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50) nItems = (UBound(DataList) + 1) / 3 j = 0 For i = 1 To nItems xList(i, 1) = DataList(j) xList(i, 2) = DataList(j + 1) xList(i, 3) = DataList(j + 2) j = j + 3 Next i s = "" For i = 1 To nItems s = s & Chr(i) Next nn = 0 Call ChoiceBin(1, "") For i = 1 To Len(xss) j = Asc(Mid(xss, i, 1)) Debug.Print xList(j, 1) Next i Debug.Print "count=" & Len(xss), "weight=" & xwei, "value=" & xval End Sub Private Sub ChoiceBin(n As String, ss As String) Dim r As String Dim i As Integer, j As Integer, iwei As Integer, ival As Integer Dim ipct As Integer If n = Len(s) + 1 Then iwei = 0: ival = 0 For i = 1 To Len(ss) j = Asc(Mid(ss, i, 1)) iwei = iwei + xList(j, 2) ival = ival + xList(j, 3) Next If iwei <= maxWeight And ival > xval Then xss = ss: xwei = iwei: xval = ival End If Else r = Mid(s, n, 1) Call ChoiceBin(n + 1, ss & r) Call ChoiceBin(n + 1, ss) End If End Sub
#include <vector> #include <string> #include <iostream> #include <boost/tuple/tuple.hpp> #include <set> int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , std::set<int> & , const int ) ; int main( ) { std::vector<boost::tuple<std::string , int , int> > items ; items.push_back( boost::make_tuple( "" , 0 , 0 ) ) ; items.push_back( boost::make_tuple( "map" , 9 , 150 ) ) ; items.push_back( boost::make_tuple( "compass" , 13 , 35 ) ) ; items.push_back( boost::make_tuple( "water" , 153 , 200 ) ) ; items.push_back( boost::make_tuple( "sandwich", 50 , 160 ) ) ; items.push_back( boost::make_tuple( "glucose" , 15 , 60 ) ) ; items.push_back( boost::make_tuple( "tin", 68 , 45 ) ) ; items.push_back( boost::make_tuple( "banana", 27 , 60 ) ) ; items.push_back( boost::make_tuple( "apple" , 39 , 40 ) ) ; items.push_back( boost::make_tuple( "cheese" , 23 , 30 ) ) ; items.push_back( boost::make_tuple( "beer" , 52 , 10 ) ) ; items.push_back( boost::make_tuple( "suntan creme" , 11 , 70 ) ) ; items.push_back( boost::make_tuple( "camera" , 32 , 30 ) ) ; items.push_back( boost::make_tuple( "T-shirt" , 24 , 15 ) ) ; items.push_back( boost::make_tuple( "trousers" , 48 , 10 ) ) ; items.push_back( boost::make_tuple( "umbrella" , 73 , 40 ) ) ; items.push_back( boost::make_tuple( "waterproof trousers" , 42 , 70 ) ) ; items.push_back( boost::make_tuple( "waterproof overclothes" , 43 , 75 ) ) ; items.push_back( boost::make_tuple( "note-case" , 22 , 80 ) ) ; items.push_back( boost::make_tuple( "sunglasses" , 7 , 20 ) ) ; items.push_back( boost::make_tuple( "towel" , 18 , 12 ) ) ; items.push_back( boost::make_tuple( "socks" , 4 , 50 ) ) ; items.push_back( boost::make_tuple( "book" , 30 , 10 ) ) ; const int maximumWeight = 400 ; std::set<int> bestItems ; int bestValue = findBestPack( items , bestItems , maximumWeight ) ; std::cout << "The best value that can be packed in the given knapsack is " << bestValue << " !\n" ; int totalweight = 0 ; std::cout << "The following items should be packed in the knapsack:\n" ; for ( std::set<int>::const_iterator si = bestItems.begin( ) ; si != bestItems.end( ) ; si++ ) { std::cout << (items.begin( ) + *si)->get<0>( ) << "\n" ; totalweight += (items.begin( ) + *si)->get<1>( ) ; } std::cout << "The total weight of all items is " << totalweight << " !\n" ; return 0 ; } int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) { const int n = items.size( ) ; int bestValues [ n ][ weightlimit ] ; std::set<int> solutionSets[ n ][ weightlimit ] ; std::set<int> emptyset ; for ( int i = 0 ; i < n ; i++ ) { for ( int j = 0 ; j < weightlimit ; j++ ) { bestValues[ i ][ j ] = 0 ; solutionSets[ i ][ j ] = emptyset ; } } for ( int i = 0 ; i < n ; i++ ) { for ( int weight = 0 ; weight < weightlimit ; weight++ ) { if ( i == 0 ) bestValues[ i ][ weight ] = 0 ; else { int itemweight = (items.begin( ) + i)->get<1>( ) ; if ( weight < itemweight ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } else { if ( bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) > bestValues[ i - 1 ][ weight ] ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight - itemweight ] ; solutionSets[ i ][ weight ].insert( i ) ; } else { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } } } } } bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ; return bestValues[ n - 1 ][ weightlimit - 1 ] ; }
Generate a C++ translation of this VB snippet without changing its computational steps.
Option Explicit Const maxWeight = 400 Dim DataList As Variant Dim xList(64, 3) As Variant Dim nItems As Integer Dim s As String, xss As String Dim xwei As Integer, xval As Integer, nn As Integer Sub Main() Dim i As Integer, j As Integer DataList = Array("map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160, _ "glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40, _ "cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30, _ "T-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10, _ "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _ "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50) nItems = (UBound(DataList) + 1) / 3 j = 0 For i = 1 To nItems xList(i, 1) = DataList(j) xList(i, 2) = DataList(j + 1) xList(i, 3) = DataList(j + 2) j = j + 3 Next i s = "" For i = 1 To nItems s = s & Chr(i) Next nn = 0 Call ChoiceBin(1, "") For i = 1 To Len(xss) j = Asc(Mid(xss, i, 1)) Debug.Print xList(j, 1) Next i Debug.Print "count=" & Len(xss), "weight=" & xwei, "value=" & xval End Sub Private Sub ChoiceBin(n As String, ss As String) Dim r As String Dim i As Integer, j As Integer, iwei As Integer, ival As Integer Dim ipct As Integer If n = Len(s) + 1 Then iwei = 0: ival = 0 For i = 1 To Len(ss) j = Asc(Mid(ss, i, 1)) iwei = iwei + xList(j, 2) ival = ival + xList(j, 3) Next If iwei <= maxWeight And ival > xval Then xss = ss: xwei = iwei: xval = ival End If Else r = Mid(s, n, 1) Call ChoiceBin(n + 1, ss & r) Call ChoiceBin(n + 1, ss) End If End Sub
#include <vector> #include <string> #include <iostream> #include <boost/tuple/tuple.hpp> #include <set> int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , std::set<int> & , const int ) ; int main( ) { std::vector<boost::tuple<std::string , int , int> > items ; items.push_back( boost::make_tuple( "" , 0 , 0 ) ) ; items.push_back( boost::make_tuple( "map" , 9 , 150 ) ) ; items.push_back( boost::make_tuple( "compass" , 13 , 35 ) ) ; items.push_back( boost::make_tuple( "water" , 153 , 200 ) ) ; items.push_back( boost::make_tuple( "sandwich", 50 , 160 ) ) ; items.push_back( boost::make_tuple( "glucose" , 15 , 60 ) ) ; items.push_back( boost::make_tuple( "tin", 68 , 45 ) ) ; items.push_back( boost::make_tuple( "banana", 27 , 60 ) ) ; items.push_back( boost::make_tuple( "apple" , 39 , 40 ) ) ; items.push_back( boost::make_tuple( "cheese" , 23 , 30 ) ) ; items.push_back( boost::make_tuple( "beer" , 52 , 10 ) ) ; items.push_back( boost::make_tuple( "suntan creme" , 11 , 70 ) ) ; items.push_back( boost::make_tuple( "camera" , 32 , 30 ) ) ; items.push_back( boost::make_tuple( "T-shirt" , 24 , 15 ) ) ; items.push_back( boost::make_tuple( "trousers" , 48 , 10 ) ) ; items.push_back( boost::make_tuple( "umbrella" , 73 , 40 ) ) ; items.push_back( boost::make_tuple( "waterproof trousers" , 42 , 70 ) ) ; items.push_back( boost::make_tuple( "waterproof overclothes" , 43 , 75 ) ) ; items.push_back( boost::make_tuple( "note-case" , 22 , 80 ) ) ; items.push_back( boost::make_tuple( "sunglasses" , 7 , 20 ) ) ; items.push_back( boost::make_tuple( "towel" , 18 , 12 ) ) ; items.push_back( boost::make_tuple( "socks" , 4 , 50 ) ) ; items.push_back( boost::make_tuple( "book" , 30 , 10 ) ) ; const int maximumWeight = 400 ; std::set<int> bestItems ; int bestValue = findBestPack( items , bestItems , maximumWeight ) ; std::cout << "The best value that can be packed in the given knapsack is " << bestValue << " !\n" ; int totalweight = 0 ; std::cout << "The following items should be packed in the knapsack:\n" ; for ( std::set<int>::const_iterator si = bestItems.begin( ) ; si != bestItems.end( ) ; si++ ) { std::cout << (items.begin( ) + *si)->get<0>( ) << "\n" ; totalweight += (items.begin( ) + *si)->get<1>( ) ; } std::cout << "The total weight of all items is " << totalweight << " !\n" ; return 0 ; } int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) { const int n = items.size( ) ; int bestValues [ n ][ weightlimit ] ; std::set<int> solutionSets[ n ][ weightlimit ] ; std::set<int> emptyset ; for ( int i = 0 ; i < n ; i++ ) { for ( int j = 0 ; j < weightlimit ; j++ ) { bestValues[ i ][ j ] = 0 ; solutionSets[ i ][ j ] = emptyset ; } } for ( int i = 0 ; i < n ; i++ ) { for ( int weight = 0 ; weight < weightlimit ; weight++ ) { if ( i == 0 ) bestValues[ i ][ weight ] = 0 ; else { int itemweight = (items.begin( ) + i)->get<1>( ) ; if ( weight < itemweight ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } else { if ( bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) > bestValues[ i - 1 ][ weight ] ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight - itemweight ] ; solutionSets[ i ][ weight ].insert( i ) ; } else { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } } } } } bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ; return bestValues[ n - 1 ][ weightlimit - 1 ] ; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
Imports System.Math Module Module1 Const MAXPRIME = 99 Const MAXPARENT = 99 Const NBRCHILDREN = 547100 Public Primes As New Collection() Public PrimesR As New Collection() Public Ancestors As New Collection() Public Parents(MAXPARENT + 1) As Integer Public CptDescendants(MAXPARENT + 1) As Integer Public Children(NBRCHILDREN) As ChildStruct Public iChildren As Integer Public Delimiter As String = ", " Public Structure ChildStruct Public Child As Long Public pLower As Integer Public pHigher As Integer End Structure Sub Main() Dim Parent As Short Dim Sum As Short Dim i As Short Dim TotDesc As Integer = 0 Dim MidPrime As Integer If GetPrimes(Primes, MAXPRIME) = vbFalse Then Return End If For i = Primes.Count To 1 Step -1 PrimesR.Add(Primes.Item(i)) Next MidPrime = PrimesR.Item(1) / 2 For Each Prime In PrimesR Parents(Prime) = InsertChild(Parents(Prime), Prime) CptDescendants(Prime) += 1 If Prime > MidPrime Then Continue For End If For Parent = 1 To MAXPARENT Sum = Parent + Prime If Sum > MAXPARENT Then Exit For End If If Parents(Parent) Then InsertPreorder(Parents(Parent), Sum, Prime) CptDescendants(Sum) += CptDescendants(Parent) End If Next Next RemoveFalseChildren() If MAXPARENT > MAXPRIME Then If GetPrimes(Primes, MAXPARENT) = vbFalse Then Return End If End If FileOpen(1, "Ancestors.txt", OpenMode.Output) For Parent = 1 To MAXPARENT GetAncestors(Parent) PrintLine(1, "[" & Parent.ToString & "] Level: " & Ancestors.Count.ToString) If Ancestors.Count Then Print(1, "Ancestors: " & Ancestors.Item(1).ToString) For i = 2 To Ancestors.Count Print(1, ", " & Ancestors.Item(i).ToString) Next PrintLine(1) Ancestors.Clear() Else PrintLine(1, "Ancestors: None") End If If CptDescendants(Parent) Then PrintLine(1, "Descendants: " & CptDescendants(Parent).ToString) Delimiter = "" PrintDescendants(Parents(Parent)) PrintLine(1) TotDesc += CptDescendants(Parent) Else PrintLine(1, "Descendants: None") End If PrintLine(1) Next Primes.Clear() PrimesR.Clear() PrintLine(1, "Total descendants " & TotDesc.ToString) PrintLine(1) FileClose(1) End Sub Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short) Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime) If Children(_index).pLower Then InsertPreorder(Children(_index).pLower, _sum, _prime) End If If Children(_index).pHigher Then InsertPreorder(Children(_index).pHigher, _sum, _prime) End If Return Nothing End Function Function InsertChild(_index As Integer, _child As Long) As Integer If _index Then If _child <= Children(_index).Child Then Children(_index).pLower = InsertChild(Children(_index).pLower, _child) Else Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child) End If Else iChildren += 1 _index = iChildren Children(_index).Child = _child Children(_index).pLower = 0 Children(_index).pHigher = 0 End If Return _index End Function Function RemoveFalseChildren() Dim Exclusions As New Collection Exclusions.Add(4) For Each Prime In Primes Exclusions.Add(Prime) Next For Each ex In Exclusions Parents(ex) = Children(Parents(ex)).pHigher CptDescendants(ex) -= 1 Next Exclusions.Clear() Return Nothing End Function Function GetAncestors(_child As Short) Dim Child As Short = _child Dim Parent As Short = 0 For Each Prime In Primes If Child = 1 Then Exit For End If While Child Mod Prime = 0 Child /= Prime Parent += Prime End While Next If Parent = _child Or _child = 1 Then Return Nothing End If GetAncestors(Parent) Ancestors.Add(Parent) Return Nothing End Function Function PrintDescendants(_index As Integer) If Children(_index).pLower Then PrintDescendants(Children(_index).pLower) End If Print(1, Delimiter.ToString & Children(_index).Child.ToString) Delimiter = ", " If Children(_index).pHigher Then PrintDescendants(Children(_index).pHigher) End If Return Nothing End Function Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean Dim Value As Integer = 3 Dim Max As Integer Dim Prime As Integer If _maxPrime < 2 Then Return vbFalse End If _primes.Add(2) While Value <= _maxPrime Max = Floor(Sqrt(Value)) For Each Prime In _primes If Prime > Max Then _primes.Add(Value) Exit For End If If Value Mod Prime = 0 Then Exit For End If Next Value += 2 End While Return vbTrue End Function End Module
#include <algorithm> #include <iostream> #include <vector> typedef unsigned long long integer; std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) { std::vector<integer> result; for (integer a = ancestor[n]; a != 0 && a != n; ) { n = a; a = ancestor[n]; result.push_back(n); } return result; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()) { std::cout << "none\n"; return; } auto i = vec.begin(); std::cout << *i++; for (; i != vec.end(); ++i) std::cout << ", " << *i; std::cout << '\n'; } bool is_prime(integer n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; for (integer p = 3; p * p <= n; p += 2) { if (n % p == 0) return false; } return true; } int main(int argc, char** argv) { const size_t limit = 100; std::vector<integer> ancestor(limit, 0); std::vector<std::vector<integer>> descendants(limit); for (size_t prime = 0; prime < limit; ++prime) { if (!is_prime(prime)) continue; descendants[prime].push_back(prime); for (size_t i = 0; i + prime < limit; ++i) { integer s = i + prime; for (integer n : descendants[i]) { integer prod = n * prime; descendants[s].push_back(prod); if (prod < limit) ancestor[prod] = s; } } } size_t total_descendants = 0; for (integer i = 1; i < limit; ++i) { std::vector<integer> ancestors(get_ancestors(ancestor, i)); std::cout << "[" << i << "] Level: " << ancestors.size() << '\n'; std::cout << "Ancestors: "; std::sort(ancestors.begin(), ancestors.end()); print_vector(ancestors); std::cout << "Descendants: "; std::vector<integer>& desc = descendants[i]; if (!desc.empty()) { std::sort(desc.begin(), desc.end()); if (desc[0] == i) desc.erase(desc.begin()); } std::cout << desc.size() << '\n'; total_descendants += desc.size(); if (!desc.empty()) print_vector(desc); std::cout << '\n'; } std::cout << "Total descendants: " << total_descendants << '\n'; return 0; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
#include <iostream> #include <vector> #include <algorithm> void print(const std::vector<std::vector<int>>& v) { std::cout << "{ "; for (const auto& p : v) { std::cout << "("; for (const auto& e : p) { std::cout << e << " "; } std::cout << ") "; } std::cout << "}" << std::endl; } auto product(const std::vector<std::vector<int>>& lists) { std::vector<std::vector<int>> result; if (std::find_if(std::begin(lists), std::end(lists), [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) { return result; } for (auto& e : lists[0]) { result.push_back({ e }); } for (size_t i = 1; i < lists.size(); ++i) { std::vector<std::vector<int>> temp; for (auto& e : result) { for (auto f : lists[i]) { auto e_tmp = e; e_tmp.push_back(f); temp.push_back(e_tmp); } } result = temp; } return result; } int main() { std::vector<std::vector<int>> prods[] = { { { 1, 2 }, { 3, 4 } }, { { 3, 4 }, { 1, 2} }, { { 1, 2 }, { } }, { { }, { 1, 2 } }, { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } }, { { 1, 2, 3 }, { 30 }, { 500, 100 } }, { { 1, 2, 3 }, { }, { 500, 100 } } }; for (const auto& p : prods) { print(product(p)); } std::cin.ignore(); std::cin.get(); return 0; }
Change the programming language of this snippet from VB to C++ without modifying what it does.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
#include <iostream> #include <vector> #include <algorithm> void print(const std::vector<std::vector<int>>& v) { std::cout << "{ "; for (const auto& p : v) { std::cout << "("; for (const auto& e : p) { std::cout << e << " "; } std::cout << ") "; } std::cout << "}" << std::endl; } auto product(const std::vector<std::vector<int>>& lists) { std::vector<std::vector<int>> result; if (std::find_if(std::begin(lists), std::end(lists), [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) { return result; } for (auto& e : lists[0]) { result.push_back({ e }); } for (size_t i = 1; i < lists.size(); ++i) { std::vector<std::vector<int>> temp; for (auto& e : result) { for (auto f : lists[i]) { auto e_tmp = e; e_tmp.push_back(f); temp.push_back(e_tmp); } } result = temp; } return result; } int main() { std::vector<std::vector<int>> prods[] = { { { 1, 2 }, { 3, 4 } }, { { 3, 4 }, { 1, 2} }, { { 1, 2 }, { } }, { { }, { 1, 2 } }, { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } }, { { 1, 2, 3 }, { 30 }, { 500, 100 } }, { { 1, 2, 3 }, { }, { 500, 100 } } }; for (const auto& p : prods) { print(product(p)); } std::cin.ignore(); std::cin.get(); return 0; }
Convert this VB snippet to C++ and keep its semantics consistent.
dim _proper_divisors(100) sub proper_divisors(n) dim i dim _proper_divisors_count = 0 if n <> 1 then for i = 1 to (n \ 2) if n %% i = 0 then _proper_divisors_count = _proper_divisors_count + 1 _proper_divisors(_proper_divisors_count) = i end if next end if return _proper_divisors_count end sub sub show_proper_divisors(n, tabbed) dim cnt = proper_divisors(n) print str$(n) + ":"; tab(4);"(" + str$(cnt) + " items) "; dim j for j = 1 to cnt if tabbed then print str$(_proper_divisors(j)), else print str$(_proper_divisors(j)); end if if (j < cnt) then print ","; next print end sub dim i for i = 1 to 10 show_proper_divisors(i, false) next dim c dim maxindex = 0 dim maxlength = 0 for t = 1 to 20000 c = proper_divisors(t) if c > maxlength then maxindex = t maxlength = c end if next print "A maximum at "; show_proper_divisors(maxindex, false)
#include <vector> #include <iostream> #include <algorithm> std::vector<int> properDivisors ( int number ) { std::vector<int> divisors ; for ( int i = 1 ; i < number / 2 + 1 ; i++ ) if ( number % i == 0 ) divisors.push_back( i ) ; return divisors ; } int main( ) { std::vector<int> divisors ; unsigned int maxdivisors = 0 ; int corresponding_number = 0 ; for ( int i = 1 ; i < 11 ; i++ ) { divisors = properDivisors ( i ) ; std::cout << "Proper divisors of " << i << ":\n" ; for ( int number : divisors ) { std::cout << number << " " ; } std::cout << std::endl ; divisors.clear( ) ; } for ( int i = 11 ; i < 20001 ; i++ ) { divisors = properDivisors ( i ) ; if ( divisors.size( ) > maxdivisors ) { maxdivisors = divisors.size( ) ; corresponding_number = i ; } divisors.clear( ) ; } std::cout << "Most divisors has " << corresponding_number << " , it has " << maxdivisors << " divisors!\n" ; return 0 ; }
Maintain the same structure and functionality when rewriting this code in C++.
Module XMLOutput Sub Main() Dim charRemarks As New Dictionary(Of String, String) charRemarks.Add("April", "Bubbly: I charRemarks.Add("Tam O charRemarks.Add("Emily", "Short & shrift") Dim xml = <CharacterRemarks> <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %> </CharacterRemarks> Console.WriteLine(xml) End Sub End Module
#include <vector> #include <utility> #include <iostream> #include <boost/algorithm/string.hpp> std::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ; int main( ) { std::vector<std::string> names , remarks ; names.push_back( "April" ) ; names.push_back( "Tam O'Shantor" ) ; names.push_back ( "Emily" ) ; remarks.push_back( "Bubbly, I'm > Tam and <= Emily" ) ; remarks.push_back( "Burns: \"When chapman billies leave the street ...\"" ) ; remarks.push_back( "Short & shrift" ) ; std::cout << "This is in XML:\n" ; std::cout << create_xml( names , remarks ) << std::endl ; return 0 ; } std::string create_xml( std::vector<std::string> & names , std::vector<std::string> & remarks ) { std::vector<std::pair<std::string , std::string> > entities ; entities.push_back( std::make_pair( "&" , "&amp;" ) ) ; entities.push_back( std::make_pair( "<" , "&lt;" ) ) ; entities.push_back( std::make_pair( ">" , "&gt;" ) ) ; std::string xmlstring ( "<CharacterRemarks>\n" ) ; std::vector<std::string>::iterator vsi = names.begin( ) ; typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ; for ( ; vsi != names.end( ) ; vsi++ ) { for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) { boost::replace_all ( *vsi , vs->first , vs->second ) ; } } for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) { for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) { boost::replace_all ( *vsi , vs->first , vs->second ) ; } } for ( int i = 0 ; i < names.size( ) ; i++ ) { xmlstring.append( "\t<Character name=\"").append( names[ i ] ).append( "\">") .append( remarks[ i ] ).append( "</Character>\n" ) ; } xmlstring.append( "</CharacterRemarks>" ) ; return xmlstring ; }
Maintain the same structure and functionality when rewriting this code in C++.
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlLine .HasLegend = False .HasTitle = True .ChartTitle.Text = "Time" .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(1).Values = y .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds" End With End Sub Public Sub main() x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}] y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}] plot_coordinate_pairs x, y End Sub
#include <windows.h> #include <string> #include <vector> using namespace std; const int HSTEP = 46, MWID = 40, MHEI = 471; const float VSTEP = 2.3f; class vector2 { public: vector2() { x = y = 0; } vector2( float a, float b ) { x = a; y = b; } void set( float a, float b ) { x = a; y = b; } float x, y; }; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class plot { public: plot() { bmp.create( 512, 512 ); } void draw( vector<vector2>* pairs ) { bmp.clear( 0xff ); drawGraph( pairs ); plotIt( pairs ); HDC dc = GetDC( GetConsoleWindow() ); BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( GetConsoleWindow(), dc ); } private: void drawGraph( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); bmp.setPenColor( RGB( 240, 240, 240 ) ); DWORD b = 11, c = 40, x; RECT rc; char txt[8]; for( x = 0; x < pairs->size(); x++ ) { MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b ); MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 ); wsprintf( txt, "%d", ( pairs->size() - x ) * 20 ); SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); wsprintf( txt, "%d", x ); SetRect( &rc, c - 8, 472, c + 8, 492 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); c += 46; b += 46; } SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); bmp.setPenColor( 0 ); bmp.setPenWidth( 3 ); MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 ); MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 ); } void plotIt( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); HBRUSH br = CreateSolidBrush( 255 ); RECT rc; bmp.setPenColor( 255 ); bmp.setPenWidth( 2 ); vector<vector2>::iterator it = pairs->begin(); int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); MoveToEx( dc, a, b, NULL ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); it++; for( ; it < pairs->end(); it++ ) { a = MWID + HSTEP * static_cast<int>( ( *it ).x ); b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); LineTo( dc, a, b ); } DeleteObject( br ); } myBitmap bmp; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); plot pt; vector<vector2> pairs; pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) ); pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) ); pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) ); pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) ); pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) ); pt.draw( &pairs ); system( "pause" ); return 0; }
Port the provided VB code into C++ while preserving the original functionality.
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlLine .HasLegend = False .HasTitle = True .ChartTitle.Text = "Time" .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(1).Values = y .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds" End With End Sub Public Sub main() x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}] y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}] plot_coordinate_pairs x, y End Sub
#include <windows.h> #include <string> #include <vector> using namespace std; const int HSTEP = 46, MWID = 40, MHEI = 471; const float VSTEP = 2.3f; class vector2 { public: vector2() { x = y = 0; } vector2( float a, float b ) { x = a; y = b; } void set( float a, float b ) { x = a; y = b; } float x, y; }; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class plot { public: plot() { bmp.create( 512, 512 ); } void draw( vector<vector2>* pairs ) { bmp.clear( 0xff ); drawGraph( pairs ); plotIt( pairs ); HDC dc = GetDC( GetConsoleWindow() ); BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( GetConsoleWindow(), dc ); } private: void drawGraph( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); bmp.setPenColor( RGB( 240, 240, 240 ) ); DWORD b = 11, c = 40, x; RECT rc; char txt[8]; for( x = 0; x < pairs->size(); x++ ) { MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b ); MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 ); wsprintf( txt, "%d", ( pairs->size() - x ) * 20 ); SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); wsprintf( txt, "%d", x ); SetRect( &rc, c - 8, 472, c + 8, 492 ); DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); c += 46; b += 46; } SetRect( &rc, 0, b - 9, 36, b + 11 ); DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); bmp.setPenColor( 0 ); bmp.setPenWidth( 3 ); MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 ); MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 ); } void plotIt( vector<vector2>* pairs ) { HDC dc = bmp.getDC(); HBRUSH br = CreateSolidBrush( 255 ); RECT rc; bmp.setPenColor( 255 ); bmp.setPenWidth( 2 ); vector<vector2>::iterator it = pairs->begin(); int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); MoveToEx( dc, a, b, NULL ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); it++; for( ; it < pairs->end(); it++ ) { a = MWID + HSTEP * static_cast<int>( ( *it ).x ); b = MHEI - static_cast<int>( VSTEP * ( *it ).y ); SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); LineTo( dc, a, b ); } DeleteObject( br ); } myBitmap bmp; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); plot pt; vector<vector2> pairs; pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) ); pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) ); pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) ); pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) ); pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) ); pt.draw( &pairs ); system( "pause" ); return 0; }
Generate an equivalent C++ version of this VB code.
text = "I need more coffee!!!" Set regex = New RegExp regex.Global = True regex.Pattern = "\s" If regex.Test(text) Then WScript.StdOut.Write regex.Replace(text,vbCrLf) Else WScript.StdOut.Write "No matching pattern" End If
#include <iostream> #include <string> #include <iterator> #include <regex> int main() { std::regex re(".* string$"); std::string s = "Hi, I am a string"; if (std::regex_match(s, re)) std::cout << "The string matches.\n"; else std::cout << "Oops - not found?\n"; std::regex re2(" a.*a"); std::smatch match; if (std::regex_search(s, match, re2)) { std::cout << "Matched " << match.length() << " characters starting at " << match.position() << ".\n"; std::cout << "Matched character sequence: \"" << match.str() << "\"\n"; } else { std::cout << "Oops - not found?\n"; } std::string dest_string; std::regex_replace(std::back_inserter(dest_string), s.begin(), s.end(), re2, "'m now a changed"); std::cout << dest_string << std::endl; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
Set dict = CreateObject("Scripting.Dictionary") os = Array("Windows", "Linux", "MacOS") owner = Array("Microsoft", "Linus Torvalds", "Apple") For n = 0 To 2 dict.Add os(n), owner(n) Next MsgBox dict.Item("Linux") MsgBox dict.Item("MacOS") MsgBox dict.Item("Windows")
#include <unordered_map> #include <string> int main() { std::string keys[] = { "1", "2", "3" }; std::string vals[] = { "a", "b", "c" }; std::unordered_map<std::string, std::string> hash; for( int i = 0 ; i < 3 ; i++ ) hash[ keys[i] ] = vals[i] ; }
Preserve the algorithm and functionality while converting the code from VB to C++.
Public Class Main Inherits System.Windows.Forms.Form Public Sub New() Me.FormBorderStyle = FormBorderStyle.None Me.WindowState = FormWindowState.Maximized End Sub Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load Dim Index As Integer Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White} Dim Height = (Me.ClientSize.Height / 4) + 1 For y = 1 To 4 Dim Top = Me.ClientSize.Height / 4 * (y - 1) For x = 0 To Me.ClientSize.Width Step y If Index = 6 Then Index = 0 Else Index += 1 Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)}) Next Next End Sub End Class
#include <windows.h> class pinstripe { public: pinstripe() { createColors(); } void setDimensions( int x, int y ) { _mw = x; _mh = y; } void createColors() { colors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 ); colors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); colors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); colors[7] = RGB( 255, 255, 255 ); } void draw( HDC dc ) { HPEN pen; int lh = _mh / 4, row, cp; for( int lw = 1; lw < 5; lw++ ) { cp = 0; row = ( lw - 1 ) * lh; for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw ) { pen = CreatePen( PS_SOLID, lw, colors[cp] ); ++cp %= 8; SelectObject( dc, pen ); MoveToEx( dc, x, row, NULL ); LineTo( dc, x, row + lh ); DeleteObject( pen ); } } } private: int _mw, _mh; DWORD colors[8]; }; pinstripe pin; void PaintWnd( HWND hWnd ) { PAINTSTRUCT ps; HDC hdc = BeginPaint( hWnd, &ps ); pin.draw( hdc ); EndPaint( hWnd, &ps ); } LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_PAINT: PaintWnd( hWnd ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll( HINSTANCE hInstance ) { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_CLR_PS_"; RegisterClassEx( &wcex ); return CreateWindow( "_CLR_PS_", ".: Clr Pinstripe -- PJorente :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL ); } int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); HWND hwnd = InitAll( hInstance ); if( !hwnd ) return -1; int mw = GetSystemMetrics( SM_CXSCREEN ), mh = GetSystemMetrics( SM_CYSCREEN ); pin.setDimensions( mw, mh ); RECT rc = { 0, 0, mw, mh }; AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 ); int w = rc.right - rc.left, h = rc.bottom - rc.top; int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ), posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 ); SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER ); ShowWindow( hwnd, nCmdShow ); UpdateWindow( hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } return UnregisterClass( "_CLR_PS_", hInstance ); }
Write a version of this VB function in C++ with identical behavior.
Public Class Main Inherits System.Windows.Forms.Form Public Sub New() Me.FormBorderStyle = FormBorderStyle.None Me.WindowState = FormWindowState.Maximized End Sub Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load Dim Index As Integer Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White} Dim Height = (Me.ClientSize.Height / 4) + 1 For y = 1 To 4 Dim Top = Me.ClientSize.Height / 4 * (y - 1) For x = 0 To Me.ClientSize.Width Step y If Index = 6 Then Index = 0 Else Index += 1 Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)}) Next Next End Sub End Class
#include <windows.h> class pinstripe { public: pinstripe() { createColors(); } void setDimensions( int x, int y ) { _mw = x; _mh = y; } void createColors() { colors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 ); colors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); colors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); colors[7] = RGB( 255, 255, 255 ); } void draw( HDC dc ) { HPEN pen; int lh = _mh / 4, row, cp; for( int lw = 1; lw < 5; lw++ ) { cp = 0; row = ( lw - 1 ) * lh; for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw ) { pen = CreatePen( PS_SOLID, lw, colors[cp] ); ++cp %= 8; SelectObject( dc, pen ); MoveToEx( dc, x, row, NULL ); LineTo( dc, x, row + lh ); DeleteObject( pen ); } } } private: int _mw, _mh; DWORD colors[8]; }; pinstripe pin; void PaintWnd( HWND hWnd ) { PAINTSTRUCT ps; HDC hdc = BeginPaint( hWnd, &ps ); pin.draw( hdc ); EndPaint( hWnd, &ps ); } LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_PAINT: PaintWnd( hWnd ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll( HINSTANCE hInstance ) { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_CLR_PS_"; RegisterClassEx( &wcex ); return CreateWindow( "_CLR_PS_", ".: Clr Pinstripe -- PJorente :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL ); } int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); HWND hwnd = InitAll( hInstance ); if( !hwnd ) return -1; int mw = GetSystemMetrics( SM_CXSCREEN ), mh = GetSystemMetrics( SM_CYSCREEN ); pin.setDimensions( mw, mh ); RECT rc = { 0, 0, mw, mh }; AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 ); int w = rc.right - rc.left, h = rc.bottom - rc.top; int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ), posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 ); SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER ); ShowWindow( hwnd, nCmdShow ); UpdateWindow( hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } return UnregisterClass( "_CLR_PS_", hInstance ); }
Produce a language-to-language conversion: from VB to C++, same semantics.
Function cocktailShakerSort(ByVal A As Variant) As Variant beginIdx = LBound(A) endIdx = UBound(A) - 1 Do While beginIdx <= endIdx newBeginIdx = endIdx newEndIdx = beginIdx For ii = beginIdx To endIdx If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newEndIdx = ii End If Next ii endIdx = newEndIdx - 1 For ii = endIdx To beginIdx Step -1 If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newBeginIdx = ii End If Next ii beginIdx = newBeginIdx + 1 Loop cocktailShakerSort = A End Function Public Sub main() Dim B(20) As Variant For i = LBound(B) To UBound(B) B(i) = Int(Rnd() * 100) Next i Debug.Print Join(B, ", ") Debug.Print Join(cocktailShakerSort(B), ", ") End Sub
#include <algorithm> #include <cassert> #include <iostream> #include <iterator> #include <vector> template <typename iterator> void cocktail_shaker_sort(iterator begin, iterator end) { if (begin == end) return; for (--end; begin < end; ) { iterator new_begin = end; iterator new_end = begin; for (iterator i = begin; i < end; ++i) { iterator j = i + 1; if (*j < *i) { std::iter_swap(i, j); new_end = i; } } end = new_end; for (iterator i = end; i > begin; --i) { iterator j = i - 1; if (*i < *j) { std::iter_swap(i, j); new_begin = i; } } begin = new_begin; } } template <typename iterator> void print(iterator begin, iterator end) { if (begin == end) return; std::cout << *begin++; while (begin != end) std::cout << ' ' << *begin++; std::cout << '\n'; } int main() { std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15}; std::cout << "before: "; print(v.begin(), v.end()); cocktail_shaker_sort(v.begin(), v.end()); assert(std::is_sorted(v.begin(), v.end())); std::cout << "after: "; print(v.begin(), v.end()); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
option explicit const dt = 0.15 const length=23 dim ans0:ans0=chr(27)&"[" dim Veloc,Accel,angle,olr,olc,r,c const r0=1 const c0=40 cls angle=0.7 while 1 wscript.sleep(50) Accel = -.9 * sin(Angle) Veloc = Veloc + Accel * dt Angle = Angle + Veloc * dt r = r0 + int(cos(Angle) * Length) c = c0+ int(2*sin(Angle) * Length) cls draw_line r,c,r0,c0 toxy r,c,"O" olr=r :olc=c wend sub cls() wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub sub toxy(r,c,s) wscript.StdOut.Write ans0 & r & ";" & c & "f" & s :end sub Sub draw_line(r1,c1, r2,c2) Dim x,y,xf,yf,dx,dy,sx,sy,err,err2 x =r1 : y =c1 xf=r2 : yf=c2 dx=Abs(xf-x) : dy=Abs(yf-y) If x<xf Then sx=+1: Else sx=-1 If y<yf Then sy=+1: Else sy=-1 err=dx-dy Do toxy x,y,"." If x=xf And y=yf Then Exit Do err2=err+err If err2>-dy Then err=err-dy: x=x+sx If err2< dx Then err=err+dx: y=y+sy Loop End Sub
#ifndef __wxPendulumDlg_h__ #define __wxPendulumDlg_h__ #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include <wx/wx.h> #include <wx/dialog.h> #else #include <wx/wxprec.h> #endif #include <wx/timer.h> #include <wx/dcbuffer.h> #include <cmath> class wxPendulumDlgApp : public wxApp { public: bool OnInit(); int OnExit(); }; class wxPendulumDlg : public wxDialog { public: wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("wxPendulum"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX); virtual ~wxPendulumDlg(); void wxPendulumDlgPaint(wxPaintEvent& event); void wxPendulumDlgSize(wxSizeEvent& event); void OnTimer(wxTimerEvent& event); private: wxTimer *m_timer; unsigned int m_uiLength; double m_Angle; double m_AngleVelocity; enum wxIDs { ID_WXTIMER1 = 1001, ID_DUMMY_VALUE_ }; void OnClose(wxCloseEvent& event); void CreateGUIControls(); DECLARE_EVENT_TABLE() }; #endif
Write the same algorithm in C++ as shown in this VB implementation.
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
Ensure the translated C++ code behaves exactly like the original VB snippet.
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
class playingcard dim suit dim pips end class class carddeck private suitnames private pipnames private cardno private deck(52) private nTop sub class_initialize dim suit dim pips suitnames = split("H,D,C,S",",") pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",") cardno = 0 for suit = 1 to 4 for pips = 1 to 13 set deck(cardno) = new playingcard deck(cardno).suit = suitnames(suit-1) deck(cardno).pips = pipnames(pips-1) cardno = cardno + 1 next next nTop = 0 end sub public sub showdeck dim a redim a(51-nTop) for i = nTop to 51 a(i) = deck(i).pips & deck(i).suit next wscript.echo join( a, ", ") end sub public sub shuffle dim r randomize timer for i = nTop to 51 r = int( rnd * ( 52 - nTop ) ) if r <> i then objswap deck(i),deck(r) end if next end sub public function deal() set deal = deck( nTop ) nTop = nTop + 1 end function public property get cardsRemaining cardsRemaining = 52 - nTop end property private sub objswap( a, b ) dim tmp set tmp = a set a = b set b = tmp end sub end class
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; enum { unique_count = pip_count * suite_count }; card(suite_type s, pip_type p): value(s + suite_count * p) {} explicit card(unsigned char v = 0): value(v) {} pip_type pip() { return pip_type(value / suite_count); } suite_type suite() { return suite_type(value % suite_count); } private: unsigned char value; }; const char* const pip_names[] = { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace" }; std::ostream& operator<<(std::ostream& os, card::pip_type pip) { return os << pip_names[pip]; } const char* const suite_names[] = { "hearts", "spades", "diamonds", "clubs" }; std::ostream& operator<<(std::ostream& os, card::suite_type suite) { return os << suite_names[suite]; } std::ostream& operator<<(std::ostream& os, card c) { return os << c.pip() << " of " << c.suite(); } class deck { public: deck() { for (int i = 0; i < card::unique_count; ++i) { cards.push_back(card(i)); } } void shuffle() { std::random_shuffle(cards.begin(), cards.end()); } card deal() { card c = cards.front(); cards.pop_front(); return c; } typedef std::deque<card>::const_iterator const_iterator; const_iterator begin() const { return cards.cbegin(); } const_iterator end() const { return cards.cend(); } private: std::deque<card> cards; }; inline std::ostream& operator<<(std::ostream& os, const deck& d) { std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n")); return os; } }
Write the same code in C++ as shown below in VB.
class playingcard dim suit dim pips end class class carddeck private suitnames private pipnames private cardno private deck(52) private nTop sub class_initialize dim suit dim pips suitnames = split("H,D,C,S",",") pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",") cardno = 0 for suit = 1 to 4 for pips = 1 to 13 set deck(cardno) = new playingcard deck(cardno).suit = suitnames(suit-1) deck(cardno).pips = pipnames(pips-1) cardno = cardno + 1 next next nTop = 0 end sub public sub showdeck dim a redim a(51-nTop) for i = nTop to 51 a(i) = deck(i).pips & deck(i).suit next wscript.echo join( a, ", ") end sub public sub shuffle dim r randomize timer for i = nTop to 51 r = int( rnd * ( 52 - nTop ) ) if r <> i then objswap deck(i),deck(r) end if next end sub public function deal() set deal = deck( nTop ) nTop = nTop + 1 end function public property get cardsRemaining cardsRemaining = 52 - nTop end property private sub objswap( a, b ) dim tmp set tmp = a set a = b set b = tmp end sub end class
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; enum { unique_count = pip_count * suite_count }; card(suite_type s, pip_type p): value(s + suite_count * p) {} explicit card(unsigned char v = 0): value(v) {} pip_type pip() { return pip_type(value / suite_count); } suite_type suite() { return suite_type(value % suite_count); } private: unsigned char value; }; const char* const pip_names[] = { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace" }; std::ostream& operator<<(std::ostream& os, card::pip_type pip) { return os << pip_names[pip]; } const char* const suite_names[] = { "hearts", "spades", "diamonds", "clubs" }; std::ostream& operator<<(std::ostream& os, card::suite_type suite) { return os << suite_names[suite]; } std::ostream& operator<<(std::ostream& os, card c) { return os << c.pip() << " of " << c.suite(); } class deck { public: deck() { for (int i = 0; i < card::unique_count; ++i) { cards.push_back(card(i)); } } void shuffle() { std::random_shuffle(cards.begin(), cards.end()); } card deal() { card c = cards.front(); cards.pop_front(); return c; } typedef std::deque<card>::const_iterator const_iterator; const_iterator begin() const { return cards.cbegin(); } const_iterator end() const { return cards.cend(); } private: std::deque<card> cards; }; inline std::ostream& operator<<(std::ostream& os, const deck& d) { std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n")); return os; } }
Translate this program into C++ but keep the logic exactly as in VB.
Option Base {0|1}
#include <array> #include <vector> #include <algorithm> #include <iostream> #include <iterator> #include <string> template <typename Array> void demonstrate(Array& array) { array[2] = "Three"; array.at(1) = "Two"; std::reverse(begin(array), end(array)); std::for_each(begin(array), end(array), [](typename Array::value_type const& element) { std::cout << element << ' '; }); std::cout << '\n'; } int main() { auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" }; auto dynamic_array = std::vector<std::string>{ "One", "Four" }; dynamic_array.push_back("Eight"); demonstrate(fixed_size_array); demonstrate(dynamic_array); }
Convert the following code from VB to C++, ensuring the logic remains intact.
Const Order = 4 Function InCarpet(ByVal x As Integer, ByVal y As Integer) Do While x <> 0 And y <> 0 If x Mod 3 = 1 And y Mod 3 = 1 Then InCarpet = " " Exit Function End If x = x \ 3 y = y \ 3 Loop InCarpet = "#" End Function Public Sub sierpinski_carpet() Dim i As Integer, j As Integer For i = 0 To 3 ^ Order - 1 For j = 0 To 3 ^ Order - 1 Debug.Print InCarpet(i, j); Next j Debug.Print Next i End Sub
#include <cstdint> #include <cstdlib> #include <cstdio> static constexpr int32_t bct_low_bits = 0x55555555; static int32_t bct_decrement(int32_t v) { --v; return v ^ (v & (v>>1) & bct_low_bits); } int main (int argc, char *argv[]) { const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3; if (n < 0 || 9 < n) { std::printf("N out of range (use 0..9): %ld\n", long(n)); return 1; } const int32_t size_bct = 1<<(n*2); int32_t y = size_bct; do { y = bct_decrement(y); int32_t x = size_bct; do { x = bct_decrement(x); std::putchar((x & y & bct_low_bits) ? ' ' : '#'); } while (0 < x); std::putchar('\n'); } while (0 < y); return 0; }
Port the provided VB code into C++ while preserving the original functionality.
Private Function Knuth(a As Variant) As Variant Dim t As Variant, i As Integer If Not IsMissing(a) Then For i = UBound(a) To LBound(a) + 1 Step -1 j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a)) t = a(i) a(i) = a(j) a(j) = t Next i End If Knuth = a End Function Private Function inOrder(s As Variant) i = 2 Do While i <= UBound(s) If s(i) < s(i - 1) Then inOrder = False Exit Function End If i = i + 1 Loop inOrder = True End Function Private Function bogosort(ByVal s As Variant) As Variant Do While Not inOrder(s) Debug.Print Join(s, ", ") s = Knuth(s) Loop bogosort = s End Function Public Sub main() Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), ", ") End Sub
#include <algorithm> #include <iostream> #include <iterator> #include <random> template <typename RandomAccessIterator, typename Predicate> void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end, Predicate p) { std::random_device rd; std::mt19937 generator(rd()); while (!std::is_sorted(begin, end, p)) { std::shuffle(begin, end, generator); } } template <typename RandomAccessIterator> void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) { bogo_sort( begin, end, std::less< typename std::iterator_traits<RandomAccessIterator>::value_type>()); } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bogo_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
Convert the following code from VB to C++, ensuring the logic remains intact.
Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer) Dim t As Integer Debug.Print " Step "; step; ": ", Do While t <= end_t If t Mod 10 = 0 Then Debug.Print Format(y, "0.000"), y = y + step * Application.Run(f, y) t = t + step Loop Debug.Print End Sub Sub analytic() Debug.Print " Time: ", For t = 0 To 100 Step 10 Debug.Print " "; t, Next t Debug.Print Debug.Print "Analytic: ", For t = 0 To 100 Step 10 Debug.Print Format(20 + 80 * Exp(-0.07 * t), "0.000"), Next t Debug.Print End Sub Private Function cooling(temp As Double) As Double cooling = -0.07 * (temp - 20) End Function Public Sub euler_method() Dim r_cooling As String r_cooling = "cooling" analytic ivp_euler r_cooling, 100, 2, 100 ivp_euler r_cooling, 100, 5, 100 ivp_euler r_cooling, 100, 10, 100 End Sub
#include <iomanip> #include <iostream> typedef double F(double,double); void euler(F f, double y0, double a, double b, double h) { double y = y0; for (double t = a; t < b; t += h) { std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n"; y += h * f(t, y); } std::cout << "done\n"; } double newtonCoolingLaw(double, double t) { return -0.07 * (t - 20); } int main() { euler(newtonCoolingLaw, 100, 0, 100, 2); euler(newtonCoolingLaw, 100, 0, 100, 5); euler(newtonCoolingLaw, 100, 0, 100, 10); }
Write the same code in C++ as shown below in VB.
Sub Main() Dim i&, c&, j#, s$ Const N& = 1000000 s = "values for n in the range 1 to 22 : " For i = 1 To 22 s = s & ns(i) & ", " Next For i = 1 To N j = Sqr(ns(i)) If j = CInt(j) Then c = c + 1 Next Debug.Print s Debug.Print c & " squares less than " & N End Sub Private Function ns(l As Long) As Long ns = l + Int(1 / 2 + Sqr(l)) End Function
#include <iostream> #include <algorithm> #include <vector> #include <cmath> #include <boost/bind.hpp> #include <iterator> double nextNumber( double number ) { return number + floor( 0.5 + sqrt( number ) ) ; } int main( ) { std::vector<double> non_squares ; typedef std::vector<double>::iterator SVI ; non_squares.reserve( 1000000 ) ; for ( double i = 1.0 ; i < 100001.0 ; i += 1 ) non_squares.push_back( nextNumber( i ) ) ; std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 , std::ostream_iterator<double>(std::cout, " " ) ) ; std::cout << '\n' ; SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) , boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ; if ( found != non_squares.end( ) ) { std::cout << "Found a square number in the sequence!\n" ; std::cout << "It is " << *found << " !\n" ; } else { std::cout << "Up to 1000000, found no square number in the sequence!\n" ; } return 0 ; }
Write the same algorithm in C++ as shown in this VB implementation.
Public Sub substring() sentence = "the last thing the man said was the" n = 10: m = 5 Debug.Print Mid(sentence, n, 5) Debug.Print Right(sentence, Len(sentence) - n + 1) Debug.Print Left(sentence, Len(sentence) - 1) k = InStr(1, sentence, "m") Debug.Print Mid(sentence, k, 5) k = InStr(1, sentence, "aid") Debug.Print Mid(sentence, k, 5) End Sub
#include <iostream> #include <string> int main() { std::string s = "0123456789"; int const n = 3; int const m = 4; char const c = '2'; std::string const sub = "456"; std::cout << s.substr(n, m)<< "\n"; std::cout << s.substr(n) << "\n"; std::cout << s.substr(0, s.size()-1) << "\n"; std::cout << s.substr(s.find(c), m) << "\n"; std::cout << s.substr(s.find(sub), m) << "\n"; }
Rewrite this program in C++ while keeping its functionality equivalent to the VB version.
Function JortSort(s) JortSort = True arrPreSort = Split(s,",") Set arrSorted = CreateObject("System.Collections.ArrayList") For i = 0 To UBound(arrPreSort) arrSorted.Add(arrPreSort(i)) Next arrSorted.Sort() For j = 0 To UBound(arrPreSort) If arrPreSort(j) <> arrSorted(j) Then JortSort = False Exit For End If Next End Function WScript.StdOut.Write JortSort("1,2,3,4,5") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("1,2,3,5,4") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("a,b,c") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("a,c,b")
#include <algorithm> #include <string> #include <iostream> #include <iterator> class jortSort { public: template<class T> bool jort_sort( T* o, size_t s ) { T* n = copy_array( o, s ); sort_array( n, s ); bool r = false; if( n ) { r = check( o, n, s ); delete [] n; } return r; } private: template<class T> T* copy_array( T* o, size_t s ) { T* z = new T[s]; memcpy( z, o, s * sizeof( T ) ); return z; } template<class T> void sort_array( T* n, size_t s ) { std::sort( n, n + s ); } template<class T> bool check( T* n, T* o, size_t s ) { for( size_t x = 0; x < s; x++ ) if( n[x] != o[x] ) return false; return true; } }; jortSort js; template<class T> void displayTest( T* o, size_t s ) { std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) ); std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n"; } int main( int argc, char* argv[] ) { const size_t s = 5; std::string oStr[] = { "5", "A", "D", "R", "S" }; displayTest( oStr, s ); std::swap( oStr[0], oStr[1] ); displayTest( oStr, s ); int oInt[] = { 1, 2, 3, 4, 5 }; displayTest( oInt, s ); std::swap( oInt[0], oInt[1] ); displayTest( oInt, s ); return 0; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
Public Function Leap_year(year As Integer) As Boolean Leap_year = (Month(DateSerial(year, 2, 29)) = 2) End Function
#include <iostream> bool is_leap_year(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } int main() { for (auto year : {1900, 1994, 1996, 1997, 2000}) { std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n"; } }
Ensure the translated C++ code behaves exactly like the original VB snippet.
dim i,j Wscript.StdOut.WriteLine "-- Long Integer - Permutations - from 1 to 12" for i=1 to 12 for j=1 to i Wscript.StdOut.Write "P(" & i & "," & j & ")=" & perm(i,j) & " " next Wscript.StdOut.WriteLine "" next Wscript.StdOut.WriteLine "-- Float integer - Combinations from 10 to 60" for i=10 to 60 step 10 for j=1 to i step i\5 Wscript.StdOut.Write "C(" & i & "," & j & ")=" & comb(i,j) & " " next Wscript.StdOut.WriteLine "" next Wscript.StdOut.WriteLine "-- Float integer - Permutations from 5000 to 15000" for i=5000 to 15000 step 5000 for j=10 to 70 step 20 Wscript.StdOut.Write "C(" & i & "," & j & ")=" & perm(i,j) & " " next Wscript.StdOut.WriteLine "" next Wscript.StdOut.WriteLine "-- Float integer - Combinations from 200 to 1000" for i=200 to 1000 step 200 for j=20 to 100 step 20 Wscript.StdOut.Write "P(" & i & "," & j & ")=" & comb(i,j) & " " next Wscript.StdOut.WriteLine "" next function perm(x,y) dim i,z z=1 for i=x-y+1 to x z=z*i next perm=z end function function fact(x) dim i,z z=1 for i=2 to x z=z*i next fact=z end function function comb(byval x,byval y) if y>x then comb=0 elseif x=y then comb=1 else if x-y<y then y=x-y comb=perm(x,y)/fact(y) end if end function
#include <boost/multiprecision/gmp.hpp> #include <iostream> using namespace boost::multiprecision; mpz_int p(uint n, uint p) { mpz_int r = 1; mpz_int k = n - p; while (n > k) r *= n--; return r; } mpz_int c(uint n, uint k) { mpz_int r = p(n, k); while (k) r /= k--; return r; } int main() { for (uint i = 1u; i < 12u; i++) std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl; for (uint i = 10u; i < 60u; i += 10u) std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl; return 0; }
Change the programming language of this snippet from VB to C++ without modifying what it does.
Public Function sortlexicographically(N As Integer) Dim arrList As Object Set arrList = CreateObject("System.Collections.ArrayList") For i = 1 To N arrList.Add CStr(i) Next i arrList.Sort Dim item As Variant For Each item In arrList Debug.Print item & ", "; Next End Function Public Sub main() Call sortlexicographically(13) End Sub
#include <algorithm> #include <iostream> #include <numeric> #include <string> #include <vector> void lexicographical_sort(std::vector<int>& numbers) { std::vector<std::string> strings(numbers.size()); std::transform(numbers.begin(), numbers.end(), strings.begin(), [](int i) { return std::to_string(i); }); std::sort(strings.begin(), strings.end()); std::transform(strings.begin(), strings.end(), numbers.begin(), [](const std::string& s) { return std::stoi(s); }); } std::vector<int> lexicographically_sorted_vector(int n) { std::vector<int> numbers(n >= 1 ? n : 2 - n); std::iota(numbers.begin(), numbers.end(), std::min(1, n)); lexicographical_sort(numbers); return numbers; } template <typename T> void print_vector(std::ostream& out, const std::vector<T>& v) { out << '['; if (!v.empty()) { auto i = v.begin(); out << *i++; for (; i != v.end(); ++i) out << ',' << *i; } out << "]\n"; } int main(int argc, char** argv) { for (int i : { 0, 5, 13, 21, -22 }) { std::cout << i << ": "; print_vector(std::cout, lexicographically_sorted_vector(i)); } return 0; }
Change the following VB code into C++ without altering its purpose.
Public twenties As Variant Public decades As Variant Public orders As Variant Private Sub init() twenties = [{"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}] decades = [{"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}] orders = [{1E15,"quadrillion"; 1E12,"trillion"; 1E9,"billion"; 1E6,"million"; 1E3,"thousand"}] End Sub Private Function Twenty(N As Variant) Twenty = twenties(N Mod 20 + 1) End Function Private Function Decade(N As Variant) Decade = decades(N Mod 10 - 1) End Function Private Function Hundred(N As Variant) If N < 20 Then Hundred = Twenty(N) Exit Function Else If N Mod 10 = 0 Then Hundred = Decade((N \ 10) Mod 10) Exit Function End If End If Hundred = Decade(N \ 10) & "-" & Twenty(N Mod 10) End Function Private Function Thousand(N As Variant, withand As String) If N < 100 Then Thousand = withand & Hundred(N) Exit Function Else If N Mod 100 = 0 Then Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & " hundred" Exit Function End If End If Thousand = Twenty(N \ 100) & " hundred and " & Hundred(N Mod 100) End Function Private Function Triplet(N As Variant) Dim Order, High As Variant, Low As Variant Dim Name As String, res As String For i = 1 To UBound(orders) Order = orders(i, 1) Name = orders(i, 2) High = WorksheetFunction.Floor_Precise(N / Order) Low = N - High * Order If High <> 0 Then res = res & Thousand(High, "") & " " & Name End If N = Low If Low = 0 Then Exit For If Len(res) And High <> 0 Then res = res & ", " End If Next i If N <> 0 Or res = "" Then res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = "", "", "and ")) N = N - Int(N) If N > 0.000001 Then res = res & " point" For i = 1 To 10 n_ = WorksheetFunction.Floor_Precise(N * 10.0000001) res = res & " " & twenties(n_ + 1) N = N * 10 - n_ If Abs(N) < 0.000001 Then Exit For Next i End If End If Triplet = res End Function Private Function spell(N As Variant) Dim res As String If N < 0 Then res = "minus " N = -N End If res = res & Triplet(N) spell = res End Function Private Function smartp(N As Variant) Dim res As String If N = WorksheetFunction.Floor_Precise(N) Then smartp = CStr(N) Exit Function End If res = CStr(N) If InStr(1, res, ".") Then res = Left(res, InStr(1, res, ".")) End If smartp = res End Function Sub Main() Dim si As Variant init Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}] Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}] For i = 1 To UBound(Samples1) si = Samples1(i) Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si) Next i For i = 1 To UBound(Samples2) si = Samples2(i) Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si) Next i End Sub
#include <string> #include <iostream> using std::string; const char* smallNumbers[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; string spellHundreds(unsigned n) { string res; if (n > 99) { res = smallNumbers[n/100]; res += " hundred"; n %= 100; if (n) res += " and "; } if (n >= 20) { static const char* Decades[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; res += Decades[n/10]; n %= 10; if (n) res += "-"; } if (n < 20 && n > 0) res += smallNumbers[n]; return res; } const char* thousandPowers[] = { " billion", " million", " thousand", "" }; typedef unsigned long Spellable; string spell(Spellable n) { if (n < 20) return smallNumbers[n]; string res; const char** pScaleName = thousandPowers; Spellable scaleFactor = 1000000000; while (scaleFactor > 0) { if (n >= scaleFactor) { Spellable h = n / scaleFactor; res += spellHundreds(h) + *pScaleName; n %= scaleFactor; if (n) res += ", "; } scaleFactor /= 1000; ++pScaleName; } return res; } int main() { #define SPELL_IT(x) std::cout << #x " " << spell(x) << std::endl; SPELL_IT( 99); SPELL_IT( 300); SPELL_IT( 310); SPELL_IT( 1501); SPELL_IT( 12609); SPELL_IT( 512609); SPELL_IT(43112609); SPELL_IT(1234567890); return 0; }
Produce a functionally identical C++ code for the snippet given in VB.
Sub arrShellSort(ByVal arrData As Variant) Dim lngHold, lngGap As Long Dim lngCount, lngMin, lngMax As Long Dim varItem As Variant lngMin = LBound(arrData) lngMax = UBound(arrData) lngGap = lngMin Do While (lngGap < lngMax) lngGap = 3 * lngGap + 1 Loop Do While (lngGap > 1) lngGap = lngGap \ 3 For lngCount = lngGap + lngMin To lngMax varItem = arrData(lngCount) lngHold = lngCount Do While ((arrData(lngHold - lngGap) > varItem)) arrData(lngHold) = arrData(lngHold - lngGap) lngHold = lngHold - lngGap If (lngHold < lngMin + lngGap) Then Exit Do Loop arrData(lngHold) = varItem Next Loop arrShellSort = arrData End Sub
#include <time.h> #include <iostream> using namespace std; const int MAX = 126; class shell { public: shell() { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; } void sort( int* a, int count ) { _cnt = count; for( int x = 0; x < 9; x++ ) if( count > _gap[x] ) { _idx = x; break; } sortIt( a ); } private: void sortIt( int* arr ) { bool sorted = false; while( true ) { sorted = true; int st = 0; for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] ) { if( arr[st] > arr[x] ) { swap( arr[st], arr[x] ); sorted = false; } st = x; } if( ++_idx >= 8 ) _idx = 8; if( sorted && _idx == 8 ) break; } } void swap( int& a, int& b ) { int t = a; a = b; b = t; } int _gap[9], _idx, _cnt; }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX]; for( int x = 0; x < MAX; x++ ) arr[x] = rand() % MAX - rand() % MAX; cout << " Before: \n=========\n"; for( int x = 0; x < 7; x++ ) { for( int a = 0; a < 18; a++ ) { cout << arr[x * 18 + a] << " "; } cout << endl; } cout << endl; shell s; s.sort( arr, MAX ); cout << " After: \n========\n"; for( int x = 0; x < 7; x++ ) { for( int a = 0; a < 18; a++ ) { cout << arr[x * 18 + a] << " "; } cout << endl; } cout << endl << endl; return system( "pause" ); }
Write the same algorithm in C++ as shown in this VB implementation.
Public Class DoubleLinkList(Of T) Private m_Head As Node(Of T) Private m_Tail As Node(Of T) Public Sub AddHead(ByVal value As T) Dim node As New Node(Of T)(Me, value) If m_Head Is Nothing Then m_Head = Node m_Tail = m_Head Else node.Next = m_Head m_Head = node End If End Sub Public Sub AddTail(ByVal value As T) Dim node As New Node(Of T)(Me, value) If m_Tail Is Nothing Then m_Head = node m_Tail = m_Head Else node.Previous = m_Tail m_Tail = node End If End Sub Public ReadOnly Property Head() As Node(Of T) Get Return m_Head End Get End Property Public ReadOnly Property Tail() As Node(Of T) Get Return m_Tail End Get End Property Public Sub RemoveTail() If m_Tail Is Nothing Then Return If m_Tail.Previous Is Nothing Then m_Head = Nothing m_Tail = Nothing Else m_Tail = m_Tail.Previous m_Tail.Next = Nothing End If End Sub Public Sub RemoveHead() If m_Head Is Nothing Then Return If m_Head.Next Is Nothing Then m_Head = Nothing m_Tail = Nothing Else m_Head = m_Head.Next m_Head.Previous = Nothing End If End Sub End Class Public Class Node(Of T) Private ReadOnly m_Value As T Private m_Next As Node(Of T) Private m_Previous As Node(Of T) Private ReadOnly m_Parent As DoubleLinkList(Of T) Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T) m_Parent = parent m_Value = value End Sub Public Property [Next]() As Node(Of T) Get Return m_Next End Get Friend Set(ByVal value As Node(Of T)) m_Next = value End Set End Property Public Property Previous() As Node(Of T) Get Return m_Previous End Get Friend Set(ByVal value As Node(Of T)) m_Previous = value End Set End Property Public ReadOnly Property Value() As T Get Return m_Value End Get End Property Public Sub InsertAfter(ByVal value As T) If m_Next Is Nothing Then m_Parent.AddTail(value) ElseIf m_Previous Is Nothing Then m_Parent.AddHead(value) Else Dim node As New Node(Of T)(m_Parent, value) node.Previous = Me node.Next = Me.Next Me.Next.Previous = node Me.Next = node End If End Sub Public Sub Remove() If m_Next Is Nothing Then m_Parent.RemoveTail() ElseIf m_Previous Is Nothing Then m_Parent.RemoveHead() Else m_Previous.Next = Me.Next m_Next.Previous = Me.Previous End If End Sub End Class
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; numbers.insert(numbers.begin(), 9); numbers.insert(numbers.end(), 4); auto it = std::next(numbers.begin(), numbers.size() / 2); numbers.insert(it, 6); for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
Write a version of this VB function in C++ with identical behavior.
TYPE regChar Character AS STRING * 3 Count AS LONG END TYPE DIM iChar AS INTEGER DIM iCL AS INTEGER DIM iCountChars AS INTEGER DIM iFile AS INTEGER DIM i AS INTEGER DIM lMUC AS LONG DIM iMUI AS INTEGER DIM lLUC AS LONG DIM iLUI AS INTEGER DIM iMaxIdx AS INTEGER DIM iP AS INTEGER DIM iPause AS INTEGER DIM iPMI AS INTEGER DIM iPrint AS INTEGER DIM lHowMany AS LONG DIM lTotChars AS LONG DIM sTime AS SINGLE DIM strFile AS STRING DIM strTxt AS STRING DIM strDate AS STRING DIM strTime AS STRING DIM strKey AS STRING CONST LngReg = 256 CONST Letters = 1 CONST FALSE = 0 CONST TRUE = NOT FALSE strDate = DATE$ strTime = TIME$ iFile = FREEFILE DO CLS PRINT "This program counts letters or characters in a text file." PRINT INPUT "File to open: ", strFile OPEN strFile FOR BINARY AS #iFile IF LOF(iFile) > 0 THEN PRINT "Count: 1) Letters 2) Characters (1 or 2)"; DO strKey = INKEY$ LOOP UNTIL strKey = "1" OR strKey = "2" PRINT ". Option selected: "; strKey iCL = VAL(strKey) sTime = TIMER iP = POS(0) lHowMany = LOF(iFile) strTxt = SPACE$(LngReg) IF iCL = Letters THEN iMaxIdx = 26 ELSE iMaxIdx = 255 END IF IF iMaxIdx <> iPMI THEN iPMI = iMaxIdx REDIM rChar(0 TO iMaxIdx) AS regChar FOR i = 0 TO iMaxIdx IF iCL = Letters THEN strTxt = CHR$(i + 65) IF i = 26 THEN strTxt = CHR$(165) ELSE SELECT CASE i CASE 0: strTxt = "nul" CASE 7: strTxt = "bel" CASE 9: strTxt = "tab" CASE 10: strTxt = "lf" CASE 11: strTxt = "vt" CASE 12: strTxt = "ff" CASE 13: strTxt = "cr" CASE 28: strTxt = "fs" CASE 29: strTxt = "gs" CASE 30: strTxt = "rs" CASE 31: strTxt = "us" CASE 32: strTxt = "sp" CASE ELSE: strTxt = CHR$(i) END SELECT END IF rChar(i).Character = strTxt NEXT i ELSE FOR i = 0 TO iMaxIdx rChar(i).Count = 0 NEXT i END IF PRINT "Looking for "; IF iCL = Letters THEN PRINT "letters."; ELSE PRINT "characters."; PRINT " File is"; STR$(lHowMany); " in size. Working"; : COLOR 23: PRINT "..."; : COLOR (7) DO WHILE LOC(iFile) < LOF(iFile) IF LOC(iFile) + LngReg > LOF(iFile) THEN strTxt = SPACE$(LOF(iFile) - LOC(iFile)) END IF GET #iFile, , strTxt FOR i = 1 TO LEN(strTxt) IF iCL = Letters THEN iChar = ASC(UCASE$(MID$(strTxt, i, 1))) SELECT CASE iChar CASE 164: iChar = 165 CASE 160: iChar = 65 CASE 130, 144: iChar = 69 CASE 161: iChar = 73 CASE 162: iChar = 79 CASE 163, 129: iChar = 85 END SELECT iChar = iChar - 65 IF iChar >= 0 AND iChar <= 25 THEN rChar(iChar).Count = rChar(iChar).Count + 1 ELSEIF iChar = 100 THEN rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1 END IF ELSE iChar = ASC(MID$(strTxt, i, 1)) rChar(iChar).Count = rChar(iChar).Count + 1 END IF NEXT i LOOP CLOSE #iFile lMUC = 0 iMUI = 0 lLUC = 2147483647 iLUI = 0 iPrint = FALSE lTotChars = 0 iCountChars = 0 iPause = FALSE CLS IF iCL = Letters THEN PRINT "Letters found: "; ELSE PRINT "Characters found: "; FOR i = 0 TO iMaxIdx IF lMUC < rChar(i).Count THEN lMUC = rChar(i).Count iMUI = i END IF IF rChar(i).Count > 0 THEN strTxt = "" IF iPrint THEN strTxt = ", " ELSE iPrint = TRUE strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character)) strTxt = strTxt + "=" + LTRIM$(STR$(rChar(i).Count)) iP = POS(0) IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN PRINT "," IF CSRLIN >= 23 AND NOT iPause THEN iPause = TRUE PRINT "Press a key to continue..." DO strKey = INKEY$ LOOP UNTIL strKey <> "" END IF strTxt = MID$(strTxt, 3) END IF PRINT strTxt; lTotChars = lTotChars + rChar(i).Count iCountChars = iCountChars + 1 IF lLUC > rChar(i).Count THEN lLUC = rChar(i).Count iLUI = i END IF END IF NEXT i PRINT "." PRINT PRINT "File analyzed....................: "; strFile PRINT "Looked for.......................: "; : IF iCL = Letters THEN PRINT "Letters" ELSE PRINT "Characters" PRINT "Total characters in file.........:"; lHowMany PRINT "Total characters counted.........:"; lTotChars IF iCL = Letters THEN PRINT "Characters discarded on count....:"; lHowMany - lTotChars PRINT "Distinct characters found in file:"; iCountChars; "of"; iMaxIdx + 1 PRINT "Most used character was..........: "; iPrint = FALSE FOR i = 0 TO iMaxIdx IF rChar(i).Count = lMUC THEN IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE PRINT RTRIM$(LTRIM$(rChar(i).Character)); END IF NEXT i PRINT " ("; LTRIM$(STR$(rChar(iMUI).Count)); " times)" PRINT "Least used character was.........: "; iPrint = FALSE FOR i = 0 TO iMaxIdx IF rChar(i).Count = lLUC THEN IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE PRINT RTRIM$(LTRIM$(rChar(i).Character)); END IF NEXT i PRINT " ("; LTRIM$(STR$(rChar(iLUI).Count)); " times)" PRINT "Time spent in the process........:"; TIMER - sTime; "seconds" ELSE CLOSE #iFile KILL strFile PRINT PRINT "File does not exist." END IF PRINT PRINT "Again? (Y/n)" DO strTxt = UCASE$(INKEY$) LOOP UNTIL strTxt = "N" OR strTxt = "Y" OR strTxt = CHR$(13) OR strTxt = CHR$(27) LOOP UNTIL strTxt = "N" OR strTxt = CHR$(27) CLS PRINT "End of execution." PRINT "Start time: "; strDate; " "; strTime; ", end time: "; DATE$; " "; TIME$; "." END
#include <fstream> #include <iostream> int main() { std::ifstream input("filename.txt", std::ios_base::binary); if (!input) { std::cerr << "error: can't open file\n"; return -1; } size_t count[256]; std::fill_n(count, 256, 0); for (char c; input.get(c); ++count[uint8_t(c)]) ; for (size_t i = 0; i < 256; ++i) { if (count[i] && isgraph(i)) { std::cout << char(i) << " = " << count[i] << '\n'; } } }
Generate a C++ translation of this VB snippet without changing its computational steps.
Dim s As String = "123" s = CStr(CInt("123") + 1) s = (CInt("123") + 1).ToString
#include <cstdlib> #include <string> #include <sstream> std::string s = "12345"; int i; std::istringstream(s) >> i; i++; std::ostringstream oss; if (oss << i) s = oss.str();
Produce a language-to-language conversion: from VB to C++, same semantics.
Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean) Dim i As Integer, stReplace As String If bSpace = True Then stReplace = " " Else stReplace = "" End If For i = 1 To Len(stStripChars) stString = Replace(stString, Mid(stStripChars, i, 1), stReplace) Next i StripChars = stString End Function
#include <algorithm> #include <iostream> #include <string> std::string stripchars(std::string str, const std::string &chars) { str.erase( std::remove_if(str.begin(), str.end(), [&](char c){ return chars.find(c) != std::string::npos; }), str.end() ); return str; } int main() { std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n'; return 0; }
Convert this VB block to C++, preserving its control flow and logic.
Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean) Dim i As Integer, stReplace As String If bSpace = True Then stReplace = " " Else stReplace = "" End If For i = 1 To Len(stStripChars) stString = Replace(stString, Mid(stStripChars, i, 1), stReplace) Next i StripChars = stString End Function
#include <algorithm> #include <iostream> #include <string> std::string stripchars(std::string str, const std::string &chars) { str.erase( std::remove_if(str.begin(), str.end(), [&](char c){ return chars.find(c) != std::string::npos; }), str.end() ); return str; } int main() { std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n'; return 0; }
Port the following code from VB to C++ with equivalent syntax and logic.
Private Function mean(v() As Double, ByVal leng As Integer) As Variant Dim sum As Double, i As Integer sum = 0: i = 0 For i = 0 To leng - 1 sum = sum + vv Next i If leng = 0 Then mean = CVErr(xlErrDiv0) Else mean = sum / leng End If End Function Public Sub main() Dim v(4) As Double Dim i As Integer, leng As Integer v(0) = 1# v(1) = 2# v(2) = 2.178 v(3) = 3# v(4) = 3.142 For leng = 5 To 0 Step -1 Debug.Print "mean["; For i = 0 To leng - 1 Debug.Print IIf(i, "; " & v(i), "" & v(i)); Next i Debug.Print "] = "; mean(v, leng) Next leng End Sub
#include <vector> double mean(const std::vector<double>& numbers) { if (numbers.size() == 0) return 0; double sum = 0; for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++) sum += *i; return sum / numbers.size(); }
Write the same algorithm in C++ as shown in this VB implementation.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " commandtable = Split(s, " ") Dim i As Integer, word As Variant, number As Integer For i = LBound(commandtable) To UBound(commandtable) word = commandtable(i) If Len(word) > 0 Then i = i + 1 Do While Len(commandtable(i)) = 0: i = i + 1: Loop number = Val(commandtable(i)) If number > 0 Then command_table.Add Key:=word, Item:=number Else command_table.Add Key:=word, Item:=Len(word) i = i - 1 End If End If Next i For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } bool parse_integer(const std::string& word, int& value) { try { size_t pos; int i = std::stoi(word, &pos, 10); if (pos < word.length()) return false; value = i; return true; } catch (const std::exception& ex) { return false; } } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::istringstream is(table); std::string word; std::vector<std::string> words; while (is >> word) { uppercase(word); words.push_back(word); } for (size_t i = 0, n = words.size(); i < n; ++i) { word = words[i]; int len = word.length(); if (i + 1 < n && parse_integer(words[i + 1], len)) ++i; commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Preserve the algorithm and functionality while converting the code from VB to C++.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " commandtable = Split(s, " ") Dim i As Integer, word As Variant, number As Integer For i = LBound(commandtable) To UBound(commandtable) word = commandtable(i) If Len(word) > 0 Then i = i + 1 Do While Len(commandtable(i)) = 0: i = i + 1: Loop number = Val(commandtable(i)) If number > 0 Then command_table.Add Key:=word, Item:=number Else command_table.Add Key:=word, Item:=Len(word) i = i - 1 End If End If Next i For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } bool parse_integer(const std::string& word, int& value) { try { size_t pos; int i = std::stoi(word, &pos, 10); if (pos < word.length()) return false; value = i; return true; } catch (const std::exception& ex) { return false; } } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::istringstream is(table); std::string word; std::vector<std::string> words; while (is >> word) { uppercase(word); words.push_back(word); } for (size_t i = 0, n = words.size(); i < n; ++i) { word = words[i]; int len = word.length(); if (i + 1 < n && parse_integer(words[i + 1], len)) ++i; commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Change the programming language of this snippet from VB to C++ without modifying what it does.
Private Function tokenize(s As String, sep As String, esc As String) As Collection Dim ret As New Collection Dim this As String Dim skip As Boolean If Len(s) <> 0 Then For i = 1 To Len(s) si = Mid(s, i, 1) If skip Then this = this & si skip = False Else If si = esc Then skip = True Else If si = sep Then ret.Add this this = "" Else this = this & si End If End If End If Next i ret.Add this End If Set tokenize = ret End Function Public Sub main() Dim out As Collection Set out = tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^") Dim outstring() As String ReDim outstring(out.Count - 1) For i = 0 To out.Count - 1 outstring(i) = out(i + 1) Next i Debug.Print Join(outstring, ", ") End Sub
#include <iostream> #include <stdexcept> #include <string> #include <vector> using namespace std; vector<string> tokenize(const string& input, char seperator, char escape) { vector<string> output; string token; bool inEsc = false; for (char ch : input) { if (inEsc) { inEsc = false; } else if (ch == escape) { inEsc = true; continue; } else if (ch == seperator) { output.push_back(token); token = ""; continue; } token += ch; } if (inEsc) throw new invalid_argument("Invalid terminal escape"); output.push_back(token); return output; } int main() { string sample = "one^|uno||three^^^^|four^^^|^cuatro|"; cout << sample << endl; cout << '['; for (auto t : tokenize(sample, '|', '^')) { cout << '"' << t << "\", "; } cout << ']' << endl; return 0; }
Change the programming language of this snippet from VB to C++ without modifying what it does.
Public Sub hello_world_text Debug.Print "Hello World!" End Sub
#include <iostream> int main () { std::cout << "Hello world!" << std::endl; }
Write the same algorithm in C++ as shown in this VB implementation.
Module ForwardDifference Sub Main() Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}) For i As UInteger = 0 To 9 Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray())) Next Console.ReadKey() End Sub Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer) If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers") For i As Integer = 1 To Level Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _ Select Numbers(n + 1) - Numbers(n)).ToList() Next Return Numbers End Function End Module
#include <vector> #include <iterator> #include <algorithm> template<typename InputIterator, typename OutputIterator> OutputIterator forward_difference(InputIterator first, InputIterator last, OutputIterator dest) { if (first == last) return dest; typedef typename std::iterator_traits<InputIterator>::value_type value_type; value_type temp = *first++; while (first != last) { value_type temp2 = *first++; *dest++ = temp2 - temp; temp = temp2; } return dest; } template<typename InputIterator, typename OutputIterator> OutputIterator nth_forward_difference(int order, InputIterator first, InputIterator last, OutputIterator dest) { if (order == 0) return std::copy(first, last, dest); if (order == 1) return forward_difference(first, last, dest); typedef typename std::iterator_traits<InputIterator>::value_type value_type; std::vector<value_type> temp_storage; forward_difference(first, last, std::back_inserter(temp_storage)); typename std::vector<value_type>::iterator begin = temp_storage.begin(), end = temp_storage.end(); for (int i = 1; i < order-1; ++i) end = forward_difference(begin, end, begin); return forward_difference(begin, end, dest); } #include <iostream> int main() { double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 }; std::vector<double> dest; nth_forward_difference(1, array, array+10, std::back_inserter(dest)); std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; double* end = nth_forward_difference(3, array, array+10, array); for (double* p = array; p < end; ++p) std::cout << *p << " "; std::cout << std::endl; return 0; }
Write the same algorithm in C++ as shown in this VB implementation.
Option Explicit Sub FirstTwentyPrimes() Dim count As Integer, i As Long, t(19) As String Do i = i + 1 If IsPrime(i) Then t(count) = i count = count + 1 End If Loop While count <= UBound(t) Debug.Print Join(t, ", ") End Sub Function IsPrime(Nb As Long) As Boolean If Nb = 2 Then IsPrime = True ElseIf Nb < 2 Or Nb Mod 2 = 0 Then Exit Function Else Dim i As Long For i = 3 To Sqr(Nb) Step 2 If Nb Mod i = 0 Then Exit Function Next IsPrime = True End If End Function
#include <cmath> bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false; return true; }
Keep all operations the same but rewrite the snippet in C++.
Function binomial(n,k) binomial = factorial(n)/(factorial(n-k)*factorial(k)) End Function Function factorial(n) If n = 0 Then factorial = 1 Else For i = n To 1 Step -1 If i = n Then factorial = n Else factorial = factorial * i End If Next End If End Function WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3) WScript.StdOut.WriteLine
double Factorial(double nValue) { double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; } double binomialCoefficient(double n, double k) { if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0; if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n; return Factorial(n) /(Factorial(k)*Factorial((n - k))); }
Produce a functionally identical C++ code for the snippet given in VB.
Dim coll As New Collection coll.Add "apple" coll.Add "banana"
int a[5]; a[0] = 1; int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; #include <string> std::string strings[4];
Generate an equivalent PHP version of this C# code.
static void bitwise(int a, int b) { Console.WriteLine("a and b is {0}", a & b); Console.WriteLine("a or b is {0}", a | b); Console.WriteLine("a xor b is {0}", a ^ b); Console.WriteLine("not a is {0}", ~a); Console.WriteLine("a lshift b is {0}", a << b); Console.WriteLine("a arshift b is {0}", a >> b); uint c = (uint)a; Console.WriteLine("c rshift b is {0}", c >> b); }
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Port the provided C# code into PHP while preserving the original functionality.
foreach (string readLine in File.ReadLines("FileName")) DoSomething(readLine);
<?php $file = fopen(__FILE__, 'r'); // read current file while ($line = fgets($file)) { $line = rtrim($line); // removes linebreaks and spaces at end echo strrev($line) . "\n"; // reverse line and upload it }
Change the programming language of this snippet from C# to PHP without modifying what it does.
public static class BaseConverter { public static long stringToLong(string s, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); checked { int slen = s.Length; long result = 0; bool isNegative = false; for ( int i = 0; i < slen; i++ ) { char c = s[i]; int num; if ( c == '-' ) { if ( i != 0 ) throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s"); isNegative = true; continue; } if ( c > 0x2F && c < 0x3A ) num = c - 0x30; else if ( c > 0x40 && c < 0x5B ) num = c - 0x37; else if ( c > 0x60 && c < 0x7B ) num = c - 0x57; else throw new ArgumentException("The string contains an invalid character '" + c + "'", "s"); if ( num >= b ) throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s"); result *= b; result += num; } if ( isNegative ) result = -result; return result; } } public static string longToString(long n, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); if ( b == 10 ) return n.ToString(); checked { long longBase = b; StringBuilder sb = new StringBuilder(); if ( n < 0 ) { n = -n; sb.Append('-'); } long div = 1; while ( n / div >= b ) div *= b; while ( true ) { byte digit = (byte) (n / div); if ( digit < 10 ) sb.Append((char) (digit + 0x30)); else sb.Append((char) (digit + 0x57)); if ( div == 1 ) break; n %= div; div /= b; } return sb.ToString(); } } }
base_convert("26", 10, 16); // returns "1a"
Generate an equivalent PHP version of this C# code.
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Rewrite the snippet below in PHP so it works the same as the original C# code.
public class Crc32 { #region Constants private const UInt32 s_generator = 0xEDB88320; #endregion #region Constructors public Crc32() { m_checksumTable = Enumerable.Range(0, 256).Select(i => { var tableEntry = (uint)i; for (var j = 0; j < 8; ++j) { tableEntry = ((tableEntry & 1) != 0) ? (s_generator ^ (tableEntry >> 1)) : (tableEntry >> 1); } return tableEntry; }).ToArray(); } #endregion #region Methods public UInt32 Get<T>(IEnumerable<T> byteStream) { try { return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8))); } catch (FormatException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (InvalidCastException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (OverflowException e) { throw new CrcException("Could not read the stream out as bytes.", e); } } #endregion #region Fields private readonly UInt32[] m_checksumTable; #endregion }
printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));
Change the following C# code into PHP without altering its purpose.
public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { MyClass instance = new MyClass(); instance.SomeMethod(); instance.Variable = 99; System.Console.WriteLine( "Variable=" + instance.Variable.ToString() ); } }
class MyClass { public static $classVar; public $instanceVar; // can also initialize it here function __construct() { $this->instanceVar = 0; } function someMethod() { $this->instanceVar = 1; self::$classVar = 3; } } $myObj = new MyClass();
Change the programming language of this snippet from C# to PHP without modifying what it does.
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
Convert this C# snippet to PHP and keep its semantics consistent.
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
Rewrite this program in PHP while keeping its functionality equivalent to the C# version.
static int Fib(int n) { if (n < 0) throw new ArgumentException("Must be non negativ", "n"); Func<int, int> fib = null; fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p; return fib(n); }
<?php function fib($n) { if ($n < 0) throw new Exception('Negative numbers not allowed'); $f = function($n) { // This function must be called using call_user_func() only if ($n < 2) return 1; else { $g = debug_backtrace()[1]['args'][0]; return call_user_func($g, $n-1) + call_user_func($g, $n-2); } }; return call_user_func($f, $n); } echo fib(8), "\n"; ?>
Transform the following C# implementation into PHP, maintaining the same output and logic.
using System; using System.IO; class Program { static void Main(string[] args) { File.Create("output.txt"); File.Create(@"\output.txt"); Directory.CreateDirectory("docs"); Directory.CreateDirectory(@"\docs"); } }
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Write the same code in PHP as shown below in C#.
using System; interface IOperable { string Operate(); } class Inoperable { } class Operable : IOperable { public string Operate() { return "Delegate implementation."; } } class Delegator : IOperable { object Delegate; public string Operate() { var operable = Delegate as IOperable; return operable != null ? operable.Operate() : "Default implementation."; } static void Main() { var delegator = new Delegator(); foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() }) { delegator.Delegate = @delegate; Console.WriteLine(delegator.Operate()); } } }
class Delegator { function __construct() { $this->delegate = NULL ; } function operation() { if(method_exists($this->delegate, "thing")) return $this->delegate->thing() ; return 'default implementation' ; } } class Delegate { function thing() { return 'Delegate Implementation' ; } } $a = new Delegator() ; print "{$a->operation()}\n" ; $a->delegate = 'A delegate may be any object' ; print "{$a->operation()}\n" ; $a->delegate = new Delegate() ; print "{$a->operation()}\n" ;
Keep all operations the same but rewrite the snippet in PHP.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
Port the following code from C# to PHP with equivalent syntax and logic.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
Change the programming language of this snippet from C# to PHP without modifying what it does.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { int[] a = { 1, 2, 3 }; int[] b = { 4, 5, 6 }; int[] c = new int[a.Length + b.Length]; a.CopyTo(c, 0); b.CopyTo(c, a.Length); foreach(int n in c) { Console.WriteLine(n.ToString()); } } } }
$arr1 = array(1, 2, 3); $arr2 = array(4, 5, 6); $arr3 = array_merge($arr1, $arr2);
Transform the following C# implementation into PHP, maintaining the same output and logic.
using System; namespace C_Sharp_Console { class example { static void Main() { string word; int num; Console.Write("Enter an integer: "); num = Console.Read(); Console.Write("Enter a String: "); word = Console.ReadLine(); } } }
#!/usr/bin/php <?php $string = fgets(STDIN); $integer = (int) fgets(STDIN);
Convert this C# block to PHP, preserving its control flow and logic.
using System; using System.Collections.Generic; namespace Tests_With_Framework_4 { class Bag : IEnumerable<Bag.Item> { List<Item> items; const int MaxWeightAllowed = 400; public Bag() { items = new List<Item>(); } void AddItem(Item i) { if ((TotalWeight + i.Weight) <= MaxWeightAllowed) items.Add(i); } public void Calculate(List<Item> items) { foreach (Item i in Sorte(items)) { AddItem(i); } } List<Item> Sorte(List<Item> inputItems) { List<Item> choosenItems = new List<Item>(); for (int i = 0; i < inputItems.Count; i++) { int j = -1; if (i == 0) { choosenItems.Add(inputItems[i]); } if (i > 0) { if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j)) { choosenItems.Add(inputItems[i]); } } } return choosenItems; } bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd) { if (!(lastBound < 0)) { if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV ) { indxToAdd = lastBound; } return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd); } if (indxToAdd > -1) { choosenItems.Insert(indxToAdd, knapsackItems[i]); return true; } return false; } #region IEnumerable<Item> Members IEnumerator<Item> IEnumerable<Item>.GetEnumerator() { foreach (Item i in items) yield return i; } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return items.GetEnumerator(); } #endregion public int TotalWeight { get { var sum = 0; foreach (Item i in this) { sum += i.Weight; } return sum; } } public class Item { public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return Weight-Value; } } public override string ToString() { return "Name : " + Name + " Wieght : " + Weight + " Value : " + Value + " ResultWV : " + ResultWV; } } } class Program { static void Main(string[] args) {List<Bag.Item> knapsackItems = new List<Bag.Item>(); knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 }); knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 }); knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 }); knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 }); knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 }); knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 }); knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 }); knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 }); knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 }); knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 }); knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 }); Bag b = new Bag(); b.Calculate(knapsackItems); b.All(x => { Console.WriteLine(x); return true; }); Console.WriteLine(b.Sum(x => x.Weight)); Console.ReadKey(); } } }
######################################################### # 0-1 Knapsack Problem Solve with memoization optimize and index returns # $w = weight of item # $v = value of item # $i = index # $aW = Available Weight # $m = Memo items array # PHP Translation from Python, Memoization, # and index return functionality added by Brian Berneker # ######################################################### function knapSolveFast2($w, $v, $i, $aW, &$m) { global $numcalls; $numcalls ++; if (isset($m[$i][$aW])) { return array( $m[$i][$aW], $m['picked'][$i][$aW] ); } else { if ($i == 0) { if ($w[$i] <= $aW) { // Will this item fit? $m[$i][$aW] = $v[$i]; // Memo this item $m['picked'][$i][$aW] = array($i); // and the picked item return array($v[$i],array($i)); // Return the value of this item and add it to the picked list } else { $m[$i][$aW] = 0; // Memo zero $m['picked'][$i][$aW] = array(); // and a blank array entry... return array(0,array()); // Return nothing } } list ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m); if ($w[$i] > $aW) { // Does it return too many? $m[$i][$aW] = $without_i; // Memo without including this one $m['picked'][$i][$aW] = $without_PI; // and a blank array entry... return array($without_i, $without_PI); // and return it } else { list ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m); $with_i += $v[$i]; // ..and add the value of this one.. if ($with_i > $without_i) { $res = $with_i; $picked = $with_PI; array_push($picked,$i); } else { $res = $without_i; $picked = $without_PI; } $m[$i][$aW] = $res; // Store it in the memo $m['picked'][$i][$aW] = $picked; // and store the picked item return array ($res,$picked); // and then return it } } } $items4 = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese","beer","suntan cream","camera","t-shirt","trousers","umbrella","waterproof trousers","waterproof overclothes","note-case","sunglasses","towel","socks","book"); $w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30); $v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10); ## Initialize $numcalls = 0; $m = array(); $pickedItems = array(); ## Solve list ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m); # Display Result echo "<b>Items:</b><br>".join(", ",$items4)."<br>"; echo "<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>"; echo "<b>Array Indices:</b><br>".join(",",$pickedItems)."<br>"; echo "<b>Chosen Items:</b><br>"; echo "<table border cellspacing=0>"; echo "<tr><td>Item</td><td>Value</td><td>Weight</td></tr>"; $totalVal = $totalWt = 0; foreach($pickedItems as $key) { $totalVal += $v4[$key]; $totalWt += $w4[$key]; echo "<tr><td>".$items4[$key]."</td><td>".$v4[$key]."</td><td>".$w4[$key]."</td></tr>"; } echo "<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>"; echo "</table><hr>";
Please provide an equivalent version of this C# code in PHP.
using System; class Program { static void Main(string[] args) { var cube = new Func<double, double>(x => Math.Pow(x, 3.0)); var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0)); var functionTuples = new[] { (forward: Math.Sin, backward: Math.Asin), (forward: Math.Cos, backward: Math.Acos), (forward: cube, backward: croot) }; foreach (var ft in functionTuples) { Console.WriteLine(ft.backward(ft.forward(0.5))); } } }
$compose = function ($f, $g) { return function ($x) use ($f, $g) { return $f($g($x)); }; }; $fn = array('sin', 'cos', function ($x) { return pow($x, 3); }); $inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); }); for ($i = 0; $i < 3; $i++) { $f = $compose($inv[$i], $fn[$i]); echo $f(0.5), PHP_EOL; }
Port the following code from C# to PHP with equivalent syntax and logic.
namespace RosettaCode.ProperDivisors { using System; using System.Collections.Generic; using System.Linq; internal static class Program { private static IEnumerable<int> ProperDivisors(int number) { return Enumerable.Range(1, number / 2) .Where(divisor => number % divisor == 0); } private static void Main() { foreach (var number in Enumerable.Range(1, 10)) { Console.WriteLine("{0}: {{{1}}}", number, string.Join(", ", ProperDivisors(number))); } var record = Enumerable.Range(1, 20000).Select(number => new { Number = number, Count = ProperDivisors(number).Count() }).OrderByDescending(currentRecord => currentRecord.Count).First(); Console.WriteLine("{0}: {1}", record.Number, record.Count); } } }
<?php function ProperDivisors($n) { yield 1; $large_divisors = []; for ($i = 2; $i <= sqrt($n); $i++) { if ($n % $i == 0) { yield $i; if ($i*$i != $n) { $large_divisors[] = $n / $i; } } } foreach (array_reverse($large_divisors) as $i) { yield $i; } } assert([1, 2, 4, 5, 10, 20, 25, 50] == iterator_to_array(ProperDivisors(100))); foreach (range(1, 10) as $n) { echo "$n =>"; foreach (ProperDivisors($n) as $divisor) { echo " $divisor"; } echo "\n"; } $divisorsCount = []; for ($i = 1; $i < 20000; $i++) { $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i; } ksort($divisorsCount); echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n"; echo "They have ", key($divisorsCount), " divisors.\n";
Translate this program into PHP but keep the logic exactly as in C#.
using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string str = "I am a string"; if (new Regex("string$").IsMatch(str)) { Console.WriteLine("Ends with string."); } str = new Regex(" a ").Replace(str, " another "); Console.WriteLine(str); } }
$string = 'I am a string'; # Test if (preg_match('/string$/', $string)) { echo "Ends with 'string'\n"; } # Replace $string = preg_replace('/\ba\b/', 'another', $string); echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";
Translate this program into PHP but keep the logic exactly as in C#.
static class Program { static void Main() { System.Collections.Hashtable h = new System.Collections.Hashtable(); string[] keys = { "foo", "bar", "val" }; string[] values = { "little", "miss", "muffet" }; System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length."); for (int i = 0; i < keys.Length; i++) { h.Add(keys[i], values[i]); } } }
$keys = array('a', 'b', 'c'); $values = array(1, 2, 3); $hash = array_combine($keys, $values);
Rewrite the snippet below in PHP so it works the same as the original C# code.
using System; using System.Linq; using System.Collections.Generic; public struct Card { public Card(string rank, string suit) : this() { Rank = rank; Suit = suit; } public string Rank { get; } public string Suit { get; } public override string ToString() => $"{Rank} of {Suit}"; } public class Deck : IEnumerable<Card> { static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" }; static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" }; readonly List<Card> cards; public Deck() { cards = (from suit in suits from rank in ranks select new Card(rank, suit)).ToList(); } public int Count => cards.Count; public void Shuffle() { var random = new Random(); for (int i = 0; i < cards.Count; i++) { int r = random.Next(i, cards.Count); var temp = cards[i]; cards[i] = cards[r]; cards[r] = temp; } } public Card Deal() { int last = cards.Count - 1; Card card = cards[last]; cards.RemoveAt(last); return card; } public IEnumerator<Card> GetEnumerator() { for (int i = cards.Count - 1; i >= 0; i--) yield return cards[i]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); }
class Card { protected static $suits = array( '♠', '♥', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __construct( $suit, $pip ) { if( !in_array( $suit, self::$suits ) ) { throw new InvalidArgumentException( 'Invalid suit' ); } if( !in_array( $pip, self::$pips ) ) { throw new InvalidArgumentException( 'Invalid pip' ); } $this->suit = $suit; $this->pip = $pip; } public function getSuit() { return $this->suit; } public function getPip() { return $this->pip; } public function getSuitOrder() { if( !isset( $this->suitOrder ) ) { $this->suitOrder = array_search( $this->suit, self::$suits ); } return $this->suitOrder; } public function getPipOrder() { if( !isset( $this->pipOrder ) ) { $this->pipOrder = array_search( $this->pip, self::$pips ); } return $this->pipOrder; } public function getOrder() { if( !isset( $this->order ) ) { $suitOrder = $this->getSuitOrder(); $pipOrder = $this->getPipOrder(); $this->order = $pipOrder * count( self::$suits ) + $suitOrder; } return $this->order; } public function compareSuit( Card $other ) { return $this->getSuitOrder() - $other->getSuitOrder(); } public function comparePip( Card $other ) { return $this->getPipOrder() - $other->getPipOrder(); } public function compare( Card $other ) { return $this->getOrder() - $other->getOrder(); } public function __toString() { return $this->suit . $this->pip; } public static function getSuits() { return self::$suits; } public static function getPips() { return self::$pips; } } class CardCollection implements Countable, Iterator { protected $cards = array(); protected function __construct( array $cards = array() ) { foreach( $cards as $card ) { $this->addCard( $card ); } } public function count() { return count( $this->cards ); } public function key() { return key( $this->cards ); } public function valid() { return null !== $this->key(); } public function next() { next( $this->cards ); } public function current() { return current( $this->cards ); } public function rewind() { reset( $this->cards ); } public function sort( $comparer = null ) { $comparer = $comparer ?: function( $a, $b ) { return $a->compare( $b ); }; if( !is_callable( $comparer ) ) { throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' ); } usort( $this->cards, $comparer ); return $this; } public function toString() { return implode( ' ', $this->cards ); } public function __toString() { return $this->toString(); } protected function addCard( Card $card ) { if( in_array( $card, $this->cards ) ) { throw new DomainException( 'Card is already present in this collection' ); } $this->cards[] = $card; } } class Deck extends CardCollection { public function __construct( $shuffled = false ) { foreach( Card::getSuits() as $suit ) { foreach( Card::getPips() as $pip ) { $this->addCard( new Card( $suit, $pip ) ); } } if( $shuffled ) { $this->shuffle(); } } public function deal( $amount = 1, CardCollection $cardCollection = null ) { if( !is_int( $amount ) || $amount < 1 ) { throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' ); } if( $amount > count( $this->cards ) ) { throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' ); } $cards = array_splice( $this->cards, 0, $amount ); $cardCollection = $cardCollection ?: new CardCollection; foreach( $cards as $card ) { $cardCollection->addCard( $card ); } return $cardCollection; } public function shuffle() { shuffle( $this->cards ); } } class Hand extends CardCollection { public function __construct() {} public function play( $position ) { if( !isset( $this->cards[ $position ] ) ) { throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' ); } $result = array_splice( $this->cards, $position, 1 ); return $result[ 0 ]; } }
Translate the given C# code snippet into PHP without altering its behavior.
int[] numbers = new int[10];
$NumberArray = array(0, 1, 2, 3, 4, 5, 6); $LetterArray = array("a", "b", "c", "d", "e", "f"); $simpleForm = ['apple', 'orange'];