Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from VB to C++ with equivalent syntax and logic.
Dim chosen(10) For j = 1 To 1000000 c = one_of_n(10) chosen(c) = chosen(c) + 1 Next For k = 1 To 10 WScript.StdOut.WriteLine k & ". " & chosen(k) Next Function one_of_n(n) Randomize For i = 1 To n If Rnd(1) < 1/i Then one_of_n = i End If Next End Function
#include <random> #include <iostream> #include <iterator> #include <algorithm> using namespace std; mt19937 engine; unsigned int one_of_n(unsigned int n) { unsigned int choice; for(unsigned int i = 0; i < n; ++i) { uniform_int_distribution<unsigned int> distribution(0, i); if(!distribution(engine)) choice = i; } return choice; } int main() { engine = mt19937(random_device()()); unsigned int results[10] = {0}; for(unsigned int i = 0; i < 1000000; ++i) results[one_of_n(10)]++; ostream_iterator<unsigned int> out_it(cout, " "); copy(results, results+10, out_it); cout << '\n'; }
Write a version of this VB function in C++ with identical behavior.
Private Function ordinal(s As String) As String Dim irregs As New Collection irregs.Add "first", "one" irregs.Add "second", "two" irregs.Add "third", "three" irregs.Add "fifth", "five" irregs.Add "eighth", "eight" irregs.Add "ninth", "nine" irregs.Add "twelfth", "twelve" Dim i As Integer For i = Len(s) To 1 Step -1 ch = Mid(s, i, 1) If ch = " " Or ch = "-" Then Exit For Next i On Error GoTo 1 ord = irregs(Right(s, Len(s) - i)) ordinal = Left(s, i) & ord Exit Function 1: If Right(s, 1) = "y" Then s = Left(s, Len(s) - 1) & "ieth" Else s = s & "th" End If ordinal = s End Function Public Sub ordinals() tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}] init For i = 1 To UBound(tests) Debug.Print ordinal(spell(tests(i))) Next i End Sub
#include <iostream> #include <string> #include <cstdint> typedef std::uint64_t integer; struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; struct named_number { const char* cardinal; const char* ordinal; integer number; }; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_name(const number_names& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const char* get_name(const named_number& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const named_number& get_named_number(integer n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return named_numbers[i]; } return named_numbers[names_len - 1]; } std::string number_name(integer n, bool ordinal) { std::string result; if (n < 20) result = get_name(small[n], ordinal); else if (n < 100) { if (n % 10 == 0) { result = get_name(tens[n/10 - 2], ordinal); } else { result = get_name(tens[n/10 - 2], false); result += "-"; result += get_name(small[n % 10], ordinal); } } else { const named_number& num = get_named_number(n); integer p = num.number; result = number_name(n/p, false); result += " "; if (n % p == 0) { result += get_name(num, ordinal); } else { result += get_name(num, false); result += " "; result += number_name(n % p, ordinal); } } return result; } void test_ordinal(integer n) { std::cout << n << ": " << number_name(n, true) << '\n'; } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
Generate a C++ translation of this VB snippet without changing its computational steps.
Function IsSelfDescribing(n) IsSelfDescribing = False Set digit = CreateObject("Scripting.Dictionary") For i = 1 To Len(n) k = Mid(n,i,1) If digit.Exists(k) Then digit.Item(k) = digit.Item(k) + 1 Else digit.Add k,1 End If Next c = 0 For j = 0 To Len(n)-1 l = Mid(n,j+1,1) If digit.Exists(CStr(j)) Then If digit.Item(CStr(j)) = CInt(l) Then c = c + 1 End If ElseIf l = 0 Then c = c + 1 Else Exit For End If Next If c = Len(n) Then IsSelfDescribing = True End If End Function start_time = Now s = "" For m = 1 To 100000000 If IsSelfDescribing(m) Then WScript.StdOut.WriteLine m End If Next end_time = Now WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
#include <iostream> typedef unsigned long long bigint; using namespace std; class sdn { public: bool check( bigint n ) { int cc = digitsCount( n ); return compare( n, cc ); } void displayAll( bigint s ) { for( bigint y = 1; y < s; y++ ) if( check( y ) ) cout << y << " is a Self-Describing Number." << endl; } private: bool compare( bigint n, int cc ) { bigint a; while( cc ) { cc--; a = n % 10; if( dig[cc] != a ) return false; n -= a; n /= 10; } return true; } int digitsCount( bigint n ) { int cc = 0; bigint a; memset( dig, 0, sizeof( dig ) ); while( n ) { a = n % 10; dig[a]++; cc++ ; n -= a; n /= 10; } return cc; } int dig[10]; }; int main( int argc, char* argv[] ) { sdn s; s. displayAll( 1000000000000 ); cout << endl << endl; system( "pause" ); bigint n; while( true ) { system( "cls" ); cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n; if( !n ) return 0; if( s.check( n ) ) cout << n << " is"; else cout << n << " is NOT"; cout << " a Self-Describing Number!" << endl << endl; system( "pause" ); } return 0; }
Write a version of this VB function in C++ with identical behavior.
Module Module1 Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer) Dim result As New List(Of Integer) From { n } result.AddRange(seq) Return result End Function Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer) If pos > min_len OrElse seq(0) > n Then Return Tuple.Create(min_len, 0) End If If seq(0) = n Then Return Tuple.Create(pos, 1) End If If pos < min_len Then Return TryPerm(0, pos, seq, n, min_len) End If Return Tuple.Create(min_len, 0) End Function Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer) If i > pos Then Return Tuple.Create(min_len, 0) End If Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len) Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1) If res2.Item1 < res1.Item1 Then Return res2 End If If res2.Item1 = res1.Item1 Then Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2) End If Throw New Exception("TryPerm exception") End Function Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer) Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12) End Function Sub FindBrauer(num As Integer) Dim res = InitTryPerm(num) Console.WriteLine("N = {0}", num) Console.WriteLine("Minimum length of chains: L(n) = {0}", res.Item1) Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2) Console.WriteLine() End Sub Sub Main() Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379} Array.ForEach(nums, Sub(n) FindBrauer(n)) End Sub End Module
#include <iostream> #include <tuple> #include <vector> std::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int); std::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) { if (pos > minLen || seq[0] > n) return { minLen, 0 }; else if (seq[0] == n) return { pos, 1 }; else if (pos < minLen) return tryPerm(0, pos, seq, n, minLen); else return { minLen, 0 }; } std::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) { if (i > pos) return { minLen, 0 }; std::vector<int> seq2{ seq[0] + seq[i] }; seq2.insert(seq2.end(), seq.cbegin(), seq.cend()); auto res1 = checkSeq(pos + 1, seq2, n, minLen); auto res2 = tryPerm(i + 1, pos, seq, n, res1.first); if (res2.first < res1.first) return res2; else if (res2.first == res1.first) return { res2.first, res1.second + res2.second }; else throw std::runtime_error("tryPerm exception"); } std::pair<int, int> initTryPerm(int x) { return tryPerm(0, 0, { 1 }, x, 12); } void findBrauer(int num) { auto res = initTryPerm(num); std::cout << '\n'; std::cout << "N = " << num << '\n'; std::cout << "Minimum length of chains: L(n)= " << res.first << '\n'; std::cout << "Number of minimum length Brauer chains: " << res.second << '\n'; } int main() { std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 }; for (int i : nums) { findBrauer(i); } return 0; }
Generate a C++ translation of this VB snippet without changing its computational steps.
Private Sub Repeat(rid As String, n As Integer) For i = 1 To n Application.Run rid Next i End Sub Private Sub Hello() Debug.Print "Hello" End Sub Public Sub main() Repeat "Hello", 5 End Sub
template <typename Function> void repeat(Function f, unsigned int n) { for(unsigned int i=n; 0<i; i--) f(); }
Write the same algorithm in C++ as shown in this VB implementation.
sub ensure_cscript() if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then createobject("wscript.shell").run "CSCRIPT //nologo """ &_ WScript.ScriptFullName &"""" ,,0 wscript.quit end if end sub class bargraph private bar,mn,mx,nn,cnt Private sub class_initialize() bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_ chrw(&h2586)&chrw(&h2587)&chrw(&h2588) nn=8 end sub public function bg (s) a=split(replace(replace(s,","," ")," "," ")," ") mn=999999:mx=-999999:cnt=ubound(a)+1 for i=0 to ubound(a) a(i)=cdbl(trim(a(i))) if a(i)>mx then mx=a(i) if a(i)<mn then mn=a(i) next ss="Data: " for i=0 to ubound(a) :ss=ss & right (" "& a(i),6) :next ss=ss+vbcrlf + "sparkline: " for i=0 to ubound(a) x=scale(a(i)) ss=ss & string(6,mid(bar,x,1)) next bg=ss &vbcrlf & "min: "&mn & " max: "& mx & _ " cnt: "& ubound(a)+1 &vbcrlf end function private function scale(x) if x=<mn then scale=1 elseif x>=mx then scale=nn else scale=int(nn* (x-mn)/(mx-mn)+1) end if end function end class ensure_cscript set b=new bargraph wscript.stdout.writeblanklines 2 wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1") wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5") wscript.echo b.bg("0, 1, 19, 20") wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999") set b=nothing wscript.echo "If bars don "font to DejaVu Sans Mono or any other that has the bargrph characters" & _ vbcrlf wscript.stdout.write "Press any key.." : wscript.stdin.read 1
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <algorithm> #include <locale> class Sparkline { public: Sparkline(std::wstring &cs) : charset( cs ){ } virtual ~Sparkline(){ } void print(std::string spark){ const char *delim = ", "; std::vector<float> data; std::string::size_type last = spark.find_first_not_of(delim, 0); std::string::size_type pos = spark.find_first_of(delim, last); while( pos != std::string::npos || last != std::string::npos ){ std::string tok = spark.substr(last, pos-last); std::stringstream ss(tok); float entry; ss >> entry; data.push_back( entry ); last = spark.find_first_not_of(delim, pos); pos = spark.find_first_of(delim, last); } float min = *std::min_element( data.begin(), data.end() ); float max = *std::max_element( data.begin(), data.end() ); float skip = (charset.length()-1) / (max - min); std::wcout<<L"Min: "<<min<<L"; Max: "<<max<<L"; Range: "<<(max-min)<<std::endl; std::vector<float>::const_iterator it; for(it = data.begin(); it != data.end(); it++){ float v = ( (*it) - min ) * skip; std::wcout<<charset[ (int)floor( v ) ]; } std::wcout<<std::endl; } private: std::wstring &charset; }; int main( int argc, char **argv ){ std::wstring charset = L"\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588"; std::locale::global(std::locale("en_US.utf8")); Sparkline sl(charset); sl.print("1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"); sl.print("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"); return 0; }
Write the same algorithm in C++ as shown in this VB implementation.
sub ensure_cscript() if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then createobject("wscript.shell").run "CSCRIPT //nologo """ &_ WScript.ScriptFullName &"""" ,,0 wscript.quit end if end sub class bargraph private bar,mn,mx,nn,cnt Private sub class_initialize() bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_ chrw(&h2586)&chrw(&h2587)&chrw(&h2588) nn=8 end sub public function bg (s) a=split(replace(replace(s,","," ")," "," ")," ") mn=999999:mx=-999999:cnt=ubound(a)+1 for i=0 to ubound(a) a(i)=cdbl(trim(a(i))) if a(i)>mx then mx=a(i) if a(i)<mn then mn=a(i) next ss="Data: " for i=0 to ubound(a) :ss=ss & right (" "& a(i),6) :next ss=ss+vbcrlf + "sparkline: " for i=0 to ubound(a) x=scale(a(i)) ss=ss & string(6,mid(bar,x,1)) next bg=ss &vbcrlf & "min: "&mn & " max: "& mx & _ " cnt: "& ubound(a)+1 &vbcrlf end function private function scale(x) if x=<mn then scale=1 elseif x>=mx then scale=nn else scale=int(nn* (x-mn)/(mx-mn)+1) end if end function end class ensure_cscript set b=new bargraph wscript.stdout.writeblanklines 2 wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1") wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5") wscript.echo b.bg("0, 1, 19, 20") wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999") set b=nothing wscript.echo "If bars don "font to DejaVu Sans Mono or any other that has the bargrph characters" & _ vbcrlf wscript.stdout.write "Press any key.." : wscript.stdin.read 1
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <algorithm> #include <locale> class Sparkline { public: Sparkline(std::wstring &cs) : charset( cs ){ } virtual ~Sparkline(){ } void print(std::string spark){ const char *delim = ", "; std::vector<float> data; std::string::size_type last = spark.find_first_not_of(delim, 0); std::string::size_type pos = spark.find_first_of(delim, last); while( pos != std::string::npos || last != std::string::npos ){ std::string tok = spark.substr(last, pos-last); std::stringstream ss(tok); float entry; ss >> entry; data.push_back( entry ); last = spark.find_first_not_of(delim, pos); pos = spark.find_first_of(delim, last); } float min = *std::min_element( data.begin(), data.end() ); float max = *std::max_element( data.begin(), data.end() ); float skip = (charset.length()-1) / (max - min); std::wcout<<L"Min: "<<min<<L"; Max: "<<max<<L"; Range: "<<(max-min)<<std::endl; std::vector<float>::const_iterator it; for(it = data.begin(); it != data.end(); it++){ float v = ( (*it) - min ) * skip; std::wcout<<charset[ (int)floor( v ) ]; } std::wcout<<std::endl; } private: std::wstring &charset; }; int main( int argc, char **argv ){ std::wstring charset = L"\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588"; std::locale::global(std::locale("en_US.utf8")); Sparkline sl(charset); sl.print("1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"); sl.print("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"); return 0; }
Translate this program into C++ but keep the logic exactly as in VB.
Private Function mul_inv(a As Long, n As Long) As Variant If n < 0 Then n = -n If a < 0 Then a = n - ((-a) Mod n) Dim t As Long: t = 0 Dim nt As Long: nt = 1 Dim r As Long: r = n Dim nr As Long: nr = a Dim q As Long Do While nr <> 0 q = r \ nr tmp = t t = nt nt = tmp - q * nt tmp = r r = nr nr = tmp - q * nr Loop If r > 1 Then mul_inv = "a is not invertible" Else If t < 0 Then t = t + n mul_inv = t End If End Function Public Sub mi() Debug.Print mul_inv(42, 2017) Debug.Print mul_inv(40, 1) Debug.Print mul_inv(52, -217) Debug.Print mul_inv(-486, 217) Debug.Print mul_inv(40, 2018) End Sub
#include <iostream> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { std::cout << mul_inv(42, 2017) << std::endl; return 0; }
Keep all operations the same but rewrite the snippet in C++.
Module Module1 Dim atomicMass As New Dictionary(Of String, Double) From { {"H", 1.008}, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.63}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.9055}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.71}, {"Sb", 121.76}, {"Te", 127.6}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.5}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.9804}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299} } Function Evaluate(s As String) As Double s += "[" Dim sum = 0.0 Dim symbol = "" Dim number = "" For i = 1 To s.Length Dim c = s(i - 1) If "@" <= c AndAlso c <= "[" Then Dim n = 1 If number <> "" Then n = Integer.Parse(number) End If If symbol <> "" Then sum += atomicMass(symbol) * n End If If c = "[" Then Exit For End If symbol = c.ToString number = "" ElseIf "a" <= c AndAlso c <= "z" Then symbol += c ElseIf "0" <= c AndAlso c <= "9" Then number += c Else Throw New Exception(String.Format("Unexpected symbol {0} in molecule", c)) End If Next Return sum End Function Function ReplaceFirst(text As String, search As String, replace As String) As String Dim pos = text.IndexOf(search) If pos < 0 Then Return text Else Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length) End If End Function Function ReplaceParens(s As String) As String Dim letter = "s"c While True Dim start = s.IndexOf("(") If start = -1 Then Exit While End If For i = start + 1 To s.Length - 1 If s(i) = ")" Then Dim expr = s.Substring(start + 1, i - start - 1) Dim symbol = String.Format("@{0}", letter) s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol) atomicMass(symbol) = Evaluate(expr) letter = Chr(Asc(letter) + 1) Exit For End If If s(i) = "(" Then start = i Continue For End If Next End While Return s End Function Sub Main() Dim molecules() As String = { "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" } For Each molecule In molecules Dim mass = Evaluate(ReplaceParens(molecule)) Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass) Next End Sub End Module
#include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> std::map<std::string, double> atomicMass = { {"H", 1.008}, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.630}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.90550}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.710}, {"Sb", 121.760}, {"Te", 127.60}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.500}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.98040}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299}, }; double evaluate(std::string s) { s += '['; double sum = 0.0; std::string symbol; std::string number; for (auto c : s) { if ('@' <= c && c <= '[') { int n = 1; if (number != "") { n = stoi(number); } if (symbol != "") { sum += atomicMass[symbol] * n; } if (c == '[') { break; } symbol = c; number = ""; } else if ('a' <= c && c <= 'z') { symbol += c; } else if ('0' <= c && c <= '9') { number += c; } else { std::string msg = "Unexpected symbol "; msg += c; msg += " in molecule"; throw std::runtime_error(msg); } } return sum; } std::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) { auto pos = text.find(search); if (pos == std::string::npos) { return text; } auto beg = text.substr(0, pos); auto end = text.substr(pos + search.length()); return beg + replace + end; } std::string replaceParens(std::string s) { char letter = 'a'; while (true) { auto start = s.find("("); if (start == std::string::npos) { break; } for (size_t i = start + 1; i < s.length(); i++) { if (s[i] == ')') { auto expr = s.substr(start + 1, i - start - 1); std::string symbol = "@"; symbol += letter; auto search = s.substr(start, i + 1 - start); s = replaceFirst(s, search, symbol); atomicMass[symbol] = evaluate(expr); letter++; break; } if (s[i] == '(') { start = i; continue; } } } return s; } int main() { std::vector<std::string> molecules = { "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" }; for (auto molecule : molecules) { auto mass = evaluate(replaceParens(molecule)); std::cout << std::setw(17) << molecule << " -> " << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\n'; } return 0; }
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
Const n = 2200 Public Sub pq() Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3 Dim l(n) As Boolean, l_add(9680000) As Boolean For x = 1 To n x2 = x * x For y = x To n l_add(x2 + y * y) = True Next y Next x For x = 1 To n s1 = s s = s + 2 s2 = s For y = x + 1 To n If l_add(s1) Then l(y) = True s1 = s1 + s2 s2 = s2 + 2 Next Next For x = 1 To n If Not l(x) Then Debug.Print x; Next Debug.Print End Sub
#include <iostream> #include <vector> constexpr int N = 2200; constexpr int N2 = 2 * N * N; int main() { using namespace std; vector<bool> found(N + 1); vector<bool> aabb(N2 + 1); int s = 3; for (int a = 1; a < N; ++a) { int aa = a * a; for (int b = 1; b < N; ++b) { aabb[aa + b * b] = true; } } for (int c = 1; c <= N; ++c) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= N; ++d) { if (aabb[s1]) { found[d] = true; } s1 += s2; s2 += 2; } } cout << "The values of d <= " << N << " which can't be represented:" << endl; for (int d = 1; d <= N; ++d) { if (!found[d]) { cout << d << " "; } } cout << endl; return 0; }
Produce a functionally identical C++ code for the snippet given in VB.
Option Explicit Dim seed As Long Sub Main() Dim i As Integer seed = 675248 For i = 1 To 5 Debug.Print Rand Next i End Sub Function Rand() As Variant Dim s As String s = CStr(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End Function
#include <exception> #include <iostream> using ulong = unsigned long; class MiddleSquare { private: ulong state; ulong div, mod; public: MiddleSquare() = delete; MiddleSquare(ulong start, ulong length) { if (length % 2) throw std::invalid_argument("length must be even"); div = mod = 1; for (ulong i=0; i<length/2; i++) div *= 10; for (ulong i=0; i<length; i++) mod *= 10; state = start % mod; } ulong next() { return state = state * state / div % mod; } }; int main() { MiddleSquare msq(675248, 6); for (int i=0; i<5; i++) std::cout << msq.next() << std::endl; return 0; }
Generate a C++ translation of this VB snippet without changing its computational steps.
Option Explicit Dim seed As Long Sub Main() Dim i As Integer seed = 675248 For i = 1 To 5 Debug.Print Rand Next i End Sub Function Rand() As Variant Dim s As String s = CStr(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End Function
#include <exception> #include <iostream> using ulong = unsigned long; class MiddleSquare { private: ulong state; ulong div, mod; public: MiddleSquare() = delete; MiddleSquare(ulong start, ulong length) { if (length % 2) throw std::invalid_argument("length must be even"); div = mod = 1; for (ulong i=0; i<length/2; i++) div *= 10; for (ulong i=0; i<length; i++) mod *= 10; state = start % mod; } ulong next() { return state = state * state / div % mod; } }; int main() { MiddleSquare msq(675248, 6); for (int i=0; i<5; i++) std::cout << msq.next() << std::endl; return 0; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
Option Base 1 Public Enum attr Colour = 1 Nationality Beverage Smoke Pet End Enum Public Enum Drinks_ Beer = 1 Coffee Milk Tea Water End Enum Public Enum nations Danish = 1 English German Norwegian Swedish End Enum Public Enum colors Blue = 1 Green Red White Yellow End Enum Public Enum tobaccos Blend = 1 BlueMaster Dunhill PallMall Prince End Enum Public Enum animals Bird = 1 Cat Dog Horse Zebra End Enum Public permutation As New Collection Public perm(5) As Variant Const factorial5 = 120 Public Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant Private Sub generate(n As Integer, A As Variant) If n = 1 Then permutation.Add A Else For i = 1 To n generate n - 1, A If n Mod 2 = 0 Then tmp = A(i) A(i) = A(n) A(n) = tmp Else tmp = A(1) A(1) = A(n) A(n) = tmp End If Next i End If End Sub Function house(i As Integer, name As Variant) As Integer Dim x As Integer For x = 1 To 5 If perm(i)(x) = name Then house = x Exit For End If Next x End Function Function left_of(h1 As Integer, h2 As Integer) As Boolean left_of = (h1 - h2) = -1 End Function Function next_to(h1 As Integer, h2 As Integer) As Boolean next_to = Abs(h1 - h2) = 1 End Function Private Sub print_house(i As Integer) Debug.Print i & ": "; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _ Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i)) End Sub Public Sub Zebra_puzzle() Colours = [{"blue","green","red","white","yellow"}] Nationalities = [{"Dane","English","German","Norwegian","Swede"}] Drinks = [{"beer","coffee","milk","tea","water"}] Smokes = [{"Blend","Blue Master","Dunhill","Pall Mall","Prince"}] Pets = [{"birds","cats","dog","horse","zebra"}] Dim solperms As New Collection Dim solutions As Integer Dim b(5) As Integer, i As Integer For i = 1 To 5: b(i) = i: Next i generate 5, b For c = 1 To factorial5 perm(Colour) = permutation(c) If left_of(house(Colour, Green), house(Colour, White)) Then For n = 1 To factorial5 perm(Nationality) = permutation(n) If house(Nationality, Norwegian) = 1 _ And house(Nationality, English) = house(Colour, Red) _ And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then For d = 1 To factorial5 perm(Beverage) = permutation(d) If house(Nationality, Danish) = house(Beverage, Tea) _ And house(Beverage, Coffee) = house(Colour, Green) _ And house(Beverage, Milk) = 3 Then For s = 1 To factorial5 perm(Smoke) = permutation(s) If house(Colour, Yellow) = house(Smoke, Dunhill) _ And house(Nationality, German) = house(Smoke, Prince) _ And house(Smoke, BlueMaster) = house(Beverage, Beer) _ And next_to(house(Beverage, Water), house(Smoke, Blend)) Then For p = 1 To factorial5 perm(Pet) = permutation(p) If house(Nationality, Swedish) = house(Pet, Dog) _ And house(Smoke, PallMall) = house(Pet, Bird) _ And next_to(house(Smoke, Blend), house(Pet, Cat)) _ And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then For i = 1 To 5 print_house i Next i Debug.Print solutions = solutions + 1 solperms.Add perm End If Next p End If Next s End If Next d End If Next n End If Next c Debug.Print Format(solutions, "@"); " solution" & IIf(solutions > 1, "s", "") & " found" For i = 1 To solperms.Count For j = 1 To 5 perm(j) = solperms(i)(j) Next j Debug.Print "The " & Nationalities(perm(Nationality)(house(Pet, Zebra))) & " owns the Zebra" Next i End Sub
#include <stdio.h> #include <string.h> #define defenum(name, val0, val1, val2, val3, val4) \ enum name { val0, val1, val2, val3, val4 }; \ const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 } defenum( Attrib, Color, Man, Drink, Animal, Smoke ); defenum( Colors, Red, Green, White, Yellow, Blue ); defenum( Mans, English, Swede, Dane, German, Norwegian ); defenum( Drinks, Tea, Coffee, Milk, Beer, Water ); defenum( Animals, Dog, Birds, Cats, Horse, Zebra ); defenum( Smokes, PallMall, Dunhill, Blend, BlueMaster, Prince ); void printHouses(int ha[5][5]) { const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str}; printf("%-10s", "House"); for (const char *name : Attrib_str) printf("%-10s", name); printf("\n"); for (int i = 0; i < 5; i++) { printf("%-10d", i); for (int j = 0; j < 5; j++) printf("%-10s", attr_names[j][ha[i][j]]); printf("\n"); } } struct HouseNoRule { int houseno; Attrib a; int v; } housenos[] = { {2, Drink, Milk}, {0, Man, Norwegian} }; struct AttrPairRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5], int i) { return (ha[i][a1] >= 0 && ha[i][a2] >= 0) && ((ha[i][a1] == v1 && ha[i][a2] != v2) || (ha[i][a1] != v1 && ha[i][a2] == v2)); } } pairs[] = { {Man, English, Color, Red}, {Man, Swede, Animal, Dog}, {Man, Dane, Drink, Tea}, {Color, Green, Drink, Coffee}, {Smoke, PallMall, Animal, Birds}, {Smoke, Dunhill, Color, Yellow}, {Smoke, BlueMaster, Drink, Beer}, {Man, German, Smoke, Prince} }; struct NextToRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5], int i) { return (ha[i][a1] == v1) && ((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) || (i == 4 && ha[i - 1][a2] != v2) || (ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2)); } } nexttos[] = { {Smoke, Blend, Animal, Cats}, {Smoke, Dunhill, Animal, Horse}, {Man, Norwegian, Color, Blue}, {Smoke, Blend, Drink, Water} }; struct LeftOfRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5]) { return (ha[0][a2] == v2) || (ha[4][a1] == v1); } bool invalid(int ha[5][5], int i) { return ((i > 0 && ha[i][a1] >= 0) && ((ha[i - 1][a1] == v1 && ha[i][a2] != v2) || (ha[i - 1][a1] != v1 && ha[i][a2] == v2))); } } leftofs[] = { {Color, Green, Color, White} }; bool invalid(int ha[5][5]) { for (auto &rule : leftofs) if (rule.invalid(ha)) return true; for (int i = 0; i < 5; i++) { #define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true; eval_rules(pairs); eval_rules(nexttos); eval_rules(leftofs); } return false; } void search(bool used[5][5], int ha[5][5], const int hno, const int attr) { int nexthno, nextattr; if (attr < 4) { nextattr = attr + 1; nexthno = hno; } else { nextattr = 0; nexthno = hno + 1; } if (ha[hno][attr] != -1) { search(used, ha, nexthno, nextattr); } else { for (int i = 0; i < 5; i++) { if (used[attr][i]) continue; used[attr][i] = true; ha[hno][attr] = i; if (!invalid(ha)) { if ((hno == 4) && (attr == 4)) { printHouses(ha); } else { search(used, ha, nexthno, nextattr); } } used[attr][i] = false; } ha[hno][attr] = -1; } } int main() { bool used[5][5] = {}; int ha[5][5]; memset(ha, -1, sizeof(ha)); for (auto &rule : housenos) { ha[rule.houseno][rule.a] = rule.v; used[rule.a][rule.v] = true; } search(used, ha, 0, 0); return 0; }
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
Imports System, BI = System.Numerics.BigInteger, System.Console Module Module1 Function isqrt(ByVal x As BI) As BI Dim t As BI, q As BI = 1, r As BI = 0 While q <= x : q <<= 2 : End While While q > 1 : q >>= 2 : t = x - r - q : r >>= 1 If t >= 0 Then x = t : r += q End While : Return r End Function Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String digs += 1 Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1 For n As BI = 0 To dg - 1 If n > 0 Then t3 = t3 * BI.Pow(n, 6) te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6 If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z) If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t) su += te : If te < 10 Then digs -= 1 If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _ "after the decimal point." & vbLf, n, digs) Exit For End If For j As BI = n * 6 + 1 To n * 6 + 6 t1 = t1 * j : Next d += 2 : t2 += 126 + 532 * d Next Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _ / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5))) Return s(0) & "." & s.Substring(1, digs) End Function Sub Main(ByVal args As String()) WriteLine(dump(70, true)) End Sub End Module
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } big_int almkvist_giullera(int n) { return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) / (pow(factorial(n), 6) * 3); } int main() { std::cout << "n | Integer portion of nth term\n" << "------------------------------------------------\n"; for (int n = 0; n < 10; ++n) std::cout << n << " | " << std::setw(44) << almkvist_giullera(n) << '\n'; big_float epsilon(pow(big_float(10), -70)); big_float prev = 0, pi = 0; rational sum = 0; for (int n = 0;; ++n) { rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3)); sum += term; pi = sqrt(big_float(1 / sum)); if (abs(pi - prev) < epsilon) break; prev = pi; } std::cout << "\nPi to 70 decimal places is:\n" << std::fixed << std::setprecision(70) << pi << '\n'; }
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
Imports System, BI = System.Numerics.BigInteger, System.Console Module Module1 Function isqrt(ByVal x As BI) As BI Dim t As BI, q As BI = 1, r As BI = 0 While q <= x : q <<= 2 : End While While q > 1 : q >>= 2 : t = x - r - q : r >>= 1 If t >= 0 Then x = t : r += q End While : Return r End Function Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String digs += 1 Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1 For n As BI = 0 To dg - 1 If n > 0 Then t3 = t3 * BI.Pow(n, 6) te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6 If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z) If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t) su += te : If te < 10 Then digs -= 1 If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _ "after the decimal point." & vbLf, n, digs) Exit For End If For j As BI = n * 6 + 1 To n * 6 + 6 t1 = t1 * j : Next d += 2 : t2 += 126 + 532 * d Next Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _ / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5))) Return s(0) & "." & s.Substring(1, digs) End Function Sub Main(ByVal args As String()) WriteLine(dump(70, true)) End Sub End Module
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } big_int almkvist_giullera(int n) { return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) / (pow(factorial(n), 6) * 3); } int main() { std::cout << "n | Integer portion of nth term\n" << "------------------------------------------------\n"; for (int n = 0; n < 10; ++n) std::cout << n << " | " << std::setw(44) << almkvist_giullera(n) << '\n'; big_float epsilon(pow(big_float(10), -70)); big_float prev = 0, pi = 0; rational sum = 0; for (int n = 0;; ++n) { rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3)); sum += term; pi = sqrt(big_float(1 / sum)); if (abs(pi - prev) < epsilon) break; prev = pi; } std::cout << "\nPi to 70 decimal places is:\n" << std::fixed << std::setprecision(70) << pi << '\n'; }
Translate this program into C++ but keep the logic exactly as in VB.
Imports System.Collections.Generic, System.Linq, System.Console Module Module1 Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean If n <= 0 Then Return False Else If f.Contains(n) Then Return True Select Case n.CompareTo(f.Sum()) Case 1 : Return False : Case 0 : Return True Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf) End Select : Return true End Function Function ip(ByVal n As Integer) As Boolean Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList() Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f)) End Function Sub Main() Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m If ip(i) OrElse i = 1 Then c += 1 : Write("{0,3} {1}", i, If(c Mod 10 = 0, vbLf, "")) i += If(i = 1, 1, 2) : End While Write(vbLf & "Found {0} practical numbers between 1 and {1} inclusive." & vbLf, c, m) Do : m = If(m < 500, m << 1, m * 10 + 6) Write(vbLf & "{0,5} is a{1}practical number.", m, If(ip(m), " ", "n im")) : Loop While m < 1e4 End Sub End Module
#include <algorithm> #include <iostream> #include <numeric> #include <sstream> #include <vector> template <typename iterator> bool sum_of_any_subset(int n, iterator begin, iterator end) { if (begin == end) return false; if (std::find(begin, end, n) != end) return true; int total = std::accumulate(begin, end, 0); if (n == total) return true; if (n > total) return false; --end; int d = n - *end; return (d > 0 && sum_of_any_subset(d, begin, end)) || sum_of_any_subset(n, begin, end); } std::vector<int> factors(int n) { std::vector<int> f{1}; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { f.push_back(i); if (i * i != n) f.push_back(n / i); } } std::sort(f.begin(), f.end()); return f; } bool is_practical(int n) { std::vector<int> f = factors(n); for (int i = 1; i < n; ++i) { if (!sum_of_any_subset(i, f.begin(), f.end())) return false; } return true; } std::string shorten(const std::vector<int>& v, size_t n) { std::ostringstream out; size_t size = v.size(), i = 0; if (n > 0 && size > 0) out << v[i++]; for (; i < n && i < size; ++i) out << ", " << v[i]; if (size > i + n) { out << ", ..."; i = size - n; } for (; i < size; ++i) out << ", " << v[i]; return out.str(); } int main() { std::vector<int> practical; for (int n = 1; n <= 333; ++n) { if (is_practical(n)) practical.push_back(n); } std::cout << "Found " << practical.size() << " practical numbers:\n" << shorten(practical, 10) << '\n'; for (int n : {666, 6666, 66666, 672, 720, 222222}) std::cout << n << " is " << (is_practical(n) ? "" : "not ") << "a practical number.\n"; return 0; }
Change the following VB code into C++ without altering its purpose.
Sub Main() Dim d As Double Dim s As Single d = -12.3456 d = 1000# d = 0.00001 d = 67# d = 8.9 d = 0.33 d = 0# d = 2# * 10 ^ 3 d = 2E+50 d = 2E-50 s = -12.3456! s = 1000! s = 0.00001! s = 67! s = 8.9! s = 0.33! s = 0! s = 2! * 10 ^ 3 End Sub
#include <iostream> int main() { auto double1 = 2.5; auto float1 = 2.5f; auto longdouble1 = 2.5l; auto double2 = 2.5e-3; auto float2 = 2.5e3f; auto double3 = 0x1p4; auto float3 = 0xbeefp-8f; std::cout << "\ndouble1: " << double1; std::cout << "\nfloat1: " << float1; std::cout << "\nlongdouble1: " << longdouble1; std::cout << "\ndouble2: " << double2; std::cout << "\nfloat2: " << float2; std::cout << "\ndouble3: " << double3; std::cout << "\nfloat3: " << float3; std::cout << "\n"; }
Translate the given VB code snippet into C++ without altering its behavior.
Module Module1 ReadOnly Dirs As Integer(,) = { {1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1} } Const RowCount = 10 Const ColCount = 10 Const GridSize = RowCount * ColCount Const MinWords = 25 Class Grid Public cells(RowCount - 1, ColCount - 1) As Char Public solutions As New List(Of String) Public numAttempts As Integer Sub New() For i = 0 To RowCount - 1 For j = 0 To ColCount - 1 cells(i, j) = ControlChars.NullChar Next Next End Sub End Class Dim Rand As New Random() Sub Main() PrintResult(CreateWordSearch(ReadWords("unixdict.txt"))) End Sub Function ReadWords(filename As String) As List(Of String) Dim maxlen = Math.Max(RowCount, ColCount) Dim words As New List(Of String) Dim objReader As New IO.StreamReader(filename) Dim line As String Do While objReader.Peek() <> -1 line = objReader.ReadLine() If line.Length > 3 And line.Length < maxlen Then If line.All(Function(c) Char.IsLetter(c)) Then words.Add(line) End If End If Loop Return words End Function Function CreateWordSearch(words As List(Of String)) As Grid For numAttempts = 1 To 1000 Shuffle(words) Dim grid As New Grid() Dim messageLen = PlaceMessage(grid, "Rosetta Code") Dim target = GridSize - messageLen Dim cellsFilled = 0 For Each word In words cellsFilled = cellsFilled + TryPlaceWord(grid, word) If cellsFilled = target Then If grid.solutions.Count >= MinWords Then grid.numAttempts = numAttempts Return grid Else Exit For End If End If Next Next Return Nothing End Function Function PlaceMessage(grid As Grid, msg As String) As Integer msg = msg.ToUpper() msg = msg.Replace(" ", "") If msg.Length > 0 And msg.Length < GridSize Then Dim gapSize As Integer = GridSize / msg.Length Dim pos = 0 Dim lastPos = -1 For i = 0 To msg.Length - 1 If i = 0 Then pos = pos + Rand.Next(gapSize - 1) Else pos = pos + Rand.Next(2, gapSize - 1) End If Dim r As Integer = Math.Floor(pos / ColCount) Dim c = pos Mod ColCount grid.cells(r, c) = msg(i) lastPos = pos Next Return msg.Length End If Return 0 End Function Function TryPlaceWord(grid As Grid, word As String) As Integer Dim randDir = Rand.Next(Dirs.GetLength(0)) Dim randPos = Rand.Next(GridSize) For d = 0 To Dirs.GetLength(0) - 1 Dim dd = (d + randDir) Mod Dirs.GetLength(0) For p = 0 To GridSize - 1 Dim pp = (p + randPos) Mod GridSize Dim lettersPLaced = TryLocation(grid, word, dd, pp) If lettersPLaced > 0 Then Return lettersPLaced End If Next Next Return 0 End Function Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer Dim r As Integer = pos / ColCount Dim c = pos Mod ColCount Dim len = word.Length If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then Return 0 End If If r = RowCount OrElse c = ColCount Then Return 0 End If Dim rr = r Dim cc = c For i = 0 To len - 1 If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then Return 0 End If cc = cc + Dirs(dir, 0) rr = rr + Dirs(dir, 1) Next Dim overlaps = 0 rr = r cc = c For i = 0 To len - 1 If grid.cells(rr, cc) = word(i) Then overlaps = overlaps + 1 Else grid.cells(rr, cc) = word(i) End If If i < len - 1 Then cc = cc + Dirs(dir, 0) rr = rr + Dirs(dir, 1) End If Next Dim lettersPlaced = len - overlaps If lettersPlaced > 0 Then grid.solutions.Add(String.Format("{0,-10} ({1},{2})({3},{4})", word, c, r, cc, rr)) End If Return lettersPlaced End Function Sub PrintResult(grid As Grid) If IsNothing(grid) OrElse grid.numAttempts = 0 Then Console.WriteLine("No grid to display") Return End If Console.WriteLine("Attempts: {0}", grid.numAttempts) Console.WriteLine("Number of words: {0}", GridSize) Console.WriteLine() Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9") For r = 0 To RowCount - 1 Console.WriteLine() Console.Write("{0} ", r) For c = 0 To ColCount - 1 Console.Write(" {0} ", grid.cells(r, c)) Next Next Console.WriteLine() Console.WriteLine() For i = 0 To grid.solutions.Count - 1 If i Mod 2 = 0 Then Console.Write("{0}", grid.solutions(i)) Else Console.WriteLine(" {0}", grid.solutions(i)) End If Next Console.WriteLine() End Sub Sub Shuffle(Of T)(list As IList(Of T)) Dim r As Random = New Random() For i = 0 To list.Count - 1 Dim index As Integer = r.Next(i, list.Count) If i <> index Then Dim temp As T = list(i) list(i) = list(index) list(index) = temp End If Next End Sub End Module
#include <iomanip> #include <ctime> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <fstream> const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25; class Cell { public: Cell() : val( 0 ), cntOverlap( 0 ) {} char val; int cntOverlap; }; class Word { public: Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {} bool operator ==( const std::string& s ) { return 0 == word.compare( s ); } std::string word; int cols, rows, cole, rowe, dx, dy; }; class words { public: void create( std::string& file ) { std::ifstream f( file.c_str(), std::ios_base::in ); std::string word; while( f >> word ) { if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue; if( word.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" ) != word.npos ) continue; dictionary.push_back( word ); } f.close(); std::random_shuffle( dictionary.begin(), dictionary.end() ); buildPuzzle(); } void printOut() { std::cout << "\t"; for( int x = 0; x < WID; x++ ) std::cout << x << " "; std::cout << "\n\n"; for( int y = 0; y < HEI; y++ ) { std::cout << y << "\t"; for( int x = 0; x < WID; x++ ) std::cout << puzzle[x][y].val << " "; std::cout << "\n"; } size_t wid1 = 0, wid2 = 0; for( size_t x = 0; x < used.size(); x++ ) { if( x & 1 ) { if( used[x].word.length() > wid1 ) wid1 = used[x].word.length(); } else { if( used[x].word.length() > wid2 ) wid2 = used[x].word.length(); } } std::cout << "\n"; std::vector<Word>::iterator w = used.begin(); while( w != used.end() ) { std::cout << std::right << std::setw( wid1 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") (" << ( *w ).cole << ", " << ( *w ).rowe << ")\t"; w++; if( w == used.end() ) break; std::cout << std::setw( wid2 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") (" << ( *w ).cole << ", " << ( *w ).rowe << ")\n"; w++; } std::cout << "\n\n"; } private: void addMsg() { std::string msg = "ROSETTACODE"; int stp = 9, p = rand() % stp; for( size_t x = 0; x < msg.length(); x++ ) { puzzle[p % WID][p / HEI].val = msg.at( x ); p += rand() % stp + 4; } } int getEmptySpaces() { int es = 0; for( int y = 0; y < HEI; y++ ) { for( int x = 0; x < WID; x++ ) { if( !puzzle[x][y].val ) es++; } } return es; } bool check( std::string word, int c, int r, int dc, int dr ) { for( size_t a = 0; a < word.length(); a++ ) { if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false; if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false; c += dc; r += dr; } return true; } bool setWord( std::string word, int c, int r, int dc, int dr ) { if( !check( word, c, r, dc, dr ) ) return false; int sx = c, sy = r; for( size_t a = 0; a < word.length(); a++ ) { if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a ); else puzzle[c][r].cntOverlap++; c += dc; r += dr; } used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) ); return true; } bool add2Puzzle( std::string word ) { int x = rand() % WID, y = rand() % HEI, z = rand() % 8; for( int d = z; d < z + 8; d++ ) { switch( d % 8 ) { case 0: if( setWord( word, x, y, 1, 0 ) ) return true; break; case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break; case 2: if( setWord( word, x, y, 0, 1 ) ) return true; break; case 3: if( setWord( word, x, y, 1, -1 ) ) return true; break; case 4: if( setWord( word, x, y, -1, 0 ) ) return true; break; case 5: if( setWord( word, x, y, -1, 1 ) ) return true; break; case 6: if( setWord( word, x, y, 0, -1 ) ) return true; break; case 7: if( setWord( word, x, y, 1, 1 ) ) return true; break; } } return false; } void clearWord() { if( used.size() ) { Word lastW = used.back(); used.pop_back(); for( size_t a = 0; a < lastW.word.length(); a++ ) { if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) { puzzle[lastW.cols][lastW.rows].val = 0; } if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) { puzzle[lastW.cols][lastW.rows].cntOverlap--; } lastW.cols += lastW.dx; lastW.rows += lastW.dy; } } } void buildPuzzle() { addMsg(); int es = 0, cnt = 0; size_t idx = 0; do { for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) { if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue; if( add2Puzzle( *w ) ) { es = getEmptySpaces(); if( !es && used.size() >= MIN_WORD_CNT ) return; } } clearWord(); std::random_shuffle( dictionary.begin(), dictionary.end() ); } while( ++cnt < 100 ); } std::vector<Word> used; std::vector<std::string> dictionary; Cell puzzle[WID][HEI]; }; int main( int argc, char* argv[] ) { unsigned s = unsigned( time( 0 ) ); srand( s ); words w; w.create( std::string( "unixdict.txt" ) ); w.printOut(); return 0; }
Change the following VB code into C++ without altering its purpose.
Imports System.Reflection Public Class MyClazz Private answer As Integer = 42 End Class Public Class Program Public Shared Sub Main() Dim myInstance = New MyClazz() Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance) Dim answer = fieldInfo.GetValue(myInstance) Console.WriteLine(answer) End Sub End Class
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); public: CWidget(CFactory& parent); ~CWidget(); }; CFactory::CFactory() : m_uiCount(0) {} CFactory::~CFactory() {} CWidget* CFactory::GetWidget() { return new CWidget(*this); } CWidget::CWidget(CFactory& parent) : m_parent(parent) { ++m_parent.m_uiCount; std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } CWidget::~CWidget() { --m_parent.m_uiCount; std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } int main() { CFactory factory; CWidget* pWidget1 = factory.GetWidget(); CWidget* pWidget2 = factory.GetWidget(); delete pWidget1; CWidget* pWidget3 = factory.GetWidget(); delete pWidget3; delete pWidget2; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
Imports System.Reflection Public Class MyClazz Private answer As Integer = 42 End Class Public Class Program Public Shared Sub Main() Dim myInstance = New MyClazz() Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance) Dim answer = fieldInfo.GetValue(myInstance) Console.WriteLine(answer) End Sub End Class
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); public: CWidget(CFactory& parent); ~CWidget(); }; CFactory::CFactory() : m_uiCount(0) {} CFactory::~CFactory() {} CWidget* CFactory::GetWidget() { return new CWidget(*this); } CWidget::CWidget(CFactory& parent) : m_parent(parent) { ++m_parent.m_uiCount; std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } CWidget::~CWidget() { --m_parent.m_uiCount; std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } int main() { CFactory factory; CWidget* pWidget1 = factory.GetWidget(); CWidget* pWidget2 = factory.GetWidget(); delete pWidget1; CWidget* pWidget3 = factory.GetWidget(); delete pWidget3; delete pWidget2; }
Translate this program into C++ but keep the logic exactly as in VB.
Imports System.Reflection Public Class MyClazz Private answer As Integer = 42 End Class Public Class Program Public Shared Sub Main() Dim myInstance = New MyClazz() Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance) Dim answer = fieldInfo.GetValue(myInstance) Console.WriteLine(answer) End Sub End Class
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); public: CWidget(CFactory& parent); ~CWidget(); }; CFactory::CFactory() : m_uiCount(0) {} CFactory::~CFactory() {} CWidget* CFactory::GetWidget() { return new CWidget(*this); } CWidget::CWidget(CFactory& parent) : m_parent(parent) { ++m_parent.m_uiCount; std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } CWidget::~CWidget() { --m_parent.m_uiCount; std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } int main() { CFactory factory; CWidget* pWidget1 = factory.GetWidget(); CWidget* pWidget2 = factory.GetWidget(); delete pWidget1; CWidget* pWidget3 = factory.GetWidget(); delete pWidget3; delete pWidget2; }
Write the same code in C++ as shown below in VB.
Module Module1 Class Node Public Sub New(Len As Integer) Length = Len Edges = New Dictionary(Of Char, Integer) End Sub Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer) Length = len Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg) Suffix = suf End Sub Property Edges As Dictionary(Of Char, Integer) Property Length As Integer Property Suffix As Integer End Class ReadOnly EVEN_ROOT As Integer = 0 ReadOnly ODD_ROOT As Integer = 1 Function Eertree(s As String) As List(Of Node) Dim tree As New List(Of Node) From { New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT), New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT) } Dim suffix = ODD_ROOT Dim n As Integer Dim k As Integer For i = 1 To s.Length Dim c = s(i - 1) n = suffix While True k = tree(n).Length Dim b = i - k - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If n = tree(n).Suffix End While If tree(n).Edges.ContainsKey(c) Then suffix = tree(n).Edges(c) Continue For End If suffix = tree.Count tree.Add(New Node(k + 2)) tree(n).Edges(c) = suffix If tree(suffix).Length = 1 Then tree(suffix).Suffix = 0 Continue For End If While True n = tree(n).Suffix Dim b = i - tree(n).Length - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If End While Dim a = tree(n) Dim d = a.Edges(c) Dim e = tree(suffix) e.Suffix = d Next Return tree End Function Function SubPalindromes(tree As List(Of Node)) As List(Of String) Dim s As New List(Of String) Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String) For Each c In tree(n).Edges.Keys Dim m = tree(n).Edges(c) Dim p1 = c + p + c s.Add(p1) children(m, p1) Next End Sub children(0, "") For Each c In tree(1).Edges.Keys Dim m = tree(1).Edges(c) Dim ct = c.ToString() s.Add(ct) children(m, ct) Next Return s End Function Sub Main() Dim tree = Eertree("eertree") Dim result = SubPalindromes(tree) Dim listStr = String.Join(", ", result) Console.WriteLine("[{0}]", listStr) End Sub End Module
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
Translate this program into C++ but keep the logic exactly as in VB.
Module Module1 Class Node Public Sub New(Len As Integer) Length = Len Edges = New Dictionary(Of Char, Integer) End Sub Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer) Length = len Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg) Suffix = suf End Sub Property Edges As Dictionary(Of Char, Integer) Property Length As Integer Property Suffix As Integer End Class ReadOnly EVEN_ROOT As Integer = 0 ReadOnly ODD_ROOT As Integer = 1 Function Eertree(s As String) As List(Of Node) Dim tree As New List(Of Node) From { New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT), New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT) } Dim suffix = ODD_ROOT Dim n As Integer Dim k As Integer For i = 1 To s.Length Dim c = s(i - 1) n = suffix While True k = tree(n).Length Dim b = i - k - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If n = tree(n).Suffix End While If tree(n).Edges.ContainsKey(c) Then suffix = tree(n).Edges(c) Continue For End If suffix = tree.Count tree.Add(New Node(k + 2)) tree(n).Edges(c) = suffix If tree(suffix).Length = 1 Then tree(suffix).Suffix = 0 Continue For End If While True n = tree(n).Suffix Dim b = i - tree(n).Length - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If End While Dim a = tree(n) Dim d = a.Edges(c) Dim e = tree(suffix) e.Suffix = d Next Return tree End Function Function SubPalindromes(tree As List(Of Node)) As List(Of String) Dim s As New List(Of String) Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String) For Each c In tree(n).Edges.Keys Dim m = tree(n).Edges(c) Dim p1 = c + p + c s.Add(p1) children(m, p1) Next End Sub children(0, "") For Each c In tree(1).Edges.Keys Dim m = tree(1).Edges(c) Dim ct = c.ToString() s.Add(ct) children(m, ct) Next Return s End Function Sub Main() Dim tree = Eertree("eertree") Dim result = SubPalindromes(tree) Dim listStr = String.Join(", ", result) Console.WriteLine("[{0}]", listStr) End Sub End Module
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
Convert this VB snippet to C++ and keep its semantics consistent.
DEFINT A-Z DECLARE FUNCTION p% (Yr AS INTEGER) DECLARE FUNCTION LongYear% (Yr AS INTEGER) DIM iYi, iYf, i CLS PRINT "This program calculates which are 53-week years in a range." PRINT INPUT "Initial year"; iYi INPUT "Final year (could be the same)"; iYf IF iYf >= iYi THEN FOR i = iYi TO iYf IF LongYear(i) THEN PRINT i; " "; END IF NEXT i END IF PRINT PRINT PRINT "End of program." END FUNCTION LongYear% (Yr AS INTEGER) LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3) END FUNCTION FUNCTION p% (Yr AS INTEGER) p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7 END FUNCTION
#include <stdio.h> #include <math.h> int p(int year) { return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7; } int is_long_year(int year) { return p(year) == 4 || p(year - 1) == 3; } void print_long_years(int from, int to) { for (int year = from; year <= to; ++year) { if (is_long_year(year)) { printf("%d ", year); } } } int main() { printf("Long (53 week) years between 1800 and 2100\n\n"); print_long_years(1800, 2100); printf("\n"); return 0; }
Produce a functionally identical C++ code for the snippet given in VB.
Module Module1 Function GetDivisors(n As Integer) As List(Of Integer) Dim divs As New List(Of Integer) From { 1, n } Dim i = 2 While i * i <= n If n Mod i = 0 Then Dim j = n \ i divs.Add(i) If i <> j Then divs.Add(j) End If End If i += 1 End While Return divs End Function Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean If sum = 0 Then Return True End If Dim le = divs.Count If le = 0 Then Return False End If Dim last = divs(le - 1) Dim newDivs As New List(Of Integer) For i = 1 To le - 1 newDivs.Add(divs(i - 1)) Next If last > sum Then Return IsPartSum(newDivs, sum) End If Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last) End Function Function IsZumkeller(n As Integer) As Boolean Dim divs = GetDivisors(n) Dim sum = divs.Sum() REM if sum is odd can If sum Mod 2 = 1 Then Return False End If REM if n is odd use If n Mod 2 = 1 Then Dim abundance = sum - 2 * n Return abundance > 0 AndAlso abundance Mod 2 = 0 End If REM if n and sum are both even check if there Return IsPartSum(divs, sum \ 2) End Function Sub Main() Console.WriteLine("The first 220 Zumkeller numbers are:") Dim i = 2 Dim count = 0 While count < 220 If IsZumkeller(i) Then Console.Write("{0,3} ", i) count += 1 If count Mod 20 = 0 Then Console.WriteLine() End If End If i += 1 End While Console.WriteLine() Console.WriteLine("The first 40 odd Zumkeller numbers are:") i = 3 count = 0 While count < 40 If IsZumkeller(i) Then Console.Write("{0,5} ", i) count += 1 If count Mod 10 = 0 Then Console.WriteLine() End If End If i += 2 End While Console.WriteLine() Console.WriteLine("The first 40 odd Zumkeller numbers which don i = 3 count = 0 While count < 40 If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then Console.Write("{0,7} ", i) count += 1 If count Mod 8 = 0 Then Console.WriteLine() End If End If i += 2 End While End Sub End Module
#include <iostream"> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> #include <numeric> using namespace std; const uint* binary(uint n, uint length); uint sum_subset_unrank_bin(const vector<uint>& d, uint r); vector<uint> factors(uint x); bool isPrime(uint number); bool isZum(uint n); ostream& operator<<(ostream& os, const vector<uint>& zumz) { for (uint i = 0; i < zumz.size(); i++) { if (i % 10 == 0) os << endl; os << setw(10) << zumz[i] << ' '; } return os; } int main() { cout << "First 220 Zumkeller numbers:" << endl; vector<uint> zumz; for (uint n = 2; zumz.size() < 220; n++) if (isZum(n)) zumz.push_back(n); cout << zumz << endl << endl; cout << "First 40 odd Zumkeller numbers:" << endl; vector<uint> zumz2; for (uint n = 2; zumz2.size() < 40; n++) if (n % 2 && isZum(n)) zumz2.push_back(n); cout << zumz2 << endl << endl; cout << "First 40 odd Zumkeller numbers not ending in 5:" << endl; vector<uint> zumz3; for (uint n = 2; zumz3.size() < 40; n++) if (n % 2 && (n % 10) != 5 && isZum(n)) zumz3.push_back(n); cout << zumz3 << endl << endl; return 0; } const uint* binary(uint n, uint length) { uint* bin = new uint[length]; fill(bin, bin + length, 0); for (uint i = 0; n > 0; i++) { uint rem = n % 2; n /= 2; if (rem) bin[length - 1 - i] = 1; } return bin; } uint sum_subset_unrank_bin(const vector<uint>& d, uint r) { vector<uint> subset; const uint* bits = binary(r, d.size() - 1); for (uint i = 0; i < d.size() - 1; i++) if (bits[i]) subset.push_back(d[i]); delete[] bits; return accumulate(subset.begin(), subset.end(), 0u); } vector<uint> factors(uint x) { vector<uint> result; for (uint i = 1; i * i <= x; i++) { if (x % i == 0) { result.push_back(i); if (x / i != i) result.push_back(x / i); } } sort(result.begin(), result.end()); return result; } bool isPrime(uint number) { if (number < 2) return false; if (number == 2) return true; if (number % 2 == 0) return false; for (uint i = 3; i * i <= number; i += 2) if (number % i == 0) return false; return true; } bool isZum(uint n) { if (isPrime(n)) return false; const auto d = factors(n); uint s = accumulate(d.begin(), d.end(), 0u); if (s % 2 || s < 2 * n) return false; if (n % 2 || d.size() >= 24) return true; if (!(s % 2) && d[d.size() - 1] <= s / 2) for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) if (sum_subset_unrank_bin(d, x) == s / 2) return true; return false; }
Translate the given VB code snippet into C++ without altering its behavior.
Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Result End Sub Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative) Dim i As Long, Respons As Long Res = Base For i = LBound(Update) To UBound(Update) If Exist(Respons, Base, Update(i).Key) Then Res(Respons).Value = Update(i).Value Else ReDim Preserve Res(UBound(Res) + 1) Res(UBound(Res)).Key = Update(i).Key Res(UBound(Res)).Value = Update(i).Value End If Next End Sub Private Function Exist(R As Long, B() As Associative, K As String) As Boolean Dim i As Long Do If B(i).Key = K Then Exist = True R = i End If i = i + 1 Loop While i <= UBound(B) And Not Exist End Function Private Sub FillArrays(B() As Associative, U() As Associative) B(0).Key = "name" B(0).Value = "Rocket Skates" B(1).Key = "price" B(1).Value = 12.75 B(2).Key = "color" B(2).Value = "yellow" U(0).Key = "price" U(0).Value = 15.25 U(1).Key = "color" U(1).Value = "red" U(2).Key = "year" U(2).Value = 1974 End Sub Private Sub PrintOut(A() As Associative) Dim i As Long Debug.Print "Key", "Value" For i = LBound(A) To UBound(A) Debug.Print A(i).Key, A(i).Value Next i Debug.Print "-----------------------------" End Sub
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; map original{ {"name", "Rocket Skates"}, {"price", "12.75"}, {"color", "yellow"} }; map update{ {"price", "15.25"}, {"color", "red"}, {"year", "1974"} }; map merged(merge(original, update)); for (auto&& i : merged) std::cout << "key: " << i.first << ", value: " << i.second << '\n'; return 0; }
Rewrite the snippet below in C++ so it works the same as the original VB code.
Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Result End Sub Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative) Dim i As Long, Respons As Long Res = Base For i = LBound(Update) To UBound(Update) If Exist(Respons, Base, Update(i).Key) Then Res(Respons).Value = Update(i).Value Else ReDim Preserve Res(UBound(Res) + 1) Res(UBound(Res)).Key = Update(i).Key Res(UBound(Res)).Value = Update(i).Value End If Next End Sub Private Function Exist(R As Long, B() As Associative, K As String) As Boolean Dim i As Long Do If B(i).Key = K Then Exist = True R = i End If i = i + 1 Loop While i <= UBound(B) And Not Exist End Function Private Sub FillArrays(B() As Associative, U() As Associative) B(0).Key = "name" B(0).Value = "Rocket Skates" B(1).Key = "price" B(1).Value = 12.75 B(2).Key = "color" B(2).Value = "yellow" U(0).Key = "price" U(0).Value = 15.25 U(1).Key = "color" U(1).Value = "red" U(2).Key = "year" U(2).Value = 1974 End Sub Private Sub PrintOut(A() As Associative) Dim i As Long Debug.Print "Key", "Value" For i = LBound(A) To UBound(A) Debug.Print A(i).Key, A(i).Value Next i Debug.Print "-----------------------------" End Sub
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; map original{ {"name", "Rocket Skates"}, {"price", "12.75"}, {"color", "yellow"} }; map update{ {"price", "15.25"}, {"color", "red"}, {"year", "1974"} }; map merged(merge(original, update)); for (auto&& i : merged) std::cout << "key: " << i.first << ", value: " << i.second << '\n'; return 0; }
Generate an equivalent C++ version of this VB code.
Imports BI = System.Numerics.BigInteger Module Module1 Function IntSqRoot(v As BI, res As BI) As BI REM res is the initial guess Dim term As BI = 0 Dim d As BI = 0 Dim dl As BI = 1 While dl <> d term = v / res res = (res + term) >> 1 dl = d d = term - res End While Return term End Function Function DoOne(b As Integer, digs As Integer) As String REM calculates result via square root, not iterations Dim s = b * b + 4 digs += 1 Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs)) Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g) bs += b * BI.Parse("1" + New String("0", digs)) bs >>= 1 bs += 4 Dim st = bs.ToString digs -= 1 Return String.Format("{0}.{1}", st(0), st.Substring(1, digs)) End Function Function DivIt(a As BI, b As BI, digs As Integer) As String REM performs division Dim al = a.ToString.Length Dim bl = b.ToString.Length digs += 1 a *= BI.Pow(10, digs << 1) b *= BI.Pow(10, digs) Dim s = (a / b + 5).ToString digs -= 1 Return s(0) + "." + s.Substring(1, digs) End Function REM custom formatting Function Joined(x() As BI) As String Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Dim res = "" For i = 0 To x.Length - 1 res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i)) Next Return res End Function Sub Main() REM calculates and checks each "metal" Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc") Dim t = "" Dim n As BI Dim nm1 As BI Dim k As Integer Dim j As Integer For b = 0 To 9 Dim lst(14) As BI lst(0) = 1 lst(1) = 1 For i = 2 To 14 lst(i) = b * lst(i - 1) + lst(i - 2) Next REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15 n = lst(14) nm1 = lst(13) k = 0 j = 13 While k = 0 Dim lt = t t = DivIt(n, nm1, 32) If lt = t Then k = If(b = 0, 1, j) End If Dim onn = n n = b * n + nm1 nm1 = onn j += 1 End While Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst)) Next REM now calculate and check big one n = 1 nm1 = 1 k = 0 j = 1 While k = 0 Dim lt = t t = DivIt(n, nm1, 256) If lt = t Then k = j End If Dim onn = n n += nm1 nm1 = onn j += 1 End While Console.WriteLine() Console.WriteLine("Au to 256 digits:") Console.WriteLine(t) Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256)) End Sub End Module
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: "; auto x0 = 1L, x1 = 1L; std::cout << x0 << ", " << x1; for (auto i = 1u; i <= N - 1 - 1; i++) { auto x2 = b * x1 + x0; std::cout << ", " << x2; x0 = x1; x1 = x2; } std::cout << std::endl; } template<const ushort P> void metallic(ulong b) { using namespace boost::multiprecision; using bfloat = number<cpp_dec_float<P+1>>; bfloat x0(1), x1(1); auto prev = bfloat(1).str(P+1); for (auto i = 0u;;) { i++; bfloat x2(b * x1 + x0); auto thiz = bfloat(x2 / x1).str(P+1); if (prev == thiz) { std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl; break; } prev = thiz; x0 = x1; x1 = x2; } } int main() { for (auto b = 0L; b < 10L; b++) { lucas<15>(b); metallic<32>(b); } std::cout << "Golden ratio, where b = 1:" << std::endl; metallic<256>(1); return 0; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
Imports BI = System.Numerics.BigInteger Module Module1 Function IntSqRoot(v As BI, res As BI) As BI REM res is the initial guess Dim term As BI = 0 Dim d As BI = 0 Dim dl As BI = 1 While dl <> d term = v / res res = (res + term) >> 1 dl = d d = term - res End While Return term End Function Function DoOne(b As Integer, digs As Integer) As String REM calculates result via square root, not iterations Dim s = b * b + 4 digs += 1 Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs)) Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g) bs += b * BI.Parse("1" + New String("0", digs)) bs >>= 1 bs += 4 Dim st = bs.ToString digs -= 1 Return String.Format("{0}.{1}", st(0), st.Substring(1, digs)) End Function Function DivIt(a As BI, b As BI, digs As Integer) As String REM performs division Dim al = a.ToString.Length Dim bl = b.ToString.Length digs += 1 a *= BI.Pow(10, digs << 1) b *= BI.Pow(10, digs) Dim s = (a / b + 5).ToString digs -= 1 Return s(0) + "." + s.Substring(1, digs) End Function REM custom formatting Function Joined(x() As BI) As String Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Dim res = "" For i = 0 To x.Length - 1 res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i)) Next Return res End Function Sub Main() REM calculates and checks each "metal" Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc") Dim t = "" Dim n As BI Dim nm1 As BI Dim k As Integer Dim j As Integer For b = 0 To 9 Dim lst(14) As BI lst(0) = 1 lst(1) = 1 For i = 2 To 14 lst(i) = b * lst(i - 1) + lst(i - 2) Next REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15 n = lst(14) nm1 = lst(13) k = 0 j = 13 While k = 0 Dim lt = t t = DivIt(n, nm1, 32) If lt = t Then k = If(b = 0, 1, j) End If Dim onn = n n = b * n + nm1 nm1 = onn j += 1 End While Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst)) Next REM now calculate and check big one n = 1 nm1 = 1 k = 0 j = 1 While k = 0 Dim lt = t t = DivIt(n, nm1, 256) If lt = t Then k = j End If Dim onn = n n += nm1 nm1 = onn j += 1 End While Console.WriteLine() Console.WriteLine("Au to 256 digits:") Console.WriteLine(t) Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256)) End Sub End Module
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: "; auto x0 = 1L, x1 = 1L; std::cout << x0 << ", " << x1; for (auto i = 1u; i <= N - 1 - 1; i++) { auto x2 = b * x1 + x0; std::cout << ", " << x2; x0 = x1; x1 = x2; } std::cout << std::endl; } template<const ushort P> void metallic(ulong b) { using namespace boost::multiprecision; using bfloat = number<cpp_dec_float<P+1>>; bfloat x0(1), x1(1); auto prev = bfloat(1).str(P+1); for (auto i = 0u;;) { i++; bfloat x2(b * x1 + x0); auto thiz = bfloat(x2 / x1).str(P+1); if (prev == thiz) { std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl; break; } prev = thiz; x0 = x1; x1 = x2; } } int main() { for (auto b = 0L; b < 10L; b++) { lucas<15>(b); metallic<32>(b); } std::cout << "Golden ratio, where b = 1:" << std::endl; metallic<256>(1); return 0; }
Port the provided VB code into C++ while preserving the original functionality.
Imports BI = System.Numerics.BigInteger Module Module1 Function IntSqRoot(v As BI, res As BI) As BI REM res is the initial guess Dim term As BI = 0 Dim d As BI = 0 Dim dl As BI = 1 While dl <> d term = v / res res = (res + term) >> 1 dl = d d = term - res End While Return term End Function Function DoOne(b As Integer, digs As Integer) As String REM calculates result via square root, not iterations Dim s = b * b + 4 digs += 1 Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs)) Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g) bs += b * BI.Parse("1" + New String("0", digs)) bs >>= 1 bs += 4 Dim st = bs.ToString digs -= 1 Return String.Format("{0}.{1}", st(0), st.Substring(1, digs)) End Function Function DivIt(a As BI, b As BI, digs As Integer) As String REM performs division Dim al = a.ToString.Length Dim bl = b.ToString.Length digs += 1 a *= BI.Pow(10, digs << 1) b *= BI.Pow(10, digs) Dim s = (a / b + 5).ToString digs -= 1 Return s(0) + "." + s.Substring(1, digs) End Function REM custom formatting Function Joined(x() As BI) As String Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Dim res = "" For i = 0 To x.Length - 1 res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i)) Next Return res End Function Sub Main() REM calculates and checks each "metal" Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc") Dim t = "" Dim n As BI Dim nm1 As BI Dim k As Integer Dim j As Integer For b = 0 To 9 Dim lst(14) As BI lst(0) = 1 lst(1) = 1 For i = 2 To 14 lst(i) = b * lst(i - 1) + lst(i - 2) Next REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15 n = lst(14) nm1 = lst(13) k = 0 j = 13 While k = 0 Dim lt = t t = DivIt(n, nm1, 32) If lt = t Then k = If(b = 0, 1, j) End If Dim onn = n n = b * n + nm1 nm1 = onn j += 1 End While Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst)) Next REM now calculate and check big one n = 1 nm1 = 1 k = 0 j = 1 While k = 0 Dim lt = t t = DivIt(n, nm1, 256) If lt = t Then k = j End If Dim onn = n n += nm1 nm1 = onn j += 1 End While Console.WriteLine() Console.WriteLine("Au to 256 digits:") Console.WriteLine(t) Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256)) End Sub End Module
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: "; auto x0 = 1L, x1 = 1L; std::cout << x0 << ", " << x1; for (auto i = 1u; i <= N - 1 - 1; i++) { auto x2 = b * x1 + x0; std::cout << ", " << x2; x0 = x1; x1 = x2; } std::cout << std::endl; } template<const ushort P> void metallic(ulong b) { using namespace boost::multiprecision; using bfloat = number<cpp_dec_float<P+1>>; bfloat x0(1), x1(1); auto prev = bfloat(1).str(P+1); for (auto i = 0u;;) { i++; bfloat x2(b * x1 + x0); auto thiz = bfloat(x2 / x1).str(P+1); if (prev == thiz) { std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl; break; } prev = thiz; x0 = x1; x1 = x2; } } int main() { for (auto b = 0L; b < 10L; b++) { lucas<15>(b); metallic<32>(b); } std::cout << "Golden ratio, where b = 1:" << std::endl; metallic<256>(1); return 0; }
Write the same code in C++ as shown below in VB.
Class Branch Public from As Node Public towards As Node Public length As Integer Public distance As Integer Public key As String Class Node Public key As String Public correspondingBranch As Branch Const INFINITY = 32767 Private Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node) Dim a As New Collection Dim b As New Collection Dim c As New Collection Dim I As New Collection Dim II As New Collection Dim III As New Collection Dim u As Node, R_ As Node, dist As Integer For Each n In Nodes c.Add n, n.key Next n For Each e In Branches III.Add e, e.key Next e a.Add P, P.key c.Remove P.key Set u = P Do For Each r In III If r.from Is u Then Set R_ = r.towards If Belongs(R_, c) Then c.Remove R_.key b.Add R_, R_.key Set R_.correspondingBranch = r If u.correspondingBranch Is Nothing Then R_.correspondingBranch.distance = r.length Else R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length End If III.Remove r.key II.Add r, r.key Else If Belongs(R_, b) Then If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then II.Remove R_.correspondingBranch.key II.Add r, r.key Set R_.correspondingBranch = r R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length End If End If End If End If Next r dist = INFINITY Set u = Nothing For Each n In b If dist > n.correspondingBranch.distance Then dist = n.correspondingBranch.distance Set u = n End If Next n b.Remove u.key a.Add u, u.key II.Remove u.correspondingBranch.key I.Add u.correspondingBranch, u.correspondingBranch.key Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q) If Not Q Is Nothing Then GetPath Q End Sub Private Function Belongs(n As Node, col As Collection) As Boolean Dim obj As Node On Error GoTo err Belongs = True Set obj = col(n.key) Exit Function err: Belongs = False End Function Private Sub GetPath(Target As Node) Dim path As String If Target.correspondingBranch Is Nothing Then path = "no path" Else path = Target.key Set u = Target Do While Not u.correspondingBranch Is Nothing path = u.correspondingBranch.from.key & " " & path Set u = u.correspondingBranch.from Loop Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path End If End Sub Public Sub test() Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = "ab": ab.distance = INFINITY Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = "ac": ac.distance = INFINITY Set af.from = a: Set af.towards = f: af.length = 14: af.key = "af": af.distance = INFINITY Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = "bc": bc.distance = INFINITY Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = "bd": bd.distance = INFINITY Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = "cd": cd.distance = INFINITY Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = "cf": cf.distance = INFINITY Set de.from = d: Set de.towards = e: de.length = 6: de.key = "de": de.distance = INFINITY Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = "ef": ef.distance = INFINITY a.key = "a" b.key = "b" c.key = "c" d.key = "d" e.key = "e" f.key = "f" Dim testNodes As New Collection Dim testBranches As New Collection testNodes.Add a, "a" testNodes.Add b, "b" testNodes.Add c, "c" testNodes.Add d, "d" testNodes.Add e, "e" testNodes.Add f, "f" testBranches.Add ab, "ab" testBranches.Add ac, "ac" testBranches.Add af, "af" testBranches.Add bc, "bc" testBranches.Add bd, "bd" testBranches.Add cd, "cd" testBranches.Add cf, "cf" testBranches.Add de, "de" testBranches.Add ef, "ef" Debug.Print "From", "To", "Distance", "Path" Dijkstra testNodes, testBranches, a, e Dijkstra testNodes, testBranches, a GetPath f End Sub
#include <iostream> #include <vector> #include <string> #include <list> #include <limits> #include <set> #include <utility> #include <algorithm> #include <iterator> typedef int vertex_t; typedef double weight_t; const weight_t max_weight = std::numeric_limits<double>::infinity(); struct neighbor { vertex_t target; weight_t weight; neighbor(vertex_t arg_target, weight_t arg_weight) : target(arg_target), weight(arg_weight) { } }; typedef std::vector<std::vector<neighbor> > adjacency_list_t; void DijkstraComputePaths(vertex_t source, const adjacency_list_t &adjacency_list, std::vector<weight_t> &min_distance, std::vector<vertex_t> &previous) { int n = adjacency_list.size(); min_distance.clear(); min_distance.resize(n, max_weight); min_distance[source] = 0; previous.clear(); previous.resize(n, -1); std::set<std::pair<weight_t, vertex_t> > vertex_queue; vertex_queue.insert(std::make_pair(min_distance[source], source)); while (!vertex_queue.empty()) { weight_t dist = vertex_queue.begin()->first; vertex_t u = vertex_queue.begin()->second; vertex_queue.erase(vertex_queue.begin()); const std::vector<neighbor> &neighbors = adjacency_list[u]; for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin(); neighbor_iter != neighbors.end(); neighbor_iter++) { vertex_t v = neighbor_iter->target; weight_t weight = neighbor_iter->weight; weight_t distance_through_u = dist + weight; if (distance_through_u < min_distance[v]) { vertex_queue.erase(std::make_pair(min_distance[v], v)); min_distance[v] = distance_through_u; previous[v] = u; vertex_queue.insert(std::make_pair(min_distance[v], v)); } } } } std::list<vertex_t> DijkstraGetShortestPathTo( vertex_t vertex, const std::vector<vertex_t> &previous) { std::list<vertex_t> path; for ( ; vertex != -1; vertex = previous[vertex]) path.push_front(vertex); return path; } int main() { adjacency_list_t adjacency_list(6); adjacency_list[0].push_back(neighbor(1, 7)); adjacency_list[0].push_back(neighbor(2, 9)); adjacency_list[0].push_back(neighbor(5, 14)); adjacency_list[1].push_back(neighbor(0, 7)); adjacency_list[1].push_back(neighbor(2, 10)); adjacency_list[1].push_back(neighbor(3, 15)); adjacency_list[2].push_back(neighbor(0, 9)); adjacency_list[2].push_back(neighbor(1, 10)); adjacency_list[2].push_back(neighbor(3, 11)); adjacency_list[2].push_back(neighbor(5, 2)); adjacency_list[3].push_back(neighbor(1, 15)); adjacency_list[3].push_back(neighbor(2, 11)); adjacency_list[3].push_back(neighbor(4, 6)); adjacency_list[4].push_back(neighbor(3, 6)); adjacency_list[4].push_back(neighbor(5, 9)); adjacency_list[5].push_back(neighbor(0, 14)); adjacency_list[5].push_back(neighbor(2, 2)); adjacency_list[5].push_back(neighbor(4, 9)); std::vector<weight_t> min_distance; std::vector<vertex_t> previous; DijkstraComputePaths(0, adjacency_list, min_distance, previous); std::cout << "Distance from 0 to 4: " << min_distance[4] << std::endl; std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous); std::cout << "Path : "; std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, " ")); std::cout << std::endl; return 0; }
Translate the given VB code snippet into C++ without altering its behavior.
Option Strict On Imports System.Text Module Module1 Structure Vector Private ReadOnly dims() As Double Public Sub New(da() As Double) dims = da End Sub Public Shared Operator -(v As Vector) As Vector Return v * -1.0 End Operator Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector Dim result(31) As Double Array.Copy(lhs.dims, 0, result, 0, lhs.Length) For i = 1 To result.Length Dim i2 = i - 1 result(i2) = lhs(i2) + rhs(i2) Next Return New Vector(result) End Operator Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector Dim result(31) As Double For i = 1 To lhs.Length Dim i2 = i - 1 If lhs(i2) <> 0.0 Then For j = 1 To lhs.Length Dim j2 = j - 1 If rhs(j2) <> 0.0 Then Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2) Dim k = i2 Xor j2 result(k) += s End If Next End If Next Return New Vector(result) End Operator Public Shared Operator *(v As Vector, scale As Double) As Vector Dim result = CType(v.dims.Clone, Double()) For i = 1 To result.Length Dim i2 = i - 1 result(i2) *= scale Next Return New Vector(result) End Operator Default Public Property Index(key As Integer) As Double Get Return dims(key) End Get Set(value As Double) dims(key) = value End Set End Property Public ReadOnly Property Length As Integer Get Return dims.Length End Get End Property Public Function Dot(rhs As Vector) As Vector Return (Me * rhs + rhs * Me) * 0.5 End Function Private Shared Function BitCount(i As Integer) As Integer i -= ((i >> 1) And &H55555555) i = (i And &H33333333) + ((i >> 2) And &H33333333) i = (i + (i >> 4)) And &HF0F0F0F i += (i >> 8) i += (i >> 16) Return i And &H3F End Function Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double Dim k = i >> 1 Dim sum = 0 While k <> 0 sum += BitCount(k And j) k >>= 1 End While Return If((sum And 1) = 0, 1.0, -1.0) End Function Public Overrides Function ToString() As String Dim it = dims.GetEnumerator Dim sb As New StringBuilder("[") If it.MoveNext() Then sb.Append(it.Current) End If While it.MoveNext sb.Append(", ") sb.Append(it.Current) End While sb.Append("]") Return sb.ToString End Function End Structure Function DoubleArray(size As Integer) As Double() Dim result(size - 1) As Double For i = 1 To size Dim i2 = i - 1 result(i2) = 0.0 Next Return result End Function Function E(n As Integer) As Vector If n > 4 Then Throw New ArgumentException("n must be less than 5") End If Dim result As New Vector(DoubleArray(32)) result(1 << n) = 1.0 Return result End Function ReadOnly r As New Random() Function RandomVector() As Vector Dim result As New Vector(DoubleArray(32)) For i = 1 To 5 Dim i2 = i - 1 Dim singleton() As Double = {r.NextDouble()} result += New Vector(singleton) * E(i2) Next Return result End Function Function RandomMultiVector() As Vector Dim result As New Vector(DoubleArray(32)) For i = 1 To result.Length Dim i2 = i - 1 result(i2) = r.NextDouble() Next Return result End Function Sub Main() For i = 1 To 5 Dim i2 = i - 1 For j = 1 To 5 Dim j2 = j - 1 If i2 < j2 Then If E(i2).Dot(E(j2))(0) <> 0.0 Then Console.Error.WriteLine("Unexpected non-null scalar product") Return End If ElseIf i2 = j2 Then If E(i2).Dot(E(j2))(0) = 0.0 Then Console.Error.WriteLine("Unexpected null scalar product") Return End If End If Next Next Dim a = RandomMultiVector() Dim b = RandomMultiVector() Dim c = RandomMultiVector() Dim x = RandomVector() Console.WriteLine((a * b) * c) Console.WriteLine(a * (b * c)) Console.WriteLine() Console.WriteLine(a * (b + c)) Console.WriteLine(a * b + a * c) Console.WriteLine() Console.WriteLine((a + b) * c) Console.WriteLine(a * c + b * c) Console.WriteLine() Console.WriteLine(x * x) End Sub End Module
#include <algorithm> #include <iostream> #include <random> #include <vector> double uniform01() { static std::default_random_engine generator; static std::uniform_real_distribution<double> distribution(0.0, 1.0); return distribution(generator); } int bitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F0F0F; i += (i >> 8); i += (i >> 16); return i & 0x0000003F; } double reorderingSign(int i, int j) { int k = i >> 1; int sum = 0; while (k != 0) { sum += bitCount(k & j); k = k >> 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } struct MyVector { public: MyVector(const std::vector<double> &da) : dims(da) { } double &operator[](size_t i) { return dims[i]; } const double &operator[](size_t i) const { return dims[i]; } MyVector operator+(const MyVector &rhs) const { std::vector<double> temp(dims); for (size_t i = 0; i < rhs.dims.size(); ++i) { temp[i] += rhs[i]; } return MyVector(temp); } MyVector operator*(const MyVector &rhs) const { std::vector<double> temp(dims.size(), 0.0); for (size_t i = 0; i < dims.size(); i++) { if (dims[i] != 0.0) { for (size_t j = 0; j < dims.size(); j++) { if (rhs[j] != 0.0) { auto s = reorderingSign(i, j) * dims[i] * rhs[j]; auto k = i ^ j; temp[k] += s; } } } } return MyVector(temp); } MyVector operator*(double scale) const { std::vector<double> temp(dims); std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; }); return MyVector(temp); } MyVector operator-() const { return *this * -1.0; } MyVector dot(const MyVector &rhs) const { return (*this * rhs + rhs * *this) * 0.5; } friend std::ostream &operator<<(std::ostream &, const MyVector &); private: std::vector<double> dims; }; std::ostream &operator<<(std::ostream &os, const MyVector &v) { auto it = v.dims.cbegin(); auto end = v.dims.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } MyVector e(int n) { if (n > 4) { throw new std::runtime_error("n must be less than 5"); } auto result = MyVector(std::vector<double>(32, 0.0)); result[1 << n] = 1.0; return result; } MyVector randomVector() { auto result = MyVector(std::vector<double>(32, 0.0)); for (int i = 0; i < 5; i++) { result = result + MyVector(std::vector<double>(1, uniform01())) * e(i); } return result; } MyVector randomMultiVector() { auto result = MyVector(std::vector<double>(32, 0.0)); for (int i = 0; i < 32; i++) { result[i] = uniform01(); } return result; } int main() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i < j) { if (e(i).dot(e(j))[0] != 0.0) { std::cout << "Unexpected non-null scalar product."; return 1; } else if (i == j) { if (e(i).dot(e(j))[0] == 0.0) { std::cout << "Unexpected null scalar product."; } } } } } auto a = randomMultiVector(); auto b = randomMultiVector(); auto c = randomMultiVector(); auto x = randomVector(); std::cout << ((a * b) * c) << '\n'; std::cout << (a * (b * c)) << "\n\n"; std::cout << (a * (b + c)) << '\n'; std::cout << (a * b + a * c) << "\n\n"; std::cout << ((a + b) * c) << '\n'; std::cout << (a * c + b * c) << "\n\n"; std::cout << (x * x) << '\n'; return 0; }
Change the programming language of this snippet from VB to C++ without modifying what it does.
Option Explicit Sub Test() Dim h As Object, i As Long, u, v, s Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 For Each s In h.Keys Debug.Print s Next For Each s In h.Items Debug.Print s Next u = h.Keys v = h.Items For i = 0 To h.Count - 1 Debug.Print u(i), v(i) Next End Sub
#include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> dict { {"One", 1}, {"Two", 2}, {"Three", 7} }; dict["Three"] = 3; std::cout << "One: " << dict["One"] << std::endl; std::cout << "Key/Value pairs: " << std::endl; for(auto& kv: dict) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } return 0; }
Translate the given VB code snippet into C++ without altering its behavior.
Private mvarValue As Integer Public Property Let Value(ByVal vData As Integer) If (vData > 10) Or (vData < 1) Then Error 380 Else mvarValue = vData End If End Property Public Property Get Value() As Integer Value = mvarValue End Property Private Sub Class_Initialize() mvarValue = 1 End Sub
#include <stdexcept> class tiny_int { public: tiny_int(int i): value(i) { if (value < 1) throw std::out_of_range("tiny_int: value smaller than 1"); if (value > 10) throw std::out_of_range("tiny_int: value larger than 10"); } operator int() const { return value; } tiny_int& operator+=(int i) { *this = value + i; return *this; } tiny_int& operator-=(int i) { *this = value - i; return *this; } tiny_int& operator*=(int i) { *this = value * i; return *this; } tiny_int& operator/=(int i) { *this = value / i; return *this; } tiny_int& operator<<=(int i) { *this = value << i; return *this; } tiny_int& operator>>=(int i) { *this = value >> i; return *this; } tiny_int& operator&=(int i) { *this = value & i; return *this; } tiny_int& operator|=(int i) { *this = value | i; return *this; } private: unsigned char value; };
Port the provided VB code into C++ while preserving the original functionality.
Dim t_age(4,1) t_age(0,0) = 27 : t_age(0,1) = "Jonah" t_age(1,0) = 18 : t_age(1,1) = "Alan" t_age(2,0) = 28 : t_age(2,1) = "Glory" t_age(3,0) = 18 : t_age(3,1) = "Popeye" t_age(4,0) = 28 : t_age(4,1) = "Alan" Dim t_nemesis(4,1) t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales" t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders" t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts" t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies" t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy" Call hash_join(t_age,1,t_nemesis,0) Sub hash_join(table_1,index_1,table_2,index_2) Set hash = CreateObject("Scripting.Dictionary") For i = 0 To UBound(table_1) hash.Add i,Array(table_1(i,0),table_1(i,1)) Next For j = 0 To UBound(table_2) For Each key In hash.Keys If hash(key)(index_1) = table_2(j,index_2) Then WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_ " = " & table_2(j,0) & "," & table_2(j,1) End If Next Next End Sub
#include <iostream> #include <string> #include <vector> #include <unordered_map> using tab_t = std::vector<std::vector<std::string>>; tab_t tab1 { {"27", "Jonah"} , {"18", "Alan"} , {"28", "Glory"} , {"18", "Popeye"} , {"28", "Alan"} }; tab_t tab2 { {"Jonah", "Whales"} , {"Jonah", "Spiders"} , {"Alan", "Ghosts"} , {"Alan", "Zombies"} , {"Glory", "Buffy"} }; std::ostream& operator<<(std::ostream& o, const tab_t& t) { for(size_t i = 0; i < t.size(); ++i) { o << i << ":"; for(const auto& e : t[i]) o << '\t' << e; o << std::endl; } return o; } tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) { std::unordered_multimap<std::string, size_t> hashmap; for(size_t i = 0; i < a.size(); ++i) { hashmap.insert(std::make_pair(a[i][columna], i)); } tab_t result; for(size_t i = 0; i < b.size(); ++i) { auto range = hashmap.equal_range(b[i][columnb]); for(auto it = range.first; it != range.second; ++it) { tab_t::value_type row; row.insert(row.end() , a[it->second].begin() , a[it->second].end()); row.insert(row.end() , b[i].begin() , b[i].end()); result.push_back(std::move(row)); } } return result; } int main(int argc, char const *argv[]) { using namespace std; int ret = 0; cout << "Table A: " << endl << tab1 << endl; cout << "Table B: " << endl << tab2 << endl; auto tab3 = Join(tab1, 1, tab2, 0); cout << "Joined tables: " << endl << tab3 << endl; return ret; }
Change the following VB code into C++ without altering its purpose.
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 const raiz2=1.4142135623730950488016887242097 sub media_sierp (niv,sz) if niv=0 then x.fw sz: exit sub media_sierp niv-1,sz x.lt 1 x.fw sz*raiz2 x.lt 1 media_sierp niv-1,sz x.rt 2 x.fw sz x.rt 2 media_sierp niv-1,sz x.lt 1 x.fw sz*raiz2 x.lt 1 media_sierp niv-1,sz end sub sub sierp(niv,sz) media_sierp niv,sz x.rt 2 x.fw sz x.rt 2 media_sierp niv,sz x.rt 2 x.fw sz x.rt 2 end sub dim x set x=new turtle x.iangle=45 x.orient=0 x.incr=1 x.x=100:x.y=270 sierp 5,4 set x=nothing
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_square { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::string& s); double x_; double y_; int angle_; int length_; }; void sierpinski_square::write(std::ostream& out, int size, int length, int order) { length_ = length; x_ = (size - length)/2; y_ = length; angle_ = 0; out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; std::string s = "F+XF+F+XF"; for (int i = 0; i < order; ++i) s = rewrite(s); execute(out, s); out << "'/>\n</svg>\n"; } std::string sierpinski_square::rewrite(const std::string& s) { std::string t; for (char c : s) { if (c == 'X') t += "XF-F+F-XF+F+XF-F+F-X"; else t += c; } return t; } void sierpinski_square::line(std::ostream& out) { double theta = (3.14159265359 * angle_)/180.0; x_ += length_ * std::cos(theta); y_ += length_ * std::sin(theta); out << " L" << x_ << ',' << y_; } void sierpinski_square::execute(std::ostream& out, const std::string& s) { out << 'M' << x_ << ',' << y_; for (char c : s) { switch (c) { case 'F': line(out); break; case '+': angle_ = (angle_ + 90) % 360; break; case '-': angle_ = (angle_ - 90) % 360; break; } } } int main() { std::ofstream out("sierpinski_square.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return 1; } sierpinski_square s; s.write(out, 635, 5, 5); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) set d= createobject("Scripting.Dictionary") for each aa in a x=trim(aa) l=len(x) if l>5 then d.removeall for i=1 to 3 m=mid(x,i,1) if not d.exists(m) then d.add m,null next res=true for i=l-2 to l m=mid(x,i,1) if not d.exists(m) then res=false:exit for else d.remove(m) end if next if res then wscript.stdout.write left(x & space(15),15) if left(x,3)=right(x,3) then wscript.stdout.write "*" wscript.stdout.writeline end if end if next
#include <cstdlib> #include <fstream> #include <iostream> int main(int argc, char** argv) { 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 word; int n = 0; while (getline(in, word)) { const size_t len = word.size(); if (len > 5 && word.compare(0, 3, word, len - 3) == 0) std::cout << ++n << ": " << word << '\n'; } return EXIT_SUCCESS; }
Write a version of this VB function in C++ with identical behavior.
Module Module1 Structure Node Private ReadOnly m_val As String Private ReadOnly m_parsed As List(Of String) Sub New(initial As String) m_val = initial m_parsed = New List(Of String) End Sub Sub New(s As String, p As List(Of String)) m_val = s m_parsed = p End Sub Public Function Value() As String Return m_val End Function Public Function Parsed() As List(Of String) Return m_parsed End Function End Structure Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String)) Dim matches As New List(Of List(Of String)) Dim q As New Queue(Of Node) q.Enqueue(New Node(s)) While q.Count > 0 Dim node = q.Dequeue() REM check if fully parsed If node.Value.Length = 0 Then matches.Add(node.Parsed) Else For Each word In dictionary REM check for match If node.Value.StartsWith(word) Then Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length) Dim parsedNew As New List(Of String) parsedNew.AddRange(node.Parsed) parsedNew.Add(word) q.Enqueue(New Node(valNew, parsedNew)) End If Next End If End While Return matches End Function Sub Main() Dim dict As New List(Of String) From {"a", "aa", "b", "ab", "aab"} For Each testString In {"aab", "aa b"} Dim matches = WordBreak(testString, dict) Console.WriteLine("String = {0}, Dictionary = {1}. Solutions = {2}", testString, dict, matches.Count) For Each match In matches Console.WriteLine(" Word Break = [{0}]", String.Join(", ", match)) Next Console.WriteLine() Next dict = New List(Of String) From {"abc", "a", "ac", "b", "c", "cb", "d"} For Each testString In {"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} Dim matches = WordBreak(testString, dict) Console.WriteLine("String = {0}, Dictionary = {1}. Solutions = {2}", testString, dict, matches.Count) For Each match In matches Console.WriteLine(" Word Break = [{0}]", String.Join(", ", match)) Next Console.WriteLine() Next End Sub End Module
#include <algorithm> #include <iostream> #include <optional> #include <set> #include <string> #include <string_view> #include <vector> struct string_comparator { using is_transparent = void; bool operator()(const std::string& lhs, const std::string& rhs) const { return lhs < rhs; } bool operator()(const std::string& lhs, const std::string_view& rhs) const { return lhs < rhs; } bool operator()(const std::string_view& lhs, const std::string& rhs) const { return lhs < rhs; } }; using dictionary = std::set<std::string, string_comparator>; template <typename iterator, typename separator> std::string join(iterator begin, iterator end, separator sep) { std::string result; if (begin != end) { result += *begin++; for (; begin != end; ++begin) { result += sep; result += *begin; } } return result; } auto create_string(const std::string_view& s, const std::vector<std::optional<size_t>>& v) { auto idx = s.size(); std::vector<std::string_view> sv; while (v[idx].has_value()) { size_t prev = v[idx].value(); sv.push_back(s.substr(prev, idx - prev)); idx = prev; } std::reverse(sv.begin(), sv.end()); return join(sv.begin(), sv.end(), ' '); } std::optional<std::string> word_break(const std::string_view& str, const dictionary& dict) { auto size = str.size() + 1; std::vector<std::optional<size_t>> possible(size); auto check_word = [&dict, &str](size_t i, size_t j) -> std::optional<size_t> { if (dict.find(str.substr(i, j - i)) != dict.end()) return i; return std::nullopt; }; for (size_t i = 1; i < size; ++i) { if (!possible[i].has_value()) possible[i] = check_word(0, i); if (possible[i].has_value()) { for (size_t j = i + 1; j < size; ++j) { if (!possible[j].has_value()) possible[j] = check_word(i, j); } if (possible[str.size()].has_value()) return create_string(str, possible); } } return std::nullopt; } int main(int argc, char** argv) { dictionary dict; dict.insert("a"); dict.insert("bc"); dict.insert("abc"); dict.insert("cd"); dict.insert("b"); auto result = word_break("abcd", dict); if (result.has_value()) std::cout << result.value() << '\n'; return 0; }
Write a version of this VB function in C++ with identical behavior.
Option Strict On Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer)) Module Module1 Sub Swap(Of T)(ByRef a As T, ByRef b As T) Dim u = a a = b b = u End Sub Sub PrintSquare(latin As Matrix) For Each row In latin Dim it = row.GetEnumerator Console.Write("[") If it.MoveNext Then Console.Write(it.Current) End If While it.MoveNext Console.Write(", ") Console.Write(it.Current) End While Console.WriteLine("]") Next Console.WriteLine() End Sub Function DList(n As Integer, start As Integer) As Matrix start -= 1 REM use 0 based indexes Dim a = Enumerable.Range(0, n).ToArray a(start) = a(0) a(0) = start Array.Sort(a, 1, a.Length - 1) Dim first = a(1) REM recursive closure permutes a[1:] Dim r As New Matrix Dim Recurse As Action(Of Integer) = Sub(last As Integer) If last = first Then REM bottom of recursion. you get here once for each permutation REM test if permutation is deranged. For j = 1 To a.Length - 1 Dim v = a(j) If j = v Then Return REM no, ignore it End If Next REM yes, save a copy with 1 based indexing Dim b = a.Select(Function(v) v + 1).ToArray r.Add(b.ToList) Return End If For i = last To 1 Step -1 Swap(a(i), a(last)) Recurse(last - 1) Swap(a(i), a(last)) Next End Sub Recurse(n - 1) Return r End Function Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong If n <= 0 Then If echo Then Console.WriteLine("[]") Console.WriteLine() End If Return 0 End If If n = 1 Then If echo Then Console.WriteLine("[1]") Console.WriteLine() End If Return 1 End If Dim rlatin As New Matrix For i = 0 To n - 1 rlatin.Add(New List(Of Integer)) For j = 0 To n - 1 rlatin(i).Add(0) Next Next REM first row For j = 0 To n - 1 rlatin(0)(j) = j + 1 Next Dim count As ULong = 0 Dim Recurse As Action(Of Integer) = Sub(i As Integer) Dim rows = DList(n, i) For r = 0 To rows.Count - 1 rlatin(i - 1) = rows(r) For k = 0 To i - 2 For j = 1 To n - 1 If rlatin(k)(j) = rlatin(i - 1)(j) Then If r < rows.Count - 1 Then GoTo outer End If If i > 2 Then Return End If End If Next Next If i < n Then Recurse(i + 1) Else count += 1UL If echo Then PrintSquare(rlatin) End If End If outer: While False REM empty End While Next End Sub REM remiain rows Recurse(2) Return count End Function Function Factorial(n As ULong) As ULong If n <= 0 Then Return 1 End If Dim prod = 1UL For i = 2UL To n prod *= i Next Return prod End Function Sub Main() Console.WriteLine("The four reduced latin squares of order 4 are:") Console.WriteLine() ReducedLatinSquares(4, True) Console.WriteLine("The size of the set of reduced latin squares for the following orders") Console.WriteLine("and hence the total number of latin squares of these orders are:") Console.WriteLine() For n = 1 To 6 Dim nu As ULong = CULng(n) Dim size = ReducedLatinSquares(n, False) Dim f = Factorial(nu - 1UL) f *= f * nu * size Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f) Next End Sub End Module
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <vector> typedef std::vector<std::vector<int>> matrix; matrix dList(int n, int start) { start--; std::vector<int> a(n); std::iota(a.begin(), a.end(), 0); a[start] = a[0]; a[0] = start; std::sort(a.begin() + 1, a.end()); auto first = a[1]; matrix r; std::function<void(int)> recurse; recurse = [&](int last) { if (last == first) { for (size_t j = 1; j < a.size(); j++) { auto v = a[j]; if (j == v) { return; } } std::vector<int> b; std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; }); r.push_back(b); return; } for (int i = last; i >= 1; i--) { std::swap(a[i], a[last]); recurse(last - 1); std::swap(a[i], a[last]); } }; recurse(n - 1); return r; } void printSquare(const matrix &latin, int n) { for (auto &row : latin) { auto it = row.cbegin(); auto end = row.cend(); std::cout << '['; if (it != end) { std::cout << *it; it = std::next(it); } while (it != end) { std::cout << ", " << *it; it = std::next(it); } std::cout << "]\n"; } std::cout << '\n'; } unsigned long reducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { std::cout << "[]\n"; } return 0; } else if (n == 1) { if (echo) { std::cout << "[1]\n"; } return 1; } matrix rlatin; for (int i = 0; i < n; i++) { rlatin.push_back({}); for (int j = 0; j < n; j++) { rlatin[i].push_back(j); } } for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } unsigned long count = 0; std::function<void(int)> recurse; recurse = [&](int i) { auto rows = dList(n, i); for (size_t r = 0; r < rows.size(); r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.size() - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { printSquare(rlatin, n); } } outer: {} } }; recurse(2); return count; } unsigned long factorial(unsigned long n) { if (n <= 0) return 1; unsigned long prod = 1; for (unsigned long i = 2; i <= n; i++) { prod *= i; } return prod; } int main() { std::cout << "The four reduced lating squares of order 4 are:\n"; reducedLatinSquares(4, true); std::cout << "The size of the set of reduced latin squares for the following orders\n"; std::cout << "and hence the total number of latin squares of these orders are:\n\n"; for (int n = 1; n < 7; n++) { auto size = reducedLatinSquares(n, false); auto f = factorial(n - 1); f *= f * n * size; std::cout << "Order " << n << ": Size " << size << " x " << n << "! x " << (n - 1) << "! => Total " << f << '\n'; } return 0; }
Write the same algorithm in C++ as shown in this VB implementation.
Option Explicit Const m_limit ="# #" Const m_middle=" # # " Dim a,bnum,i,check,odic a=array(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",_ " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",_ " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",_ " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",_ " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",_ " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",_ " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",_ " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",_ " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",_ " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ") bnum=Array("0001101","0011001","0010011","0111101","0100011"," 0110001","0101111","0111011","0110111","0001011") Set oDic = WScript.CreateObject("scripting.dictionary") For i=0 To 9: odic.Add bin2dec(bnum(i),Asc("1")),i+1 odic.Add bin2dec(bnum(i),Asc("0")),-i-1 Next For i=0 To UBound(a) : print pad(i+1,-2) & ": "& upc(a(i)) :Next WScript.Quit(1) Function bin2dec(ByVal B,a) Dim n While len(b) n =n *2 - (asc(b)=a) b=mid(b,2) Wend bin2dec= n And 127 End Function Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else pad= left(s& space(n),n) end if :end function Function iif(t,a,b) If t Then iif=a Else iif=b End If :End Function Function getnum(s,r) Dim n,s1,r1 s1=Left(s,7) s=Mid(s,8) r1=r Do If r Then s1=StrReverse(s1) n=bin2dec(s1,asc("#")) If odic.exists(n) Then getnum=odic(n) Exit Function Else If r1<>r Then getnum=0:Exit Function r=Not r End If Loop End Function Function getmarker(s,m) getmarker= (InStr(s,m)= 1) s=Mid(s,Len(m)+1) End Function Function checksum(ByVal s) Dim n,i : n=0 do n=n+(Asc(s)-48)*3 s=Mid(s,2) n=n+(Asc(s)-48)*1 s=Mid(s,2) Loop until Len(s)=0 checksum= ((n mod 10)=0) End function Function upc(ByVal s1) Dim i,n,s,out,rev,j s=Trim(s1) If getmarker(s,m_limit)=False Then upc= "bad start marker ":Exit function rev=False out="" For j= 0 To 1 For i=0 To 5 n=getnum(s,rev) If n=0 Then upc= pad(out,16) & pad ("bad code",-10) & pad("pos "& i+j*6+1,-11): Exit Function out=out & Abs(n)-1 Next If j=0 Then If getmarker(s,m_middle)=False Then upc= "bad middle marker " & out :Exit Function Next If getmarker(s,m_limit)=False Then upc= "bad end marker " :Exit function If rev Then out=strreverse(out) upc= pad(out,16) & pad(iif (checksum(out),"valid","not valid"),-10)& pad(iif(rev,"reversed",""),-11) End Function
#include <iostream> #include <locale> #include <map> #include <vector> std::string trim(const std::string &str) { auto s = str; auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(it1.base(), s.end()); auto it2 = std::find_if(s.begin(), s.end(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(s.begin(), it2); return s; } template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } const std::map<std::string, int> LEFT_DIGITS = { {" ## #", 0}, {" ## #", 1}, {" # ##", 2}, {" #### #", 3}, {" # ##", 4}, {" ## #", 5}, {" # ####", 6}, {" ### ##", 7}, {" ## ###", 8}, {" # ##", 9} }; const std::map<std::string, int> RIGHT_DIGITS = { {"### # ", 0}, {"## ## ", 1}, {"## ## ", 2}, {"# # ", 3}, {"# ### ", 4}, {"# ### ", 5}, {"# # ", 6}, {"# # ", 7}, {"# # ", 8}, {"### # ", 9} }; const std::string END_SENTINEL = "# #"; const std::string MID_SENTINEL = " # # "; void decodeUPC(const std::string &input) { auto decode = [](const std::string &candidate) { using OT = std::vector<int>; OT output; size_t pos = 0; auto part = candidate.substr(pos, END_SENTINEL.length()); if (part == END_SENTINEL) { pos += END_SENTINEL.length(); } else { return std::make_pair(false, OT{}); } for (size_t i = 0; i < 6; i++) { part = candidate.substr(pos, 7); pos += 7; auto e = LEFT_DIGITS.find(part); if (e != LEFT_DIGITS.end()) { output.push_back(e->second); } else { return std::make_pair(false, output); } } part = candidate.substr(pos, MID_SENTINEL.length()); if (part == MID_SENTINEL) { pos += MID_SENTINEL.length(); } else { return std::make_pair(false, OT{}); } for (size_t i = 0; i < 6; i++) { part = candidate.substr(pos, 7); pos += 7; auto e = RIGHT_DIGITS.find(part); if (e != RIGHT_DIGITS.end()) { output.push_back(e->second); } else { return std::make_pair(false, output); } } part = candidate.substr(pos, END_SENTINEL.length()); if (part == END_SENTINEL) { pos += END_SENTINEL.length(); } else { return std::make_pair(false, OT{}); } int sum = 0; for (size_t i = 0; i < output.size(); i++) { if (i % 2 == 0) { sum += 3 * output[i]; } else { sum += output[i]; } } return std::make_pair(sum % 10 == 0, output); }; auto candidate = trim(input); auto out = decode(candidate); if (out.first) { std::cout << out.second << '\n'; } else { std::reverse(candidate.begin(), candidate.end()); out = decode(candidate); if (out.first) { std::cout << out.second << " Upside down\n"; } else if (out.second.size()) { std::cout << "Invalid checksum\n"; } else { std::cout << "Invalid digit(s)\n"; } } } int main() { std::vector<std::string> barcodes = { " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", }; for (auto &barcode : barcodes) { decodeUPC(barcode); } return 0; }
Translate this program into C++ but keep the logic exactly as in VB.
Option Explicit Private Type Adress Row As Integer Column As Integer End Type Private myTable() As String Sub Main() Dim keyw As String, boolQ As Boolean, text As String, test As Long Dim res As String keyw = InputBox("Enter your keyword : ", "KeyWord", "Playfair example") If keyw = "" Then GoTo ErrorHand Debug.Print "Enter your keyword : " & keyw boolQ = MsgBox("Ignore Q when buiding table y/n : ", vbYesNo) = vbYes Debug.Print "Ignore Q when buiding table y/n : " & IIf(boolQ, "Y", "N") Debug.Print "" Debug.Print "Table : " myTable = CreateTable(keyw, boolQ) On Error GoTo ErrorHand test = UBound(myTable) On Error GoTo 0 text = InputBox("Enter your text", "Encode", "hide the gold in the TRRE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res text = InputBox("Enter your text", "Encode", "hide the gold in the TREE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res Exit Sub ErrorHand: Debug.Print "error" End Sub Private Function CreateTable(strKeyword As String, Q As Boolean) As String() Dim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer Dim strT As String, coll As New Collection Dim s As String strKeyword = UCase(Replace(strKeyword, " ", "")) If Q Then If InStr(strKeyword, "J") > 0 Then Debug.Print "Your keyword isn Exit Function End If Else If InStr(strKeyword, "Q") > 0 Then Debug.Print "Your keyword isn Exit Function End If End If strT = IIf(Not Q, "ABCDEFGHIKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPRSTUVWXYZ") t = Split(StrConv(strKeyword, vbUnicode), Chr(0)) For c = LBound(t) To UBound(t) - 1 strT = Replace(strT, t(c), "") On Error Resume Next coll.Add t(c), t(c) On Error GoTo 0 Next strKeyword = vbNullString For c = 1 To coll.Count strKeyword = strKeyword & coll(c) Next t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0)) c = 1: r = 1 For cpt = LBound(t) To UBound(t) - 1 temp(r, c) = t(cpt) s = s & " " & t(cpt) c = c + 1 If c = 6 Then c = 1: r = r + 1: Debug.Print " " & s: s = "" Next CreateTable = temp End Function Private Function Encode(s As String) As String Dim i&, t() As String, cpt& s = UCase(Replace(s, " ", "")) For i = 1 To Len(s) - 1 If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & "X" & Right(s, Len(s) - i) Next For i = 1 To Len(s) Step 2 ReDim Preserve t(cpt) t(cpt) = Mid(s, i, 2) cpt = cpt + 1 Next i If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & "X" Debug.Print "[the pairs : " & Join(t, " ") & "]" For i = LBound(t) To UBound(t) t(i) = SwapPairsEncoding(t(i)) Next Encode = Join(t, " ") End Function Private Function SwapPairsEncoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1) resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1) SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1) resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1) SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function Private Function Decode(s As String) As String Dim t, i&, j&, e& t = Split(s, " ") e = UBound(t) - 1 For i = LBound(t) To UBound(t) t(i) = SwapPairsDecoding(CStr(t(i))) Next For i = LBound(t) To e If Right(t(i), 1) = "X" And Left(t(i), 1) = Left(t(i + 1), 1) Then t(i) = Left(t(i), 1) & Left(t(i + 1), 1) For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If ElseIf Left(t(i + 1), 1) = "X" And Right(t(i), 1) = Right(t(i + 1), 1) Then For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If End If Next Decode = Join(t, " ") End Function Private Function SwapPairsDecoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1) resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1) SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1) resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1) SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function
#include <iostream> #include <string> using namespace std; class playfair { public: void doIt( string k, string t, bool ij, bool e ) { createGrid( k, ij ); getTextReady( t, ij, e ); if( e ) doIt( 1 ); else doIt( -1 ); display(); } private: void doIt( int dir ) { int a, b, c, d; string ntxt; for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ ) { if( getCharPos( *ti++, a, b ) ) if( getCharPos( *ti, c, d ) ) { if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); } else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); } else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); } } } _txt = ntxt; } void display() { cout << "\n\n OUTPUT:\n=========" << endl; string::iterator si = _txt.begin(); int cnt = 0; while( si != _txt.end() ) { cout << *si; si++; cout << *si << " "; si++; if( ++cnt >= 26 ) cout << endl, cnt = 0; } cout << endl << endl; } char getChar( int a, int b ) { return _m[ (b + 5) % 5 ][ (a + 5) % 5 ]; } bool getCharPos( char l, int &a, int &b ) { for( int y = 0; y < 5; y++ ) for( int x = 0; x < 5; x++ ) if( _m[y][x] == l ) { a = x; b = y; return true; } return false; } void getTextReady( string t, bool ij, bool e ) { for( string::iterator si = t.begin(); si != t.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( *si == 'J' && ij ) *si = 'I'; else if( *si == 'Q' && !ij ) continue; _txt += *si; } if( e ) { string ntxt = ""; size_t len = _txt.length(); for( size_t x = 0; x < len; x += 2 ) { ntxt += _txt[x]; if( x + 1 < len ) { if( _txt[x] == _txt[x + 1] ) ntxt += 'X'; ntxt += _txt[x + 1]; } } _txt = ntxt; } if( _txt.length() & 1 ) _txt += 'X'; } void createGrid( string k, bool ij ) { if( k.length() < 1 ) k = "KEYWORD"; k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = ""; for( string::iterator si = k.begin(); si != k.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue; if( nk.find( *si ) == -1 ) nk += *si; } copy( nk.begin(), nk.end(), &_m[0][0] ); } string _txt; char _m[5][5]; }; int main( int argc, char* argv[] ) { string key, i, txt; bool ij, e; cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' ); cout << "Enter a en/decryption key: "; getline( cin, key ); cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' ); cout << "Enter the text: "; getline( cin, txt ); playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" ); }
Maintain the same structure and functionality when rewriting this code in C++.
Option Explicit Private Type Adress Row As Integer Column As Integer End Type Private myTable() As String Sub Main() Dim keyw As String, boolQ As Boolean, text As String, test As Long Dim res As String keyw = InputBox("Enter your keyword : ", "KeyWord", "Playfair example") If keyw = "" Then GoTo ErrorHand Debug.Print "Enter your keyword : " & keyw boolQ = MsgBox("Ignore Q when buiding table y/n : ", vbYesNo) = vbYes Debug.Print "Ignore Q when buiding table y/n : " & IIf(boolQ, "Y", "N") Debug.Print "" Debug.Print "Table : " myTable = CreateTable(keyw, boolQ) On Error GoTo ErrorHand test = UBound(myTable) On Error GoTo 0 text = InputBox("Enter your text", "Encode", "hide the gold in the TRRE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res text = InputBox("Enter your text", "Encode", "hide the gold in the TREE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res Exit Sub ErrorHand: Debug.Print "error" End Sub Private Function CreateTable(strKeyword As String, Q As Boolean) As String() Dim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer Dim strT As String, coll As New Collection Dim s As String strKeyword = UCase(Replace(strKeyword, " ", "")) If Q Then If InStr(strKeyword, "J") > 0 Then Debug.Print "Your keyword isn Exit Function End If Else If InStr(strKeyword, "Q") > 0 Then Debug.Print "Your keyword isn Exit Function End If End If strT = IIf(Not Q, "ABCDEFGHIKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPRSTUVWXYZ") t = Split(StrConv(strKeyword, vbUnicode), Chr(0)) For c = LBound(t) To UBound(t) - 1 strT = Replace(strT, t(c), "") On Error Resume Next coll.Add t(c), t(c) On Error GoTo 0 Next strKeyword = vbNullString For c = 1 To coll.Count strKeyword = strKeyword & coll(c) Next t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0)) c = 1: r = 1 For cpt = LBound(t) To UBound(t) - 1 temp(r, c) = t(cpt) s = s & " " & t(cpt) c = c + 1 If c = 6 Then c = 1: r = r + 1: Debug.Print " " & s: s = "" Next CreateTable = temp End Function Private Function Encode(s As String) As String Dim i&, t() As String, cpt& s = UCase(Replace(s, " ", "")) For i = 1 To Len(s) - 1 If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & "X" & Right(s, Len(s) - i) Next For i = 1 To Len(s) Step 2 ReDim Preserve t(cpt) t(cpt) = Mid(s, i, 2) cpt = cpt + 1 Next i If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & "X" Debug.Print "[the pairs : " & Join(t, " ") & "]" For i = LBound(t) To UBound(t) t(i) = SwapPairsEncoding(t(i)) Next Encode = Join(t, " ") End Function Private Function SwapPairsEncoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1) resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1) SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1) resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1) SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function Private Function Decode(s As String) As String Dim t, i&, j&, e& t = Split(s, " ") e = UBound(t) - 1 For i = LBound(t) To UBound(t) t(i) = SwapPairsDecoding(CStr(t(i))) Next For i = LBound(t) To e If Right(t(i), 1) = "X" And Left(t(i), 1) = Left(t(i + 1), 1) Then t(i) = Left(t(i), 1) & Left(t(i + 1), 1) For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If ElseIf Left(t(i + 1), 1) = "X" And Right(t(i), 1) = Right(t(i + 1), 1) Then For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If End If Next Decode = Join(t, " ") End Function Private Function SwapPairsDecoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1) resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1) SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1) resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1) SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function
#include <iostream> #include <string> using namespace std; class playfair { public: void doIt( string k, string t, bool ij, bool e ) { createGrid( k, ij ); getTextReady( t, ij, e ); if( e ) doIt( 1 ); else doIt( -1 ); display(); } private: void doIt( int dir ) { int a, b, c, d; string ntxt; for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ ) { if( getCharPos( *ti++, a, b ) ) if( getCharPos( *ti, c, d ) ) { if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); } else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); } else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); } } } _txt = ntxt; } void display() { cout << "\n\n OUTPUT:\n=========" << endl; string::iterator si = _txt.begin(); int cnt = 0; while( si != _txt.end() ) { cout << *si; si++; cout << *si << " "; si++; if( ++cnt >= 26 ) cout << endl, cnt = 0; } cout << endl << endl; } char getChar( int a, int b ) { return _m[ (b + 5) % 5 ][ (a + 5) % 5 ]; } bool getCharPos( char l, int &a, int &b ) { for( int y = 0; y < 5; y++ ) for( int x = 0; x < 5; x++ ) if( _m[y][x] == l ) { a = x; b = y; return true; } return false; } void getTextReady( string t, bool ij, bool e ) { for( string::iterator si = t.begin(); si != t.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( *si == 'J' && ij ) *si = 'I'; else if( *si == 'Q' && !ij ) continue; _txt += *si; } if( e ) { string ntxt = ""; size_t len = _txt.length(); for( size_t x = 0; x < len; x += 2 ) { ntxt += _txt[x]; if( x + 1 < len ) { if( _txt[x] == _txt[x + 1] ) ntxt += 'X'; ntxt += _txt[x + 1]; } } _txt = ntxt; } if( _txt.length() & 1 ) _txt += 'X'; } void createGrid( string k, bool ij ) { if( k.length() < 1 ) k = "KEYWORD"; k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = ""; for( string::iterator si = k.begin(); si != k.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue; if( nk.find( *si ) == -1 ) nk += *si; } copy( nk.begin(), nk.end(), &_m[0][0] ); } string _txt; char _m[5][5]; }; int main( int argc, char* argv[] ) { string key, i, txt; bool ij, e; cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' ); cout << "Enter a en/decryption key: "; getline( cin, key ); cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' ); cout << "Enter the text: "; getline( cin, txt ); playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" ); }
Change the programming language of this snippet from VB to C++ without modifying what it does.
Option Explicit Private Type Adress Row As Integer Column As Integer End Type Private myTable() As String Sub Main() Dim keyw As String, boolQ As Boolean, text As String, test As Long Dim res As String keyw = InputBox("Enter your keyword : ", "KeyWord", "Playfair example") If keyw = "" Then GoTo ErrorHand Debug.Print "Enter your keyword : " & keyw boolQ = MsgBox("Ignore Q when buiding table y/n : ", vbYesNo) = vbYes Debug.Print "Ignore Q when buiding table y/n : " & IIf(boolQ, "Y", "N") Debug.Print "" Debug.Print "Table : " myTable = CreateTable(keyw, boolQ) On Error GoTo ErrorHand test = UBound(myTable) On Error GoTo 0 text = InputBox("Enter your text", "Encode", "hide the gold in the TRRE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res text = InputBox("Enter your text", "Encode", "hide the gold in the TREE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res Exit Sub ErrorHand: Debug.Print "error" End Sub Private Function CreateTable(strKeyword As String, Q As Boolean) As String() Dim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer Dim strT As String, coll As New Collection Dim s As String strKeyword = UCase(Replace(strKeyword, " ", "")) If Q Then If InStr(strKeyword, "J") > 0 Then Debug.Print "Your keyword isn Exit Function End If Else If InStr(strKeyword, "Q") > 0 Then Debug.Print "Your keyword isn Exit Function End If End If strT = IIf(Not Q, "ABCDEFGHIKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPRSTUVWXYZ") t = Split(StrConv(strKeyword, vbUnicode), Chr(0)) For c = LBound(t) To UBound(t) - 1 strT = Replace(strT, t(c), "") On Error Resume Next coll.Add t(c), t(c) On Error GoTo 0 Next strKeyword = vbNullString For c = 1 To coll.Count strKeyword = strKeyword & coll(c) Next t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0)) c = 1: r = 1 For cpt = LBound(t) To UBound(t) - 1 temp(r, c) = t(cpt) s = s & " " & t(cpt) c = c + 1 If c = 6 Then c = 1: r = r + 1: Debug.Print " " & s: s = "" Next CreateTable = temp End Function Private Function Encode(s As String) As String Dim i&, t() As String, cpt& s = UCase(Replace(s, " ", "")) For i = 1 To Len(s) - 1 If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & "X" & Right(s, Len(s) - i) Next For i = 1 To Len(s) Step 2 ReDim Preserve t(cpt) t(cpt) = Mid(s, i, 2) cpt = cpt + 1 Next i If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & "X" Debug.Print "[the pairs : " & Join(t, " ") & "]" For i = LBound(t) To UBound(t) t(i) = SwapPairsEncoding(t(i)) Next Encode = Join(t, " ") End Function Private Function SwapPairsEncoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1) resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1) SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1) resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1) SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function Private Function Decode(s As String) As String Dim t, i&, j&, e& t = Split(s, " ") e = UBound(t) - 1 For i = LBound(t) To UBound(t) t(i) = SwapPairsDecoding(CStr(t(i))) Next For i = LBound(t) To e If Right(t(i), 1) = "X" And Left(t(i), 1) = Left(t(i + 1), 1) Then t(i) = Left(t(i), 1) & Left(t(i + 1), 1) For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If ElseIf Left(t(i + 1), 1) = "X" And Right(t(i), 1) = Right(t(i + 1), 1) Then For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If End If Next Decode = Join(t, " ") End Function Private Function SwapPairsDecoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1) resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1) SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1) resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1) SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function
#include <iostream> #include <string> using namespace std; class playfair { public: void doIt( string k, string t, bool ij, bool e ) { createGrid( k, ij ); getTextReady( t, ij, e ); if( e ) doIt( 1 ); else doIt( -1 ); display(); } private: void doIt( int dir ) { int a, b, c, d; string ntxt; for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ ) { if( getCharPos( *ti++, a, b ) ) if( getCharPos( *ti, c, d ) ) { if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); } else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); } else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); } } } _txt = ntxt; } void display() { cout << "\n\n OUTPUT:\n=========" << endl; string::iterator si = _txt.begin(); int cnt = 0; while( si != _txt.end() ) { cout << *si; si++; cout << *si << " "; si++; if( ++cnt >= 26 ) cout << endl, cnt = 0; } cout << endl << endl; } char getChar( int a, int b ) { return _m[ (b + 5) % 5 ][ (a + 5) % 5 ]; } bool getCharPos( char l, int &a, int &b ) { for( int y = 0; y < 5; y++ ) for( int x = 0; x < 5; x++ ) if( _m[y][x] == l ) { a = x; b = y; return true; } return false; } void getTextReady( string t, bool ij, bool e ) { for( string::iterator si = t.begin(); si != t.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( *si == 'J' && ij ) *si = 'I'; else if( *si == 'Q' && !ij ) continue; _txt += *si; } if( e ) { string ntxt = ""; size_t len = _txt.length(); for( size_t x = 0; x < len; x += 2 ) { ntxt += _txt[x]; if( x + 1 < len ) { if( _txt[x] == _txt[x + 1] ) ntxt += 'X'; ntxt += _txt[x + 1]; } } _txt = ntxt; } if( _txt.length() & 1 ) _txt += 'X'; } void createGrid( string k, bool ij ) { if( k.length() < 1 ) k = "KEYWORD"; k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = ""; for( string::iterator si = k.begin(); si != k.end(); si++ ) { *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue; if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue; if( nk.find( *si ) == -1 ) nk += *si; } copy( nk.begin(), nk.end(), &_m[0][0] ); } string _txt; char _m[5][5]; }; int main( int argc, char* argv[] ) { string key, i, txt; bool ij, e; cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' ); cout << "Enter a en/decryption key: "; getline( cin, key ); cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' ); cout << "Enter the text: "; getline( cin, txt ); playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" ); }
Generate a C++ translation of this VB snippet without changing its computational steps.
Option Explicit Private Type MyPoint X As Single Y As Single End Type Private Type MyPair p1 As MyPoint p2 As MyPoint End Type Sub Main() Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long Dim T# Randomize Timer Nb = 10 Do ReDim points(1 To Nb) For i = 1 To Nb points(i).X = Rnd * Nb points(i).Y = Rnd * Nb Next d = 1000000000000# T = Timer BF = BruteForce(points, d) Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec." Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y Debug.Print "dist : " & d Debug.Print "--------------------------------------------------" Nb = Nb * 10 Loop While Nb <= 10000 End Sub Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair Dim i As Long, j As Long, d As Single, ClosestPair As MyPair For i = 1 To UBound(p) - 1 For j = i + 1 To UBound(p) d = Dist(p(i), p(j)) If d < mindist Then mindist = d ClosestPair.p1 = p(i) ClosestPair.p2 = p(j) End If Next Next BruteForce = ClosestPair End Function Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2) End Function
#include <iostream> #include <vector> #include <utility> #include <cmath> #include <random> #include <chrono> #include <algorithm> #include <iterator> typedef std::pair<double, double> point_t; typedef std::pair<point_t, point_t> points_t; double distance_between(const point_t& a, const point_t& b) { return std::sqrt(std::pow(b.first - a.first, 2) + std::pow(b.second - a.second, 2)); } std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) { if (points.size() < 2) { return { -1, { { 0, 0 }, { 0, 0 } } }; } auto minDistance = std::abs(distance_between(points.at(0), points.at(1))); points_t minPoints = { points.at(0), points.at(1) }; for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) { for (auto j = i + 1; j < std::end(points); ++j) { auto newDistance = std::abs(distance_between(*i, *j)); if (newDistance < minDistance) { minDistance = newDistance; minPoints.first = *i; minPoints.second = *j; } } } return { minDistance, minPoints }; } std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP, const std::vector<point_t>& yP) { if (xP.size() <= 3) { return find_closest_brute(xP); } auto N = xP.size(); auto xL = std::vector<point_t>(); auto xR = std::vector<point_t>(); std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL)); std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR)); auto xM = xP.at((N-1) / 2).first; auto yL = std::vector<point_t>(); auto yR = std::vector<point_t>(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) { return p.first <= xM; }); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) { return p.first > xM; }); auto p1 = find_closest_optimized(xL, yL); auto p2 = find_closest_optimized(xR, yR); auto minPair = (p1.first <= p2.first) ? p1 : p2; auto yS = std::vector<point_t>(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) { return std::abs(xM - p.first) < minPair.first; }); auto result = minPair; for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) { for (auto k = i + 1; k != std::end(yS) && ((k->second - i->second) < minPair.first); ++k) { auto newDistance = std::abs(distance_between(*k, *i)); if (newDistance < result.first) { result = { newDistance, { *k, *i } }; } } } return result; } void print_point(const point_t& point) { std::cout << "(" << point.first << ", " << point.second << ")"; } int main(int argc, char * argv[]) { std::default_random_engine re(std::chrono::system_clock::to_time_t( std::chrono::system_clock::now())); std::uniform_real_distribution<double> urd(-500.0, 500.0); std::vector<point_t> points(100); std::generate(std::begin(points), std::end(points), [&urd, &re]() { return point_t { 1000 + urd(re), 1000 + urd(re) }; }); auto answer = find_closest_brute(points); std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { return a.first < b.first; }); auto xP = points; std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { return a.second < b.second; }); auto yP = points; std::cout << "Min distance (brute): " << answer.first << " "; print_point(answer.second.first); std::cout << ", "; print_point(answer.second.second); answer = find_closest_optimized(xP, yP); std::cout << "\nMin distance (optimized): " << answer.first << " "; print_point(answer.second.first); std::cout << ", "; print_point(answer.second.second); return 0; }
Translate this program into C++ but keep the logic exactly as in VB.
Dim TheAddress as long Dim SecVar as byte Dim MyVar as byte MyVar = 10 TheAddress = varptr(MyVar) MEMSET(TheAddress, 102, SizeOf(byte)) showmessage "MyVar = " + str$(MyVar) MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte)) showmessage "SecVar = " + str$(SecVar)
int i; void* address_of_i = &i;
Keep all operations the same but rewrite the snippet in C++.
Class Animal End Class Class Dog Inherits Animal End Class Class Lab Inherits Dog End Class Class Collie Inherits Dog End Class Class Cat Inherits Animal End Class
class Animal { }; class Dog: public Animal { }; class Lab: public Dog { }; class Collie: public Dog { }; class Cat: public Animal { };
Rewrite this program in C++ while keeping its functionality equivalent to the VB version.
Option Explicit Sub Test() Dim h As Object Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 Debug.Print h.Item("A") h.Item("C") = 4 h.Key("C") = "D" Debug.Print h.exists("C") h.Remove "B" Debug.Print h.Count h.RemoveAll Debug.Print h.Count End Sub
#include <map>
Write the same code in C++ as shown below in VB.
Option Explicit Sub Test() Dim h As Object Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 Debug.Print h.Item("A") h.Item("C") = 4 h.Key("C") = "D" Debug.Print h.exists("C") h.Remove "B" Debug.Print h.Count h.RemoveAll Debug.Print h.Count End Sub
#include <map>
Generate an equivalent C++ version of this VB code.
Option explicit Class ImgClass Private ImgL,ImgH,ImgDepth,bkclr,loc,tt private xmini,xmaxi,ymini,ymaxi,dirx,diry public ImgArray() private filename private Palette,szpal public property get xmin():xmin=xmini:end property public property get ymin():ymin=ymini:end property public property get xmax():xmax=xmaxi:end property public property get ymax():ymax=ymaxi:end property public property let depth(x) if x<>8 and x<>32 then err.raise 9 Imgdepth=x end property public sub set0 (x0,y0) if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 xmini=-x0 ymini=-y0 xmaxi=xmini+imgl-1 ymaxi=ymini+imgh-1 end sub Public Default Function Init(name,w,h,orient,dep,bkg,mipal) dim i,j ImgL=w ImgH=h tt=timer loc=getlocale set0 0,0 redim imgArray(ImgL-1,ImgH-1) bkclr=bkg if bkg<>0 then for i=0 to ImgL-1 for j=0 to ImgH-1 imgarray(i,j)=bkg next next end if Select Case orient Case 1: dirx=1 : diry=1 Case 2: dirx=-1 : diry=1 Case 3: dirx=-1 : diry=-1 Case 4: dirx=1 : diry=-1 End select filename=name ImgDepth =dep if imgdepth=8 then loadpal(mipal) end if set init=me end function private sub loadpal(mipale) if isarray(mipale) Then palette=mipale szpal=UBound(mipale)+1 Else szpal=256 , not relevant End if End Sub Private Sub Class_Terminate if err<>0 then wscript.echo "Error " & err.number wscript.echo "copying image to bmp file" savebmp wscript.echo "opening " & filename & " with your default bmp viewer" CreateObject("Shell.Application").ShellExecute filename wscript.echo timer-tt & " iseconds" End Sub function long2wstr( x) dim k1,k2,x1 k1= (x and &hffff&) k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0)) long2wstr=chrw(k1) & chrw(k2) end function function int2wstr(x) int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0))) End Function Public Sub SaveBMP Dim s,ostream, x,y,loc const hdrs=54 dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4) dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0 with CreateObject("ADODB.Stream") .Charset = "UTF-16LE" .Type = 2 .open .writetext ChrW(&h4d42) .writetext long2wstr(hdrs+palsize+bms) .writetext long2wstr(0) .writetext long2wstr (hdrs+palsize) .writetext long2wstr(40) .writetext long2wstr(Imgl) .writetext long2wstr(imgh) .writetext int2wstr(1) .writetext int2wstr(imgdepth) .writetext long2wstr(&H0) .writetext long2wstr(bms) .writetext long2wstr(&Hc4e) .writetext long2wstr(&hc43) .writetext long2wstr(szpal) .writetext long2wstr(&H0) Dim x1,x2,y1,y2 If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1 If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 Select Case imgdepth Case 32 For y=y1 To y2 step diry For x=x1 To x2 Step dirx .writetext long2wstr(Imgarray(x,y)) Next Next Case 8 For x=0 to szpal-1 .writetext long2wstr(palette(x)) Next dim pad:pad=ImgL mod 4 For y=y1 to y2 step diry For x=x1 To x2 step dirx*2 .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255)) Next if pad and 1 then .writetext chrw(ImgArray(x2,y)) if pad >1 then .writetext chrw(0) Next Case Else WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits" End Select Dim outf:Set outf= CreateObject("ADODB.Stream") outf.Type = 1 outf.Open .position=2 .CopyTo outf .close outf.savetofile filename,2 outf.close end with End Sub end class function hsv2rgb( Hue, Sat, Value) dim Angle, Radius,Ur,Vr,Wr,Rdim dim r,g,b, rgb Angle = (Hue-150) *0.01745329251994329576923690768489 Ur = Value * 2.55 Radius = Ur * tan(Sat *0.01183199) Vr = Radius * cos(Angle) *0.70710678 Wr = Radius * sin(Angle) *0.40824829 r = (Ur - Vr - Wr) g = (Ur + Vr - Wr) b = (Ur + Wr + Wr) if r >255 then Rdim = (Ur - 255) / (Vr + Wr) r = 255 g = Ur + (Vr - Wr) * Rdim b = Ur + 2 * Wr * Rdim elseif r < 0 then Rdim = Ur / (Vr + Wr) r = 0 g = Ur + (Vr - Wr) * Rdim b = Ur + 2 * Wr * Rdim end if if g >255 then Rdim = (255 - Ur) / (Vr - Wr) r = Ur - (Vr + Wr) * Rdim g = 255 b = Ur + 2 * Wr * Rdim elseif g<0 then Rdim = -Ur / (Vr - Wr) r = Ur - (Vr + Wr) * Rdim g = 0 b = Ur + 2 * Wr * Rdim end if if b>255 then Rdim = (255 - Ur) / (Wr + Wr) r = Ur - (Vr + Wr) * Rdim g = Ur + (Vr - Wr) * Rdim b = 255 elseif b<0 then Rdim = -Ur / (Wr + Wr) r = Ur - (Vr + Wr) * Rdim g = Ur + (Vr - Wr) * Rdim b = 0 end If hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff) end function function ang(col,row) if col =0 then if row<0 then ang=90 else ang=270 end if else if col>0 then ang=atn(-row/col)*57.2957795130 else ang=(atn(row/-col)*57.2957795130)+180 end if end if ang=(ang+360) mod 360 end function Dim X,row,col,fn,tt,hr,sat,row2 const h=160 const w=160 const rad=159 const r2=25500 tt=timer fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\testwchr.bmp" Set X = (New ImgClass)(fn,w*2,h*2,1,32,0,0) x.set0 w,h for row=x.xmin+1 to x.xmax row2=row*row hr=int(Sqr(r2-row2)) For col=hr To 159 Dim a:a=((col\16 +row\16) And 1)* &hffffff x.imgArray(col+160,row+160)=a x.imgArray(-col+160,row+160)=a next for col=-hr to hr sat=100-sqr(row2+col*col)/rad *50 x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat) next next Set X = Nothing
#include "colorwheelwidget.h" #include <QPainter> #include <QPaintEvent> #include <cmath> namespace { QColor hsvToRgb(int h, double s, double v) { double hp = h/60.0; double c = s * v; double x = c * (1 - std::abs(std::fmod(hp, 2) - 1)); double m = v - c; double r = 0, g = 0, b = 0; if (hp <= 1) { r = c; g = x; } else if (hp <= 2) { r = x; g = c; } else if (hp <= 3) { g = c; b = x; } else if (hp <= 4) { g = x; b = c; } else if (hp <= 5) { r = x; b = c; } else { r = c; b = x; } r += m; g += m; b += m; return QColor(r * 255, g * 255, b * 255); } } ColorWheelWidget::ColorWheelWidget(QWidget *parent) : QWidget(parent) { setWindowTitle(tr("Color Wheel")); resize(400, 400); } void ColorWheelWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); const QColor backgroundColor(0, 0, 0); const QColor white(255, 255, 255); painter.fillRect(event->rect(), backgroundColor); const int margin = 10; const double diameter = std::min(width(), height()) - 2*margin; QPointF center(width()/2.0, height()/2.0); QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0, diameter, diameter); for (int angle = 0; angle < 360; ++angle) { QColor color(hsvToRgb(angle, 1.0, 1.0)); QRadialGradient gradient(center, diameter/2.0); gradient.setColorAt(0, white); gradient.setColorAt(1, color); QBrush brush(gradient); QPen pen(brush, 1.0); painter.setPen(pen); painter.setBrush(brush); painter.drawPie(rect, angle * 16, 16); } }
Write a version of this VB function in C++ with identical behavior.
Option explicit Class ImgClass Private ImgL,ImgH,ImgDepth,bkclr,loc,tt private xmini,xmaxi,ymini,ymaxi,dirx,diry public ImgArray() private filename private Palette,szpal public property get xmin():xmin=xmini:end property public property get ymin():ymin=ymini:end property public property get xmax():xmax=xmaxi:end property public property get ymax():ymax=ymaxi:end property public property let depth(x) if x<>8 and x<>32 then err.raise 9 Imgdepth=x end property public sub set0 (x0,y0) if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 xmini=-x0 ymini=-y0 xmaxi=xmini+imgl-1 ymaxi=ymini+imgh-1 end sub Public Default Function Init(name,w,h,orient,dep,bkg,mipal) dim i,j ImgL=w ImgH=h tt=timer loc=getlocale set0 0,0 redim imgArray(ImgL-1,ImgH-1) bkclr=bkg if bkg<>0 then for i=0 to ImgL-1 for j=0 to ImgH-1 imgarray(i,j)=bkg next next end if Select Case orient Case 1: dirx=1 : diry=1 Case 2: dirx=-1 : diry=1 Case 3: dirx=-1 : diry=-1 Case 4: dirx=1 : diry=-1 End select filename=name ImgDepth =dep if imgdepth=8 then loadpal(mipal) end if set init=me end function private sub loadpal(mipale) if isarray(mipale) Then palette=mipale szpal=UBound(mipale)+1 Else szpal=256 , not relevant End if End Sub Private Sub Class_Terminate if err<>0 then wscript.echo "Error " & err.number wscript.echo "copying image to bmp file" savebmp wscript.echo "opening " & filename & " with your default bmp viewer" CreateObject("Shell.Application").ShellExecute filename wscript.echo timer-tt & " iseconds" End Sub function long2wstr( x) dim k1,k2,x1 k1= (x and &hffff&) k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0)) long2wstr=chrw(k1) & chrw(k2) end function function int2wstr(x) int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0))) End Function Public Sub SaveBMP Dim s,ostream, x,y,loc const hdrs=54 dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4) dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0 with CreateObject("ADODB.Stream") .Charset = "UTF-16LE" .Type = 2 .open .writetext ChrW(&h4d42) .writetext long2wstr(hdrs+palsize+bms) .writetext long2wstr(0) .writetext long2wstr (hdrs+palsize) .writetext long2wstr(40) .writetext long2wstr(Imgl) .writetext long2wstr(imgh) .writetext int2wstr(1) .writetext int2wstr(imgdepth) .writetext long2wstr(&H0) .writetext long2wstr(bms) .writetext long2wstr(&Hc4e) .writetext long2wstr(&hc43) .writetext long2wstr(szpal) .writetext long2wstr(&H0) Dim x1,x2,y1,y2 If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1 If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 Select Case imgdepth Case 32 For y=y1 To y2 step diry For x=x1 To x2 Step dirx .writetext long2wstr(Imgarray(x,y)) Next Next Case 8 For x=0 to szpal-1 .writetext long2wstr(palette(x)) Next dim pad:pad=ImgL mod 4 For y=y1 to y2 step diry For x=x1 To x2 step dirx*2 .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255)) Next if pad and 1 then .writetext chrw(ImgArray(x2,y)) if pad >1 then .writetext chrw(0) Next Case Else WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits" End Select Dim outf:Set outf= CreateObject("ADODB.Stream") outf.Type = 1 outf.Open .position=2 .CopyTo outf .close outf.savetofile filename,2 outf.close end with End Sub end class function hsv2rgb( Hue, Sat, Value) dim Angle, Radius,Ur,Vr,Wr,Rdim dim r,g,b, rgb Angle = (Hue-150) *0.01745329251994329576923690768489 Ur = Value * 2.55 Radius = Ur * tan(Sat *0.01183199) Vr = Radius * cos(Angle) *0.70710678 Wr = Radius * sin(Angle) *0.40824829 r = (Ur - Vr - Wr) g = (Ur + Vr - Wr) b = (Ur + Wr + Wr) if r >255 then Rdim = (Ur - 255) / (Vr + Wr) r = 255 g = Ur + (Vr - Wr) * Rdim b = Ur + 2 * Wr * Rdim elseif r < 0 then Rdim = Ur / (Vr + Wr) r = 0 g = Ur + (Vr - Wr) * Rdim b = Ur + 2 * Wr * Rdim end if if g >255 then Rdim = (255 - Ur) / (Vr - Wr) r = Ur - (Vr + Wr) * Rdim g = 255 b = Ur + 2 * Wr * Rdim elseif g<0 then Rdim = -Ur / (Vr - Wr) r = Ur - (Vr + Wr) * Rdim g = 0 b = Ur + 2 * Wr * Rdim end if if b>255 then Rdim = (255 - Ur) / (Wr + Wr) r = Ur - (Vr + Wr) * Rdim g = Ur + (Vr - Wr) * Rdim b = 255 elseif b<0 then Rdim = -Ur / (Wr + Wr) r = Ur - (Vr + Wr) * Rdim g = Ur + (Vr - Wr) * Rdim b = 0 end If hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff) end function function ang(col,row) if col =0 then if row<0 then ang=90 else ang=270 end if else if col>0 then ang=atn(-row/col)*57.2957795130 else ang=(atn(row/-col)*57.2957795130)+180 end if end if ang=(ang+360) mod 360 end function Dim X,row,col,fn,tt,hr,sat,row2 const h=160 const w=160 const rad=159 const r2=25500 tt=timer fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\testwchr.bmp" Set X = (New ImgClass)(fn,w*2,h*2,1,32,0,0) x.set0 w,h for row=x.xmin+1 to x.xmax row2=row*row hr=int(Sqr(r2-row2)) For col=hr To 159 Dim a:a=((col\16 +row\16) And 1)* &hffffff x.imgArray(col+160,row+160)=a x.imgArray(-col+160,row+160)=a next for col=-hr to hr sat=100-sqr(row2+col*col)/rad *50 x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat) next next Set X = Nothing
#include "colorwheelwidget.h" #include <QPainter> #include <QPaintEvent> #include <cmath> namespace { QColor hsvToRgb(int h, double s, double v) { double hp = h/60.0; double c = s * v; double x = c * (1 - std::abs(std::fmod(hp, 2) - 1)); double m = v - c; double r = 0, g = 0, b = 0; if (hp <= 1) { r = c; g = x; } else if (hp <= 2) { r = x; g = c; } else if (hp <= 3) { g = c; b = x; } else if (hp <= 4) { g = x; b = c; } else if (hp <= 5) { r = x; b = c; } else { r = c; b = x; } r += m; g += m; b += m; return QColor(r * 255, g * 255, b * 255); } } ColorWheelWidget::ColorWheelWidget(QWidget *parent) : QWidget(parent) { setWindowTitle(tr("Color Wheel")); resize(400, 400); } void ColorWheelWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); const QColor backgroundColor(0, 0, 0); const QColor white(255, 255, 255); painter.fillRect(event->rect(), backgroundColor); const int margin = 10; const double diameter = std::min(width(), height()) - 2*margin; QPointF center(width()/2.0, height()/2.0); QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0, diameter, diameter); for (int angle = 0; angle < 360; ++angle) { QColor color(hsvToRgb(angle, 1.0, 1.0)); QRadialGradient gradient(center, diameter/2.0); gradient.setColorAt(0, white); gradient.setColorAt(1, color); QBrush brush(gradient); QPen pen(brush, 1.0); painter.setPen(pen); painter.setBrush(brush); painter.drawPie(rect, angle * 16, 16); } }
Generate a C++ translation of this VB snippet without changing its computational steps.
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) dim b(25) dim c(128) with new regexp .pattern="([^aeiou])" .global=true for each i in a if len(trim(i))>10 then set matches= .execute(i) rep=false for each m in matches x=asc(m) c(x)=c(x)+1 if c(x)>1 then rep=true :exit for next erase c if not rep then x1=matches.count b(x1)=b(x1)&" "&i end if end if next end with for i=25 to 0 step -1 if b(i)<>"" then wscript.echo i & " "& b(i) & vbcrlf next
#include <bitset> #include <cctype> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> size_t consonants(const std::string& word) { std::bitset<26> bits; size_t bit = 0; for (char ch : word) { ch = std::tolower(static_cast<unsigned char>(ch)); if (ch < 'a' || ch > 'z') continue; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: bit = ch - 'a'; if (bits.test(bit)) return 0; bits.set(bit); break; } } return bits.count(); } int main(int argc, char** argv) { 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 word; std::map<size_t, std::vector<std::string>, std::greater<int>> map; while (getline(in, word)) { if (word.size() <= 10) continue; size_t count = consonants(word); if (count != 0) map[count].push_back(word); } const int columns = 4; for (const auto& p : map) { std::cout << p.first << " consonants (" << p.second.size() << "):\n"; int n = 0; for (const auto& word : p.second) { std::cout << std::left << std::setw(18) << word; ++n; if (n % columns == 0) std::cout << '\n'; } if (n % columns != 0) std::cout << '\n'; std::cout << '\n'; } return EXIT_SUCCESS; }
Port the provided VB code into C++ while preserving the original functionality.
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) dim b(25) dim c(128) with new regexp .pattern="([^aeiou])" .global=true for each i in a if len(trim(i))>10 then set matches= .execute(i) rep=false for each m in matches x=asc(m) c(x)=c(x)+1 if c(x)>1 then rep=true :exit for next erase c if not rep then x1=matches.count b(x1)=b(x1)&" "&i end if end if next end with for i=25 to 0 step -1 if b(i)<>"" then wscript.echo i & " "& b(i) & vbcrlf next
#include <bitset> #include <cctype> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> size_t consonants(const std::string& word) { std::bitset<26> bits; size_t bit = 0; for (char ch : word) { ch = std::tolower(static_cast<unsigned char>(ch)); if (ch < 'a' || ch > 'z') continue; switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: bit = ch - 'a'; if (bits.test(bit)) return 0; bits.set(bit); break; } } return bits.count(); } int main(int argc, char** argv) { 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 word; std::map<size_t, std::vector<std::string>, std::greater<int>> map; while (getline(in, word)) { if (word.size() <= 10) continue; size_t count = consonants(word); if (count != 0) map[count].push_back(word); } const int columns = 4; for (const auto& p : map) { std::cout << p.first << " consonants (" << p.second.size() << "):\n"; int n = 0; for (const auto& word : p.second) { std::cout << std::left << std::setw(18) << word; ++n; if (n % columns == 0) std::cout << '\n'; } if (n % columns != 0) std::cout << '\n'; std::cout << '\n'; } return EXIT_SUCCESS; }
Write the same algorithm in C++ as shown in this VB implementation.
Option Explicit Public vTime As Single Public PlaysCount As Long Sub Main_MineSweeper() Dim Userf As New cMinesweeper Userf.Show 0, True End Sub
#include <iostream> #include <string> #include <windows.h> using namespace std; typedef unsigned char byte; enum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR }; class fieldData { public: fieldData() : value( CLOSED ), open( false ) {} byte value; bool open, mine; }; class game { public: ~game() { if( field ) delete [] field; } game( int x, int y ) { go = false; wid = x; hei = y; field = new fieldData[x * y]; memset( field, 0, x * y * sizeof( fieldData ) ); oMines = ( ( 22 - rand() % 11 ) * x * y ) / 100; mMines = 0; int mx, my, m = 0; for( ; m < oMines; m++ ) { do { mx = rand() % wid; my = rand() % hei; } while( field[mx + wid * my].mine ); field[mx + wid * my].mine = true; } graphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*'; graphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X'; } void gameLoop() { string c, r, a; int col, row; while( !go ) { drawBoard(); cout << "Enter column, row and an action( c r a ):\nActions: o => open, f => flag, ? => unknown\n"; cin >> c >> r >> a; if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32; col = c[0] - 65; row = r[0] - 49; makeMove( col, row, a ); } } private: void makeMove( int x, int y, string a ) { fieldData* fd = &field[wid * y + x]; if( fd->open && fd->value < CLOSED ) { cout << "This cell is already open!"; Sleep( 3000 ); return; } if( a[0] == 'O' ) openCell( x, y ); else if( a[0] == 'F' ) { fd->open = true; fd->value = FLAG; mMines++; checkWin(); } else { fd->open = true; fd->value = UNKNOWN; } } bool openCell( int x, int y ) { if( !isInside( x, y ) ) return false; if( field[x + y * wid].mine ) boom(); else { if( field[x + y * wid].value == FLAG ) { field[x + y * wid].value = CLOSED; field[x + y * wid].open = false; mMines--; } recOpen( x, y ); checkWin(); } return true; } void drawBoard() { system( "cls" ); cout << "Marked mines: " << mMines << " from " << oMines << "\n\n"; for( int x = 0; x < wid; x++ ) cout << " " << ( char )( 65 + x ) << " "; cout << "\n"; int yy; for( int y = 0; y < hei; y++ ) { yy = y * wid; for( int x = 0; x < wid; x++ ) cout << "+---"; cout << "+\n"; fieldData* fd; for( int x = 0; x < wid; x++ ) { fd = &field[x + yy]; cout<< "| "; if( !fd->open ) cout << ( char )graphs[1] << " "; else { if( fd->value > 9 ) cout << ( char )graphs[fd->value - 9] << " "; else { if( fd->value < 1 ) cout << " "; else cout << ( char )(fd->value + 48 ) << " "; } } } cout << "| " << y + 1 << "\n"; } for( int x = 0; x < wid; x++ ) cout << "+---"; cout << "+\n\n"; } void checkWin() { int z = wid * hei - oMines, yy; fieldData* fd; for( int y = 0; y < hei; y++ ) { yy = wid * y; for( int x = 0; x < wid; x++ ) { fd = &field[x + yy]; if( fd->open && fd->value != FLAG ) z--; } } if( !z ) lastMsg( "Congratulations, you won the game!"); } void boom() { int yy; fieldData* fd; for( int y = 0; y < hei; y++ ) { yy = wid * y; for( int x = 0; x < wid; x++ ) { fd = &field[x + yy]; if( fd->value == FLAG ) { fd->open = true; fd->value = fd->mine ? MINE : ERR; } else if( fd->mine ) { fd->open = true; fd->value = MINE; } } } lastMsg( "B O O O M M M M M !" ); } void lastMsg( string s ) { go = true; drawBoard(); cout << s << "\n\n"; } bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); } void recOpen( int x, int y ) { if( !isInside( x, y ) || field[x + y * wid].open ) return; int bc = getMineCount( x, y ); field[x + y * wid].open = true; field[x + y * wid].value = bc; if( bc ) return; for( int yy = -1; yy < 2; yy++ ) for( int xx = -1; xx < 2; xx++ ) { if( xx == 0 && yy == 0 ) continue; recOpen( x + xx, y + yy ); } } int getMineCount( int x, int y ) { int m = 0; for( int yy = -1; yy < 2; yy++ ) for( int xx = -1; xx < 2; xx++ ) { if( xx == 0 && yy == 0 ) continue; if( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++; } return m; } int wid, hei, mMines, oMines; fieldData* field; bool go; int graphs[6]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); game g( 4, 6 ); g.gameLoop(); return system( "pause" ); }
Generate an equivalent C++ version of this VB code.
Module Module1 Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer) Dim size = g.Count Dim vis(size - 1) As Boolean Dim l(size - 1) As Integer Dim x = size Dim t As New List(Of List(Of Integer)) For i = 1 To size t.Add(New List(Of Integer)) Next Dim visit As Action(Of Integer) = Sub(u As Integer) If Not vis(u) Then vis(u) = True For Each v In g(u) visit(v) t(v).Add(u) Next x -= 1 l(x) = u End If End Sub For i = 1 To size visit(i - 1) Next Dim c(size - 1) As Integer Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer) If vis(u) Then vis(u) = False c(u) = root For Each v In t(u) assign(v, root) Next End If End Sub For Each u In l assign(u, u) Next Return c.ToList End Function Sub Main() Dim g = New List(Of List(Of Integer)) From { New List(Of Integer) From {1}, New List(Of Integer) From {2}, New List(Of Integer) From {0}, New List(Of Integer) From {1, 2, 4}, New List(Of Integer) From {3, 5}, New List(Of Integer) From {2, 6}, New List(Of Integer) From {5}, New List(Of Integer) From {4, 6, 7} } Dim output = Kosaraju(g) Console.WriteLine("[{0}]", String.Join(", ", output)) End Sub End Module
#include <functional> #include <iostream> #include <ostream> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto it = v.cbegin(); auto end = v.cend(); os << "["; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << "]"; } std::vector<int> kosaraju(std::vector<std::vector<int>>& g) { auto size = g.size(); std::vector<bool> vis(size); std::vector<int> l(size); auto x = size; std::vector<std::vector<int>> t(size); std::function<void(int)> visit; visit = [&](int u) { if (!vis[u]) { vis[u] = true; for (auto v : g[u]) { visit(v); t[v].push_back(u); } l[--x] = u; } }; for (int i = 0; i < g.size(); ++i) { visit(i); } std::vector<int> c(size); std::function<void(int, int)> assign; assign = [&](int u, int root) { if (vis[u]) { vis[u] = false; c[u] = root; for (auto v : t[u]) { assign(v, root); } } }; for (auto u : l) { assign(u, u); } return c; } std::vector<std::vector<int>> g = { {1}, {2}, {0}, {1, 2, 4}, {3, 5}, {2, 6}, {5}, {4, 6, 7}, }; int main() { using namespace std; cout << kosaraju(g) << endl; return 0; }
Write the same code in C++ as shown below in VB.
Module Module1 Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer) Dim size = g.Count Dim vis(size - 1) As Boolean Dim l(size - 1) As Integer Dim x = size Dim t As New List(Of List(Of Integer)) For i = 1 To size t.Add(New List(Of Integer)) Next Dim visit As Action(Of Integer) = Sub(u As Integer) If Not vis(u) Then vis(u) = True For Each v In g(u) visit(v) t(v).Add(u) Next x -= 1 l(x) = u End If End Sub For i = 1 To size visit(i - 1) Next Dim c(size - 1) As Integer Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer) If vis(u) Then vis(u) = False c(u) = root For Each v In t(u) assign(v, root) Next End If End Sub For Each u In l assign(u, u) Next Return c.ToList End Function Sub Main() Dim g = New List(Of List(Of Integer)) From { New List(Of Integer) From {1}, New List(Of Integer) From {2}, New List(Of Integer) From {0}, New List(Of Integer) From {1, 2, 4}, New List(Of Integer) From {3, 5}, New List(Of Integer) From {2, 6}, New List(Of Integer) From {5}, New List(Of Integer) From {4, 6, 7} } Dim output = Kosaraju(g) Console.WriteLine("[{0}]", String.Join(", ", output)) End Sub End Module
#include <functional> #include <iostream> #include <ostream> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto it = v.cbegin(); auto end = v.cend(); os << "["; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << "]"; } std::vector<int> kosaraju(std::vector<std::vector<int>>& g) { auto size = g.size(); std::vector<bool> vis(size); std::vector<int> l(size); auto x = size; std::vector<std::vector<int>> t(size); std::function<void(int)> visit; visit = [&](int u) { if (!vis[u]) { vis[u] = true; for (auto v : g[u]) { visit(v); t[v].push_back(u); } l[--x] = u; } }; for (int i = 0; i < g.size(); ++i) { visit(i); } std::vector<int> c(size); std::function<void(int, int)> assign; assign = [&](int u, int root) { if (vis[u]) { vis[u] = false; c[u] = root; for (auto v : t[u]) { assign(v, root); } } }; for (auto u : l) { assign(u, u); } return c; } std::vector<std::vector<int>> g = { {1}, {2}, {0}, {1, 2, 4}, {3, 5}, {2, 6}, {5}, {4, 6, 7}, }; int main() { using namespace std; cout << kosaraju(g) << endl; return 0; }
Produce a functionally identical C++ code for the snippet given in VB.
Public Sub test() Dim t(2) As Variant t(0) = [{1,2}] t(1) = [{3,4,1}] t(2) = 5 p = [{"Payload#0","Payload#1","Payload#2","Payload#3","Payload#4","Payload#5","Payload#6"}] Dim q(6) As Boolean For i = LBound(t) To UBound(t) If IsArray(t(i)) Then For j = LBound(t(i)) To UBound(t(i)) q(t(i)(j)) = True t(i)(j) = p(t(i)(j) + 1) Next j Else q(t(i)) = True t(i) = p(t(i) + 1) End If Next i For i = LBound(t) To UBound(t) If IsArray(t(i)) Then Debug.Print Join(t(i), ", ") Else Debug.Print t(i) End If Next i For i = LBound(q) To UBound(q) If Not q(i) Then Debug.Print p(i + 1); " is not used" Next i End Sub
#include <iostream> #include <set> #include <tuple> #include <vector> using namespace std; template<typename P> void PrintPayloads(const P &payloads, int index, bool isLast) { if(index < 0 || index >= (int)size(payloads)) cout << "null"; else cout << "'" << payloads[index] << "'"; if (!isLast) cout << ", "; } template<typename P, typename... Ts> void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true) { std::apply ( [&payloads, isLast](Ts const&... tupleArgs) { size_t n{0}; cout << "["; (PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...); cout << "]"; cout << (isLast ? "\n" : ",\n"); }, nestedTuple ); } void FindUniqueIndexes(set<int> &indexes, int index) { indexes.insert(index); } template<typename... Ts> void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple) { std::apply ( [&indexes](Ts const&... tupleArgs) { (FindUniqueIndexes(indexes, tupleArgs),...); }, nestedTuple ); } template<typename P> void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads) { for(size_t i = 0; i < size(payloads); i++) { if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n"; } } int main() { vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"}; const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"}; auto tpl = make_tuple(make_tuple( make_tuple(1, 2), make_tuple(3, 4, 1), 5)); cout << "Mapping indexes to payloads:\n"; PrintPayloads(payloads, tpl); cout << "\nFinding unused payloads:\n"; set<int> usedIndexes; FindUniqueIndexes(usedIndexes, tpl); PrintUnusedPayloads(usedIndexes, payloads); cout << "\nMapping to some out of range payloads:\n"; PrintPayloads(shortPayloads, tpl); return 0; }
Rewrite the snippet below in PHP so it works the same as the original C# code.
using System; using System.IO; namespace DeleteFile { class Program { static void Main() { File.Delete("input.txt"); Directory.Delete("docs"); File.Delete("/input.txt"); Directory.Delete("/docs"); } } }
<?php unlink('input.txt'); unlink('/input.txt'); rmdir('docs'); rmdir('/docs'); ?>
Port the provided C# code into PHP while preserving the original functionality.
using System; public static class DiscordianDate { static readonly string[] seasons = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" }; static readonly string[] weekdays = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" }; static readonly string[] apostles = { "Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" }; static readonly string[] holidays = { "Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux" }; public static string Discordian(this DateTime date) { string yold = $" in the YOLD {date.Year + 1166}."; int dayOfYear = date.DayOfYear; if (DateTime.IsLeapYear(date.Year)) { if (dayOfYear == 60) return "St. Tib's day" + yold; else if (dayOfYear > 60) dayOfYear--; } dayOfYear--; int seasonDay = dayOfYear % 73 + 1; int seasonNr = dayOfYear / 73; int weekdayNr = dayOfYear % 5; string holyday = ""; if (seasonDay == 5) holyday = $" Celebrate {apostles[seasonNr]}!"; else if (seasonDay == 50) holyday = $" Celebrate {holidays[seasonNr]}!"; return $"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}"; } public static void Main() { foreach (var (day, month, year) in new [] { (1, 1, 2010), (5, 1, 2010), (19, 2, 2011), (28, 2, 2012), (29, 2, 2012), (1, 3, 2012), (19, 3, 2013), (3, 5, 2014), (31, 5, 2015), (22, 6, 2016), (15, 7, 2016), (12, 8, 2017), (19, 9, 2018), (26, 9, 2018), (24, 10, 2019), (8, 12, 2020), (31, 12, 2020) }) { Console.WriteLine($"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}"); } } }
<?php $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31); $MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath"); $DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle"); $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th'); $Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay"); $Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux"); $edate = explode(" ",date('Y m j L')); $usery = $edate[0]; $userm = $edate[1]; $userd = $edate[2]; $IsLeap = $edate[3]; if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { $usery = $_GET['y']; $userm = $_GET['m']; $userd = $_GET['d']; $IsLeap = 0; if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; if ($usery%400 == 0) $IsLeap = 1; } $userdays = 0; $i = 0; while ($i < ($userm-1)) { $userdays = $userdays + $Anerisia[$i]; $i = $i +1; } $userdays = $userdays + $userd; $IsHolyday = 0; $dyear = $usery + 1166; $dmonth = $MONTHS[$userdays/73.2]; $dday = $userdays%73; if (0 == $dday) $dday = 73; $Dname = $DAYS[$userdays%5]; $Holyday = "St. Tibs Day"; if ($dday == 5) { $Holyday = $Holy5[$userdays/73.2]; $IsHolyday =1; } if ($dday == 50) { $Holyday = $Holy50[$userdays/73.2]; $IsHolyday =1; } if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2; $suff = $Dsuff[$dday%10] ; if ((11 <= $dday) && (19 >= $dday)) $suff='th'; if ($IsHolyday ==2) echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear; if ($IsHolyday ==1) echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday; if ($IsHolyday == 0) echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear; ?>
Convert this C# snippet to PHP and keep its semantics consistent.
class Program { static void Main() { string extra = "little"; string formatted = $"Mary had a {extra} lamb."; System.Console.WriteLine(formatted); } }
<?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?>
Change the programming language of this snippet from C# to PHP without modifying what it does.
using System; using System.IO; using System.Text; namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT"; private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt); } else { var sb = new StringBuilder(); sb.Append(DateTime.Now).Append("\n\t"); foreach (string s in args) sb.Append(s).Append(" "); sb.Append("\n"); if (File.Exists(FileName)) File.AppendAllText(FileName, sb.ToString()); else File.WriteAllText(FileName, sb.ToString()); } } } }
#!/usr/bin/php <?php if ($argc > 1) file_put_contents( 'notes.txt', date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", FILE_APPEND ); else @readfile('notes.txt');
Change the programming language of this snippet from C# to PHP without modifying what it does.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks { class Program { static void Main ( string[ ] args ) { FindCommonDirectoryPath.Test ( ); } } class FindCommonDirectoryPath { public static void Test ( ) { Console.WriteLine ( "Find Common Directory Path" ); Console.WriteLine ( ); List<string> PathSet1 = new List<string> ( ); PathSet1.Add ( "/home/user1/tmp/coverage/test" ); PathSet1.Add ( "/home/user1/tmp/covert/operator" ); PathSet1.Add ( "/home/user1/tmp/coven/members" ); Console.WriteLine("Path Set 1 (All Absolute Paths):"); foreach ( string path in PathSet1 ) { Console.WriteLine ( path ); } Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) ); } public static string FindCommonPath ( string Separator, List<string> Paths ) { string CommonPath = String.Empty; List<string> SeparatedPath = Paths .First ( str => str.Length == Paths.Max ( st2 => st2.Length ) ) .Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries ) .ToList ( ); foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) ) { if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) ) { CommonPath = PathSegment; } else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) ) { CommonPath += Separator + PathSegment; } else { break; } } return CommonPath; } } }
<?php function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]); $arr[$i] = count($dirList[$i]); } $min = min($arr); for($i = 0; $i < count($dirList); $i++) { while(count($dirList[$i]) > $min) { array_pop($dirList[$i]); } $dirList[$i] = '/' . implode('/' , $dirList[$i]); } $dirList = array_unique($dirList); while(count($dirList) !== 1) { $dirList = array_map('dirname', $dirList); $dirList = array_unique($dirList); } reset($dirList); return current($dirList); } $dirs = array( '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members', ); if('/home/user1/tmp' !== common_path($dirs)) { echo 'test fail'; } else { echo 'test success'; } ?>
Change the following C# code into PHP without altering its purpose.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
Write the same code in PHP as shown below in C#.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
Translate this program into PHP but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaTicTacToe { class Program { static string[][] Players = new string[][] { new string[] { "COMPUTER", "X" }, new string[] { "HUMAN", "O" } }; const int Unplayed = -1; const int Computer = 0; const int Human = 1; static int[] GameBoard = new int[9]; static int[] corners = new int[] { 0, 2, 6, 8 }; static int[][] wins = new int[][] { new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } }; static void Main(string[] args) { while (true) { Console.Clear(); Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#."); initializeGameBoard(); displayGameBoard(); int currentPlayer = rnd.Next(0, 2); Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer)); while (true) { int thisMove = getMoveFor(currentPlayer); if (thisMove == Unplayed) { Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer)); break; } playMove(thisMove, currentPlayer); displayGameBoard(); if (isGameWon()) { Console.WriteLine("{0} has won the game!", playerName(currentPlayer)); break; } else if (isGameTied()) { Console.WriteLine("Cat game ... we have a tie."); break; } currentPlayer = getNextPlayer(currentPlayer); } if (!playAgain()) return; } } static int getMoveFor(int player) { if (player == Human) return getManualMove(player); else { int selectedMove = getSemiRandomMove(player); Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1); return selectedMove; } } static int getManualMove(int player) { while (true) { Console.Write("{0}, enter you move (number): ", playerName(player)); ConsoleKeyInfo keyInfo = Console.ReadKey(); Console.WriteLine(); if (keyInfo.Key == ConsoleKey.Escape) return Unplayed; if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9) { int move = keyInfo.KeyChar - '1'; if (GameBoard[move] == Unplayed) return move; else Console.WriteLine("Spot {0} is already taken, please select again.", move + 1); } else Console.WriteLine("Illegal move, please select again.\n"); } } static int getRandomMove(int player) { int movesLeft = GameBoard.Count(position => position == Unplayed); int x = rnd.Next(0, movesLeft); for (int i = 0; i < GameBoard.Length; i++) { if (GameBoard[i] == Unplayed && x < 0) return i; x--; } return Unplayed; } static int getSemiRandomMove(int player) { int posToPlay; if (checkForWinningMove(player, out posToPlay)) return posToPlay; if (checkForBlockingMove(player, out posToPlay)) return posToPlay; return getRandomMove(player); } static int getBestMove(int player) { return -1; } static bool checkForWinningMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(player, line, out posToPlay)) return true; return false; } static bool checkForBlockingMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay)) return true; return false; } static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay) { int cnt = 0; posToPlay = int.MinValue; foreach (int pos in line) { if (GameBoard[pos] == player) cnt++; else if (GameBoard[pos] == Unplayed) posToPlay = pos; } return cnt == 2 && posToPlay >= 0; } static void playMove(int boardPosition, int player) { GameBoard[boardPosition] = player; } static bool isGameWon() { return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2])); } static bool takenBySamePlayer(int a, int b, int c) { return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c]; } static bool isGameTied() { return !GameBoard.Any(spot => spot == Unplayed); } static Random rnd = new Random(); static void initializeGameBoard() { for (int i = 0; i < GameBoard.Length; i++) GameBoard[i] = Unplayed; } static string playerName(int player) { return Players[player][0]; } static string playerToken(int player) { return Players[player][1]; } static int getNextPlayer(int player) { return (player + 1) % 2; } static void displayGameBoard() { Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8)); Console.WriteLine(); } static string pieceAt(int boardPosition) { if (GameBoard[boardPosition] == Unplayed) return (boardPosition + 1).ToString(); return playerToken(GameBoard[boardPosition]); } private static bool playAgain() { Console.WriteLine("\nDo you want to play again?"); return Console.ReadKey(false).Key == ConsoleKey.Y; } } }
<?php const BOARD_NUM = 9; const ROW_NUM = 3; $EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM); function isGameOver($board, $pin) { $pat = '/X{3}|' . //Horz 'X..X..X..|' . //Vert Left '.X..X..X.|' . //Vert Middle '..X..X..X|' . //Vert Right '..X.X.X..|' . //Diag TL->BR 'X...X...X|' . //Diag TR->BL '[^\.]{9}/i'; //Cat's game if ($pin == 'O') $pat = str_replace('X', 'O', $pat); return preg_match($pat, $board); } $boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR; $turn = substr_count($boardStr, '.')%2==0? 'O' : 'X'; $oppTurn = $turn == 'X'? 'O' : 'X'; $gameOver = isGameOver($boardStr, $oppTurn); echo '<style>'; echo 'td {width: 200px; height: 200px; text-align: center; }'; echo '.pin {font-size:72pt; text-decoration:none; color: black}'; echo '.pin.X {color:red}'; echo '.pin.O {color:blue}'; echo '</style>'; echo '<table border="1">'; $p = 0; for ($r = 0; $r < ROW_NUM; $r++) { echo '<tr>'; for ($c = 0; $c < ROW_NUM; $c++) { $pin = $boardStr[$p]; echo '<td>'; if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied else { //Available $boardDelta = $boardStr; $boardDelta[$p] = $turn; echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">'; echo $boardStr[$p]; echo '</a>'; } echo '</td>'; $p++; } echo '</tr>'; echo '<input type="hidden" name="b" value="', $boardStr, '"/>'; } echo '</table>'; echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>'; if ($gameOver) echo '<h1>Game Over!</h1>';
Convert this C# snippet to PHP and keep its semantics consistent.
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
<?php $ipv4_record = dns_get_record("www.kame.net",DNS_A); $ipv6_record = dns_get_record("www.kame.net",DNS_AAAA); print "ipv4: " . $ipv4_record[0]["ip"] . "\n"; print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n"; ?>
Change the programming language of this snippet from C# to PHP without modifying what it does.
using System; static class YCombinator<T, TResult> { private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r); public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } = f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x))); } static class Program { static void Main() { var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1)); var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2)); Console.WriteLine(fac(10)); Console.WriteLine(fib(10)); } }
<?php function Y($f) { $g = function($w) use($f) { return $f(function() use($w) { return call_user_func_array($w($w), func_get_args()); }); }; return $g($g); } $fibonacci = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); }; }); echo $fibonacci(10), "\n"; $factorial = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); }; }); echo $factorial(10), "\n"; ?>
Please provide an equivalent version of this C# code in PHP.
using System; class Program { static void Main(string[] args) { for (int i = 1; i <= 10; i++) { Console.Write(i); if (i % 5 == 0) { Console.WriteLine(); continue; } Console.Write(", "); } } }
for ($i = 1; $i <= 10; $i++) { echo $i; if ($i % 5 == 0) { echo "\n"; continue; } echo ', '; }
Can you help me rewrite this code in PHP instead of C#, keeping it the same logically?
using System; public class GeneralFizzBuzz { public static void Main() { int i; int j; int k; int limit; string iString; string jString; string kString; Console.WriteLine("First integer:"); i = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("First string:"); iString = Console.ReadLine(); Console.WriteLine("Second integer:"); j = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Second string:"); jString = Console.ReadLine(); Console.WriteLine("Third integer:"); k = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Third string:"); kString = Console.ReadLine(); Console.WriteLine("Limit (inclusive):"); limit = Convert.ToInt32(Console.ReadLine()); for(int n = 1; n<= limit; n++) { bool flag = true; if(n%i == 0) { Console.Write(iString); flag = false; } if(n%j == 0) { Console.Write(jString); flag = false; } if(n%k == 0) { Console.Write(kString); flag = false; } if(flag) Console.Write(n); Console.WriteLine(); } } }
<?php $max = 20; $factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz'); for ($i = 1 ; $i <= $max ; $i++) { $matched = false; foreach ($factor AS $number => $word) { if ($i % $number == 0) { echo $word; $matched = true; } } echo ($matched ? '' : $i), PHP_EOL; } ?>
Convert the following code from C# to PHP, ensuring the logic remains intact.
using System; namespace StringCase { class Program { public static void Main() { String input = scope .("alphaBETA"); input.ToUpper(); Console.WriteLine(input); input.ToLower(); Console.WriteLine(input); } } }
$str = "alphaBETA"; echo strtoupper($str), "\n"; // ALPHABETA echo strtolower($str), "\n"; // alphabeta echo ucfirst($str), "\n"; // AlphaBETA echo lcfirst("FOObar"), "\n"; // fOObar echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
Produce a language-to-language conversion: from C# to PHP, same semantics.
using System.Text; using System.Security.Cryptography; byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back"); byte[] hash = MD5.Create().ComputeHash(data); Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());
$string = "The quick brown fox jumped over the lazy dog's back"; echo md5( $string );
Write the same algorithm in PHP as shown in this C# implementation.
class Program { static void Main(string[] args) { CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US"); string dateString = "March 7 2009 7:30pm EST"; string format = "MMMM d yyyy h:mmtt z"; DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ; DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ; Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST")); Console.ReadLine(); } }
<?php $time = new DateTime('March 7 2009 7:30pm EST'); $time->modify('+12 hours'); echo $time->format('c'); ?>
Write the same code in PHP as shown below in C#.
using System; using System.Collections.Generic; using System.Linq; using System.Threading; class Program { static void ThreadStart(object item) { Thread.Sleep(1000 * (int)item); Console.WriteLine(item); } static void SleepSort(IEnumerable<int> items) { foreach (var item in items) { new Thread(ThreadStart).Start(item); } } static void Main(string[] arguments) { SleepSort(arguments.Select(int.Parse)); } }
<?php $buffer = 1; $pids = []; for ($i = 1; $i < $argc; $i++) { $pid = pcntl_fork(); if ($pid < 0) { die("failed to start child process"); } if ($pid === 0) { sleep($argv[$i] + $buffer); echo $argv[$i] . "\n"; exit(); } $pids[] = $pid; } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); }
Port the following code from C# to PHP with equivalent syntax and logic.
using System; class Program { static void Main(string[] args) { int[,] a = new int[10, 10]; Random r = new Random(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { a[i, j] = r.Next(0, 21) + 1; } } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { Console.Write(" {0}", a[i, j]); if (a[i, j] == 20) { goto Done; } } Console.WriteLine(); } Done: Console.WriteLine(); } }
<?php for ($i = 0; $i < 10; $i++) for ($j = 0; $j < 10; $j++) $a[$i][$j] = rand(1, 20); foreach ($a as $row) { foreach ($row as $element) { echo " $element"; if ($element == 20) break 2; // 2 is the number of loops we want to break out of } echo "\n"; } echo "\n"; ?>
Translate this program into PHP but keep the logic exactly as in C#.
int[] nums = { 1, 1, 2, 3, 4, 4 }; List<int> unique = new List<int>(); foreach (int n in nums) if (!unique.Contains(n)) unique.Add(n);
$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'); $unique_list = array_unique($list);
Write the same algorithm in PHP as shown in this C# implementation.
using System; using System.Text; using System.Linq; class Program { static string lookandsay(string number) { StringBuilder result = new StringBuilder(); char repeat = number[0]; number = number.Substring(1, number.Length-1)+" "; int times = 1; foreach (char actual in number) { if (actual != repeat) { result.Append(Convert.ToString(times)+repeat); times = 1; repeat = actual; } else { times += 1; } } return result.ToString(); } static void Main(string[] args) { string num = "1"; foreach (int i in Enumerable.Range(1, 10)) { Console.WriteLine(num); num = lookandsay(num); } } }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Change the programming language of this snippet from C# to PHP without modifying what it does.
System.Collections.Stack stack = new System.Collections.Stack(); stack.Push( obj ); bool isEmpty = stack.Count == 0; object top = stack.Peek(); top = stack.Pop(); System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>(); stack.Push(new Foo()); bool isEmpty = stack.Count == 0; Foo top = stack.Peek(); top = stack.Pop();
$stack = array(); empty( $stack ); // true array_push( $stack, 1 ); // or $stack[] = 1; array_push( $stack, 2 ); // or $stack[] = 2; empty( $stack ); // false echo array_pop( $stack ); // outputs "2" echo array_pop( $stack ); // outputs "1"
Write the same code in PHP as shown below in C#.
if (condition) { } if (condition) { } else if (condition2) { } else { }
<?php $foo = 3; if ($foo == 2) if ($foo == 3) else if ($foo != 0) { } else { } ?>
Write the same code in PHP as shown below in C#.
using System; using System.Collections.Generic; namespace RosettaCode { class SortCustomComparator { public void CustomSort() { String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; List<String> list = new List<string>(items); DisplayList("Unsorted", list); list.Sort(CustomCompare); DisplayList("Descending Length", list); list.Sort(); DisplayList("Ascending order", list); } public int CustomCompare(String x, String y) { int result = -x.Length.CompareTo(y.Length); if (result == 0) { result = x.ToLower().CompareTo(y.ToLower()); } return result; } public void DisplayList(String header, List<String> theList) { Console.WriteLine(header); Console.WriteLine("".PadLeft(header.Length, '*')); foreach (String str in theList) { Console.WriteLine(str); } Console.WriteLine(); } } }
<?php function mycmp($s1, $s2) { if ($d = strlen($s2) - strlen($s1)) return $d; return strcasecmp($s1, $s2); } $strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted"); usort($strings, "mycmp"); ?>
Generate a PHP translation of this C# snippet without changing its computational steps.
class SelectionSort<T> where T : IComparable { public T[] Sort(T[] list) { int k; T temp; for (int i = 0; i < list.Length; i++) { k = i; for (int j=i + 1; j < list.Length; j++) { if (list[j].CompareTo(list[k]) < 0) { k = j; } } temp = list[i]; list[i] = list[k]; list[k] = temp; } return list; } }
function selection_sort(&$arr) { $n = count($arr); for($i = 0; $i < count($arr); $i++) { $min = $i; for($j = $i + 1; $j < $n; $j++){ if($arr[$j] < $arr[$min]){ $min = $j; } } list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]); } }
Rewrite the snippet below in PHP so it works the same as the original C# code.
int[] intArray = { 1, 2, 3, 4, 5 }; int[] squares1 = intArray.Select(x => x * x).ToArray(); int[] squares2 = (from x in intArray select x * x).ToArray(); foreach (var i in intArray) Console.WriteLine(i * i);
function cube($n) { return($n * $n * $n); } $a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b);
Convert the following code from C# to PHP, ensuring the logic remains intact.
public sealed class Singleton1 { private static Singleton1 instance; private static readonly object lockObj = new object(); public static Singleton1 Instance { get { lock(lockObj) { if (instance == null) { instance = new Singleton1(); } } return instance; } } }
class Singleton { protected static $instance = null; public $test_var; private function __construct(){ } public static function getInstance(){ if (is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } } $foo = Singleton::getInstance(); $foo->test_var = 'One'; $bar = Singleton::getInstance(); echo $bar->test_var; //Prints 'One' $fail = new Singleton(); //Fatal error
Transform the following C# implementation into PHP, maintaining the same output and logic.
for (int i = 10; i >= 0; i--) { Console.WriteLine(i); }
for ($i = 10; $i >= 0; $i--) echo "$i\n";
Port the following code from C# to PHP with equivalent syntax and logic.
using System; class Program { static void Main(string[] args) { for (int i = 0; i < 5; i++) { for (int j = 0; j <= i; j++) { Console.Write("*"); } Console.WriteLine(); } } }
for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo '*'; } echo "\n"; }
Write a version of this C# function in PHP with identical behavior.
using System; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static decimal mx = 1E28M, hm = 1E14M, a; struct bi { public decimal hi, lo; } static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; } static string toStr(bi a, bool comma = false) { string r = a.hi == 0 ? string.Format("{0:0}", a.lo) : string.Format("{0:0}{1:" + new string('0', 28) + "}", a.hi, a.lo); if (!comma) return r; string rc = ""; for (int i = r.Length - 3; i > 0; i -= 3) rc = "," + r.Substring(i, 3) + rc; return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; } static decimal Pow_dec(decimal bas, uint exp) { if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp; if ((exp & 1) == 0) return tmp; return tmp * bas; } static void Main(string[] args) { for (uint p = 64; p < 95; p += 30) { bi x = set4sq(a = Pow_dec(2M, p)), y; WriteLine("The square of (2^{0}): {1,38:n0}", p, a); BI BS = BI.Pow((BI)a, 2); y.lo = x.lo * x.lo; y.hi = x.hi * x.hi; a = x.hi * x.lo * 2M; y.hi += Math.Floor(a / hm); y.lo += (a % hm) * hm; while (y.lo > mx) { y.lo -= mx; y.hi++; } WriteLine(" is {0,75} (which {1} match the BigInteger computation)\n", toStr(y, true), BS.ToString() == toStr(y) ? "does" : "fails to"); } } }
<?php function longMult($a, $b) { $as = (string) $a; $bs = (string) $b; for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--) { for($p = 0; $p < $pi; $p++) { $regi[$ai][] = 0; } for($bi = strlen($bs) - 1; $bi >= 0; $bi--) { $regi[$ai][] = $as[$ai] * $bs[$bi]; } } return $regi; } function longAdd($arr) { $outer = count($arr); $inner = count($arr[$outer-1]) + $outer; for($i = 0; $i <= $inner; $i++) { for($o = 0; $o < $outer; $o++) { $val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0; @$sum[$i] += $val; } } return $sum; } function carry($arr) { for($i = 0; $i < count($arr); $i++) { $s = (string) $arr[$i]; switch(strlen($s)) { case 2: $arr[$i] = $s{1}; @$arr[$i+1] += $s{0}; break; case 3: $arr[$i] = $s{2}; @$arr[$i+1] += $s{0}.$s{1}; break; } } return ltrim(implode('',array_reverse($arr)),'0'); } function lm($a,$b) { return carry(longAdd(longMult($a,$b))); } if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456') { echo 'pass!'; }; // 2^64 * 2^64
Port the provided C# code into PHP while preserving the original functionality.
using System; namespace BullsnCows { class Program { static void Main(string[] args) { int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; KnuthShuffle<int>(ref nums); int[] chosenNum = new int[4]; Array.Copy(nums, chosenNum, 4); Console.WriteLine("Your Guess ?"); while (!game(Console.ReadLine(), chosenNum)) { Console.WriteLine("Your next Guess ?"); } Console.ReadKey(); } public static void KnuthShuffle<T>(ref T[] array) { System.Random random = new System.Random(); for (int i = 0; i < array.Length; i++) { int j = random.Next(array.Length); T temp = array[i]; array[i] = array[j]; array[j] = temp; } } public static bool game(string guess, int[] num) { char[] guessed = guess.ToCharArray(); int bullsCount = 0, cowsCount = 0; if (guessed.Length != 4) { Console.WriteLine("Not a valid guess."); return false; } for (int i = 0; i < 4; i++) { int curguess = (int) char.GetNumericValue(guessed[i]); if (curguess < 1 || curguess > 9) { Console.WriteLine("Digit must be ge greater 0 and lower 10."); return false; } if (curguess == num[i]) { bullsCount++; } else { for (int j = 0; j < 4; j++) { if (curguess == num[j]) cowsCount++; } } } if (bullsCount == 4) { Console.WriteLine("Congratulations! You have won!"); return true; } else { Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount); return false; } } } }
<?php $size = 4; $chosen = implode(array_rand(array_flip(range(1,9)), $size)); echo "I've chosen a number from $size unique digits from 1 to 9; you need to input $size unique digits to guess my number\n"; for ($guesses = 1; ; $guesses++) { while (true) { echo "\nNext guess [$guesses]: "; $guess = rtrim(fgets(STDIN)); if (!checkguess($guess)) echo "$size digits, no repetition, no 0... retry\n"; else break; } if ($guess == $chosen) { echo "You did it in $guesses attempts!\n"; break; } else { $bulls = 0; $cows = 0; foreach (range(0, $size-1) as $i) { if ($guess[$i] == $chosen[$i]) $bulls++; else if (strpos($chosen, $guess[$i]) !== FALSE) $cows++; } echo "$cows cows, $bulls bulls\n"; } } function checkguess($g) { global $size; return count(array_unique(str_split($g))) == $size && preg_match("/^[1-9]{{$size}}$/", $g); } ?>
Convert this C# block to PHP, preserving its control flow and logic.
using System; using System.Collections.Generic; namespace RosettaCode.BubbleSort { public static class BubbleSortMethods { public static void BubbleSort<T>(this List<T> list) where T : IComparable { bool madeChanges; int itemCount = list.Count; do { madeChanges = false; itemCount--; for (int i = 0; i < itemCount; i++) { if (list[i].CompareTo(list[i + 1]) > 0) { T temp = list[i + 1]; list[i + 1] = list[i]; list[i] = temp; madeChanges = true; } } } while (madeChanges); } } class Program { static void Main() { List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 }; testList.BubbleSort(); foreach (var t in testList) Console.Write(t + " "); } } }
function bubbleSort(array $array){ foreach($array as $i => &$val){ foreach($array as $k => &$val2){ if($k <= $i) continue; if($val > $val2) { list($val, $val2) = [$val2, $val]; break; } } } return $array; }
Generate a PHP translation of this C# snippet without changing its computational steps.
using System; using System.IO; namespace FileIO { class Program { static void Main() { String s = scope .(); File.ReadAllText("input.txt", s); File.WriteAllText("output.txt", s); } } }
<?php if (!$in = fopen('input.txt', 'r')) { die('Could not open input file.'); } if (!$out = fopen('output.txt', 'w')) { die('Could not open output file.'); } while (!feof($in)) { $data = fread($in, 512); fwrite($out, $data); } fclose($out); fclose($in); ?>
Port the provided C# code into PHP while preserving the original functionality.
using System; class Program { static void Main(string[] args) { int a = Convert.ToInt32(args[0]); int b = Convert.ToInt32(args[1]); Console.WriteLine("{0} + {1} = {2}", a, b, a + b); Console.WriteLine("{0} - {1} = {2}", a, b, a - b); Console.WriteLine("{0} * {1} = {2}", a, b, a * b); Console.WriteLine("{0} / {1} = {2}", a, b, a / b); Console.WriteLine("{0} % {1} = {2}", a, b, a % b); Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b)); } }
<?php $a = fgets(STDIN); $b = fgets(STDIN); echo "sum: ", $a + $b, "\n", "difference: ", $a - $b, "\n", "product: ", $a * $b, "\n", "truncating quotient: ", (int)($a / $b), "\n", "flooring quotient: ", floor($a / $b), "\n", "remainder: ", $a % $b, "\n", "power: ", $a ** $b, "\n"; // PHP 5.6+ only ?>
Write a version of this C# function in PHP with identical behavior.
using System; using System.Text; namespace prog { class MainClass { public static void Main (string[] args) { double[,] m = { {1,2,3},{4,5,6},{7,8,9} }; double[,] t = Transpose( m ); for( int i=0; i<t.GetLength(0); i++ ) { for( int j=0; j<t.GetLength(1); j++ ) Console.Write( t[i,j] + " " ); Console.WriteLine(""); } } public static double[,] Transpose( double[,] m ) { double[,] t = new double[m.GetLength(1),m.GetLength(0)]; for( int i=0; i<m.GetLength(0); i++ ) for( int j=0; j<m.GetLength(1); j++ ) t[j,i] = m[i,j]; return t; } } }
function transpose($m) { if (count($m) == 0) // special case: empty matrix return array(); else if (count($m) == 1) // special case: row matrix return array_chunk($m[0], 1); array_unshift($m, NULL); // the original matrix is not modified because it was passed by value return call_user_func_array('array_map', $m); }
Ensure the translated PHP code behaves exactly like the original C# snippet.
using System; delegate T Func<T>(); class ManOrBoy { static void Main() { Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0))); } static Func<int> C(int i) { return delegate { return i; }; } static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5) { Func<int> b = null; b = delegate { k--; return A(k, b, x1, x2, x3, x4); }; return k <= 0 ? x4() + x5() : b(); } }
<?php function A($k,$x1,$x2,$x3,$x4,$x5) { $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) { return A(--$k,$b,$x1,$x2,$x3,$x4); }; return $k <= 0 ? $x4() + $x5() : $b(); } echo A(10, function () { return 1; }, function () { return -1; }, function () { return -1; }, function () { return 1; }, function () { return 0; }) . "\n"; ?>
Change the programming language of this snippet from C# to PHP without modifying what it does.
using System; class RecursionLimit { static void Main(string[] args) { Recur(0); } private static void Recur(int i) { Console.WriteLine(i); Recur(i + 1); } }
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
Write the same algorithm in PHP as shown in this C# implementation.
using System; class RecursionLimit { static void Main(string[] args) { Recur(0); } private static void Recur(int i) { Console.WriteLine(i); Recur(i + 1); } }
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
Write the same code in PHP as shown below in C#.
static void Main(string[] args) { Console.WriteLine("Perfect numbers from 1 to 33550337:"); for (int x = 0; x < 33550337; x++) { if (IsPerfect(x)) Console.WriteLine(x + " is perfect."); } Console.ReadLine(); } static bool IsPerfect(int num) { int sum = 0; for (int i = 1; i < num; i++) { if (num % i == 0) sum += i; } return sum == num ; }
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Rewrite the snippet below in PHP so it works the same as the original C# code.
using System; using System.Diagnostics; using System.Linq; using System.Numerics; static class Program { static void Main() { BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2))); string result = n.ToString(); Debug.Assert(result.Length == 183231); Debug.Assert(result.StartsWith("62060698786608744707")); Debug.Assert(result.EndsWith("92256259918212890625")); Console.WriteLine("n = 5^4^3^2"); Console.WriteLine("n = {0}...{1}", result.Substring(0, 20), result.Substring(result.Length - 20, 20) ); Console.WriteLine("n digits = {0}", result.Length); } }
<?php $y = bcpow('5', bcpow('4', bcpow('3', '2'))); printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y)); ?>
Change the following C# code into PHP without altering its purpose.
using System; using System.Collections.Generic; using System.IO; using System.Linq; class InvertedIndex { static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary) { return dictionary .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key))) .GroupBy(keyValuePair => keyValuePair.Key) .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value)); } static void Main() { Console.Write("files: "); var files = Console.ReadLine(); Console.Write("find: "); var find = Console.ReadLine(); var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable()); Console.WriteLine("{0} found in: {1}", find, string.Join(" ", Invert(dictionary)[find])); } }
<?php function buildInvertedIndex($filenames) { $invertedIndex = []; foreach($filenames as $filename) { $data = file_get_contents($filename); if($data === false) die('Unable to read file: ' . $filename); preg_match_all('/(\w+)/', $data, $matches, PREG_SET_ORDER); foreach($matches as $match) { $word = strtolower($match[0]); if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = []; if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename; } } return $invertedIndex; } function lookupWord($invertedIndex, $word) { return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false; } $invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']); foreach(['cat', 'is', 'banana', 'it'] as $word) { $matches = lookupWord($invertedIndex, $word); if($matches !== false) { echo "Found the word \"$word\" in the following files: " . implode(', ', $matches) . "\n"; } else { echo "Unable to find the word \"$word\" in the index\n"; } }
Write the same code in PHP as shown below in C#.
Using System; class Program { static int gcd(int m, int n) { return n == 0 ? Math.Abs(m) : gcd(n, n % m); } static int lcm(int m, int n) { return Math.Abs(m * n) / gcd(m, n); } static void Main() { Console.WriteLine("lcm(12,18)=" + lcm(12,18)); } }
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
Produce a language-to-language conversion: from C# to PHP, same semantics.
Using System; class Program { static int gcd(int m, int n) { return n == 0 ? Math.Abs(m) : gcd(n, n % m); } static int lcm(int m, int n) { return Math.Abs(m * n) / gcd(m, n); } static void Main() { Console.WriteLine("lcm(12,18)=" + lcm(12,18)); } }
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
Rewrite the snippet below in PHP so it works the same as the original C# code.
class Program { static void Main(string[] args) { Random random = new Random(); while (true) { int a = random.Next(20); Console.WriteLine(a); if (a == 10) break; int b = random.Next(20) Console.WriteLine(b); } Console.ReadLine(); } }
while (true) { $a = rand(0,19); echo "$a\n"; if ($a == 10) break; $b = rand(0,19); echo "$b\n"; }
Produce a language-to-language conversion: from C# to PHP, same semantics.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { string text = Math.Abs(int.Parse(Console.ReadLine())).ToString(); Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3)); } } }
function middlethree($integer) { $int = (int)str_replace('-','',$integer); $length = strlen($int); if(is_int($int)) { if($length >= 3) { if($length % 2 == 1) { $middle = floor($length / 2) - 1; return substr($int,$middle, 3); } else { return 'The value must contain an odd amount of digits...'; } } else { return 'The value must contain at least three digits...'; } } else { return 'The value does not appear to be an integer...'; } } $numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0); foreach($numbers as $nums) { echo $nums.' : '.middlethree($nums). '<br>'; }
Can you help me rewrite this code in PHP instead of C#, keeping it the same logically?
string path = @"C:\Windows\System32"; string multiline = @"Line 1. Line 2. Line 3.";
'c'; # character 'hello'; # these two strings are the same "hello"; 'Hi $name. How are you?'; # result: "Hi $name. How are you?" "Hi $name. How are you?"; # result: "Hi Bob. How are you?" '\n'; # 2-character string with a backslash and "n" "\n"; # newline character `ls`; # runs a command in the shell and returns the output as a string <<END # Here-Document Hi, whatever goes here gets put into the string, including newlines and $variables, until the label we put above END; <<'END' # Here-Document like single-quoted Same as above, but no interpolation of $variables. END;