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.
Private Function call_fn(f As String, n As Long) As Long call_fn = Application.Run(f, f, n) End Function Private Function Y(f As String) As String Y = f End Function Private Function fac(self As String, n As Long) As Long If n > 1 Then fac = n * call_fn(self, n - 1) Else fac = 1 End If End Function Private Function fib(self As String, n As Long) As Long If n > 1 Then fib = call_fn(self, n - 1) + call_fn(self, n - 2) Else fib = n End If End Function Private Sub test(name As String) Dim f As String: f = Y(name) Dim i As Long Debug.Print name For i = 1 To 10 Debug.Print call_fn(f, i); Next i Debug.Print End Sub Public Sub main() test "fac" test "fib" End Sub
#include <iostream> #include <functional> template <typename F> struct RecursiveFunc { std::function<F(RecursiveFunc)> o; }; template <typename A, typename B> std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) { RecursiveFunc<std::function<B(A)>> r = { std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) { return f(std::function<B(A)>([w](A x) { return w.o(w)(x); })); }) }; return r.o(r); } typedef std::function<int(int)> Func; typedef std::function<Func(Func)> FuncFunc; FuncFunc almost_fac = [](Func f) { return Func([f](int n) { if (n <= 1) return 1; return n * f(n - 1); }); }; FuncFunc almost_fib = [](Func f) { return Func([f](int n) { if (n <= 2) return 1; return f(n - 1) + f(n - 2); }); }; int main() { auto fib = Y(almost_fib); auto fac = Y(almost_fac); std::cout << "fib(10) = " << fib(10) << std::endl; std::cout << "fac(10) = " << fac(10) << std::endl; return 0; }
Port the following code from VB to C++ with equivalent syntax and logic.
Type Contact Name As String firstname As String Age As Byte End Type Function SetContact(N As String, Fn As String, A As Byte) As Contact SetContact.Name = N SetContact.firstname = Fn SetContact.Age = A End Function Sub Test_SetContact() Dim Cont As Contact Cont = SetContact("SMITH", "John", 23) Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old." End Sub
#include <algorithm> #include <array> #include <cstdint> #include <iostream> #include <tuple> std::tuple<int, int> minmax(const int * numbers, const std::size_t num) { const auto maximum = std::max_element(numbers, numbers + num); const auto minimum = std::min_element(numbers, numbers + num); return std::make_tuple(*minimum, *maximum) ; } int main( ) { const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}}; int min{}; int max{}; std::tie(min, max) = minmax(numbers.data(), numbers.size()); std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ; }
Transform the following VB implementation into C++, maintaining the same output and logic.
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
Write a version of this VB function in C++ with identical behavior.
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
Transform the following VB implementation into C++, maintaining the same output and logic.
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant GenerateNewDigits: For i = 1 To 4 Digit(i) = [randbetween(1,9)] Next i GetUserExpression: bValidExpression = True stFailMessage = "" stFailDigits = "" stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") bValidDigits = True stFailDigits = "" For i = 1 To 4 If InStr(stUserExpression, Digit(i)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Digit(i) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 1 To Len(stUserExpression) If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" iDigitCount = 0 For i = 1 To Len(stUserExpression) If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then iDigitCount = iDigitCount + 1 If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If End If Next i If iDigitCount > 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr End If If iDigitCount < 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr End If If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 11 To 99 If Not InStr(stUserExpression, i) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & i End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr End If On Error GoTo EvalFail vResult = Evaluate(stUserExpression) If Not vResult = 24 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult End If If bValidExpression = False Then vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") If vTryAgain = vbRetry Then vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") If vSameDigits = vbYes Then GoTo GetUserExpression Else GoTo GenerateNewDigits End If End If Else vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") If vTryAgain = vbRetry Then GoTo GenerateNewDigits End If End If Exit Sub EvalFail: bValidExpression = False vResult = Err.Description Resume End Sub
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); stk.push(f(a, b)); } void parse(char c) { if(c >= '0' && c <= '9') { stk.push(c - '0'); digits.insert(c - '0'); } else if(c == '+') op([](double a, double b) {return a+b;}); else if(c == '-') op([](double a, double b) {return a-b;}); else if(c == '*') op([](double a, double b) {return a*b;}); else if(c == '/') op([](double a, double b) {return a/b;}); } void parse(string s) { for(int i = 0; i < s.size(); ++i) parse(s[i]); } double getResult() { if(stk.size() != 1) throw "Improperly written expression"; return stk.top(); } }; int main() { random_device seed; mt19937 engine(seed()); uniform_int_distribution<> distribution(1, 9); auto rnd = bind(distribution, engine); multiset<int> digits; cout << "Make 24 with the digits: "; for(int i = 0; i < 4; ++i) { int n = rnd(); cout << " " << n; digits.insert(n); } cout << endl; RPNParse parser; try { string input; getline(cin, input); parser.parse(input); if(digits != parser.digits) cout << "Error: Not using the given digits" << endl; else { double r = parser.getResult(); cout << "Result: " << r << endl; if(r > 23.999 && r < 24.001) cout << "Good job!" << endl; else cout << "Try again." << endl; } } catch(char* e) { cout << "Error: " << e << endl; } return 0; }
Port the provided VB code into C++ while preserving the original functionality.
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant GenerateNewDigits: For i = 1 To 4 Digit(i) = [randbetween(1,9)] Next i GetUserExpression: bValidExpression = True stFailMessage = "" stFailDigits = "" stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") bValidDigits = True stFailDigits = "" For i = 1 To 4 If InStr(stUserExpression, Digit(i)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Digit(i) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 1 To Len(stUserExpression) If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" iDigitCount = 0 For i = 1 To Len(stUserExpression) If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then iDigitCount = iDigitCount + 1 If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If End If Next i If iDigitCount > 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr End If If iDigitCount < 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr End If If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 11 To 99 If Not InStr(stUserExpression, i) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & i End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr End If On Error GoTo EvalFail vResult = Evaluate(stUserExpression) If Not vResult = 24 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult End If If bValidExpression = False Then vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") If vTryAgain = vbRetry Then vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") If vSameDigits = vbYes Then GoTo GetUserExpression Else GoTo GenerateNewDigits End If End If Else vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") If vTryAgain = vbRetry Then GoTo GenerateNewDigits End If End If Exit Sub EvalFail: bValidExpression = False vResult = Err.Description Resume End Sub
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); stk.push(f(a, b)); } void parse(char c) { if(c >= '0' && c <= '9') { stk.push(c - '0'); digits.insert(c - '0'); } else if(c == '+') op([](double a, double b) {return a+b;}); else if(c == '-') op([](double a, double b) {return a-b;}); else if(c == '*') op([](double a, double b) {return a*b;}); else if(c == '/') op([](double a, double b) {return a/b;}); } void parse(string s) { for(int i = 0; i < s.size(); ++i) parse(s[i]); } double getResult() { if(stk.size() != 1) throw "Improperly written expression"; return stk.top(); } }; int main() { random_device seed; mt19937 engine(seed()); uniform_int_distribution<> distribution(1, 9); auto rnd = bind(distribution, engine); multiset<int> digits; cout << "Make 24 with the digits: "; for(int i = 0; i < 4; ++i) { int n = rnd(); cout << " " << n; digits.insert(n); } cout << endl; RPNParse parser; try { string input; getline(cin, input); parser.parse(input); if(digits != parser.digits) cout << "Error: Not using the given digits" << endl; else { double r = parser.getResult(); cout << "Result: " << r << endl; if(r > 23.999 && r < 24.001) cout << "Good job!" << endl; else cout << "Try again." << endl; } } catch(char* e) { cout << "Error: " << e << endl; } return 0; }
Keep all operations the same but rewrite the snippet in C++.
For i = 1 To 10 Console.Write(i) If i Mod 5 = 0 Then Console.WriteLine() Else Console.Write(", ") End If Next
for(int i = 1;i <= 10; i++){ cout << i; if(i % 5 == 0){ cout << endl; continue; } cout << ", "; }
Produce a functionally identical C++ code for the snippet given in VB.
Option Base 1 Private Function pivotize(m As Variant) As Variant Dim n As Integer: n = UBound(m) Dim im() As Double ReDim im(n, n) For i = 1 To n For j = 1 To n im(i, j) = 0 Next j im(i, i) = 1 Next i For i = 1 To n mx = Abs(m(i, i)) row_ = i For j = i To n If Abs(m(j, i)) > mx Then mx = Abs(m(j, i)) row_ = j End If Next j If i <> Row Then For j = 1 To n tmp = im(i, j) im(i, j) = im(row_, j) im(row_, j) = tmp Next j End If Next i pivotize = im End Function Private Function lu(a As Variant) As Variant Dim n As Integer: n = UBound(a) Dim l() As Double ReDim l(n, n) For i = 1 To n For j = 1 To n l(i, j) = 0 Next j Next i u = l p = pivotize(a) a2 = WorksheetFunction.MMult(p, a) For j = 1 To n l(j, j) = 1# For i = 1 To j sum1 = 0# For k = 1 To i sum1 = sum1 + u(k, j) * l(i, k) Next k u(i, j) = a2(i, j) - sum1 Next i For i = j + 1 To n sum2 = 0# For k = 1 To j sum2 = sum2 + u(k, j) * l(i, k) Next k l(i, j) = (a2(i, j) - sum2) / u(j, j) Next i Next j Dim res(4) As Variant res(1) = a res(2) = l res(3) = u res(4) = p lu = res End Function Public Sub main() a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}] Debug.Print "== a,l,u,p: ==" result = lu(a) For i = 1 To 4 For j = 1 To UBound(result(1)) For k = 1 To UBound(result(1), 2) Debug.Print result(i)(j, k), Next k Debug.Print Next j Debug.Print Next i a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}] Debug.Print "== a,l,u,p: ==" result = lu(a) For i = 1 To 4 For j = 1 To UBound(result(1)) For k = 1 To UBound(result(1), 2) Debug.Print Format(result(i)(j, k), "0.#####"), Next k Debug.Print Next j Debug.Print Next i End Sub
#include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <limits> #include <numeric> #include <sstream> #include <vector> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, scalar_type value) : rows_(rows), columns_(columns), elements_(rows * columns, value) {} matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<scalar_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[i]); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const scalar_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } scalar_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } private: size_t rows_; size_t columns_; std::vector<scalar_type> elements_; }; template <typename scalar_type> void print(std::wostream& out, const matrix<scalar_type>& a) { const wchar_t* box_top_left = L"\x23a1"; const wchar_t* box_top_right = L"\x23a4"; const wchar_t* box_left = L"\x23a2"; const wchar_t* box_right = L"\x23a5"; const wchar_t* box_bottom_left = L"\x23a3"; const wchar_t* box_bottom_right = L"\x23a6"; const int precision = 5; size_t rows = a.rows(), columns = a.columns(); std::vector<size_t> width(columns); for (size_t column = 0; column < columns; ++column) { size_t max_width = 0; for (size_t row = 0; row < rows; ++row) { std::ostringstream str; str << std::fixed << std::setprecision(precision) << a(row, column); max_width = std::max(max_width, str.str().length()); } width[column] = max_width; } out << std::fixed << std::setprecision(precision); for (size_t row = 0; row < rows; ++row) { const bool top(row == 0), bottom(row + 1 == rows); out << (top ? box_top_left : (bottom ? box_bottom_left : box_left)); for (size_t column = 0; column < columns; ++column) { if (column > 0) out << L' '; out << std::setw(width[column]) << a(row, column); } out << (top ? box_top_right : (bottom ? box_bottom_right : box_right)); out << L'\n'; } } template <typename scalar_type> auto lu_decompose(const matrix<scalar_type>& input) { assert(input.rows() == input.columns()); size_t n = input.rows(); std::vector<size_t> perm(n); std::iota(perm.begin(), perm.end(), 0); matrix<scalar_type> lower(n, n); matrix<scalar_type> upper(n, n); matrix<scalar_type> input1(input); for (size_t j = 0; j < n; ++j) { size_t max_index = j; scalar_type max_value = 0; for (size_t i = j; i < n; ++i) { scalar_type value = std::abs(input1(perm[i], j)); if (value > max_value) { max_index = i; max_value = value; } } if (max_value <= std::numeric_limits<scalar_type>::epsilon()) throw std::runtime_error("matrix is singular"); if (j != max_index) std::swap(perm[j], perm[max_index]); size_t jj = perm[j]; for (size_t i = j + 1; i < n; ++i) { size_t ii = perm[i]; input1(ii, j) /= input1(jj, j); for (size_t k = j + 1; k < n; ++k) input1(ii, k) -= input1(ii, j) * input1(jj, k); } } for (size_t j = 0; j < n; ++j) { lower(j, j) = 1; for (size_t i = j + 1; i < n; ++i) lower(i, j) = input1(perm[i], j); for (size_t i = 0; i <= j; ++i) upper(i, j) = input1(perm[i], j); } matrix<scalar_type> pivot(n, n); for (size_t i = 0; i < n; ++i) pivot(i, perm[i]) = 1; return std::make_tuple(lower, upper, pivot); } template <typename scalar_type> void show_lu_decomposition(const matrix<scalar_type>& input) { try { std::wcout << L"A\n"; print(std::wcout, input); auto result(lu_decompose(input)); std::wcout << L"\nL\n"; print(std::wcout, std::get<0>(result)); std::wcout << L"\nU\n"; print(std::wcout, std::get<1>(result)); std::wcout << L"\nP\n"; print(std::wcout, std::get<2>(result)); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; } } int main() { std::wcout.imbue(std::locale("")); std::wcout << L"Example 1:\n"; matrix<double> matrix1(3, 3, {{1, 3, 5}, {2, 4, 7}, {1, 1, 0}}); show_lu_decomposition(matrix1); std::wcout << '\n'; std::wcout << L"Example 2:\n"; matrix<double> matrix2(4, 4, {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}}); show_lu_decomposition(matrix2); std::wcout << '\n'; std::wcout << L"Example 3:\n"; matrix<double> matrix3(3, 3, {{-5, -6, -3}, {-1, 0, -2}, {-3, -4, -7}}); show_lu_decomposition(matrix3); std::wcout << '\n'; std::wcout << L"Example 4:\n"; matrix<double> matrix4(3, 3, {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}); show_lu_decomposition(matrix4); return 0; }
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
Option Explicit Private Type Choice Number As Integer Name As String End Type Private MaxNumber As Integer Sub Main() Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$ MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1) For i = 1 To 3 U(i) = UserChoice Next For i = 1 To MaxNumber t = vbNullString For j = 1 To 3 If i Mod U(j).Number = 0 Then t = t & U(j).Name Next Debug.Print IIf(t = vbNullString, i, t) Next i End Sub Private Function UserChoice() As Choice Dim ok As Boolean Do While Not ok UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1) UserChoice.Name = InputBox("Enter the corresponding word : ") If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True Loop End Function
#include <algorithm> #include <iostream> #include <vector> #include <string> class pair { public: pair( int s, std::string z ) { p = std::make_pair( s, z ); } bool operator < ( const pair& o ) const { return i() < o.i(); } int i() const { return p.first; } std::string s() const { return p.second; } private: std::pair<int, std::string> p; }; void gFizzBuzz( int c, std::vector<pair>& v ) { bool output; for( int x = 1; x <= c; x++ ) { output = false; for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) { if( !( x % ( *i ).i() ) ) { std::cout << ( *i ).s(); output = true; } } if( !output ) std::cout << x; std::cout << "\n"; } } int main( int argc, char* argv[] ) { std::vector<pair> v; v.push_back( pair( 7, "Baxx" ) ); v.push_back( pair( 3, "Fizz" ) ); v.push_back( pair( 5, "Buzz" ) ); std::sort( v.begin(), v.end() ); gFizzBuzz( 20, v ); return 0; }
Generate a C++ translation of this VB snippet without changing its computational steps.
Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." End If Else read_line = "Line " & n & " does not exist." End If objFile.Close Set objFSO = Nothing End Function WScript.Echo read_line("c:\temp\input.txt",7)
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look at ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ; std::getline( std::cin , input ) ; int linenumber = std::stoi( input ) ; int lines_read = 0 ; std::string line ; if ( infile.is_open( ) ) { while ( infile ) { getline( infile , line ) ; lines_read++ ; if ( lines_read == linenumber ) { std::cout << line << std::endl ; break ; } } infile.close( ) ; if ( lines_read < linenumber ) std::cout << "No " << linenumber << " lines in " << file << " !\n" ; return 0 ; } else { std::cerr << "Could not find file " << file << " !\n" ; return 1 ; } }
Rewrite the snippet below in C++ so it works the same as the original VB code.
Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." End If Else read_line = "Line " & n & " does not exist." End If objFile.Close Set objFSO = Nothing End Function WScript.Echo read_line("c:\temp\input.txt",7)
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look at ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ; std::getline( std::cin , input ) ; int linenumber = std::stoi( input ) ; int lines_read = 0 ; std::string line ; if ( infile.is_open( ) ) { while ( infile ) { getline( infile , line ) ; lines_read++ ; if ( lines_read == linenumber ) { std::cout << line << std::endl ; break ; } } infile.close( ) ; if ( lines_read < linenumber ) std::cout << "No " << linenumber << " lines in " << file << " !\n" ; return 0 ; } else { std::cerr << "Could not find file " << file << " !\n" ; return 1 ; } }
Write the same code in C++ as shown below in VB.
Module Module1 Function ToVlq(v As ULong) As ULong Dim array(8) As Byte Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray buffer.CopyTo(array, 0) Return BitConverter.ToUInt64(array, 0) End Function Function FromVlq(v As ULong) As ULong Dim collection = BitConverter.GetBytes(v).Reverse() Return FromVlqCollection(collection) End Function Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte) If v > Math.Pow(2, 56) Then Throw New OverflowException("Integer exceeds max value.") End If Dim index = 7 Dim significantBitReached = False Dim mask = &H7FUL << (index * 7) While index >= 0 Dim buffer = mask And v If buffer > 0 OrElse significantBitReached Then significantBitReached = True buffer >>= index * 7 If index > 0 Then buffer = buffer Or &H80 End If Yield buffer End If mask >>= 7 index -= 1 End While End Function Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong Dim v = 0UL Dim significantBitReached = False Using enumerator = vlq.GetEnumerator Dim index = 0 While enumerator.MoveNext Dim buffer = enumerator.Current If buffer > 0 OrElse significantBitReached Then significantBitReached = True v <<= 7 v = v Or (buffer And &H7FUL) End If index += 1 If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then Exit While End If End While End Using Return v End Function Sub Main() Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF} For Each original In values Console.WriteLine("Original: 0x{0:X}", original) REM collection Dim seq = ToVlqCollection(original) Console.WriteLine("Sequence: 0x{0}", seq.Select(Function(b) b.ToString("X2")).Aggregate(Function(a, b) String.Concat(a, b))) Dim decoded = FromVlqCollection(seq) Console.WriteLine("Decoded: 0x{0:X}", decoded) REM ints Dim encoded = ToVlq(original) Console.WriteLine("Encoded: 0x{0:X}", encoded) decoded = FromVlq(encoded) Console.WriteLine("Decoded: 0x{0:X}", decoded) Console.WriteLine() Next End Sub End Module
#include <iomanip> #include <iostream> #include <vector> std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) { auto it = v.cbegin(); auto end = v.cend(); os << "[ "; if (it != end) { os << std::setfill('0') << std::setw(2) << (uint32_t)*it; it = std::next(it); } while (it != end) { os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it; it = std::next(it); } return os << " ]"; } std::vector<uint8_t> to_seq(uint64_t x) { int i; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) { break; } } std::vector<uint8_t> out; for (int j = 0; j <= i; j++) { out.push_back(((x >> ((i - j) * 7)) & 127) | 128); } out[i] ^= 128; return out; } uint64_t from_seq(const std::vector<uint8_t> &seq) { uint64_t r = 0; for (auto b : seq) { r = (r << 7) | (b & 127); } return r; } int main() { std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL }; for (auto x : src) { auto s = to_seq(x); std::cout << std::hex; std::cout << "seq from " << x << ' ' << s << " back: " << from_seq(s) << '\n'; std::cout << std::dec; } return 0; }
Port the following code from VB to C++ with equivalent syntax and logic.
Sub Main() Const TESTSTRING As String = "alphaBETA" Debug.Print "initial = " _ & TESTSTRING Debug.Print "uppercase = " _ & UCase(TESTSTRING) Debug.Print "lowercase = " _ & LCase(TESTSTRING) Debug.Print "first letter capitalized = " _ & StrConv(TESTSTRING, vbProperCase) Debug.Print "length (in characters) = " _ & CStr(Len(TESTSTRING)) Debug.Print "length (in bytes) = " _ & CStr(LenB(TESTSTRING)) Debug.Print "reversed = " _ & StrReverse(TESTSTRING) Debug.Print "first position of letter A (case-sensitive) = " _ & InStr(1, TESTSTRING, "A", vbBinaryCompare) Debug.Print "first position of letter A (case-insensitive) = " _ & InStr(1, TESTSTRING, "A", vbTextCompare) Debug.Print "concatenated with & TESTSTRING & "123" End Sub
#include <algorithm> #include <string> #include <cctype> void str_toupper(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::toupper); } void str_tolower(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::tolower); }
Write a version of this VB function in C++ with identical behavior.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\data.txt",1) bad_readings_total = 0 good_readings_total = 0 data_gap = 0 start_date = "" end_date = "" tmp_datax_gap = 0 tmp_start_date = "" Do Until objFile.AtEndOfStream bad_readings = 0 good_readings = 0 line_total = 0 line = objFile.ReadLine token = Split(line,vbTab) n = 1 Do While n <= UBound(token) If n + 1 <= UBound(token) Then If CInt(token(n+1)) < 1 Then bad_readings = bad_readings + 1 bad_readings_total = bad_readings_total + 1 If tmp_start_date = "" Then tmp_start_date = token(0) End If tmp_data_gap = tmp_data_gap + 1 Else good_readings = good_readings + 1 line_total = line_total + CInt(token(n)) good_readings_total = good_readings_total + 1 If (tmp_start_date <> "") And (tmp_data_gap > data_gap) Then start_date = tmp_start_date end_date = token(0) data_gap = tmp_data_gap tmp_start_date = "" tmp_data_gap = 0 Else tmp_start_date = "" tmp_data_gap = 0 End If End If End If n = n + 2 Loop line_avg = line_total/good_readings WScript.StdOut.Write "Date: " & token(0) & vbTab &_ "Bad Reads: " & bad_readings & vbTab &_ "Good Reads: " & good_readings & vbTab &_ "Line Total: " & FormatNumber(line_total,3) & vbTab &_ "Line Avg: " & FormatNumber(line_avg,3) WScript.StdOut.WriteLine Loop WScript.StdOut.WriteLine WScript.StdOut.Write "Maximum run of " & data_gap &_ " consecutive bad readings from " & start_date & " to " &_ end_date & "." WScript.StdOut.WriteLine objFile.Close Set objFSO = Nothing
#include <iostream> #include <fstream> #include <string> #include <vector> #include <iomanip> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> using std::cout; using std::endl; const int NumFlags = 24; int main() { std::fstream file("readings.txt"); int badCount = 0; std::string badDate; int badCountMax = 0; while(true) { std::string line; getline(file, line); if(!file.good()) break; std::vector<std::string> tokens; boost::algorithm::split(tokens, line, boost::is_space()); if(tokens.size() != NumFlags * 2 + 1) { cout << "Bad input file." << endl; return 0; } double total = 0.0; int accepted = 0; for(size_t i = 1; i < tokens.size(); i += 2) { double val = boost::lexical_cast<double>(tokens[i]); int flag = boost::lexical_cast<int>(tokens[i+1]); if(flag > 0) { total += val; ++accepted; badCount = 0; } else { ++badCount; if(badCount > badCountMax) { badCountMax = badCount; badDate = tokens[0]; } } } cout << tokens[0]; cout << " Reject: " << std::setw(2) << (NumFlags - accepted); cout << " Accept: " << std::setw(2) << accepted; cout << " Average: " << std::setprecision(5) << total / accepted << endl; } cout << endl; cout << "Maximum number of consecutive bad readings is " << badCountMax << endl; cout << "Ends on date " << badDate << endl; }
Port the following code from VB to C++ with equivalent syntax and logic.
Imports System.Security.Cryptography Imports System.Text Module MD5hash Sub Main(args As String()) Console.WriteLine(GetMD5("Visual Basic .Net")) End Sub Private Function GetMD5(plainText As String) As String Dim hash As String = "" Using hashObject As MD5 = MD5.Create() Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText)) Dim hashBuilder As New StringBuilder For i As Integer = 0 To ptBytes.Length - 1 hashBuilder.Append(ptBytes(i).ToString("X2")) Next hash = hashBuilder.ToString End Using Return hash End Function End Module
#include <string> #include <iostream> #include "Poco/MD5Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::MD5Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ; MD5Engine md5 ; DigestOutputStream outstr( md5 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = md5.digest( ) ; std::cout << myphrase << " as a MD5 digest :\n" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
Preserve the algorithm and functionality while converting the code from VB to C++.
Option Explicit Private Type Aliquot Sequence() As Double Classification As String End Type Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String For j = 1 To 10 result = Aliq(j) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next j Dim a a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488) For j = LBound(a) To UBound(a) result = Aliq(CDbl(a(j))) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next End Sub Private Function Aliq(Nb As Double) As Aliquot Dim s() As Double, i As Long, temp, j As Long, cpt As Long temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic") ReDim s(0) s(0) = Nb For i = 1 To 15 cpt = cpt + 1 ReDim Preserve s(cpt) s(i) = SumPDiv(s(i - 1)) If s(i) > 140737488355328# Then Exit For If s(i) = 0 Then j = 1 If s(1) = s(0) Then j = 2 If s(i) = s(0) And i > 1 And i <> 2 Then j = 4 If s(i) = s(i - 1) And i > 1 Then j = 5 If i >= 2 Then If s(2) = s(0) Then j = 3 If s(i) = s(i - 2) And i <> 2 Then j = 6 End If If j > 0 Then Exit For Next Aliq.Classification = temp(j) Aliq.Sequence = s End Function Private Function SumPDiv(n As Double) As Double Dim j As Long, t As Long If n > 1 Then For j = 1 To n \ 2 If n Mod j = 0 Then t = t + j Next End If SumPDiv = t End Function
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } void classify_aliquot_sequence(integer n) { constexpr int limit = 16; integer terms[limit]; terms[0] = n; std::string classification("non-terminating"); int length = 1; for (int i = 1; i < limit; ++i) { ++length; terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1]; if (terms[i] == n) { classification = (i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable")); break; } int j = 1; for (; j < i; ++j) { if (terms[i] == terms[i - j]) break; } if (j < i) { classification = (j == 1 ? "aspiring" : "cyclic"); break; } if (terms[i] == 0) { classification = "terminating"; break; } } std::cout << n << ": " << classification << ", sequence: " << terms[0]; for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i) std::cout << ' ' << terms[i]; std::cout << '\n'; } int main() { for (integer i = 1; i <= 10; ++i) classify_aliquot_sequence(i); for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}) classify_aliquot_sequence(i); classify_aliquot_sequence(15355717786080); classify_aliquot_sequence(153557177860800); return 0; }
Convert the following code from VB to C++, ensuring the logic remains intact.
Option Explicit Private Type Aliquot Sequence() As Double Classification As String End Type Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String For j = 1 To 10 result = Aliq(j) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next j Dim a a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488) For j = LBound(a) To UBound(a) result = Aliq(CDbl(a(j))) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next End Sub Private Function Aliq(Nb As Double) As Aliquot Dim s() As Double, i As Long, temp, j As Long, cpt As Long temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic") ReDim s(0) s(0) = Nb For i = 1 To 15 cpt = cpt + 1 ReDim Preserve s(cpt) s(i) = SumPDiv(s(i - 1)) If s(i) > 140737488355328# Then Exit For If s(i) = 0 Then j = 1 If s(1) = s(0) Then j = 2 If s(i) = s(0) And i > 1 And i <> 2 Then j = 4 If s(i) = s(i - 1) And i > 1 Then j = 5 If i >= 2 Then If s(2) = s(0) Then j = 3 If s(i) = s(i - 2) And i <> 2 Then j = 6 End If If j > 0 Then Exit For Next Aliq.Classification = temp(j) Aliq.Sequence = s End Function Private Function SumPDiv(n As Double) As Double Dim j As Long, t As Long If n > 1 Then For j = 1 To n \ 2 If n Mod j = 0 Then t = t + j Next End If SumPDiv = t End Function
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } void classify_aliquot_sequence(integer n) { constexpr int limit = 16; integer terms[limit]; terms[0] = n; std::string classification("non-terminating"); int length = 1; for (int i = 1; i < limit; ++i) { ++length; terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1]; if (terms[i] == n) { classification = (i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable")); break; } int j = 1; for (; j < i; ++j) { if (terms[i] == terms[i - j]) break; } if (j < i) { classification = (j == 1 ? "aspiring" : "cyclic"); break; } if (terms[i] == 0) { classification = "terminating"; break; } } std::cout << n << ": " << classification << ", sequence: " << terms[0]; for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i) std::cout << ' ' << terms[i]; std::cout << '\n'; } int main() { for (integer i = 1; i <= 10; ++i) classify_aliquot_sequence(i); for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}) classify_aliquot_sequence(i); classify_aliquot_sequence(15355717786080); classify_aliquot_sequence(153557177860800); return 0; }
Please provide an equivalent version of this VB code in C++.
Imports System.Threading Module Module1 Sub SleepSort(items As IEnumerable(Of Integer)) For Each item In items Task.Factory.StartNew(Sub() Thread.Sleep(1000 * item) Console.WriteLine(item) End Sub) Next End Sub Sub Main() SleepSort({1, 5, 2, 1, 8, 10, 3}) Console.ReadKey() End Sub End Module
#include <chrono> #include <iostream> #include <thread> #include <vector> int main(int argc, char* argv[]) { std::vector<std::thread> threads; for (int i = 1; i < argc; ++i) { threads.emplace_back([i, &argv]() { int arg = std::stoi(argv[i]); std::this_thread::sleep_for(std::chrono::seconds(arg)); std::cout << argv[i] << std::endl; }); } for (auto& thread : threads) { thread.join(); } }
Convert the following code from VB to C++, ensuring the logic remains intact.
Public Sub LoopsNested() Dim a(1 To 10, 1 To 10) As Integer Randomize For i = 1 To 10 For j = 1 To 10 a(i, j) = Int(20 * Rnd) + 1 Next j Next i For i = 1 To 10 For j = 1 To 10 If a(i, j) <> 20 Then Debug.Print a(i, j), Else i = 10 Exit For End If Next j Debug.Print Next i End Sub
#include<cstdlib> #include<ctime> #include<iostream> using namespace std; int main() { int arr[10][10]; srand(time(NULL)); for(auto& row: arr) for(auto& col: row) col = rand() % 20 + 1; ([&](){ for(auto& row : arr) for(auto& col: row) { cout << col << endl; if(col == 20)return; } })(); return 0; }
Write the same algorithm in C++ as shown in this VB implementation.
Dim total As Variant, prim As Variant, maxPeri As Variant Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant) Dim p As Variant p = CDec(s0) + CDec(s1) + CDec(s2) If p <= maxPeri Then prim = prim + 1 total = total + maxPeri \ p newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2 newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2 newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2 End If End Sub Public Sub Program_PythagoreanTriples() maxPeri = CDec(100) Do While maxPeri <= 10000000# prim = CDec(0) total = CDec(0) newTri 3, 4, 5 Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives." maxPeri = maxPeri * 10 Loop End Sub
#include <cmath> #include <iostream> #include <numeric> #include <tuple> #include <vector> using namespace std; auto CountTriplets(unsigned long long maxPerimeter) { unsigned long long totalCount = 0; unsigned long long primitveCount = 0; auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1; for(unsigned long long m = 2; m < max_M; ++m) { for(unsigned long long n = 1 + m % 2; n < m; n+=2) { if(gcd(m,n) != 1) { continue; } auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto perimeter = a + b + c; if(perimeter <= maxPerimeter) { primitveCount++; totalCount+= maxPerimeter / perimeter; } } } return tuple(totalCount, primitveCount); } int main() { vector<unsigned long long> inputs{100, 1000, 10'000, 100'000, 1000'000, 10'000'000, 100'000'000, 1000'000'000, 10'000'000'000}; for(auto maxPerimeter : inputs) { auto [total, primitive] = CountTriplets(maxPerimeter); cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ; } }
Write a version of this VB function in C++ with identical behavior.
Dim total As Variant, prim As Variant, maxPeri As Variant Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant) Dim p As Variant p = CDec(s0) + CDec(s1) + CDec(s2) If p <= maxPeri Then prim = prim + 1 total = total + maxPeri \ p newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2 newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2 newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2 End If End Sub Public Sub Program_PythagoreanTriples() maxPeri = CDec(100) Do While maxPeri <= 10000000# prim = CDec(0) total = CDec(0) newTri 3, 4, 5 Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives." maxPeri = maxPeri * 10 Loop End Sub
#include <cmath> #include <iostream> #include <numeric> #include <tuple> #include <vector> using namespace std; auto CountTriplets(unsigned long long maxPerimeter) { unsigned long long totalCount = 0; unsigned long long primitveCount = 0; auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1; for(unsigned long long m = 2; m < max_M; ++m) { for(unsigned long long n = 1 + m % 2; n < m; n+=2) { if(gcd(m,n) != 1) { continue; } auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto perimeter = a + b + c; if(perimeter <= maxPerimeter) { primitveCount++; totalCount+= maxPerimeter / perimeter; } } } return tuple(totalCount, primitveCount); } int main() { vector<unsigned long long> inputs{100, 1000, 10'000, 100'000, 1000'000, 10'000'000, 100'000'000, 1000'000'000, 10'000'000'000}; for(auto maxPerimeter : inputs) { auto [total, primitive] = CountTriplets(maxPerimeter); cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ; } }
Port the provided VB code into C++ while preserving the original functionality.
Option Explicit Sub Main() Dim myArr() As Variant, i As Long myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235)) For i = LBound(myArr) To UBound(myArr) Debug.Print myArr(i) Next End Sub Private Function Remove_Duplicate(Arr As Variant) As Variant() Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long ReDim Temp(UBound(Arr)) For i = LBound(Arr) To UBound(Arr) On Error Resume Next myColl.Add CStr(Arr(i)), CStr(Arr(i)) If Err.Number > 0 Then On Error GoTo 0 Else Temp(cpt) = Arr(i) cpt = cpt + 1 End If Next i ReDim Preserve Temp(cpt - 1) Remove_Duplicate = Temp End Function
#include <set> #include <iostream> using namespace std; int main() { typedef set<int> TySet; int data[] = {1, 2, 3, 2, 3, 4}; TySet unique_set(data, data + 6); cout << "Set items:" << endl; for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++) cout << *iter << " "; cout << endl; }
Convert this VB block to C++, preserving its control flow and logic.
Option Explicit Sub Main() Dim myArr() As Variant, i As Long myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235)) For i = LBound(myArr) To UBound(myArr) Debug.Print myArr(i) Next End Sub Private Function Remove_Duplicate(Arr As Variant) As Variant() Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long ReDim Temp(UBound(Arr)) For i = LBound(Arr) To UBound(Arr) On Error Resume Next myColl.Add CStr(Arr(i)), CStr(Arr(i)) If Err.Number > 0 Then On Error GoTo 0 Else Temp(cpt) = Arr(i) cpt = cpt + 1 End If Next i ReDim Preserve Temp(cpt - 1) Remove_Duplicate = Temp End Function
#include <set> #include <iostream> using namespace std; int main() { typedef set<int> TySet; int data[] = {1, 2, 3, 2, 3, 4}; TySet unique_set(data, data + 6); cout << "Set items:" << endl; for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++) cout << *iter << " "; cout << endl; }
Port the provided VB code into C++ while preserving the original functionality.
function looksay( n ) dim i dim accum dim res dim c res = vbnullstring do if n = vbnullstring then exit do accum = 0 c = left( n,1 ) do while left( n, 1 ) = c accum = accum + 1 n = mid(n,2) loop if accum > 0 then res = res & accum & c end if loop looksay = res end function
#include <iostream> #include <sstream> #include <string> std::string lookandsay(const std::string& s) { std::ostringstream r; for (std::size_t i = 0; i != s.length();) { auto new_i = s.find_first_not_of(s[i], i + 1); if (new_i == std::string::npos) new_i = s.length(); r << new_i - i << s[i]; i = new_i; } return r.str(); } int main() { std::string laf = "1"; std::cout << laf << '\n'; for (int i = 0; i < 10; ++i) { laf = lookandsay(laf); std::cout << laf << '\n'; } }
Preserve the algorithm and functionality while converting the code from VB to C++.
Private myStack() Private myStackHeight As Integer Public Function Push(aValue) myStackHeight = myStackHeight + 1 ReDim Preserve myStack(myStackHeight) myStack(myStackHeight) = aValue End Function Public Function Pop() If myStackHeight > 0 Then Pop = myStack(myStackHeight) myStackHeight = myStackHeight - 1 Else MsgBox "Pop: stack is empty!" End If End Function Public Function IsEmpty() As Boolean IsEmpty = (myStackHeight = 0) End Function Property Get Size() As Integer Size = myStackHeight End Property
#include <stack>
Rewrite the snippet below in C++ so it works the same as the original VB code.
Private Function totient(ByVal n As Long) As Long Dim tot As Long: tot = n Dim i As Long: i = 2 Do While i * i <= n If n Mod i = 0 Then Do While True n = n \ i If n Mod i <> 0 Then Exit Do Loop tot = tot - tot \ i End If i = i + IIf(i = 2, 1, 2) Loop If n > 1 Then tot = tot - tot \ n End If totient = tot End Function Public Sub main() Debug.Print " n phi prime" Debug.Print " --------------" Dim count As Long Dim tot As Integer, n As Long For n = 1 To 25 tot = totient(n) prime = (n - 1 = tot) count = count - prime Debug.Print Format(n, "@@"); Format(tot, "@@@@@"); Format(prime, "@@@@@@@@") Next n Debug.Print Debug.Print "Number of primes up to 25 = "; Format(count, "@@@@") For n = 26 To 100000 count = count - (totient(n) = n - 1) Select Case n Case 100, 1000, 10000, 100000 Debug.Print "Number of primes up to"; n; String$(6 - Len(CStr(n)), " "); "="; Format(count, "@@@@@") Case Else End Select Next n End Sub
#include <cassert> #include <iomanip> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) continue; for (int j = i; j <= max; j += i) totient_[j] -= totient_[j] / i; } } int totient(int n) const { assert (n >= 1 && n < totient_.size()); return totient_[n]; } bool is_prime(int n) const { return totient(n) == n - 1; } private: std::vector<int> totient_; }; int count_primes(const totient_calculator& tc, int min, int max) { int count = 0; for (int i = min; i <= max; ++i) { if (tc.is_prime(i)) ++count; } return count; } int main() { const int max = 10000000; totient_calculator tc(max); std::cout << " n totient prime?\n"; for (int i = 1; i <= 25; ++i) { std::cout << std::setw(2) << i << std::setw(9) << tc.totient(i) << std::setw(8) << (tc.is_prime(i) ? "yes" : "no") << '\n'; } for (int n = 100; n <= max; n *= 10) { std::cout << "Count of primes up to " << n << ": " << count_primes(tc, 1, n) << '\n'; } return 0; }
Convert the following code from VB to C++, ensuring the logic remains intact.
Sub C_S_If() Dim A$, B$ A = "Hello" B = "World" If A = B Then Debug.Print A & " = " & B If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents." End If If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents." End If If A = B Then Debug.Print A & " = " & B _ Else Debug.Print A & " and " & B & " are differents." If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents." If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents." End Sub
template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse; template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType> { typedef ThenType type; }; template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType> { typedef ElseType type; }; ifthenelse<INT_MAX == 32767, long int, int> ::type myvar;
Translate this program into C++ but keep the logic exactly as in VB.
Option Base 1 Public prime As Variant Public nf As New Collection Public df As New Collection Const halt = 20 Private Sub init() prime = [{2,3,5,7,11,13,17,19,23,29,31}] End Sub Private Function factor(f As Long) As Variant Dim result(10) As Integer Dim i As Integer: i = 1 Do While f > 1 Do While f Mod prime(i) = 0 f = f \ prime(i) result(i) = result(i) + 1 Loop i = i + 1 Loop factor = result End Function Private Function decrement(ByVal a As Variant, b As Variant) As Variant For i = LBound(a) To UBound(a) a(i) = a(i) - b(i) Next i decrement = a End Function Private Function increment(ByVal a As Variant, b As Variant) As Variant For i = LBound(a) To UBound(a) a(i) = a(i) + b(i) Next i increment = a End Function Private Function test(a As Variant, b As Variant) flag = True For i = LBound(a) To UBound(a) If a(i) < b(i) Then flag = False Exit For End If Next i test = flag End Function Private Function unfactor(x As Variant) As Long result = 1 For i = LBound(x) To UBound(x) result = result * prime(i) ^ x(i) Next i unfactor = result End Function Private Sub compile(program As String) program = Replace(program, " ", "") programlist = Split(program, ",") For Each instruction In programlist parts = Split(instruction, "/") nf.Add factor(Val(parts(0))) df.Add factor(Val(parts(1))) Next instruction End Sub Private Function run(x As Long) As Variant n = factor(x) counter = 0 Do While True For i = 1 To df.Count If test(n, df(i)) Then n = increment(decrement(n, df(i)), nf(i)) Exit For End If Next i Debug.Print unfactor(n); counter = counter + 1 If num = 31 Or counter >= halt Then Exit Do Loop Debug.Print run = n End Function Private Function steps(x As Variant) As Variant For i = 1 To df.Count If test(x, df(i)) Then x = increment(decrement(x, df(i)), nf(i)) Exit For End If Next i steps = x End Function Private Function is_power_of_2(x As Variant) As Boolean flag = True For i = LBound(x) + 1 To UBound(x) If x(i) > 0 Then flag = False Exit For End If Next i is_power_of_2 = flag End Function Private Function filter_primes(x As Long, max As Integer) As Long n = factor(x) i = 0: iterations = 0 Do While i < max If is_power_of_2(steps(n)) Then Debug.Print n(1); i = i + 1 End If iterations = iterations + 1 Loop Debug.Print filter_primes = iterations End Function Public Sub main() init compile ("17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1") Debug.Print "First 20 results:" output = run(2) Debug.Print "First 30 primes:" Debug.Print "after"; filter_primes(2, 30); "iterations." End Sub
#include <iostream> #include <sstream> #include <iterator> #include <vector> #include <cmath> using namespace std; class fractran { public: void run( std::string p, int s, int l ) { start = s; limit = l; istringstream iss( p ); vector<string> tmp; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) ); string item; vector< pair<float, float> > v; pair<float, float> a; for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ ) { string::size_type pos = ( *i ).find( '/', 0 ); if( pos != std::string::npos ) { a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) ); v.push_back( a ); } } exec( &v ); } private: void exec( vector< pair<float, float> >* v ) { int cnt = 0; while( cnt < limit ) { cout << cnt << " : " << start << "\n"; cnt++; vector< pair<float, float> >::iterator it = v->begin(); bool found = false; float r; while( it != v->end() ) { r = start * ( ( *it ).first / ( *it ).second ); if( r == floor( r ) ) { found = true; break; } ++it; } if( found ) start = ( int )r; else break; } } int start, limit; }; int main( int argc, char* argv[] ) { fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 ); cin.get(); return 0; }
Produce a language-to-language conversion: from VB to C++, same semantics.
type TSettings extends QObject FullName as string FavouriteFruit as string NeedSpelling as integer SeedsRemoved as integer OtherFamily as QStringlist Constructor FullName = "" FavouriteFruit = "" NeedSpelling = 0 SeedsRemoved = 0 OtherFamily.clear end constructor end type Dim Settings as TSettings dim ConfigList as QStringList dim x as integer dim StrLine as string dim StrPara as string dim StrData as string function Trim$(Expr as string) as string Result = Rtrim$(Ltrim$(Expr)) end function Sub ConfigOption(PData as string) dim x as integer for x = 1 to tally(PData, ",") +1 Settings.OtherFamily.AddItems Trim$(field$(PData, "," ,x)) next end sub Function ConfigBoolean(PData as string) as integer PData = Trim$(PData) Result = iif(lcase$(PData)="true" or PData="1" or PData="", 1, 0) end function sub ReadSettings ConfigList.LoadFromFile("Rosetta.cfg") ConfigList.text = REPLACESUBSTR$(ConfigList.text,"="," ") for x = 0 to ConfigList.ItemCount -1 StrLine = Trim$(ConfigList.item(x)) StrPara = Trim$(field$(StrLine," ",1)) StrData = Trim$(lTrim$(StrLine - StrPara)) Select case UCase$(StrPara) case "FULLNAME" : Settings.FullName = StrData case "FAVOURITEFRUIT" : Settings.FavouriteFruit = StrData case "NEEDSPEELING" : Settings.NeedSpelling = ConfigBoolean(StrData) case "SEEDSREMOVED" : Settings.SeedsRemoved = ConfigBoolean(StrData) case "OTHERFAMILY" : Call ConfigOption(StrData) end select next end sub Call ReadSettings
#include "stdafx.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string/case_conv.hpp> using namespace std; using namespace boost; typedef boost::tokenizer<boost::char_separator<char> > Tokenizer; static const char_separator<char> sep(" ","#;,"); struct configs{ string fullname; string favoritefruit; bool needspelling; bool seedsremoved; vector<string> otherfamily; } conf; void parseLine(const string &line, configs &conf) { if (line[0] == '#' || line.empty()) return; Tokenizer tokenizer(line, sep); vector<string> tokens; for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++) tokens.push_back(*iter); if (tokens[0] == ";"){ algorithm::to_lower(tokens[1]); if (tokens[1] == "needspeeling") conf.needspelling = false; if (tokens[1] == "seedsremoved") conf.seedsremoved = false; } algorithm::to_lower(tokens[0]); if (tokens[0] == "needspeeling") conf.needspelling = true; if (tokens[0] == "seedsremoved") conf.seedsremoved = true; if (tokens[0] == "fullname"){ for (unsigned int i=1; i<tokens.size(); i++) conf.fullname += tokens[i] + " "; conf.fullname.erase(conf.fullname.size() -1, 1); } if (tokens[0] == "favouritefruit") for (unsigned int i=1; i<tokens.size(); i++) conf.favoritefruit += tokens[i]; if (tokens[0] == "otherfamily"){ unsigned int i=1; string tmp; while (i<=tokens.size()){ if ( i == tokens.size() || tokens[i] ==","){ tmp.erase(tmp.size()-1, 1); conf.otherfamily.push_back(tmp); tmp = ""; i++; } else{ tmp += tokens[i]; tmp += " "; i++; } } } } int _tmain(int argc, TCHAR* argv[]) { if (argc != 2) { wstring tmp = argv[0]; wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl; return -1; } ifstream file (argv[1]); if (file.is_open()) while(file.good()) { char line[255]; file.getline(line, 255); string linestring(line); parseLine(linestring, conf); } else { cout << "Unable to open the file" << endl; return -2; } cout << "Fullname= " << conf.fullname << endl; cout << "Favorite Fruit= " << conf.favoritefruit << endl; cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl; cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl; string otherFamily; for (unsigned int i = 0; i < conf.otherfamily.size(); i++) otherFamily += conf.otherfamily[i] + ", "; otherFamily.erase(otherFamily.size()-2, 2); cout << "Other Family= " << otherFamily << endl; return 0; }
Port the provided VB code into C++ while preserving the original functionality.
Imports System Module Sorting_Using_a_Custom_Comparator Function CustomComparator(ByVal x As String, ByVal y As String) As Integer Dim result As Integer result = y.Length - x.Length If result = 0 Then result = String.Compare(x, y, True) End If Return result End Function Sub Main() Dim strings As String() = {"test", "Zoom", "strings", "a"} Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator)) End Sub End Module
#include <algorithm> #include <string> #include <cctype> struct icompare_char { bool operator()(char c1, char c2) { return std::toupper(c1) < std::toupper(c2); } }; struct compare { bool operator()(std::string const& s1, std::string const& s2) { if (s1.length() > s2.length()) return true; if (s1.length() < s2.length()) return false; return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), icompare_char()); } }; int main() { std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; std::sort(strings, strings+8, compare()); return 0; }
Convert the following code from VB to C++, ensuring the logic remains intact.
VERSION 5.00 Begin VB.Form Form1 Begin VB.Timer Timer1 Interval = 250 End Begin VB.Label Label1 AutoSize = -1 Caption = "Hello World! " End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private goRight As Boolean Private Sub Label1_Click() goRight = Not goRight End Sub Private Sub Timer1_Timer() If goRight Then x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1) Else x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1) End If Label1.Caption = x End Sub
#include "animationwidget.h" #include <QLabel> #include <QTimer> #include <QVBoxLayout> #include <algorithm> AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) { setWindowTitle(tr("Animation")); QFont font("Courier", 24); QLabel* label = new QLabel("Hello World! "); label->setFont(font); QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(label); QTimer* timer = new QTimer(this); connect(timer, &QTimer::timeout, this, [label,this]() { QString text = label->text(); std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end()); label->setText(text); }); timer->start(200); } void AnimationWidget::mousePressEvent(QMouseEvent*) { right_ = !right_; }
Convert the following code from VB to C++, ensuring the logic remains intact.
Module ListComp Sub Main() Dim ts = From a In Enumerable.Range(1, 20) _ From b In Enumerable.Range(a, 21 - a) _ From c In Enumerable.Range(b, 21 - b) _ Where a * a + b * b = c * c _ Select New With { a, b, c } For Each t In ts System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c) Next End Sub End Module
#include <vector> #include <cmath> #include <iostream> #include <algorithm> #include <iterator> void list_comprehension( std::vector<int> & , int ) ; int main( ) { std::vector<int> triangles ; list_comprehension( triangles , 20 ) ; std::copy( triangles.begin( ) , triangles.end( ) , std::ostream_iterator<int>( std::cout , " " ) ) ; std::cout << std::endl ; return 0 ; } void list_comprehension( std::vector<int> & numbers , int upper_border ) { for ( int a = 1 ; a < upper_border ; a++ ) { for ( int b = a + 1 ; b < upper_border ; b++ ) { double c = pow( a * a + b * b , 0.5 ) ; if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) { if ( c == floor( c ) ) { numbers.push_back( a ) ; numbers.push_back( b ) ; numbers.push_back( static_cast<int>( c ) ) ; } } } } }
Convert this VB block to C++, preserving its control flow and logic.
Function Selection_Sort(s) arr = Split(s,",") For i = 0 To UBound(arr) For j = i To UBound(arr) temp = arr(i) If arr(j) < arr(i) Then arr(i) = arr(j) arr(j) = temp End If Next Next Selection_Sort = (Join(arr,",")) End Function WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted" WScript.StdOut.WriteLine WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1") WScript.StdOut.WriteLine WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
#include <algorithm> #include <iterator> #include <iostream> template<typename ForwardIterator> void selection_sort(ForwardIterator begin, ForwardIterator end) { for(auto i = begin; i != end; ++i) { std::iter_swap(i, std::min_element(i, end)); } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; selection_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
Transform the following VB implementation into C++, maintaining the same output and logic.
Option Explicit Sub Main() Dim arr, i arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next Debug.Print Join(arr, ", ") End Sub Private Function Fibonacci(N) As Variant If N <= 1 Then Fibonacci = N Else Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2) End If End Function
#include <iostream> #include <algorithm> void print_square(int i) { std::cout << i*i << " "; } int main() { int ary[]={1,2,3,4,5}; std::for_each(ary,ary+5,print_square); return 0; }
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
Public Sub case_sensitivity() Dim DOG As String DOG = "Benjamin" DOG = "Samba" DOG = "Bernie" Debug.Print "There is just one dog named " & DOG End Sub
#include <iostream> #include <string> using namespace std; int main() { string dog = "Benjamin", Dog = "Samba", DOG = "Bernie"; cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl; }
Port the provided VB code into C++ while preserving the original functionality.
For i = 10 To 0 Step -1 Debug.Print i Next i
for(int i = 10; i >= 0; --i) std::cout << i << "\n";
Preserve the algorithm and functionality while converting the code from VB to C++.
Option Explicit Const strName As String = "MyFileText.txt" Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _ "The reverse of Read entire file—for when you want to update or " & vbCrLf & _ "create a file which you would read in its entirety all at once." Sub Main() Dim Nb As Integer Nb = FreeFile Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb Print #1, Text Close #Nb End Sub
#include <fstream> using namespace std; int main() { ofstream file("new.txt"); file << "this is a string"; file.close(); return 0; }
Convert this VB snippet to C++ and keep its semantics consistent.
Public OutConsole As Scripting.TextStream For i = 0 To 4 For j = 0 To i OutConsole.Write "*" Next j OutConsole.WriteLine Next i
for(int i = 0; i < 5; ++i) { for(int j = 0; j < i; ++j) std::cout.put('*'); std::cout.put('\n'); }
Port the following code from VB to C++ with equivalent syntax and logic.
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public property let iangle(n):iang= n*pi180 :end property public sub pd() : pdown=true: end sub public sub pu() :pdown=FALSE :end sub public sub rt(i) ori=ori - i*iang: end sub public sub lt(i): ori=(ori + i*iang) end sub public sub bw(l) x= x+ cos(ori+pi)*l*incr y= y+ sin(ori+pi)*l*incr end sub public sub fw(l) dim x1,y1 x1=x + cos(ori)*l*incr y1=y + sin(ori)*l*incr if pdown then line x,y,x1,y1 x=x1:y=y1 end sub Private Sub Class_Initialize() setlocale "us" initsvg x=400:y=400:incr=100 ori=90*pi180 iang=90*pi180 clr=0 pdown=true end sub Private Sub Class_Terminate() disply end sub private sub line (x,y,x1,y1) svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>" end sub private sub disply() dim shell svg.WriteLine "</svg></body></html>" svg.close Set shell = CreateObject("Shell.Application") shell.ShellExecute fn,1,False end sub private sub initsvg() dim scriptpath Set fso = CreateObject ("Scripting.Filesystemobject") ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) fn=Scriptpath & "SIERP.HTML" Set svg = fso.CreateTextFile(fn,True) if SVG IS nothing then wscript.echo "Can svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>" svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>" svg.writeline "</head>"&vbcrlf & "<body>" svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" end sub end class sub sier(lev,lgth) dim i if lev=1 then for i=1 to 3 x.fw lgth x.lt 2 next else sier lev-1,lgth\2 x.fw lgth\2 sier lev-1,lgth\2 x.bw lgth\2 x.lt 1 x.fw lgth\2 x.rt 1 sier lev-1,lgth\2 x.lt 1 x.bw lgth\2 x.rt 1 end if end sub dim x set x=new turtle x.iangle=60 x.orient=0 x.incr=10 x.x=100:x.y=100 sier 7,64 set x=nothing
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; 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( std::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 sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
Produce a functionally identical C++ code for the snippet given in VB.
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public property let iangle(n):iang= n*pi180 :end property public sub pd() : pdown=true: end sub public sub pu() :pdown=FALSE :end sub public sub rt(i) ori=ori - i*iang: end sub public sub lt(i): ori=(ori + i*iang) end sub public sub bw(l) x= x+ cos(ori+pi)*l*incr y= y+ sin(ori+pi)*l*incr end sub public sub fw(l) dim x1,y1 x1=x + cos(ori)*l*incr y1=y + sin(ori)*l*incr if pdown then line x,y,x1,y1 x=x1:y=y1 end sub Private Sub Class_Initialize() setlocale "us" initsvg x=400:y=400:incr=100 ori=90*pi180 iang=90*pi180 clr=0 pdown=true end sub Private Sub Class_Terminate() disply end sub private sub line (x,y,x1,y1) svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>" end sub private sub disply() dim shell svg.WriteLine "</svg></body></html>" svg.close Set shell = CreateObject("Shell.Application") shell.ShellExecute fn,1,False end sub private sub initsvg() dim scriptpath Set fso = CreateObject ("Scripting.Filesystemobject") ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) fn=Scriptpath & "SIERP.HTML" Set svg = fso.CreateTextFile(fn,True) if SVG IS nothing then wscript.echo "Can svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>" svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>" svg.writeline "</head>"&vbcrlf & "<body>" svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" end sub end class sub sier(lev,lgth) dim i if lev=1 then for i=1 to 3 x.fw lgth x.lt 2 next else sier lev-1,lgth\2 x.fw lgth\2 sier lev-1,lgth\2 x.bw lgth\2 x.lt 1 x.fw lgth\2 x.rt 1 sier lev-1,lgth\2 x.lt 1 x.bw lgth\2 x.rt 1 end if end sub dim x set x=new turtle x.iangle=60 x.orient=0 x.incr=10 x.x=100:x.y=100 sier 7,64 set x=nothing
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; 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( std::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 sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public property let iangle(n):iang= n*pi180 :end property public sub pd() : pdown=true: end sub public sub pu() :pdown=FALSE :end sub public sub rt(i) ori=ori - i*iang: end sub public sub lt(i): ori=(ori + i*iang) end sub public sub bw(l) x= x+ cos(ori+pi)*l*incr y= y+ sin(ori+pi)*l*incr end sub public sub fw(l) dim x1,y1 x1=x + cos(ori)*l*incr y1=y + sin(ori)*l*incr if pdown then line x,y,x1,y1 x=x1:y=y1 end sub Private Sub Class_Initialize() setlocale "us" initsvg x=400:y=400:incr=100 ori=90*pi180 iang=90*pi180 clr=0 pdown=true end sub Private Sub Class_Terminate() disply end sub private sub line (x,y,x1,y1) svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>" end sub private sub disply() dim shell svg.WriteLine "</svg></body></html>" svg.close Set shell = CreateObject("Shell.Application") shell.ShellExecute fn,1,False end sub private sub initsvg() dim scriptpath Set fso = CreateObject ("Scripting.Filesystemobject") ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) fn=Scriptpath & "SIERP.HTML" Set svg = fso.CreateTextFile(fn,True) if SVG IS nothing then wscript.echo "Can svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>" svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>" svg.writeline "</head>"&vbcrlf & "<body>" svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" end sub end class sub sier(lev,lgth) dim i if lev=1 then for i=1 to 3 x.fw lgth x.lt 2 next else sier lev-1,lgth\2 x.fw lgth\2 sier lev-1,lgth\2 x.bw lgth\2 x.lt 1 x.fw lgth\2 x.rt 1 sier lev-1,lgth\2 x.lt 1 x.bw lgth\2 x.rt 1 end if end sub dim x set x=new turtle x.iangle=60 x.orient=0 x.incr=10 x.x=100:x.y=100 sier 7,64 set x=nothing
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; 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( std::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 sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
Transform the following VB implementation into C++, maintaining the same output and logic.
Function noncontsubseq(l) Dim i, j, g, n, r, s, w, m Dim a, b, c n = Ubound(l) For s = 0 To n-2 For g = s+1 To n-1 a = "[" For i = s To g-1 a = a & l(i) & ", " Next For w = 1 To n-g r = n+1-g-w For i = 1 To 2^r-1 Step 2 b = a For j = 0 To r-1 If i And 2^j Then b=b & l(g+w+j) & ", " Next c = (Left(b, Len(b)-1)) WScript.Echo Left(c, Len(c)-1) & "]" m = m+1 Next Next Next Next noncontsubseq = m End Function list = Array("1", "2", "3", "4") WScript.Echo "List: [" & Join(list, ", ") & "]" nn = noncontsubseq(list) WScript.Echo nn & " non-continuous subsequences"
class N{ uint n,i,g,e,l; public: N(uint n): n(n-1),i{},g{},e(1),l(n-1){} bool hasNext(){ g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i; if (l==2) {l=--n; e=1; return true;} if (e<((1<<(l-1))-1)) {++e; return true;} e=1; --l; return (l>0); } uint next() {return g;} };
Please provide an equivalent version of this VB code in C++.
Function noncontsubseq(l) Dim i, j, g, n, r, s, w, m Dim a, b, c n = Ubound(l) For s = 0 To n-2 For g = s+1 To n-1 a = "[" For i = s To g-1 a = a & l(i) & ", " Next For w = 1 To n-g r = n+1-g-w For i = 1 To 2^r-1 Step 2 b = a For j = 0 To r-1 If i And 2^j Then b=b & l(g+w+j) & ", " Next c = (Left(b, Len(b)-1)) WScript.Echo Left(c, Len(c)-1) & "]" m = m+1 Next Next Next Next noncontsubseq = m End Function list = Array("1", "2", "3", "4") WScript.Echo "List: [" & Join(list, ", ") & "]" nn = noncontsubseq(list) WScript.Echo nn & " non-continuous subsequences"
class N{ uint n,i,g,e,l; public: N(uint n): n(n-1),i{},g{},e(1),l(n-1){} bool hasNext(){ g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i; if (l==2) {l=--n; e=1; return true;} if (e<((1<<(l-1))-1)) {++e; return true;} e=1; --l; return (l>0); } uint next() {return g;} };
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
Function IsPrime(x As Long) As Boolean Dim i As Long If x Mod 2 = 0 Then Exit Function Else For i = 3 To Int(Sqr(x)) Step 2 If x Mod i = 0 Then Exit Function Next i End If IsPrime = True End Function Function TwinPrimePairs(max As Long) As Long Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long p2 = True For i = 5 To max Step 2 p1 = p2 p2 = IsPrime(i) If p1 And p2 Then count = count + 1 Next i TwinPrimePairs = count End Function Sub Test(x As Long) Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x)) End Sub Sub Main() Test 10 Test 100 Test 1000 Test 10000 Test 100000 Test 1000000 Test 10000000 End Sub
#include <cstdint> #include <iostream> #include <string> #include <primesieve.hpp> void print_twin_prime_count(long long limit) { std::cout << "Number of twin prime pairs less than " << limit << " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n'; } int main(int argc, char** argv) { std::cout.imbue(std::locale("")); if (argc > 1) { for (int i = 1; i < argc; ++i) { try { print_twin_prime_count(std::stoll(argv[i])); } catch (const std::exception& ex) { std::cerr << "Cannot parse limit from '" << argv[i] << "'\n"; } } } else { uint64_t limit = 10; for (int power = 1; power < 12; ++power, limit *= 10) print_twin_prime_count(limit); } return 0; }
Write the same algorithm in C++ as shown in this VB implementation.
Public Sub roots_of_unity() For n = 2 To 9 Debug.Print n; "th roots of 1:" For r00t = 0 To n - 1 Debug.Print " Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _ Sin(2 * WorksheetFunction.Pi() * r00t / n)) Next r00t Debug.Print Next n End Sub
#include <complex> #include <cmath> #include <iostream> double const pi = 4 * std::atan(1); int main() { for (int n = 2; n <= 10; ++n) { std::cout << n << ": "; for (int k = 0; k < n; ++k) std::cout << std::polar(1, 2*pi*k/n) << " "; std::cout << std::endl; } }
Transform the following VB implementation into C++, maintaining the same output and logic.
Public Sub roots_of_unity() For n = 2 To 9 Debug.Print n; "th roots of 1:" For r00t = 0 To n - 1 Debug.Print " Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _ Sin(2 * WorksheetFunction.Pi() * r00t / n)) Next r00t Debug.Print Next n End Sub
#include <complex> #include <cmath> #include <iostream> double const pi = 4 * std::atan(1); int main() { for (int n = 2; n <= 10; ++n) { std::cout << n << ": "; for (int k = 0; k < n; ++k) std::cout << std::polar(1, 2*pi*k/n) << " "; std::cout << std::endl; } }
Produce a language-to-language conversion: from VB to C++, same semantics.
Imports System Imports System.Console Imports BI = System.Numerics.BigInteger Module Module1 Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D Structure bd Public hi, lo As Decimal End Structure Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String Dim r As String = If(a.hi = 0, String.Format("{0:0}", a.lo), String.Format("{0:0}{1:" & New String("0"c, 28) & "}", a.hi, a.lo)) If Not comma Then Return r Dim rc As String = "" For i As Integer = r.Length - 3 To 0 Step -3 rc = "," & r.Substring(i, 3) & rc : Next toStr = r.Substring(0, r.Length Mod 3) & rc toStr = toStr.Substring(If(toStr.Chars(0) = "," , 1, 0)) End Function Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _ Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas End Function Sub Main(ByVal args As String()) For p As UInteger = 64 To 95 - 1 Step 30 Dim y As bd, x As bd : a = Pow_dec(2D, p) WriteLine("The square of (2^{0}): {1,38:n0}", p, a) x.hi = Math.Floor(a / hm) : x.lo = a Mod hm Dim BS As BI = BI.Pow(CType(a, BI), 2) y.lo = x.lo * x.lo : y.hi = x.hi * x.hi a = x.hi * x.lo * 2D y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm While y.lo > mx : y.lo -= mx : y.hi += 1 : End While WriteLine(" is {0,75} (which {1} match the BigInteger computation)" & vbLf, toStr(y, True), If(BS.ToString() = toStr(y), "does", "fails to")) Next End Sub End Module
#include <iostream> #include <sstream> typedef long long bigInt; using namespace std; class number { public: number() { s = "0"; neg = false; } number( bigInt a ) { set( a ); } number( string a ) { set( a ); } void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); } void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); } number operator * ( const number& b ) { return this->mul( b ); } number& operator *= ( const number& b ) { *this = *this * b; return *this; } number& operator = ( const number& b ) { s = b.s; return *this; } friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; } friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; } private: number mul( const number& b ) { number a; bool neg = false; string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' ); int xx, ss, rr, t, c, stp = 0; string::reverse_iterator xi = bs.rbegin(), si, ri; for( ; xi != bs.rend(); xi++ ) { c = 0; ri = r.rbegin() + stp; for( si = s.rbegin(); si != s.rend(); si++ ) { xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48; ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10; ( *ri++ ) = t + 48; } if( c > 0 ) ( *ri ) = c + 48; stp++; } trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0; if( t & 1 ) a.s = "-" + r; else a.s = r; return a; } void trimLeft( string& r ) { if( r.length() < 2 ) return; for( string::iterator x = r.begin(); x != ( r.end() - 1 ); ) { if( ( *x ) != '0' ) return; x = r.erase( x ); } } void clearStr() { for( string::iterator x = s.begin(); x != s.end(); ) { if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x ); else x++; } } string s; bool neg; }; int main( int argc, char* argv[] ) { number a, b; a.set( "18446744073709551616" ); b.set( "18446744073709551616" ); cout << a * b << endl << endl; cout << "Factor 1 = "; cin >> a; cout << "Factor 2 = "; cin >> b; cout << "Product: = " << a * b << endl << endl; return system( "pause" ); }
Produce a language-to-language conversion: from VB to C++, same semantics.
Imports System.Numerics Module Module1 Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer) Dim t As BigInteger = a : a = b : b = b * c + t End Sub Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger) Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1, e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1 While True y = r * z - y : z = (n - y * y) / z : r = (x + y) / z Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x) If a * a - n * b * b = 1 Then Exit Sub End While End Sub Sub Main() Dim x As BigInteger, y As BigInteger For Each n As Integer In {61, 109, 181, 277} SolvePell(n, x, y) Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y) Next End Sub End Module
#include <iomanip> #include <iostream> #include <tuple> std::tuple<uint64_t, uint64_t> solvePell(int n) { int x = (int)sqrt(n); if (x * x == n) { return std::make_pair(1, 0); } int y = x; int z = 1; int r = 2 * x; std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0); std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e)); f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f)); a = std::get<1>(e) + x * std::get<1>(f); b = std::get<1>(f); if (a * a - n * b * b == 1) { break; } } return std::make_pair(a, b); } void test(int n) { auto r = solvePell(n); std::cout << "x^2 - " << std::setw(3) << n << " * y^2 = 1 for x = " << std::setw(21) << std::get<0>(r) << " and y = " << std::setw(21) << std::get<1>(r) << '\n'; } int main() { test(61); test(109); test(181); test(277); return 0; }
Convert this VB block to C++, preserving its control flow and logic.
Option Explicit Sub Main_Bulls_and_cows() Dim strNumber As String, strInput As String, strMsg As String, strTemp As String Dim boolEnd As Boolean Dim lngCpt As Long Dim i As Byte, bytCow As Byte, bytBull As Byte Const NUMBER_OF_DIGITS As Byte = 4 Const MAX_LOOPS As Byte = 25 strNumber = Create_Number(NUMBER_OF_DIGITS) Do bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1 If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do strInput = AskToUser(NUMBER_OF_DIGITS) If strInput = "Exit Game" Then strMsg = "User abort": Exit Do For i = 1 To Len(strNumber) If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then bytBull = bytBull + 1 ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then bytCow = bytCow + 1 End If Next i If bytBull = Len(strNumber) Then boolEnd = True: strMsg = "You win in " & lngCpt & " loops!" Else strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows." MsgBox strTemp End If Loop While Not boolEnd MsgBox strMsg End Sub Function Create_Number(NbDigits As Byte) As String Dim myColl As New Collection Dim strTemp As String Dim bytAlea As Byte Randomize Do bytAlea = Int((Rnd * 9) + 1) On Error Resume Next myColl.Add CStr(bytAlea), CStr(bytAlea) If Err <> 0 Then On Error GoTo 0 Else strTemp = strTemp & CStr(bytAlea) End If Loop While Len(strTemp) < NbDigits Create_Number = strTemp End Function Function AskToUser(NbDigits As Byte) As String Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte Do While Not boolGood strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number") If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do If strIn <> "" Then If Len(strIn) = NbDigits Then NbDiff = 0 For i = 1 To Len(strIn) If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then NbDiff = 1 Exit For End If Next i If NbDiff = 0 Then boolGood = True End If End If Loop AskToUser = strIn End Function
#include <iostream> #include <string> #include <algorithm> #include <cstdlib> bool contains_duplicates(std::string s) { std::sort(s.begin(), s.end()); return std::adjacent_find(s.begin(), s.end()) != s.end(); } void game() { typedef std::string::size_type index; std::string symbols = "0123456789"; unsigned int const selection_length = 4; std::random_shuffle(symbols.begin(), symbols.end()); std::string selection = symbols.substr(0, selection_length); std::string guess; while (std::cout << "Your guess? ", std::getline(std::cin, guess)) { if (guess.length() != selection_length || guess.find_first_not_of(symbols) != std::string::npos || contains_duplicates(guess)) { std::cout << guess << " is not a valid guess!"; continue; } unsigned int bulls = 0; unsigned int cows = 0; for (index i = 0; i != selection_length; ++i) { index pos = selection.find(guess[i]); if (pos == i) ++bulls; else if (pos != std::string::npos) ++cows; } std::cout << bulls << " bulls, " << cows << " cows.\n"; if (bulls == selection_length) { std::cout << "Congratulations! You have won!\n"; return; } } std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n"; std::exit(EXIT_FAILURE); } int main() { std::cout << "Welcome to bulls and cows!\nDo you want to play? "; std::string answer; while (true) { while (true) { if (!std::getline(std::cin, answer)) { std::cout << "I can't get an answer. Exiting.\n"; return EXIT_FAILURE; } if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y") break; if (answer == "no" || answer == "No" || answer == "n" || answer == "N") { std::cout << "Ok. Goodbye.\n"; return EXIT_SUCCESS; } std::cout << "Please answer yes or no: "; } game(); std::cout << "Another game? "; } }
Convert this VB block to C++, preserving its control flow and logic.
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) sortable.Shuffle() Dim swapped As Boolean Do Dim index, bound As Integer bound = sortable.Ubound While index < bound If sortable(index) > sortable(index + 1) Then Dim s As Integer = sortable(index) sortable.Remove(index) sortable.Insert(index + 1, s) swapped = True End If index = index + 1 Wend Loop Until Not swapped
#include <algorithm> #include <iostream> #include <iterator> template <typename RandomAccessIterator> void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) { bool swapped = true; while (begin != end-- && swapped) { swapped = false; for (auto i = begin; i != end; ++i) { if (*(i + 1) < *i) { std::iter_swap(i, i + 1); swapped = true; } } } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bubble_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.
Sub WriteToFile(input As FolderItem, output As FolderItem) Dim tis As TextInputStream Dim tos As TextOutputStream tis = tis.Open(input) tos = tos.Create(output) While Not tis.EOF tos.WriteLine(tis.ReadLine) Wend tis.Close tos.Close End Sub
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream input ( "input.txt" ); ofstream output ("output.txt"); if (output.is_open()) { if (input.is_open()){ while (getline (input,line)) { output << line << endl; } input.close(); } else { cout << "input.txt cannot be opened!\n"; } output.close(); } else { cout << "output.txt cannot be written to!\n"; } return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
START: INPUT "Enter two integers (a,b):"; a!, b! IF a = 0 THEN END IF b = 0 THEN PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder." GOTO START END IF PRINT PRINT " Sum = "; a + b PRINT " Difference = "; a - b PRINT " Product = "; a * b PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0." PRINT " Remainder = "; a MOD b, , "* Sign matches first operand." PRINT " Exponentiation = "; a ^ b PRINT INPUT "Again? (y/N)"; a$ IF UCASE$(a$) = "Y" THEN CLS: GOTO START CLS END
#include <iostream> int main() { int a, b; std::cin >> a >> b; std::cout << "a+b = " << a+b << "\n"; std::cout << "a-b = " << a-b << "\n"; std::cout << "a*b = " << a*b << "\n"; std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n"; return 0; }
Change the programming language of this snippet from VB to C++ without modifying what it does.
Function transpose(m As Variant) As Variant transpose = WorksheetFunction.transpose(m) End Function
#include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> int main() { using namespace boost::numeric::ublas; matrix<double> m(3,3); for(int i=0; i!=m.size1(); ++i) for(int j=0; j!=m.size2(); ++j) m(i,j)=3*i+j; std::cout << trans(m) << std::endl; }
Produce a language-to-language conversion: from VB to C++, same semantics.
Private Function a(i As Variant) As Boolean Debug.Print "a: "; i = 1, a = i End Function Private Function b(j As Variant) As Boolean Debug.Print "b: "; j = 1; b = j End Function Public Sub short_circuit() Dim x As Boolean, y As Boolean Debug.Print "=====AND=====" & vbCrLf For p = 0 To 1 For q = 0 To 1 If a(p) Then x = b(q) End If Debug.Print " = x" Next q Debug.Print Next p Debug.Print "======OR=====" & vbCrLf For p = 0 To 1 For q = 0 To 1 If Not a(p) Then x = b(q) End If Debug.Print " = x" Next q Debug.Print Next p Debug.Print End Sub
#include <iostream> bool a(bool in) { std::cout << "a" << std::endl; return in; } bool b(bool in) { std::cout << "b" << std::endl; return in; } void test(bool i, bool j) { std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl; std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl; } int main() { test(false, false); test(false, true); test(true, false); test(true, true); return 0; }
Please provide an equivalent version of this VB code in C++.
Option Explicit Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 On Error Resume Next Limite_Recursivite Cpt On Error GoTo 0 Limite_Recursivite = Cpt End Function
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
Write the same code in C++ as shown below in VB.
Option Explicit Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 On Error Resume Next Limite_Recursivite Cpt On Error GoTo 0 Limite_Recursivite = Cpt End Function
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
Change the following VB code into C++ without altering its purpose.
function isarit_compo(i) cnt=0 sum=0 for j=1 to sqr(i) if (i mod j)=0 then k=i\j if k=j then cnt=cnt+1:sum=sum+j else cnt=cnt+2:sum=sum+j+k end if end if next avg= sum/cnt isarit_compo= array((fix(avg)=avg),-(cnt>2)) end function function rpad(a,n) rpad=right(space(n)&a,n) :end function dim s1 sub print(s) s1=s1& rpad(s,4) if len(s1)=40 then wscript.stdout.writeline s1:s1="" end sub cntr=0 cntcompo=0 i=1 wscript.stdout.writeline "the first 100 arithmetic numbers are:" do a=isarit_compo(i) if a(0) then cntcompo=cntcompo+a(1) cntr=cntr+1 if cntr<=100 then print i if cntr=1000 then wscript.stdout.writeline vbcrlf&"1000th  : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6) if cntr=10000 then wscript.stdout.writeline vbcrlf& "10000th  : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6) if cntr=100000 then wscript.stdout.writeline vbcrlf &"100000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6):exit do end if i=i+1 loop
#include <cstdio> void divisor_count_and_sum(unsigned int n, unsigned int& divisor_count, unsigned int& divisor_sum) { divisor_count = 0; divisor_sum = 0; for (unsigned int i = 1;; i++) { unsigned int j = n / i; if (j < i) break; if (i * j != n) continue; divisor_sum += i; divisor_count += 1; if (i != j) { divisor_sum += j; divisor_count += 1; } } } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; n++) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, divisor_count, divisor_sum); unsigned int mean = divisor_sum / divisor_count; if (mean * divisor_count != divisor_sum) continue; arithmetic_count++; if (divisor_count > 2) composite_count++; if (arithmetic_count <= 100) { std::printf("%3u ", n); if (arithmetic_count % 10 == 0) std::printf("\n"); } if ((arithmetic_count == 1000) || (arithmetic_count == 10000) || (arithmetic_count == 100000) || (arithmetic_count == 1000000)) { std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
Translate this program into C++ but keep the logic exactly as in VB.
function isarit_compo(i) cnt=0 sum=0 for j=1 to sqr(i) if (i mod j)=0 then k=i\j if k=j then cnt=cnt+1:sum=sum+j else cnt=cnt+2:sum=sum+j+k end if end if next avg= sum/cnt isarit_compo= array((fix(avg)=avg),-(cnt>2)) end function function rpad(a,n) rpad=right(space(n)&a,n) :end function dim s1 sub print(s) s1=s1& rpad(s,4) if len(s1)=40 then wscript.stdout.writeline s1:s1="" end sub cntr=0 cntcompo=0 i=1 wscript.stdout.writeline "the first 100 arithmetic numbers are:" do a=isarit_compo(i) if a(0) then cntcompo=cntcompo+a(1) cntr=cntr+1 if cntr<=100 then print i if cntr=1000 then wscript.stdout.writeline vbcrlf&"1000th  : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6) if cntr=10000 then wscript.stdout.writeline vbcrlf& "10000th  : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6) if cntr=100000 then wscript.stdout.writeline vbcrlf &"100000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6):exit do end if i=i+1 loop
#include <cstdio> void divisor_count_and_sum(unsigned int n, unsigned int& divisor_count, unsigned int& divisor_sum) { divisor_count = 0; divisor_sum = 0; for (unsigned int i = 1;; i++) { unsigned int j = n / i; if (j < i) break; if (i * j != n) continue; divisor_sum += i; divisor_count += 1; if (i != j) { divisor_sum += j; divisor_count += 1; } } } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; n++) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, divisor_count, divisor_sum); unsigned int mean = divisor_sum / divisor_count; if (mean * divisor_count != divisor_sum) continue; arithmetic_count++; if (divisor_count > 2) composite_count++; if (arithmetic_count <= 100) { std::printf("%3u ", n); if (arithmetic_count % 10 == 0) std::printf("\n"); } if ((arithmetic_count == 1000) || (arithmetic_count == 10000) || (arithmetic_count == 100000) || (arithmetic_count == 1000000)) { std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
Generate a C++ translation of this VB snippet without changing its computational steps.
Imports System.Drawing.Imaging Public Class frmSnowExercise Dim bRunning As Boolean = True Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _ Or ControlStyles.OptimizedDoubleBuffer, True) UpdateStyles() FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle MaximizeBox = False Width = 320 + Size.Width - ClientSize.Width Height = 240 + Size.Height - ClientSize.Height Show() Activate() Application.DoEvents() RenderLoop() Close() End Sub Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False End Sub Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _ System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing e.Cancel = bRunning bRunning = False End Sub Private Sub RenderLoop() Const cfPadding As Single = 5.0F Dim b As New Bitmap(ClientSize.Width, ClientSize.Width, PixelFormat.Format32bppArgb) Dim g As Graphics = Graphics.FromImage(b) Dim r As New Random(Now.Millisecond) Dim oBMPData As BitmapData = Nothing Dim oPixels() As Integer = Nothing Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb} Dim oStopwatch As New Stopwatch Dim fElapsed As Single = 0.0F Dim iLoops As Integer = 0 Dim sFPS As String = "0.0 FPS" Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font) Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height) g.Clear(Color.Black) oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb) Array.Resize(oPixels, b.Width * b.Height) Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0, oPixels, 0, oPixels.Length) b.UnlockBits(oBMPData) Do fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F oStopwatch.Reset() : oStopwatch.Start() iLoops += 1 If fElapsed >= 1.0F Then sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS" oFPSSize = g.MeasureString(sFPS, Font) oFPSBG = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height) fElapsed -= 1.0F iLoops = 0 End If For i As Integer = 0 To oPixels.GetUpperBound(0) oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length)) Next oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb) Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0, oPixels.Length) b.UnlockBits(oBMPData) g.FillRectangle(Brushes.Black, oFPSBG) g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top) BackgroundImage = b Invalidate(ClientRectangle) Application.DoEvents() Loop While bRunning End Sub End Class
#include <windows.h> #include <sstream> #include <tchar.h> using namespace std; const unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0; 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; } void* getBits( void ) const { return pBits; } 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 bmpNoise { public: bmpNoise() { QueryPerformanceFrequency( &_frequency ); _bmp.create( BMP_WID, BMP_HEI ); _frameTime = _fps = 0; _start = getTime(); _frames = 0; } void mainLoop() { float now = getTime(); if( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; } HDC wdc, dc = _bmp.getDC(); unsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() ); for( int y = 0; y < BMP_HEI; y++ ) { for( int x = 0; x < BMP_WID; x++ ) { if( rand() % 10 < 5 ) memset( bits, 255, 3 ); else memset( bits, 0, 3 ); bits++; } } ostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() ); wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); _frames++; _frameTime = getTime() - now; if( _frameTime > 1.0f ) _frameTime = 1.0f; } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: float getTime() { LARGE_INTEGER liTime; QueryPerformanceCounter( &liTime ); return liTime.QuadPart / ( float )_frequency.QuadPart; } myBitmap _bmp; HWND _hwnd; float _start, _fps, _frameTime; unsigned int _frames; LARGE_INTEGER _frequency; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _noise.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); 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 ); } else { _noise.mainLoop(); } } return UnregisterClass( "_MY_NOISE_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_NOISE_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_WID, BMP_HEI }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_NOISE_", ".: Noise image -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; bmpNoise _noise; }; wnd* wnd::_inst = 0; int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
Translate the given VB code snippet into C++ without altering its behavior.
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.") GraphicsWindow.KeyDown = OnKeyDown Sub OnKeyDown TextWindow.WriteLine(GraphicsWindow.LastKey) EndSub
#include <conio.h> #include <iostream> using namespace std; int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N'); if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.") GraphicsWindow.KeyDown = OnKeyDown Sub OnKeyDown TextWindow.WriteLine(GraphicsWindow.LastKey) EndSub
#include <conio.h> #include <iostream> using namespace std; int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N'); if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }
Keep all operations the same but rewrite the snippet in C++.
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.") GraphicsWindow.KeyDown = OnKeyDown Sub OnKeyDown TextWindow.WriteLine(GraphicsWindow.LastKey) EndSub
#include <conio.h> #include <iostream> using namespace std; int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N'); if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }
Change the following VB code into C++ without altering its purpose.
Private Function Factors(x As Long) As String Application.Volatile Dim i As Long Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors End If Next i If x <> 1 Then Factors = Factors & ", " & corresponding_factors End Function Private Function is_perfect(n As Long) fs = Split(Factors(n), ", ") Dim f() As Long ReDim f(UBound(fs)) For i = 0 To UBound(fs) f(i) = Val(fs(i)) Next i is_perfect = WorksheetFunction.Sum(f) - n = n End Function Public Sub main() Dim i As Long For i = 2 To 100000 If is_perfect(i) Then Debug.Print i Next i End Sub
#include <iostream> using namespace std ; int divisor_sum( int number ) { int sum = 0 ; for ( int i = 1 ; i < number ; i++ ) if ( number % i == 0 ) sum += i ; return sum; } int main( ) { cout << "Perfect numbers from 1 to 33550337:\n" ; for ( int num = 1 ; num < 33550337 ; num++ ) { if (divisor_sum(num) == num) cout << num << '\n' ; } return 0 ; }
Convert this VB block to C++, preserving its control flow and logic.
Private Function Factors(x As Long) As String Application.Volatile Dim i As Long Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors End If Next i If x <> 1 Then Factors = Factors & ", " & corresponding_factors End Function Private Function is_perfect(n As Long) fs = Split(Factors(n), ", ") Dim f() As Long ReDim f(UBound(fs)) For i = 0 To UBound(fs) f(i) = Val(fs(i)) Next i is_perfect = WorksheetFunction.Sum(f) - n = n End Function Public Sub main() Dim i As Long For i = 2 To 100000 If is_perfect(i) Then Debug.Print i Next i End Sub
#include <iostream> using namespace std ; int divisor_sum( int number ) { int sum = 0 ; for ( int i = 1 ; i < number ; i++ ) if ( number % i == 0 ) sum += i ; return sum; } int main( ) { cout << "Perfect numbers from 1 to 33550337:\n" ; for ( int num = 1 ; num < 33550337 ; num++ ) { if (divisor_sum(num) == num) cout << num << '\n' ; } return 0 ; }
Write the same algorithm in C++ as shown in this VB implementation.
Option Base 1 Private Function sq_add(arr As Variant, x As Double) As Variant Dim res() As Variant ReDim res(UBound(arr)) For i = 1 To UBound(arr) res(i) = arr(i) + x Next i sq_add = res End Function Private Function beadsort(ByVal a As Variant) As Variant Dim poles() As Variant ReDim poles(WorksheetFunction.Max(a)) For i = 1 To UBound(a) For j = 1 To a(i) poles(j) = poles(j) + 1 Next j Next i For j = 1 To UBound(a) a(j) = 0 Next j For i = 1 To UBound(poles) For j = 1 To poles(i) a(j) = a(j) + 1 Next j Next i beadsort = a End Function Public Sub main() Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ") End Sub
#include <iostream> #include <vector> using std::cout; using std::vector; void distribute(int dist, vector<int> &List) { if (dist > List.size() ) List.resize(dist); for (int i=0; i < dist; i++) List[i]++; } vector<int> beadSort(int *myints, int n) { vector<int> list, list2, fifth (myints, myints + n); cout << "#1 Beads falling down: "; for (int i=0; i < fifth.size(); i++) distribute (fifth[i], list); cout << '\n'; cout << "\nBeads on their sides: "; for (int i=0; i < list.size(); i++) cout << " " << list[i]; cout << '\n'; cout << "#2 Beads right side up: "; for (int i=0; i < list.size(); i++) distribute (list[i], list2); cout << '\n'; return list2; } int main() { int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1}; vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int)); cout << "Sorted list/array: "; for(unsigned int i=0; i<sorted.size(); i++) cout << sorted[i] << ' '; }
Port the provided VB code into C++ while preserving the original functionality.
Imports System.Console Imports BI = System.Numerics.BigInteger Module Module1 Dim Implems() As String = {"Built-In", "Recursive", "Iterative"}, powers() As Integer = {5, 4, 3, 2} Function intPowR(val As BI, exp As BI) As BI If exp = 0 Then Return 1 Dim ne As BI, vs As BI = val * val If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val End Function Function intPowI(val As BI, exp As BI) As BI intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val val *= val : exp >>= 1 : End While End Function Sub DoOne(title As String, p() As Integer) Dim st As DateTime = DateTime.Now, res As BI, resStr As String Select Case (Array.IndexOf(Implems, title)) Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3)))))) Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3)))) Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3)))) End Select : resStr = res.ToString() Dim et As TimeSpan = DateTime.Now - st Debug.Assert(resStr.Length = 183231) Debug.Assert(resStr.StartsWith("62060698786608744707")) Debug.Assert(resStr.EndsWith("92256259918212890625")) WriteLine("n = {0}", String.Join("^", powers)) WriteLine("n = {0}...{1}", resStr.Substring(0, 20), resStr.Substring(resStr.Length - 20, 20)) WriteLine("n digits = {0}", resStr.Length) WriteLine("{0} elasped: {1} milliseconds." & vblf, title, et.TotalMilliseconds) End Sub Sub Main() For Each itm As String in Implems : DoOne(itm, powers) : Next If Debugger.IsAttached Then Console.ReadKey() End Sub End Module
#include <iostream> #include <boost/multiprecision/gmp.hpp> #include <string> namespace mp = boost::multiprecision; int main(int argc, char const *argv[]) { uint64_t tmpres = mp::pow(mp::mpz_int(4) , mp::pow(mp::mpz_int(3) , 2).convert_to<uint64_t>() ).convert_to<uint64_t>(); mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres); std::string s = res.str(); std::cout << s.substr(0, 20) << "..." << s.substr(s.length() - 20, 20) << std::endl; return 0; }
Change the programming language of this snippet from VB to C++ without modifying what it does.
shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@") light = Array(30, 30, -50) Sub Normalize(v) length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2)) v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length End Sub Function Dot(x, y) d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2) If d < 0 Then Dot = -d Else Dot = 0 End If End Function Function Ceil(x) Ceil = Int(x) If Ceil <> x Then Ceil = Ceil + 1 End if End Function Sub DrawSphere(R, k, ambient) Dim i, j, intensity, inten, b, x, y Dim vec(3) For i = Int(-R) to Ceil(R) x = i + 0.5 line = "" For j = Int(-2*R) to Ceil(2*R) y = j / 2 + 0.5 If x * x + y * y <= R*R Then vec(0) = x vec(1) = y vec(2) = Sqr(R * R - x * x - y * y) Normalize vec b = dot(light, vec)^k + ambient intensity = Int((1 - b) * UBound(shades)) If intensity < 0 Then intensity = 0 End If If intensity >= UBound(shades) Then intensity = UBound(shades) End If line = line & shades(intensity) Else line = line & " " End If Next WScript.StdOut.WriteLine line Next End Sub Normalize light DrawSphere 20, 4, 0.1 DrawSphere 10,2,0.4
#include <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
Write a version of this VB function in C++ with identical behavior.
shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@") light = Array(30, 30, -50) Sub Normalize(v) length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2)) v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length End Sub Function Dot(x, y) d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2) If d < 0 Then Dot = -d Else Dot = 0 End If End Function Function Ceil(x) Ceil = Int(x) If Ceil <> x Then Ceil = Ceil + 1 End if End Function Sub DrawSphere(R, k, ambient) Dim i, j, intensity, inten, b, x, y Dim vec(3) For i = Int(-R) to Ceil(R) x = i + 0.5 line = "" For j = Int(-2*R) to Ceil(2*R) y = j / 2 + 0.5 If x * x + y * y <= R*R Then vec(0) = x vec(1) = y vec(2) = Sqr(R * R - x * x - y * y) Normalize vec b = dot(light, vec)^k + ambient intensity = Int((1 - b) * UBound(shades)) If intensity < 0 Then intensity = 0 End If If intensity >= UBound(shades) Then intensity = UBound(shades) End If line = line & shades(intensity) Else line = line & " " End If Next WScript.StdOut.WriteLine line Next End Sub Normalize light DrawSphere 20, 4, 0.1 DrawSphere 10,2,0.4
#include <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
Port the following code from VB to C++ with equivalent syntax and logic.
Function gcd(u As Long, v As Long) As Long Dim t As Long Do While v t = u u = v v = t Mod v Loop gcd = u End Function Function lcm(m As Long, n As Long) As Long lcm = Abs(m * n) / gcd(m, n) End Function
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
Write a version of this VB function in C++ with identical behavior.
Function gcd(u As Long, v As Long) As Long Dim t As Long Do While v t = u u = v v = t Mod v Loop gcd = u End Function Function lcm(m As Long, n As Long) As Long lcm = Abs(m * n) / gcd(m, n) End Function
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
Convert this VB block to C++, preserving its control flow and logic.
Public Sub LoopsBreak() Dim value As Integer Randomize Do While True value = Int(20 * Rnd) Debug.Print value If value = 10 Then Exit Do Debug.Print Int(20 * Rnd) Loop End Sub
#include <iostream> #include <ctime> #include <cstdlib> int main(){ srand(time(NULL)); while(true){ const int a = rand() % 20; std::cout << a << std::endl; if(a == 10) break; const int b = rand() % 20; std::cout << b << std::endl; } return 0; }
Write the same algorithm in C++ as shown in this VB implementation.
Module Module1 Sub Main(Args() As String) Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 Dim wta As Integer()() = { New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8}, New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}} Dim blk As String, lf As String = vbLf, tb = "██", wr = "≈≈", mt = " " For i As Integer = 0 To wta.Length - 1 Dim bpf As Integer blk = "" Do bpf = 0 : Dim floor As String = "" For j As Integer = 0 To wta(i).Length - 1 If wta(i)(j) > 0 Then floor &= tb : wta(i)(j) -= 1 : bpf += 1 Else floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt) End If Next If bpf > 0 Then blk = floor & lf & blk Loop Until bpf = 0 While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While If shoTow Then Console.Write("{0}{1}", lf, blk) Console.Write("Block {0} retains {1,2} water units.{2}", i + 1, (blk.Length - blk.Replace(wr, "").Length) \ 2, lf) Next End Sub End Module
#include <iostream> #include <vector> #include <algorithm> enum { EMPTY, WALL, WATER }; auto fill(const std::vector<int> b) { auto water = 0; const auto rows = *std::max_element(std::begin(b), std::end(b)); const auto cols = std::size(b); std::vector<std::vector<int>> g(rows); for (auto& r : g) { for (auto i = 0; i < cols; ++i) { r.push_back(EMPTY); } } for (auto c = 0; c < cols; ++c) { for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) { g[r][c] = WALL; } } for (auto c = 0; c < cols - 1; ++c) { auto start_row = rows - b[c]; while (start_row < rows) { if (g[start_row][c] == EMPTY) break; auto c2 = c + 1; bool hitWall = false; while (c2 < cols) { if (g[start_row][c2] == WALL) { hitWall = true; break; } ++c2; } if (hitWall) { for (auto i = c + 1; i < c2; ++i) { g[start_row][i] = WATER; ++water; } } ++start_row; } } return water; } int main() { std::vector<std::vector<int>> b = { { 1, 5, 3, 7, 2 }, { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, { 5, 5, 5, 5 }, { 5, 6, 7, 8 }, { 8, 7, 7, 6 }, { 6, 7, 10, 7, 6 } }; for (const auto v : b) { auto water = fill(v); std::cout << water << " water drops." << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
Port the provided VB code into C++ while preserving the original functionality.
Module Module1 Function Sieve(limit As Long) As List(Of Long) Dim primes As New List(Of Long) From {2} Dim c(limit + 1) As Boolean Dim p = 3L While True Dim p2 = p * p If p2 > limit Then Exit While End If For i = p2 To limit Step 2 * p c(i) = True Next While True p += 2 If Not c(p) Then Exit While End If End While End While For i = 3 To limit Step 2 If Not c(i) Then primes.Add(i) End If Next Return primes End Function Function SquareFree(from As Long, to_ As Long) As List(Of Long) Dim limit = CType(Math.Sqrt(to_), Long) Dim primes = Sieve(limit) Dim results As New List(Of Long) Dim i = from While i <= to_ For Each p In primes Dim p2 = p * p If p2 > i Then Exit For End If If (i Mod p2) = 0 Then i += 1 Continue While End If Next results.Add(i) i += 1 End While Return results End Function ReadOnly TRILLION As Long = 1_000_000_000_000 Sub Main() Console.WriteLine("Square-free integers from 1 to 145:") Dim sf = SquareFree(1, 145) For index = 0 To sf.Count - 1 Dim v = sf(index) If index > 1 AndAlso (index Mod 20) = 0 Then Console.WriteLine() End If Console.Write("{0,4}", v) Next Console.WriteLine() Console.WriteLine() Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145) sf = SquareFree(TRILLION, TRILLION + 145) For index = 0 To sf.Count - 1 Dim v = sf(index) If index > 1 AndAlso (index Mod 5) = 0 Then Console.WriteLine() End If Console.Write("{0,14}", v) Next Console.WriteLine() Console.WriteLine() Console.WriteLine("Number of square-free integers:") For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000} Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count) Next End Sub End Module
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; bool square_free(integer n) { if (n % 4 == 0) return false; for (integer p = 3; p * p <= n; p += 2) { integer count = 0; for (; n % p == 0; n /= p) { if (++count > 1) return false; } } return true; } void print_square_free_numbers(integer from, integer to) { std::cout << "Square-free numbers between " << from << " and " << to << ":\n"; std::string line; for (integer i = from; i <= to; ++i) { if (square_free(i)) { if (!line.empty()) line += ' '; line += std::to_string(i); if (line.size() >= 80) { std::cout << line << '\n'; line.clear(); } } } if (!line.empty()) std::cout << line << '\n'; } void print_square_free_count(integer from, integer to) { integer count = 0; for (integer i = from; i <= to; ++i) { if (square_free(i)) ++count; } std::cout << "Number of square-free numbers between " << from << " and " << to << ": " << count << '\n'; } int main() { print_square_free_numbers(1, 145); print_square_free_numbers(1000000000000LL, 1000000000145LL); print_square_free_count(1, 100); print_square_free_count(1, 1000); print_square_free_count(1, 10000); print_square_free_count(1, 100000); print_square_free_count(1, 1000000); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
Option Explicit Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double Dim dummyChar, match1, match2 As String Dim i, f, t, j, m, l, s1, s2, limit As Integer i = 1 Do dummyChar = Chr(i) i = i + 1 Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0 s1 = Len(text1) s2 = Len(text2) limit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1) match1 = String(s1, dummyChar) match2 = String(s2, dummyChar) For l = 1 To WorksheetFunction.Min(4, s1, s2) If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For Next l l = l - 1 For i = 1 To s1 f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2) t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2) j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare) If j > 0 Then m = m + 1 text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j) match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1) match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j) End If Next i match1 = Replace(match1, dummyChar, "", 1, -1, vbTextCompare) match2 = Replace(match2, dummyChar, "", 1, -1, vbTextCompare) t = 0 For i = 1 To m If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1 Next i JaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3 JaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p) End Function
#include <algorithm> #include <iostream> #include <string> double jaro(const std::string s1, const std::string s2) { const uint l1 = s1.length(), l2 = s2.length(); if (l1 == 0) return l2 == 0 ? 1.0 : 0.0; const uint match_distance = std::max(l1, l2) / 2 - 1; bool s1_matches[l1]; bool s2_matches[l2]; std::fill(s1_matches, s1_matches + l1, false); std::fill(s2_matches, s2_matches + l2, false); uint matches = 0; for (uint i = 0; i < l1; i++) { const int end = std::min(i + match_distance + 1, l2); for (int k = std::max(0u, i - match_distance); k < end; k++) if (!s2_matches[k] && s1[i] == s2[k]) { s1_matches[i] = true; s2_matches[k] = true; matches++; break; } } if (matches == 0) return 0.0; double t = 0.0; uint k = 0; for (uint i = 0; i < l1; i++) if (s1_matches[i]) { while (!s2_matches[k]) k++; if (s1[i] != s2[k]) t += 0.5; k++; } const double m = matches; return (m / l1 + m / l2 + (m - t) / m) / 3.0; } int main() { using namespace std; cout << jaro("MARTHA", "MARHTA") << endl; cout << jaro("DIXON", "DICKSONX") << endl; cout << jaro("JELLYFISH", "SMELLYFISH") << endl; return 0; }
Write a version of this VB function in C++ with identical behavior.
Module Module1 Function Turn(base As Integer, n As Integer) As Integer Dim sum = 0 While n <> 0 Dim re = n Mod base n \= base sum += re End While Return sum Mod base End Function Sub Fairshare(base As Integer, count As Integer) Console.Write("Base {0,2}:", base) For i = 1 To count Dim t = Turn(base, i - 1) Console.Write(" {0,2}", t) Next Console.WriteLine() End Sub Sub TurnCount(base As Integer, count As Integer) Dim cnt(base) As Integer For i = 1 To base cnt(i - 1) = 0 Next For i = 1 To count Dim t = Turn(base, i - 1) cnt(t) += 1 Next Dim minTurn = Integer.MaxValue Dim maxTurn = Integer.MinValue Dim portion = 0 For i = 1 To base Dim num = cnt(i - 1) If num > 0 Then portion += 1 End If If num < minTurn Then minTurn = num End If If num > maxTurn Then maxTurn = num End If Next Console.Write(" With {0} people: ", base) If 0 = minTurn Then Console.WriteLine("Only {0} have a turn", portion) ElseIf minTurn = maxTurn Then Console.WriteLine(minTurn) Else Console.WriteLine("{0} or {1}", minTurn, maxTurn) End If End Sub Sub Main() Fairshare(2, 25) Fairshare(3, 25) Fairshare(5, 25) Fairshare(11, 25) Console.WriteLine("How many times does each get a turn in 50000 iterations?") TurnCount(191, 50000) TurnCount(1377, 50000) TurnCount(49999, 50000) TurnCount(50000, 50000) TurnCount(50001, 50000) End Sub End Module
#include <iostream> #include <vector> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { printf("Base %2d:", base); for (int i = 0; i < count; i++) { int t = turn(base, i); printf(" %2d", t); } printf("\n"); } void turnCount(int base, int count) { std::vector<int> cnt(base, 0); for (int i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } int minTurn = INT_MAX; int maxTurn = INT_MIN; int portion = 0; for (int i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(" With %d people: ", base); if (0 == minTurn) { printf("Only %d have a turn\n", portion); } else if (minTurn == maxTurn) { printf("%d\n", minTurn); } else { printf("%d or %d\n", minTurn, maxTurn); } } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf("How many times does each get a turn in 50000 iterations?\n"); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
Write the same code in C++ as shown below in VB.
Module Module1 Class SymbolType Public ReadOnly symbol As String Public ReadOnly precedence As Integer Public ReadOnly rightAssociative As Boolean Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean) Me.symbol = symbol Me.precedence = precedence Me.rightAssociative = rightAssociative End Sub End Class ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From { {"^", New SymbolType("^", 4, True)}, {"*", New SymbolType("*", 3, False)}, {"/", New SymbolType("/", 3, False)}, {"+", New SymbolType("+", 2, False)}, {"-", New SymbolType("-", 2, False)} } Function ToPostfix(infix As String) As String Dim tokens = infix.Split(" ") Dim stack As New Stack(Of String) Dim output As New List(Of String) Dim Print = Sub(action As String) Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {String.Join(" ", stack.Reverse())} ]", $"out[ {String.Join(" ", output)} ]") For Each token In tokens Dim iv As Integer Dim op1 As SymbolType Dim op2 As SymbolType If Integer.TryParse(token, iv) Then output.Add(token) Print(token) ElseIf Operators.TryGetValue(token, op1) Then While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2) Dim c = op1.precedence.CompareTo(op2.precedence) If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then output.Add(stack.Pop()) Else Exit While End If End While stack.Push(token) Print(token) ElseIf token = "(" Then stack.Push(token) Print(token) ElseIf token = ")" Then Dim top = "" While stack.Count > 0 top = stack.Pop() If top <> "(" Then output.Add(top) Else Exit While End If End While If top <> "(" Then Throw New ArgumentException("No matching left parenthesis.") End If Print(token) End If Next While stack.Count > 0 Dim top = stack.Pop() If Not Operators.ContainsKey(top) Then Throw New ArgumentException("No matching right parenthesis.") End If output.Add(top) End While Print("pop") Return String.Join(" ", output) End Function Sub Main() Dim infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" Console.WriteLine(ToPostfix(infix)) End Sub End Module
#include <ciso646> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> using std::vector; using std::string; #include <exception> #include <stdexcept> template <typename...Args> std::runtime_error error( Args...args ) { return std::runtime_error( (std::ostringstream{} << ... << args).str() ); }; template <typename T> struct stack : public std::vector <T> { using base_type = std::vector <T> ; T push ( const T& x ) { base_type::push_back( x ); return x; } const T& top () { return base_type::back(); } T pop () { T x = std::move( top() ); base_type::pop_back(); return x; } bool empty() { return base_type::empty(); } }; using Number = double; using Operator_Name = string; using Precedence = int; enum class Associates { none, left_to_right, right_to_left }; struct Operator_Info { Precedence precedence; Associates associativity; }; std::unordered_map <Operator_Name, Operator_Info> Operators = { { "^", { 4, Associates::right_to_left } }, { "*", { 3, Associates::left_to_right } }, { "/", { 3, Associates::left_to_right } }, { "+", { 2, Associates::left_to_right } }, { "-", { 2, Associates::left_to_right } }, }; Precedence precedence ( const Operator_Name& op ) { return Operators[ op ].precedence; } Associates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; } using Token = string; bool is_number ( const Token& t ) { return regex_match( t, std::regex{ R"z((\d+(\.\d*)?|\.\d+)([Ee][\+\-]?\d+)?)z" } ); } bool is_operator ( const Token& t ) { return Operators.count( t ); } bool is_open_parenthesis ( const Token& t ) { return t == "("; } bool is_close_parenthesis( const Token& t ) { return t == ")"; } bool is_parenthesis ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); } template <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs ) { std::size_t n = 0; for (auto x : xs) outs << (n++ ? " " : "") << x; return outs; } #include <iomanip> struct Progressive_Display { string token_name; string token_type; Progressive_Display() { std::cout << "\n" " INPUT │ TYPE │ ACTION │ STACK │ OUTPUT\n" "────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\n"; } Progressive_Display& operator () ( const Token& token ) { token_name = token; token_type = is_operator ( token ) ? "op" : is_parenthesis( token ) ? "()" : is_number ( token ) ? "num" : ""; return *this; } Progressive_Display& operator () ( const string & description, const stack <Token> & stack, const vector <Token> & output ) { std::cout << std::right << std::setw( 7 ) << token_name << " │ " << std::left << std::setw( 4 ) << token_type << " │ " << std::setw( 16 ) << description << " │ " << std::setw( 12 ) << (std::ostringstream{} << stack).str() << " │ " << output << "\n"; return operator () ( "" ); } }; vector <Token> parse( const vector <Token> & tokens ) { vector <Token> output; stack <Token> stack; Progressive_Display display; for (auto token : tokens) if (is_number( token )) { output.push_back( token ); display( token )( "num --> output", stack, output ); } else if (is_operator( token ) or is_parenthesis( token )) { display( token ); if (!is_open_parenthesis( token )) { while (!stack.empty() and ( (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() )) or (precedence( stack.top() ) > precedence( token )) or ( (precedence( stack.top() ) == precedence( token )) and (associativity( token ) == Associates::left_to_right)))) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } if (is_close_parenthesis( token )) { stack.pop(); display( "pop", stack, output ); } } if (!is_close_parenthesis( token )) { stack.push( token ); display( "push op", stack, output ); } } else throw error( "unexpected token: ", token ); display( "END" ); while (!stack.empty()) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } return output; } int main( int argc, char** argv ) try { auto tokens = vector <Token> ( argv+1, argv+argc ); auto rpn_expr = parse( tokens ); std::cout << "\nInfix = " << tokens << "\nRPN = " << rpn_expr << "\n"; } catch (std::exception e) { std::cerr << "error: " << e.what() << "\n"; return 1; }
Port the following code from VB to C++ with equivalent syntax and logic.
Option Strict On Option Explicit On Imports System.IO Module vMain Public Const maxNumber As Integer = 20 Dim prime(2 * maxNumber) As Boolean Public Function countArrangements(ByVal n As Integer) As Integer If n < 2 Then Return 0 ElseIf n < 4 Then For i As Integer = 1 To n Console.Out.Write(i.ToString.PadLeft(3)) Next i Console.Out.WriteLine() Return 1 Else Dim printSolution As Boolean = true Dim used(n) As Boolean Dim number(n) As Integer For i As Integer = 0 To n - 1 number(i) = i Mod 2 Next i used(1) = True number(n) = n used(n) = True Dim count As Integer = 0 Dim p As Integer = 2 Do While p > 0 Dim p1 As Integer = number(p - 1) Dim current As Integer = number(p) Dim [next] As Integer = current + 2 Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next])) [next] += 2 Loop If [next] >= n Then [next] = 0 End If If p = n - 1 Then If [next] <> 0 Then If prime([next] + n) Then count += 1 If printSolution Then For i As Integer = 1 To n - 2 Console.Out.Write(number(i).ToString.PadLeft(3)) Next i Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3)) printSolution = False End If End If [next] = 0 End If p -= 1 End If If [next] <> 0 Then used(current) = False used([next]) = True number(p) = [next] p += 1 ElseIf p <= 2 Then p = 0 Else used(number(p)) = False number(p) = p Mod 2 p -= 1 End If Loop Return count End If End Function Public Sub Main prime(2) = True For i As Integer = 3 To UBound(prime) Step 2 prime(i) = True Next i For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2 If prime(i) Then For s As Integer = i * i To Ubound(prime) Step i + i prime(s) = False Next s End If Next i Dim arrangements(maxNumber) As Integer For n As Integer = 2 To UBound(arrangements) arrangements(n) = countArrangements(n) Next n For n As Integer = 2 To UBound(arrangements) Console.Out.Write(" " & arrangements(n)) Next n Console.Out.WriteLine() End Sub End Module
#include <cassert> #include <chrono> #include <iomanip> #include <iostream> #include <numeric> #include <vector> bool is_prime(unsigned int n) { assert(n > 0 && n < 64); return (1ULL << n) & 0x28208a20a08a28ac; } template <typename Iterator> bool prime_triangle_row(Iterator begin, Iterator end) { if (std::distance(begin, end) == 2) return is_prime(*begin + *(begin + 1)); for (auto i = begin + 1; i + 1 != end; ++i) { if (is_prime(*begin + *i)) { std::iter_swap(i, begin + 1); if (prime_triangle_row(begin + 1, end)) return true; std::iter_swap(i, begin + 1); } } return false; } template <typename Iterator> void prime_triangle_count(Iterator begin, Iterator end, int& count) { if (std::distance(begin, end) == 2) { if (is_prime(*begin + *(begin + 1))) ++count; return; } for (auto i = begin + 1; i + 1 != end; ++i) { if (is_prime(*begin + *i)) { std::iter_swap(i, begin + 1); prime_triangle_count(begin + 1, end, count); std::iter_swap(i, begin + 1); } } } template <typename Iterator> void print(Iterator begin, Iterator end) { if (begin == end) return; auto i = begin; std::cout << std::setw(2) << *i++; for (; i != end; ++i) std::cout << ' ' << std::setw(2) << *i; std::cout << '\n'; } int main() { auto start = std::chrono::high_resolution_clock::now(); for (unsigned int n = 2; n < 21; ++n) { std::vector<unsigned int> v(n); std::iota(v.begin(), v.end(), 1); if (prime_triangle_row(v.begin(), v.end())) print(v.begin(), v.end()); } std::cout << '\n'; for (unsigned int n = 2; n < 21; ++n) { std::vector<unsigned int> v(n); std::iota(v.begin(), v.end(), 1); int count = 0; prime_triangle_count(v.begin(), v.end(), count); if (n > 2) std::cout << ' '; std::cout << count; } std::cout << '\n'; auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "\nElapsed time: " << duration.count() << " seconds\n"; }
Generate an equivalent C++ version of this VB code.
Function tpk(s) arr = Split(s," ") For i = UBound(arr) To 0 Step -1 n = fx(CDbl(arr(i))) If n > 400 Then WScript.StdOut.WriteLine arr(i) & " = OVERFLOW" Else WScript.StdOut.WriteLine arr(i) & " = " & n End If Next End Function Function fx(x) fx = Sqr(Abs(x))+5*x^3 End Function WScript.StdOut.Write "Please enter a series of numbers:" list = WScript.StdIn.ReadLine tpk(list)
#include <iostream> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> int main( ) { std::vector<double> input( 11 ) , results( 11 ) ; std::cout << "Please enter 11 numbers!\n" ; for ( int i = 0 ; i < input.size( ) ; i++ ) std::cin >> input[i]; std::transform( input.begin( ) , input.end( ) , results.begin( ) , [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ; for ( int i = 10 ; i > -1 ; i-- ) { std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ; if ( results[ i ] > 400 ) std::cout << "too large!" ; else std::cout << results[ i ] << " !" ; std::cout << std::endl ; } return 0 ; }
Produce a functionally identical C++ code for the snippet given in VB.
Option Explicit Sub Main_Middle_three_digits() Dim Numbers, i& Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _ 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) For i = 0 To 16 Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i))) Next End Sub Function Middle3digits(strNb As String) As String If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1) If Len(strNb) < 3 Then Middle3digits = "Error ! Number of digits must be >= 3" ElseIf Len(strNb) Mod 2 = 0 Then Middle3digits = "Error ! Number of digits must be odd" Else Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3) End If End Function
#include <iostream> std::string middleThreeDigits(int n) { auto number = std::to_string(std::abs(n)); auto length = number.size(); if (length < 3) { return "less than three digits"; } else if (length % 2 == 0) { return "even number of digits"; } else { return number.substr(length / 2 - 1, 3); } } int main() { auto values {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}; for (auto&& v : values) { std::cout << "middleThreeDigits(" << v << "): " << middleThreeDigits(v) << "\n"; } }
Convert this VB snippet to C++ and keep its semantics consistent.
Private Function OddWordFirst(W As String) As String Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String count = 1 Do flag = Not flag l = FindNextPunct(i, W) - count + 1 If flag Then temp = temp & ExtractWord(W, count, l) Else temp = temp & ReverseWord(W, count, l) End If Loop While count < Len(W) OddWordFirst = temp End Function Private Function FindNextPunct(d As Integer, W As String) As Integer Const PUNCT As String = ",;:." Do d = d + 1 Loop While InStr(PUNCT, Mid(W, d, 1)) = 0 FindNextPunct = d End Function Private Function ExtractWord(W As String, c As Integer, i As Integer) As String ExtractWord = Mid(W, c, i) c = c + Len(ExtractWord) End Function Private Function ReverseWord(W As String, c As Integer, i As Integer) As String Dim temp As String, sep As String temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1) sep = Right(Mid(W, c, i), 1) ReverseWord = StrReverse(temp) & sep c = c + Len(ReverseWord) End Function
#include <iostream> #include <cctype> #include <functional> using namespace std; bool odd() { function<void ()> prev = []{}; while(true) { int c = cin.get(); if (!isalpha(c)) { prev(); cout.put(c); return c != '.'; } prev = [=] { cout.put(c); prev(); }; } } bool even() { while(true) { int c; cout.put(c = cin.get()); if (!isalpha(c)) return c != '.'; } } int main() { bool e = false; while( e ? odd() : even() ) e = !e; return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the VB version.
Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Dim l As List(Of Integer) = {1, 1}.ToList() Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b) End Function Sub Main(ByVal args As String()) Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1, selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1 Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last() Console.Write("The first {0} items In the Stern-Brocot sequence: ", take) Console.WriteLine("{0}" & vbLf, String.Join(", ", l.Take(take))) Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:") For Each ii As Integer In selection Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1 Console.WriteLine("{0,3}: {1:n0}", ii, j) Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For Next Console.WriteLine("The greatest common divisor of all the two consecutive items of the" & " series up to the {0}th item is {1}always one.", max, If(good, "", "not ")) End Sub End Module
#include <iostream> #include <iomanip> #include <algorithm> #include <vector> unsigned gcd( unsigned i, unsigned j ) { return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j; } void createSequence( std::vector<unsigned>& seq, int c ) { if( 1500 == seq.size() ) return; unsigned t = seq.at( c ) + seq.at( c + 1 ); seq.push_back( t ); seq.push_back( seq.at( c + 1 ) ); createSequence( seq, c + 1 ); } int main( int argc, char* argv[] ) { std::vector<unsigned> seq( 2, 1 ); createSequence( seq, 0 ); std::cout << "First fifteen members of the sequence:\n "; for( unsigned x = 0; x < 15; x++ ) { std::cout << seq[x] << " "; } std::cout << "\n\n"; for( unsigned x = 1; x < 11; x++ ) { std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x ); if( i != seq.end() ) { std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } } std::cout << "\n"; std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 ); if( i != seq.end() ) { std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } std::cout << "\n"; unsigned g; bool f = false; for( int x = 0, y = 1; x < 1000; x++, y++ ) { g = gcd( seq[x], seq[y] ); if( g != 1 ) f = true; std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", " << seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" ); } std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n"; return 0; }
Translate the given VB code snippet into C++ without altering its behavior.
Private Sub sierpinski(Order_ As Integer, Side As Double) Dim Circumradius As Double, Inradius As Double Dim Height As Double, Diagonal As Double, HeightDiagonal As Double Dim Pi As Double, p(5) As String, Shp As Shape Circumradius = Sqr(50 + 10 * Sqr(5)) / 10 Inradius = Sqr(25 + 10 * Sqr(5)) / 10 Height = Circumradius + Inradius Diagonal = (1 + Sqr(5)) / 2 HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4 Pi = WorksheetFunction.Pi Ratio = Height / (2 * Height + HeightDiagonal) Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _ 2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side) p(0) = Shp.Name Shp.Rotation = 180 Shp.Line.Weight = 0 For j = 1 To Order_ For i = 0 To 4 Set Shp = Shp.Duplicate p(i + 1) = Shp.Name If i = 0 Then Shp.Rotation = 0 Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5) Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5) Shp.Visible = msoTrue Next i Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group p(0) = Shp.Name If j < Order_ Then Shp.ScaleHeight Ratio, False Shp.ScaleWidth Ratio, False Shp.Rotation = 180 Shp.Left = 2 * Side Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side End If Next j End Sub Public Sub main() sierpinski Order_:=5, Side:=200 End Sub
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { double x, y; friend std::ostream& operator<<(std::ostream& os, const Point& p); }; std::ostream& operator<<(std::ostream& os, const Point& p) { auto f(std::cout.flags()); os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' '; std::cout.flags(f); return os; } struct Turtle { private: Point pos; double theta; bool tracing; public: Turtle() : theta(0.0), tracing(false) { pos.x = 0.0; pos.y = 0.0; } Turtle(double x, double y) : theta(0.0), tracing(false) { pos.x = x; pos.y = y; } Point position() { return pos; } void position(const Point& p) { pos = p; } double heading() { return theta; } void heading(double angle) { theta = angle; } void forward(double dist) { auto dx = dist * cos(theta); auto dy = dist * sin(theta); pos.x += dx; pos.y += dy; if (tracing) { std::cout << pos; } } void right(double angle) { theta -= angle; } void begin_fill() { if (!tracing) { std::cout << "<polygon points=\""; tracing = true; } } void end_fill() { if (tracing) { std::cout << "\"/>\n"; tracing = false; } } }; void pentagon(Turtle& turtle, double size) { turtle.right(degrees(36)); turtle.begin_fill(); for (size_t i = 0; i < 5; i++) { turtle.forward(size); turtle.right(degrees(72)); } turtle.end_fill(); } void sierpinski(int order, Turtle& turtle, double size) { turtle.heading(0.0); auto new_size = size * side_ratio; if (order-- > 1) { for (size_t j = 0; j < 4; j++) { turtle.right(degrees(36)); double small = size * side_ratio / part_ratio; auto distList = { small, size, size, small }; auto dist = *(distList.begin() + j); Turtle spawn{ turtle.position().x, turtle.position().y }; spawn.heading(turtle.heading()); spawn.forward(dist); sierpinski(order, spawn, new_size); } sierpinski(order, turtle, new_size); } else { pentagon(turtle, size); } if (order > 0) { std::cout << '\n'; } } int main() { const int order = 5; double size = 500; Turtle turtle{ size / 2.0, size }; std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n"; std::cout << "<!DOCTYPE svg PUBLIC \" - std::cout << " \"http: std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n"; std::cout << " version=\"1.1\" xmlns=\"http: size *= part_ratio; sierpinski(order, turtle, size); std::cout << "</svg>"; }
Write the same algorithm in C++ as shown in this VB implementation.
Function rep_string(s) max_len = Int(Len(s)/2) tmp = "" If max_len = 0 Then rep_string = "No Repeating String" Exit Function End If For i = 1 To max_len If InStr(i+1,s,tmp & Mid(s,i,1))Then tmp = tmp & Mid(s,i,1) Else Exit For End If Next Do While Len(tmp) > 0 If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then rep_string = tmp Exit Do Else tmp = Mid(tmp,1,Len(tmp)-1) End If Loop If Len(tmp) > 0 Then rep_string = tmp Else rep_string = "No Repeating String" End If End Function arr = Array("1001110011","1110111011","0010010010","1010101010",_ "1111111111","0100101101","0100100","101","11","00","1") For n = 0 To UBound(arr) WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n)) WScript.StdOut.WriteLine Next
#include <string> #include <vector> #include <boost/regex.hpp> bool is_repstring( const std::string & teststring , std::string & repunit ) { std::string regex( "^(.+)\\1+(.*)$" ) ; boost::regex e ( regex ) ; boost::smatch what ; if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) { std::string firstbracket( what[1 ] ) ; std::string secondbracket( what[ 2 ] ) ; if ( firstbracket.length( ) >= secondbracket.length( ) && firstbracket.find( secondbracket ) != std::string::npos ) { repunit = firstbracket ; } } return !repunit.empty( ) ; } int main( ) { std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" , "1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ; std::string theRep ; for ( std::string myString : teststrings ) { if ( is_repstring( myString , theRep ) ) { std::cout << myString << " is a rep string! Here is a repeating string:\n" ; std::cout << theRep << " " ; } else { std::cout << myString << " is no rep string!" ; } theRep.clear( ) ; std::cout << std::endl ; } return 0 ; }
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
Debug.Print "Tom said, ""The fox ran away.""" Debug.Print "Tom said,
auto strA = R"(this is a newline-separated raw string)";
Produce a language-to-language conversion: from VB to C++, same semantics.
Enum fruits apple banana cherry End Enum Enum fruits2 pear = 5 mango = 10 kiwi = 20 pineapple = 20 End Enum Sub test() Dim f As fruits f = apple Debug.Print "apple equals "; f Debug.Print "kiwi equals "; kiwi Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple End Sub
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
Convert this VB block to C++, preserving its control flow and logic.
Function parse_ip(addr) Set ipv4_pattern = New RegExp ipv4_pattern.Global = True ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}" Set ipv6_pattern = New RegExp ipv6_pattern.Global = True ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}" If ipv4_pattern.Test(addr) Then port = Split(addr,":") octet = Split(port(0),".") ipv4_hex = "" For i = 0 To UBound(octet) If octet(i) <= 255 And octet(i) >= 0 Then ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2) Else ipv4_hex = "Erroneous Address" Exit For End If Next parse_ip = "Test Case: " & addr & vbCrLf &_ "Address: " & ipv4_hex & vbCrLf If UBound(port) = 1 Then If port(1) <= 65535 And port(1) >= 0 Then parse_ip = parse_ip & "Port: " & port(1) & vbCrLf Else parse_ip = parse_ip & "Port: Invalid" & vbCrLf End If End If End If If ipv6_pattern.Test(addr) Then parse_ip = "Test Case: " & addr & vbCrLf port_v6 = "Port: " ipv6_hex = "" If InStr(1,addr,"[") Then port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1))) addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1)) End If word = Split(addr,":") word_count = 0 For i = 0 To UBound(word) If word(i) = "" Then If i < UBound(word) Then If Int((7-(i+1))/2) = 1 Then k = 1 ElseIf UBound(word) < 6 Then k = Int((7-(i+1))/2) ElseIf UBound(word) >= 6 Then k = Int((7-(i+1))/2)-1 End If For j = 0 To k ipv6_hex = ipv6_hex & "0000" word_count = word_count + 1 Next Else For j = 0 To (7-word_count) ipv6_hex = ipv6_hex & "0000" Next End If Else ipv6_hex = ipv6_hex & Right("0000" & word(i),4) word_count = word_count + 1 End If Next parse_ip = parse_ip & "Address: " & ipv6_hex &_ vbCrLf & port_v6 & vbCrLf End If If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then parse_ip = "Test Case: " & addr & vbCrLf &_ "Address: Invalid Address" & vbCrLf End If End Function ip_arr = Array("127.0.0.1","127.0.0.1:80","::1",_ "[::1]:80","2605:2700:0:3::4713:93e3","[2605:2700:0:3::4713:93e3]:80","RosettaCode") For n = 0 To UBound(ip_arr) WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf Next
#include <boost/asio/ip/address.hpp> #include <cstdint> #include <iostream> #include <iomanip> #include <limits> #include <string> using boost::asio::ip::address; using boost::asio::ip::address_v4; using boost::asio::ip::address_v6; using boost::asio::ip::make_address; using boost::asio::ip::make_address_v4; using boost::asio::ip::make_address_v6; template<typename uint> bool parse_int(const std::string& str, int base, uint& n) { try { size_t pos = 0; unsigned long u = stoul(str, &pos, base); if (pos != str.length() || u > std::numeric_limits<uint>::max()) return false; n = static_cast<uint>(u); return true; } catch (const std::exception& ex) { return false; } } void parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) { size_t pos = input.rfind(':'); if (pos != std::string::npos && pos > 1 && pos + 1 < input.length() && parse_int(input.substr(pos + 1), 10, port) && port > 0) { if (input[0] == '[' && input[pos - 1] == ']') { addr = make_address_v6(input.substr(1, pos - 2)); return; } else { try { addr = make_address_v4(input.substr(0, pos)); return; } catch (const std::exception& ex) { } } } port = 0; addr = make_address(input); } void print_address_and_port(const address& addr, uint16_t port) { std::cout << std::hex << std::uppercase << std::setfill('0'); if (addr.is_v4()) { address_v4 addr4 = addr.to_v4(); std::cout << "address family: IPv4\n"; std::cout << "address number: " << std::setw(8) << addr4.to_uint() << '\n'; } else if (addr.is_v6()) { address_v6 addr6 = addr.to_v6(); address_v6::bytes_type bytes(addr6.to_bytes()); std::cout << "address family: IPv6\n"; std::cout << "address number: "; for (unsigned char byte : bytes) std::cout << std::setw(2) << static_cast<unsigned int>(byte); std::cout << '\n'; } if (port != 0) std::cout << "port: " << std::dec << port << '\n'; else std::cout << "port not specified\n"; } void test(const std::string& input) { std::cout << "input: " << input << '\n'; try { address addr; uint16_t port = 0; parse_ip_address_and_port(input, addr, port); print_address_and_port(addr, port); } catch (const std::exception& ex) { std::cout << "parsing failed\n"; } std::cout << '\n'; } int main(int argc, char** argv) { test("127.0.0.1"); test("127.0.0.1:80"); test("::ffff:127.0.0.1"); test("::1"); test("[::1]:80"); test("1::80"); test("2605:2700:0:3::4713:93e3"); test("[2605:2700:0:3::4713:93e3]:80"); return 0; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1) Set objKeyMap = CreateObject("Scripting.Dictionary") With objKeyMap .Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5" .Add "MNO", "6" : .Add "PQRS", "7" : .Add "TUV", "8" : .Add "WXYZ", "9" End With TotalWords = 0 UniqueCombinations = 0 Set objUniqueWords = CreateObject("Scripting.Dictionary") Set objMoreThanOneWord = CreateObject("Scripting.Dictionary") Do Until objInFile.AtEndOfStream Word = objInFile.ReadLine c = 0 Num = "" If Word <> "" Then For i = 1 To Len(Word) For Each Key In objKeyMap.Keys If InStr(1,Key,Mid(Word,i,1),1) > 0 Then Num = Num & objKeyMap.Item(Key) c = c + 1 End If Next Next If c = Len(Word) Then TotalWords = TotalWords + 1 If objUniqueWords.Exists(Num) = False Then objUniqueWords.Add Num, "" UniqueCombinations = UniqueCombinations + 1 Else If objMoreThanOneWord.Exists(Num) = False Then objMoreThanOneWord.Add Num, "" End If End If End If End If Loop WScript.Echo "There are " & TotalWords & " words in ""unixdict.txt"" which can be represented by the digit key mapping." & vbCrLf &_ "They require " & UniqueCombinations & " digit combinations to represent them." & vbCrLf &_ objMoreThanOneWord.Count & " digit combinations represent Textonyms." objInFile.Close
#include <fstream> #include <iostream> #include <unordered_map> #include <vector> struct Textonym_Checker { private: int total; int elements; int textonyms; int max_found; std::vector<std::string> max_strings; std::unordered_map<std::string, std::vector<std::string>> values; int get_mapping(std::string &result, const std::string &input) { static std::unordered_map<char, char> mapping = { {'A', '2'}, {'B', '2'}, {'C', '2'}, {'D', '3'}, {'E', '3'}, {'F', '3'}, {'G', '4'}, {'H', '4'}, {'I', '4'}, {'J', '5'}, {'K', '5'}, {'L', '5'}, {'M', '6'}, {'N', '6'}, {'O', '6'}, {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'}, {'T', '8'}, {'U', '8'}, {'V', '8'}, {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'} }; result = input; for (char &c : result) { if (!isalnum(c)) return 0; if (isalpha(c)) c = mapping[toupper(c)]; } return 1; } public: Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { } ~Textonym_Checker() { } void add(const std::string &str) { std::string mapping; total++; if (!get_mapping(mapping, str)) return; const int num_strings = values[mapping].size(); if (num_strings == 1) textonyms++; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.push_back(mapping); max_found = num_strings; } else if (num_strings == max_found) max_strings.push_back(mapping); values[mapping].push_back(str); } void results(const std::string &filename) { std::cout << "Read " << total << " words from " << filename << "\n\n"; std::cout << "There are " << elements << " words in " << filename; std::cout << " which can be represented by the digit key mapping.\n"; std::cout << "They require " << values.size() << " digit combinations to represent them.\n"; std::cout << textonyms << " digit combinations represent Textonyms.\n\n"; std::cout << "The numbers mapping to the most words map to "; std::cout << max_found + 1 << " words each:\n"; for (auto it1 : max_strings) { std::cout << '\t' << it1 << " maps to: "; for (auto it2 : values[it1]) std::cout << it2 << " "; std::cout << '\n'; } std::cout << '\n'; } void match(const std::string &str) { auto match = values.find(str); if (match == values.end()) { std::cout << "Key '" << str << "' not found\n"; } else { std::cout << "Key '" << str << "' matches: "; for (auto it : values[str]) std::cout << it << " "; std::cout << '\n'; } } }; int main() { auto filename = "unixdict.txt"; std::ifstream input(filename); Textonym_Checker tc; if (input.is_open()) { std::string line; while (getline(input, line)) tc.add(line); } input.close(); tc.results(filename); tc.match("001"); tc.match("228"); tc.match("27484247"); tc.match("7244967473642"); }
Maintain the same structure and functionality when rewriting this code in C++.
Public Function RangeExtraction(AList) As String Const RangeDelim = "-" Dim result As String Dim InRange As Boolean Dim Posn, ub, lb, rangestart, rangelen As Integer result = "" ub = UBound(AList) lb = LBound(AList) Posn = lb While Posn < ub rangestart = Posn rangelen = 0 InRange = True While InRange rangelen = rangelen + 1 If Posn = ub Then InRange = False Else InRange = (AList(Posn + 1) = AList(Posn) + 1) Posn = Posn + 1 End If Wend If rangelen > 2 Then result = result & "," & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1)) Else For i = rangestart To rangestart + rangelen - 1 result = result & "," & Format$(AList(i)) Next End If Posn = rangestart + rangelen Wend RangeExtraction = Mid$(result, 2) End Function Public Sub RangeTest() Dim MyList As Variant MyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39) Debug.Print "a) "; RangeExtraction(MyList) Dim MyOtherList(1 To 20) As Integer MyOtherList(1) = -6 MyOtherList(2) = -3 MyOtherList(3) = -2 MyOtherList(4) = -1 MyOtherList(5) = 0 MyOtherList(6) = 1 MyOtherList(7) = 3 MyOtherList(8) = 4 MyOtherList(9) = 5 MyOtherList(10) = 7 MyOtherList(11) = 8 MyOtherList(12) = 9 MyOtherList(13) = 10 MyOtherList(14) = 11 MyOtherList(15) = 14 MyOtherList(16) = 15 MyOtherList(17) = 17 MyOtherList(18) = 18 MyOtherList(19) = 19 MyOtherList(20) = 20 Debug.Print "b) "; RangeExtraction(MyOtherList) End Sub
#include <iostream> #include <iterator> #include <cstddef> template<typename InIter> void extract_ranges(InIter begin, InIter end, std::ostream& os) { if (begin == end) return; int current = *begin++; os << current; int count = 1; while (begin != end) { int next = *begin++; if (next == current+1) ++count; else { if (count > 2) os << '-'; else os << ','; if (count > 1) os << current << ','; os << next; count = 1; } current = next; } if (count > 1) os << (count > 2? '-' : ',') << current; } template<typename T, std::size_t n> T* end(T (&array)[n]) { return array+n; } int main() { int data[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; extract_ranges(data, end(data), std::cout); std::cout << std::endl; }
Convert this VB block to C++, preserving its control flow and logic.
Public Sub main() Dim c(1) As Currency Dim d(1) As Double Dim dt(1) As Date Dim a(1) As Integer Dim l(1) As Long Dim s(1) As Single Dim e As Variant Dim o As Object Set o = New Application Debug.Print TypeName(o) Debug.Print TypeName(1 = 1) Debug.Print TypeName(CByte(1)) Set o = New Collection Debug.Print TypeName(o) Debug.Print TypeName(1@) Debug.Print TypeName(c) Debug.Print TypeName(CDate(1)) Debug.Print TypeName(dt) Debug.Print TypeName(CDec(1)) Debug.Print TypeName(1#) Debug.Print TypeName(d) Debug.Print TypeName(e) Debug.Print TypeName(CVErr(1)) Debug.Print TypeName(1) Debug.Print TypeName(a) Debug.Print TypeName(1&) Debug.Print TypeName(l) Set o = Nothing Debug.Print TypeName(o) Debug.Print TypeName([A1]) Debug.Print TypeName(1!) Debug.Print TypeName(s) Debug.Print TypeName(CStr(1)) Debug.Print TypeName(Worksheets(1)) End Sub
#include <iostream> template <typename T> auto typeString(const T&) { return typeid(T).name(); } class C {}; struct S {}; int main() { std::cout << typeString(1) << '\n'; std::cout << typeString(1L) << '\n'; std::cout << typeString(1.0f) << '\n'; std::cout << typeString(1.0) << '\n'; std::cout << typeString('c') << '\n'; std::cout << typeString("string") << '\n'; std::cout << typeString(C{}) << '\n'; std::cout << typeString(S{}) << '\n'; std::cout << typeString(nullptr) << '\n'; }
Change the following VB code into C++ without altering its purpose.
Set objfso = CreateObject("Scripting.FileSystemObject") Set objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\triangle.txt",1,False) row = Split(objinfile.ReadAll,vbCrLf) For i = UBound(row) To 0 Step -1 row(i) = Split(row(i)," ") If i < UBound(row) Then For j = 0 To UBound(row(i)) If (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j)) Else row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1)) End If Next End If Next WScript.Echo row(0)(0) objinfile.Close Set objfso = Nothing
#include <iostream> int main( int argc, char* argv[] ) { int triangle[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; const int size = sizeof( triangle ) / sizeof( int ); const int tn = static_cast<int>(sqrt(2.0 * size)); assert(tn * (tn + 1) == 2 * size); for (int n = tn - 1; n > 0; --n) for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]); std::cout << "Maximum total: " << triangle[0] << "\n\n"; }
Keep all operations the same but rewrite the snippet in C++.
Public n As Variant Private Sub init() n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}] End Sub Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant Dim wtb As Integer Dim bn As Integer Dim prev As String: prev = "#" Dim next_ As String Dim p2468 As String For i = 1 To UBound(n) next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1) wtb = wtb - (prev = "." And next_ <= "#") bn = bn - (i > 1 And next_ <= "#") If (i And 1) = 0 Then p2468 = p2468 & prev prev = next_ Next i If step = 2 Then p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2) End If Dim ret(2) As Variant ret(0) = wtb ret(1) = bn ret(2) = p2468 AB = ret End Function Private Sub Zhang_Suen(text As Variant) Dim wtb As Integer Dim bn As Integer Dim changed As Boolean, changes As Boolean Dim p2468 As String Dim x As Integer, y As Integer, step As Integer Do While True changed = False For step = 1 To 2 changes = False For y = 1 To UBound(text) - 1 For x = 2 To Len(text(y)) - 1 If Mid(text(y), x, 1) = "#" Then ret = AB(text, y, x, step) wtb = ret(0) bn = ret(1) p2468 = ret(2) If wtb = 1 _ And bn >= 2 And bn <= 6 _ And InStr(1, Mid(p2468, 1, 3), ".") _ And InStr(1, Mid(p2468, 2, 3), ".") Then changes = True text(y) = Left(text(y), x - 1) & "!" & Right(text(y), Len(text(y)) - x) End If End If Next x Next y If changes Then For y = 1 To UBound(text) - 1 text(y) = Replace(text(y), "!", ".") Next y changed = True End If Next step If Not changed Then Exit Do Loop Debug.Print Join(text, vbCrLf) End Sub Public Sub main() init Dim Small_rc(9) As String Small_rc(0) = "................................" Small_rc(1) = ".#########.......########......." Small_rc(2) = ".###...####.....####..####......" Small_rc(3) = ".###....###.....###....###......" Small_rc(4) = ".###...####.....###............." Small_rc(5) = ".#########......###............." Small_rc(6) = ".###.####.......###....###......" Small_rc(7) = ".###..####..###.####..####.###.." Small_rc(8) = ".###...####.###..########..###.." Small_rc(9) = "................................" Zhang_Suen (Small_rc) End Sub
#include <iostream> #include <string> #include <sstream> #include <valarray> const std::string input { "................................" ".#########.......########......." ".###...####.....####..####......" ".###....###.....###....###......" ".###...####.....###............." ".#########......###............." ".###.####.......###....###......" ".###..####..###.####..####.###.." ".###...####.###..########..###.." "................................" }; const std::string input2 { ".........................................................." ".#################...................#############........" ".##################...............################........" ".###################............##################........" ".########.....#######..........###################........" "...######.....#######.........#######.......######........" "...######.....#######........#######......................" "...#################.........#######......................" "...################..........#######......................" "...#################.........#######......................" "...######.....#######........#######......................" "...######.....#######........#######......................" "...######.....#######.........#######.......######........" ".########.....#######..........###################........" ".########.....#######.######....##################.######." ".########.....#######.######......################.######." ".########.....#######.######.........#############.######." ".........................................................." }; class ZhangSuen; class Image { public: friend class ZhangSuen; using pixel_t = char; static const pixel_t BLACK_PIX; static const pixel_t WHITE_PIX; Image(unsigned width = 1, unsigned height = 1) : width_{width}, height_{height}, data_( '\0', width_ * height_) {} Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_} {} Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)} {} ~Image() = default; Image& operator=(const Image& i) { if (this != &i) { width_ = i.width_; height_ = i.height_; data_ = i.data_; } return *this; } Image& operator=(Image&& i) { if (this != &i) { width_ = i.width_; height_ = i.height_; data_ = std::move(i.data_); } return *this; } size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; } bool operator()(unsigned x, unsigned y) { return data_[idx(x, y)]; } friend std::ostream& operator<<(std::ostream& o, const Image& i) { o << i.width_ << " x " << i.height_ << std::endl; size_t px = 0; for(const auto& e : i.data_) { o << (e?Image::BLACK_PIX:Image::WHITE_PIX); if (++px % i.width_ == 0) o << std::endl; } return o << std::endl; } friend std::istream& operator>>(std::istream& in, Image& img) { auto it = std::begin(img.data_); const auto end = std::end(img.data_); Image::pixel_t tmp; while(in && it != end) { in >> tmp; if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX) throw "Bad character found in image"; *it = (tmp == Image::BLACK_PIX)?1:0; ++it; } return in; } unsigned width() const noexcept { return width_; } unsigned height() const noexcept { return height_; } struct Neighbours { Neighbours(const Image& img, unsigned p1_x, unsigned p1_y) : img_{img} , p1_{img.idx(p1_x, p1_y)} , p2_{p1_ - img.width()} , p3_{p2_ + 1} , p4_{p1_ + 1} , p5_{p4_ + img.width()} , p6_{p5_ - 1} , p7_{p6_ - 1} , p8_{p1_ - 1} , p9_{p2_ - 1} {} const Image& img_; const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; } const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; } const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; } const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; } const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; } const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; } const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; } const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; } const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; } const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_; }; Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); } private: unsigned height_ { 0 }; unsigned width_ { 0 }; std::valarray<pixel_t> data_; }; constexpr const Image::pixel_t Image::BLACK_PIX = '#'; constexpr const Image::pixel_t Image::WHITE_PIX = '.'; class ZhangSuen { public: unsigned transitions_white_black(const Image::Neighbours& a) const { unsigned sum = 0; sum += (a.p9() == 0) && a.p2(); sum += (a.p2() == 0) && a.p3(); sum += (a.p3() == 0) && a.p4(); sum += (a.p8() == 0) && a.p9(); sum += (a.p4() == 0) && a.p5(); sum += (a.p7() == 0) && a.p8(); sum += (a.p6() == 0) && a.p7(); sum += (a.p5() == 0) && a.p6(); return sum; } unsigned black_pixels(const Image::Neighbours& a) const { unsigned sum = 0; sum += a.p9(); sum += a.p2(); sum += a.p3(); sum += a.p8(); sum += a.p4(); sum += a.p7(); sum += a.p6(); sum += a.p5(); return sum; } const Image& operator()(const Image& img) { tmp_a_ = img; size_t changed_pixels = 0; do { changed_pixels = 0; tmp_b_ = tmp_a_; for(size_t y = 1; y < tmp_a_.height() - 1; ++y) { for(size_t x = 1; x < tmp_a_.width() - 1; ++x) { if (tmp_a_.data_[tmp_a_.idx(x, y)]) { auto n = tmp_a_.neighbours(x, y); auto bp = black_pixels(n); if (bp >= 2 && bp <= 6) { auto tr = transitions_white_black(n); if ( tr == 1 && (n.p2() * n.p4() * n.p6() == 0) && (n.p4() * n.p6() * n.p8() == 0) ) { tmp_b_.data_[n.p1_] = 0; ++changed_pixels; } } } } } tmp_a_ = tmp_b_; for(size_t y = 1; y < tmp_b_.height() - 1; ++y) { for(size_t x = 1; x < tmp_b_.width() - 1; ++x) { if (tmp_b_.data_[tmp_b_.idx(x, y)]) { auto n = tmp_b_.neighbours(x, y); auto bp = black_pixels(n); if (bp >= 2 && bp <= 6) { auto tr = transitions_white_black(n); if ( tr == 1 && (n.p2() * n.p4() * n.p8() == 0) && (n.p2() * n.p6() * n.p8() == 0) ) { tmp_a_.data_[n.p1_] = 0; ++changed_pixels; } } } } } } while(changed_pixels > 0); return tmp_a_; } private: Image tmp_a_; Image tmp_b_; }; int main(int argc, char const *argv[]) { using namespace std; Image img(32, 10); istringstream iss{input}; iss >> img; cout << img; cout << "ZhangSuen" << endl; ZhangSuen zs; Image res = std::move(zs(img)); cout << res << endl; Image img2(58,18); istringstream iss2{input2}; iss2 >> img2; cout << img2; cout << "ZhangSuen with big image" << endl; Image res2 = std::move(zs(img2)); cout << res2 << endl; return 0; }
Preserve the algorithm and functionality while converting the code from VB to C++.
Option Strict On Option Explicit On Imports System.IO Module vMain Public Sub Main Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5} For i As Integer = 0 To Ubound(s) Dim curr As Integer = s(i) Dim prev As Integer If i > 1 AndAlso curr = prev Then Console.Out.WriteLine(i) End If prev = curr Next i End Sub End Module
#include <array> #include <iostream> int main() { constexpr std::array s {1,2,2,3,4,4,5}; if(!s.empty()) { int previousValue = s[0]; for(size_t i = 1; i < s.size(); ++i) { const int currentValue = s[i]; if(i > 0 && previousValue == currentValue) { std::cout << i << "\n"; } previousValue = currentValue; } } }
Translate the given VB code snippet into C++ without altering its behavior.
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public property let iangle(n):iang= n*pi180 :end property public sub pd() : pdown=true: end sub public sub pu() :pdown=FALSE :end sub public sub rt(i) ori=ori - i*iang: if ori<0 then ori = ori+pi*2 end sub public sub lt(i): ori=(ori + i*iang) if ori>(pi*2) then ori=ori-pi*2 end sub public sub bw(l) x= x+ cos(ori+pi)*l*incr y= y+ sin(ori+pi)*l*incr end sub public sub fw(l) dim x1,y1 x1=x + cos(ori)*l*incr y1=y + sin(ori)*l*incr if pdown then line x,y,x1,y1 x=x1:y=y1 end sub Private Sub Class_Initialize() setlocale "us" initsvg pdown=true end sub Private Sub Class_Terminate() disply end sub private sub line (x,y,x1,y1) svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>" end sub private sub disply() dim shell svg.WriteLine "</svg></body></html>" svg.close Set shell = CreateObject("Shell.Application") shell.ShellExecute fn,1,False end sub private sub initsvg() dim scriptpath Set fso = CreateObject ("Scripting.Filesystemobject") ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) fn=Scriptpath & "SIERP.HTML" Set svg = fso.CreateTextFile(fn,True) if SVG IS nothing then wscript.echo "Can svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>" svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>" svg.writeline "</head>"&vbcrlf & "<body>" svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" end sub end class sub koch (n,le) if n=0 then x.fw le :exit sub koch n-1, le/3 x.lt 1 koch n-1, le/3 x.rt 2 koch n-1, le/3 x.lt 1 koch n-1, le/3 end sub dim x,i set x=new turtle x.iangle=60 x.orient=0 x.incr=3 x.x=100:x.y=300 for i=0 to 3 koch 7,100 x.rt 2 next set x=nothing
#include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; struct point { double x; double y; }; std::vector<point> koch_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(4*(size - 1) + 1); double x0, y0, x1, y1; size_t j = 0; for (size_t i = 0; i + 1 < size; ++i) { x0 = points[i].x; y0 = points[i].y; x1 = points[i + 1].x; y1 = points[i + 1].y; double dy = y1 - y0; double dx = x1 - x0; output[j++] = {x0, y0}; output[j++] = {x0 + dx/3, y0 + dy/3}; output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3}; output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3}; } output[j] = {x1, y1}; return output; } std::vector<point> koch_points(int size, int iterations) { double length = size * sqrt3_2 * 0.95; double x = (size - length)/2; double y = size/2 - length * sqrt3_2/3; std::vector<point> points{ {x, y}, {x + length/2, y + length * sqrt3_2}, {x + length, y}, {x, y} }; for (int i = 0; i < iterations; ++i) points = koch_next(points); return points; } void koch_curve_svg(std::ostream& out, int size, int iterations) { out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << "<path stroke-width='1' stroke='white' fill='none' d='"; auto points(koch_points(size, iterations)); for (size_t i = 0, n = points.size(); i < n; ++i) out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n'; out << "z'/>\n</svg>\n"; } int main() { std::ofstream out("koch_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } koch_curve_svg(out, 600, 5); return EXIT_SUCCESS; }
Produce a language-to-language conversion: from VB to C++, same semantics.
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) set d=createobject("scripting.dictionary") redim b(ubound(a)) i=0 for each x in a s=trim(x) if len(s)>=9 then if len(s)= 9 then d.add s,"" b(i)=s i=i+1 end if next redim preserve b(i-1) wscript.echo i j=1 for i=0 to ubound(b)-9 s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_ mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1) if d.exists(s9) then wscript.echo j,s9 d.remove(s9) j=j+1 end if next
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int main(int argc, char** argv) { const int min_length = 9; const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string line; std::vector<std::string> words; while (getline(in, line)) { if (line.size() >= min_length) words.push_back(line); } std::sort(words.begin(), words.end()); std::string previous_word; int count = 0; for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) { std::string word; word.reserve(min_length); for (size_t j = 0; j < min_length; ++j) word += words[i + j][j]; if (previous_word == word) continue; auto w = std::lower_bound(words.begin(), words.end(), word); if (w != words.end() && *w == word) std::cout << std::setw(2) << ++count << ". " << word << '\n'; previous_word = word; } return EXIT_SUCCESS; }
Produce a functionally identical C++ code for the snippet given in VB.
n=8 pattern="1001011001101001" size=n*n: w=len(size) mult=n\4 wscript.echo "Magic square : " & n & " x " & n i=0 For r=0 To n-1 l="" For c=0 To n-1 bit=Mid(pattern, c\mult+(r\mult)*4+1, 1) If bit="1" Then t=i+1 Else t=size-i l=l & Right(Space(w) & t, w) & " " i=i+1 Next wscript.echo l Next wscript.echo "Magic constant=" & (n*n+1)*n/2
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr( int d ) { while( d % 4 > 0 ) { d++; } sz = d; sqr = new int[sz * sz]; fillSqr(); } ~magicSqr() { delete [] sqr; } void display() const { cout << "Doubly Even 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() { static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } }; int i = 0; for( int curRow = 0; curRow < sz; curRow++ ) { for( int curCol = 0; curCol < sz; curCol++ ) { sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i; i++; } } } int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s( 8 ); s.display(); return 0; }
Produce a language-to-language conversion: from VB to C++, same semantics.
Function mtf_encode(s) Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 symbol_table.Add Chr(j) Next output = "" For i = 1 To Len(s) char = Mid(s,i,1) If i = Len(s) Then output = output & symbol_table.IndexOf(char,0) symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char Else output = output & symbol_table.IndexOf(char,0) & " " symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char End If Next mtf_encode = output End Function Function mtf_decode(s) code = Split(s," ") Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 symbol_table.Add Chr(j) Next output = "" For i = 0 To UBound(code) char = symbol_table(code(i)) output = output & char If code(i) <> 0 Then symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char End If Next mtf_decode = output End Function wordlist = Array("broood","bananaaa","hiphophiphop") For Each word In wordlist WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_ mtf_decode(mtf_encode(word)) & "." WScript.StdOut.WriteBlankLines(1) Next
#include <iostream> #include <iterator> #include <sstream> #include <vector> using namespace std; class MTF { public: string encode( string str ) { fillSymbolTable(); vector<int> output; for( string::iterator it = str.begin(); it != str.end(); it++ ) { for( int i = 0; i < 26; i++ ) { if( *it == symbolTable[i] ) { output.push_back( i ); moveToFront( i ); break; } } } string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { ostringstream ss; ss << *it; r += ss.str() + " "; } return r; } string decode( string str ) { fillSymbolTable(); istringstream iss( str ); vector<int> output; copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) ); string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { r.append( 1, symbolTable[*it] ); moveToFront( *it ); } return r; } private: void moveToFront( int i ) { char t = symbolTable[i]; for( int z = i - 1; z >= 0; z-- ) symbolTable[z + 1] = symbolTable[z]; symbolTable[0] = t; } void fillSymbolTable() { for( int x = 0; x < 26; x++ ) symbolTable[x] = x + 'a'; } char symbolTable[26]; }; int main() { MTF mtf; string a, str[] = { "broood", "bananaaa", "hiphophiphop" }; for( int x = 0; x < 3; x++ ) { a = str[x]; cout << a << " -> encoded = "; a = mtf.encode( a ); cout << a << "; decoded = " << mtf.decode( a ) << endl; } return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the VB version.
Function LIS(arr) n = UBound(arr) Dim p() ReDim p(n) Dim m() ReDim m(n) l = 0 For i = 0 To n lo = 1 hi = l Do While lo <= hi middle = Int((lo+hi)/2) If arr(m(middle)) < arr(i) Then lo = middle + 1 Else hi = middle - 1 End If Loop newl = lo p(i) = m(newl-1) m(newl) = i If newL > l Then l = newl End If Next Dim s() ReDim s(l) k = m(l) For i = l-1 To 0 Step - 1 s(i) = arr(k) k = p(k) Next LIS = Join(s,",") End Function WScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1)) WScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))
#include <vector> #include <list> #include <algorithm> #include <iostream> template <typename T> struct Node { T value; Node* prev_node; }; template <typename Container> Container lis(const Container& values) { using E = typename Container::value_type; using NodePtr = Node<E>*; using ConstNodePtr = const NodePtr; std::vector<NodePtr> pileTops; std::vector<Node<E>> nodes(values.size()); auto cur_node = std::begin(nodes); for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node) { auto node = &*cur_node; node->value = *cur_value; auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node, [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; }); if (lb != pileTops.begin()) node->prev_node = *std::prev(lb); if (lb == pileTops.end()) pileTops.push_back(node); else *lb = node; } Container result(pileTops.size()); auto r = std::rbegin(result); for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r) *r = node->value; return result; } template <typename Container> void show_lis(const Container& values) { auto&& result = lis(values); for (auto& r : result) { std::cout << r << ' '; } std::cout << std::endl; } int main() { show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 }); show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }); }
Maintain the same structure and functionality when rewriting this code in C++.
Module Module1 Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String) Dim out As New List(Of String) Dim comma = False While Not String.IsNullOrEmpty(s) Dim gs = GetItem(s, depth) Dim g = gs.Item1 s = gs.Item2 If String.IsNullOrEmpty(s) Then Exit While End If out.AddRange(g) If s(0) = "}" Then If comma Then Return Tuple.Create(out, s.Substring(1)) End If Return Tuple.Create(out.Select(Function(a) "{" + a + "}").ToList(), s.Substring(1)) End If If s(0) = "," Then comma = True s = s.Substring(1) End If End While Return Nothing End Function Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String) Dim out As New List(Of String) From {""} While Not String.IsNullOrEmpty(s) Dim c = s(0) If depth > 0 AndAlso (c = "," OrElse c = "}") Then Return Tuple.Create(out, s) End If If c = "{" Then Dim x = GetGroup(s.Substring(1), depth + 1) If Not IsNothing(x) Then Dim tout As New List(Of String) For Each a In out For Each b In x.Item1 tout.Add(a + b) Next Next out = tout s = x.Item2 Continue While End If End If If c = "\" AndAlso s.Length > 1 Then c += s(1) s = s.Substring(1) End If out = out.Select(Function(a) a + c).ToList() s = s.Substring(1) End While Return Tuple.Create(out, s) End Function Sub Main() For Each s In { "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\, again\, }}more }cowbell!", "{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}" } Dim fmt = "{0}" + vbNewLine + vbTab + "{1}" Dim parts = GetItem(s) Dim res = String.Join(vbNewLine + vbTab, parts.Item1) Console.WriteLine(fmt, s, res) Next End Sub End Module
#include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> namespace detail { template <typename ForwardIterator> class tokenizer { ForwardIterator _tbegin, _tend, _end; public: tokenizer(ForwardIterator begin, ForwardIterator end) : _tbegin(begin), _tend(begin), _end(end) { } template <typename Lambda> bool next(Lambda istoken) { if (_tbegin == _end) { return false; } _tbegin = _tend; for (; _tend != _end && !istoken(*_tend); ++_tend) { if (*_tend == '\\' && std::next(_tend) != _end) { ++_tend; } } if (_tend == _tbegin) { _tend++; } return _tbegin != _end; } ForwardIterator begin() const { return _tbegin; } ForwardIterator end() const { return _tend; } bool operator==(char c) { return *_tbegin == c; } }; template <typename List> void append_all(List & lista, const List & listb) { if (listb.size() == 1) { for (auto & a : lista) { a += listb.back(); } } else { List tmp; for (auto & a : lista) { for (auto & b : listb) { tmp.push_back(a + b); } } lista = std::move(tmp); } } template <typename String, typename List, typename Tokenizer> List expand(Tokenizer & token) { std::vector<List> alts{ { String() } }; while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) { if (token == '{') { append_all(alts.back(), expand<String, List>(token)); } else if (token == ',') { alts.push_back({ String() }); } else if (token == '}') { if (alts.size() == 1) { for (auto & a : alts.back()) { a = '{' + a + '}'; } return alts.back(); } else { for (std::size_t i = 1; i < alts.size(); i++) { alts.front().insert(alts.front().end(), std::make_move_iterator(std::begin(alts[i])), std::make_move_iterator(std::end(alts[i]))); } return std::move(alts.front()); } } else { for (auto & a : alts.back()) { a.append(token.begin(), token.end()); } } } List result{ String{ '{' } }; append_all(result, alts.front()); for (std::size_t i = 1; i < alts.size(); i++) { for (auto & a : result) { a += ','; } append_all(result, alts[i]); } return result; } } template < typename ForwardIterator, typename String = std::basic_string< typename std::iterator_traits<ForwardIterator>::value_type >, typename List = std::vector<String> > List expand(ForwardIterator begin, ForwardIterator end) { detail::tokenizer<ForwardIterator> token(begin, end); List list{ String() }; while (token.next([](char c) { return c == '{'; })) { if (token == '{') { detail::append_all(list, detail::expand<String, List>(token)); } else { for (auto & a : list) { a.append(token.begin(), token.end()); } } } return list; } template < typename Range, typename String = std::basic_string<typename Range::value_type>, typename List = std::vector<String> > List expand(const Range & range) { using Iterator = typename Range::const_iterator; return expand<Iterator, String, List>(std::begin(range), std::end(range)); } int main() { for (std::string string : { R"(~/{Downloads,Pictures}/*.{jpg,gif,png})", R"(It{{em,alic}iz,erat}e{d,}, please.)", R"({,{,gotta have{ ,\, again\, }}more }cowbell!)", R"({}} some {\\{edge,edgy} }{ cases, here\\\})", R"(a{b{1,2}c)", R"(a{1,2}b}c)", R"(a{1,{2},3}b)", R"(a{b{1,2}c{}})", R"(more{ darn{ cowbell,},})", R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)", R"({a,{\,b}c)", R"(a{b,{{c}})", R"({a{\}b,c}d)", R"({a,b{{1,2}e}f)", R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})", R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)", }) { std::cout << string << '\n'; for (auto expansion : expand(string)) { std::cout << " " << expansion << '\n'; } std::cout << '\n'; } return 0; }
Convert this VB snippet to C++ and keep its semantics consistent.
VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 2265 ClientLeft = 60 ClientTop = 600 ClientWidth = 2175 LinkTopic = "Form1" ScaleHeight = 2265 ScaleWidth = 2175 StartUpPosition = 3 Begin VB.CommandButton cmdRnd Caption = "Random" Height = 495 Left = 120 TabIndex = 2 Top = 1680 Width = 1215 End Begin VB.CommandButton cmdInc Caption = "Increment" Height = 495 Left = 120 TabIndex = 1 Top = 1080 Width = 1215 End Begin VB.TextBox txtValue Height = 495 Left = 120 TabIndex = 0 Text = "0" Top = 240 Width = 1215 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private Sub Form_Load() Randomize Timer End Sub Private Sub cmdRnd_Click() If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11) End Sub Private Sub cmdInc_Click() If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1 End Sub Private Sub txtValue_KeyPress(KeyAscii As Integer) Select Case KeyAscii Case 8, 43, 45, 48 To 57 Case Else KeyAscii = 0 End Select End Sub
#ifndef INTERACTION_H #define INTERACTION_H #include <QWidget> class QPushButton ; class QLineEdit ; class QVBoxLayout ; class MyWidget : public QWidget { Q_OBJECT public : MyWidget( QWidget *parent = 0 ) ; private : QLineEdit *entryField ; QPushButton *increaseButton ; QPushButton *randomButton ; QVBoxLayout *myLayout ; private slots : void doIncrement( ) ; void findRandomNumber( ) ; } ; #endif
Translate the given VB code snippet into C++ without altering its behavior.
VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 2265 ClientLeft = 60 ClientTop = 600 ClientWidth = 2175 LinkTopic = "Form1" ScaleHeight = 2265 ScaleWidth = 2175 StartUpPosition = 3 Begin VB.CommandButton cmdRnd Caption = "Random" Height = 495 Left = 120 TabIndex = 2 Top = 1680 Width = 1215 End Begin VB.CommandButton cmdInc Caption = "Increment" Height = 495 Left = 120 TabIndex = 1 Top = 1080 Width = 1215 End Begin VB.TextBox txtValue Height = 495 Left = 120 TabIndex = 0 Text = "0" Top = 240 Width = 1215 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private Sub Form_Load() Randomize Timer End Sub Private Sub cmdRnd_Click() If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11) End Sub Private Sub cmdInc_Click() If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1 End Sub Private Sub txtValue_KeyPress(KeyAscii As Integer) Select Case KeyAscii Case 8, 43, 45, 48 To 57 Case Else KeyAscii = 0 End Select End Sub
#ifndef INTERACTION_H #define INTERACTION_H #include <QWidget> class QPushButton ; class QLineEdit ; class QVBoxLayout ; class MyWidget : public QWidget { Q_OBJECT public : MyWidget( QWidget *parent = 0 ) ; private : QLineEdit *entryField ; QPushButton *increaseButton ; QPushButton *randomButton ; QVBoxLayout *myLayout ; private slots : void doIncrement( ) ; void findRandomNumber( ) ; } ; #endif