Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the following C++ code into VB without altering its purpose.
#include <complex> #include <cmath> #include <iostream> double const pi = 4 * std::atan(1); int main() { for (int n = 2; n <= 10; ++n) { std::cout << n << ": "; for (int k = 0; k < n; ++k) std::cout << std::polar(1, 2*pi*k/n) << " "; std::cout << std::endl; } }
Public Sub roots_of_unity() For n = 2 To 9 Debug.Print n; "th roots of 1:" For r00t = 0 To n - 1 Debug.Print " Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _ Sin(2 * WorksheetFunction.Pi() * r00t / n)) Next r00t Debug.Print Next n End Sub
Keep all operations the same but rewrite the snippet in VB.
#include <iostream> #include <sstream> typedef long long bigInt; using namespace std; class number { public: number() { s = "0"; neg = false; } number( bigInt a ) { set( a ); } number( string a ) { set( a ); } void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); } void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); } number operator * ( const number& b ) { return this->mul( b ); } number& operator *= ( const number& b ) { *this = *this * b; return *this; } number& operator = ( const number& b ) { s = b.s; return *this; } friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; } friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; } private: number mul( const number& b ) { number a; bool neg = false; string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' ); int xx, ss, rr, t, c, stp = 0; string::reverse_iterator xi = bs.rbegin(), si, ri; for( ; xi != bs.rend(); xi++ ) { c = 0; ri = r.rbegin() + stp; for( si = s.rbegin(); si != s.rend(); si++ ) { xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48; ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10; ( *ri++ ) = t + 48; } if( c > 0 ) ( *ri ) = c + 48; stp++; } trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0; if( t & 1 ) a.s = "-" + r; else a.s = r; return a; } void trimLeft( string& r ) { if( r.length() < 2 ) return; for( string::iterator x = r.begin(); x != ( r.end() - 1 ); ) { if( ( *x ) != '0' ) return; x = r.erase( x ); } } void clearStr() { for( string::iterator x = s.begin(); x != s.end(); ) { if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x ); else x++; } } string s; bool neg; }; int main( int argc, char* argv[] ) { number a, b; a.set( "18446744073709551616" ); b.set( "18446744073709551616" ); cout << a * b << endl << endl; cout << "Factor 1 = "; cin >> a; cout << "Factor 2 = "; cin >> b; cout << "Product: = " << a * b << endl << endl; return system( "pause" ); }
Imports System Imports System.Console Imports BI = System.Numerics.BigInteger Module Module1 Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D Structure bd Public hi, lo As Decimal End Structure Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String Dim r As String = If(a.hi = 0, String.Format("{0:0}", a.lo), String.Format("{0:0}{1:" & New String("0"c, 28) & "}", a.hi, a.lo)) If Not comma Then Return r Dim rc As String = "" For i As Integer = r.Length - 3 To 0 Step -3 rc = "," & r.Substring(i, 3) & rc : Next toStr = r.Substring(0, r.Length Mod 3) & rc toStr = toStr.Substring(If(toStr.Chars(0) = "," , 1, 0)) End Function Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _ Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas End Function Sub Main(ByVal args As String()) For p As UInteger = 64 To 95 - 1 Step 30 Dim y As bd, x As bd : a = Pow_dec(2D, p) WriteLine("The square of (2^{0}): {1,38:n0}", p, a) x.hi = Math.Floor(a / hm) : x.lo = a Mod hm Dim BS As BI = BI.Pow(CType(a, BI), 2) y.lo = x.lo * x.lo : y.hi = x.hi * x.hi a = x.hi * x.lo * 2D y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm While y.lo > mx : y.lo -= mx : y.hi += 1 : End While WriteLine(" is {0,75} (which {1} match the BigInteger computation)" & vbLf, toStr(y, True), If(BS.ToString() = toStr(y), "does", "fails to")) Next End Sub End Module
Ensure the translated VB code behaves exactly like the original C++ snippet.
#include <iomanip> #include <iostream> #include <tuple> std::tuple<uint64_t, uint64_t> solvePell(int n) { int x = (int)sqrt(n); if (x * x == n) { return std::make_pair(1, 0); } int y = x; int z = 1; int r = 2 * x; std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0); std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e)); f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f)); a = std::get<1>(e) + x * std::get<1>(f); b = std::get<1>(f); if (a * a - n * b * b == 1) { break; } } return std::make_pair(a, b); } void test(int n) { auto r = solvePell(n); std::cout << "x^2 - " << std::setw(3) << n << " * y^2 = 1 for x = " << std::setw(21) << std::get<0>(r) << " and y = " << std::setw(21) << std::get<1>(r) << '\n'; } int main() { test(61); test(109); test(181); test(277); return 0; }
Imports System.Numerics Module Module1 Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer) Dim t As BigInteger = a : a = b : b = b * c + t End Sub Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger) Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1, e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1 While True y = r * z - y : z = (n - y * y) / z : r = (x + y) / z Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x) If a * a - n * b * b = 1 Then Exit Sub End While End Sub Sub Main() Dim x As BigInteger, y As BigInteger For Each n As Integer In {61, 109, 181, 277} SolvePell(n, x, y) Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y) Next End Sub End Module
Port the following code from C++ to VB with equivalent syntax and logic.
#include <iostream> #include <string> #include <algorithm> #include <cstdlib> bool contains_duplicates(std::string s) { std::sort(s.begin(), s.end()); return std::adjacent_find(s.begin(), s.end()) != s.end(); } void game() { typedef std::string::size_type index; std::string symbols = "0123456789"; unsigned int const selection_length = 4; std::random_shuffle(symbols.begin(), symbols.end()); std::string selection = symbols.substr(0, selection_length); std::string guess; while (std::cout << "Your guess? ", std::getline(std::cin, guess)) { if (guess.length() != selection_length || guess.find_first_not_of(symbols) != std::string::npos || contains_duplicates(guess)) { std::cout << guess << " is not a valid guess!"; continue; } unsigned int bulls = 0; unsigned int cows = 0; for (index i = 0; i != selection_length; ++i) { index pos = selection.find(guess[i]); if (pos == i) ++bulls; else if (pos != std::string::npos) ++cows; } std::cout << bulls << " bulls, " << cows << " cows.\n"; if (bulls == selection_length) { std::cout << "Congratulations! You have won!\n"; return; } } std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n"; std::exit(EXIT_FAILURE); } int main() { std::cout << "Welcome to bulls and cows!\nDo you want to play? "; std::string answer; while (true) { while (true) { if (!std::getline(std::cin, answer)) { std::cout << "I can't get an answer. Exiting.\n"; return EXIT_FAILURE; } if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y") break; if (answer == "no" || answer == "No" || answer == "n" || answer == "N") { std::cout << "Ok. Goodbye.\n"; return EXIT_SUCCESS; } std::cout << "Please answer yes or no: "; } game(); std::cout << "Another game? "; } }
Option Explicit Sub Main_Bulls_and_cows() Dim strNumber As String, strInput As String, strMsg As String, strTemp As String Dim boolEnd As Boolean Dim lngCpt As Long Dim i As Byte, bytCow As Byte, bytBull As Byte Const NUMBER_OF_DIGITS As Byte = 4 Const MAX_LOOPS As Byte = 25 strNumber = Create_Number(NUMBER_OF_DIGITS) Do bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1 If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do strInput = AskToUser(NUMBER_OF_DIGITS) If strInput = "Exit Game" Then strMsg = "User abort": Exit Do For i = 1 To Len(strNumber) If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then bytBull = bytBull + 1 ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then bytCow = bytCow + 1 End If Next i If bytBull = Len(strNumber) Then boolEnd = True: strMsg = "You win in " & lngCpt & " loops!" Else strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows." MsgBox strTemp End If Loop While Not boolEnd MsgBox strMsg End Sub Function Create_Number(NbDigits As Byte) As String Dim myColl As New Collection Dim strTemp As String Dim bytAlea As Byte Randomize Do bytAlea = Int((Rnd * 9) + 1) On Error Resume Next myColl.Add CStr(bytAlea), CStr(bytAlea) If Err <> 0 Then On Error GoTo 0 Else strTemp = strTemp & CStr(bytAlea) End If Loop While Len(strTemp) < NbDigits Create_Number = strTemp End Function Function AskToUser(NbDigits As Byte) As String Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte Do While Not boolGood strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number") If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do If strIn <> "" Then If Len(strIn) = NbDigits Then NbDiff = 0 For i = 1 To Len(strIn) If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then NbDiff = 1 Exit For End If Next i If NbDiff = 0 Then boolGood = True End If End If Loop AskToUser = strIn End Function
Change the following C++ code into VB without altering its purpose.
#include <algorithm> #include <iostream> #include <iterator> template <typename RandomAccessIterator> void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) { bool swapped = true; while (begin != end-- && swapped) { swapped = false; for (auto i = begin; i != end; ++i) { if (*(i + 1) < *i) { std::iter_swap(i, i + 1); swapped = true; } } } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bubble_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) sortable.Shuffle() Dim swapped As Boolean Do Dim index, bound As Integer bound = sortable.Ubound While index < bound If sortable(index) > sortable(index + 1) Then Dim s As Integer = sortable(index) sortable.Remove(index) sortable.Insert(index + 1, s) swapped = True End If index = index + 1 Wend Loop Until Not swapped
Ensure the translated VB code behaves exactly like the original C++ snippet.
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream input ( "input.txt" ); ofstream output ("output.txt"); if (output.is_open()) { if (input.is_open()){ while (getline (input,line)) { output << line << endl; } input.close(); } else { cout << "input.txt cannot be opened!\n"; } output.close(); } else { cout << "output.txt cannot be written to!\n"; } return 0; }
Sub WriteToFile(input As FolderItem, output As FolderItem) Dim tis As TextInputStream Dim tos As TextOutputStream tis = tis.Open(input) tos = tos.Create(output) While Not tis.EOF tos.WriteLine(tis.ReadLine) Wend tis.Close tos.Close End Sub
Please provide an equivalent version of this C++ code in VB.
#include <iostream> int main() { int a, b; std::cin >> a >> b; std::cout << "a+b = " << a+b << "\n"; std::cout << "a-b = " << a-b << "\n"; std::cout << "a*b = " << a*b << "\n"; std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n"; return 0; }
START: INPUT "Enter two integers (a,b):"; a!, b! IF a = 0 THEN END IF b = 0 THEN PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder." GOTO START END IF PRINT PRINT " Sum = "; a + b PRINT " Difference = "; a - b PRINT " Product = "; a * b PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0." PRINT " Remainder = "; a MOD b, , "* Sign matches first operand." PRINT " Exponentiation = "; a ^ b PRINT INPUT "Again? (y/N)"; a$ IF UCASE$(a$) = "Y" THEN CLS: GOTO START CLS END
Convert this C++ block to VB, preserving its control flow and logic.
#include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> int main() { using namespace boost::numeric::ublas; matrix<double> m(3,3); for(int i=0; i!=m.size1(); ++i) for(int j=0; j!=m.size2(); ++j) m(i,j)=3*i+j; std::cout << trans(m) << std::endl; }
Function transpose(m As Variant) As Variant transpose = WorksheetFunction.transpose(m) End Function
Generate an equivalent VB version of this C++ code.
#include <iostream> bool a(bool in) { std::cout << "a" << std::endl; return in; } bool b(bool in) { std::cout << "b" << std::endl; return in; } void test(bool i, bool j) { std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl; std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl; } int main() { test(false, false); test(false, true); test(true, false); test(true, true); return 0; }
Private Function a(i As Variant) As Boolean Debug.Print "a: "; i = 1, a = i End Function Private Function b(j As Variant) As Boolean Debug.Print "b: "; j = 1; b = j End Function Public Sub short_circuit() Dim x As Boolean, y As Boolean Debug.Print "=====AND=====" & vbCrLf For p = 0 To 1 For q = 0 To 1 If a(p) Then x = b(q) End If Debug.Print " = x" Next q Debug.Print Next p Debug.Print "======OR=====" & vbCrLf For p = 0 To 1 For q = 0 To 1 If Not a(p) Then x = b(q) End If Debug.Print " = x" Next q Debug.Print Next p Debug.Print End Sub
Write the same algorithm in VB as shown in this C++ implementation.
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
Option Explicit Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 On Error Resume Next Limite_Recursivite Cpt On Error GoTo 0 Limite_Recursivite = Cpt End Function
Port the following code from C++ to VB with equivalent syntax and logic.
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
Option Explicit Sub Main() Debug.Print "The limit is : " & Limite_Recursivite(0) End Sub Function Limite_Recursivite(Cpt As Long) As Long Cpt = Cpt + 1 On Error Resume Next Limite_Recursivite Cpt On Error GoTo 0 Limite_Recursivite = Cpt End Function
Generate an equivalent VB version of this C++ code.
#include <cstdio> void divisor_count_and_sum(unsigned int n, unsigned int& divisor_count, unsigned int& divisor_sum) { divisor_count = 0; divisor_sum = 0; for (unsigned int i = 1;; i++) { unsigned int j = n / i; if (j < i) break; if (i * j != n) continue; divisor_sum += i; divisor_count += 1; if (i != j) { divisor_sum += j; divisor_count += 1; } } } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; n++) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, divisor_count, divisor_sum); unsigned int mean = divisor_sum / divisor_count; if (mean * divisor_count != divisor_sum) continue; arithmetic_count++; if (divisor_count > 2) composite_count++; if (arithmetic_count <= 100) { std::printf("%3u ", n); if (arithmetic_count % 10 == 0) std::printf("\n"); } if ((arithmetic_count == 1000) || (arithmetic_count == 10000) || (arithmetic_count == 100000) || (arithmetic_count == 1000000)) { std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
function isarit_compo(i) cnt=0 sum=0 for j=1 to sqr(i) if (i mod j)=0 then k=i\j if k=j then cnt=cnt+1:sum=sum+j else cnt=cnt+2:sum=sum+j+k end if end if next avg= sum/cnt isarit_compo= array((fix(avg)=avg),-(cnt>2)) end function function rpad(a,n) rpad=right(space(n)&a,n) :end function dim s1 sub print(s) s1=s1& rpad(s,4) if len(s1)=40 then wscript.stdout.writeline s1:s1="" end sub cntr=0 cntcompo=0 i=1 wscript.stdout.writeline "the first 100 arithmetic numbers are:" do a=isarit_compo(i) if a(0) then cntcompo=cntcompo+a(1) cntr=cntr+1 if cntr<=100 then print i if cntr=1000 then wscript.stdout.writeline vbcrlf&"1000th  : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6) if cntr=10000 then wscript.stdout.writeline vbcrlf& "10000th  : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6) if cntr=100000 then wscript.stdout.writeline vbcrlf &"100000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6):exit do end if i=i+1 loop
Produce a language-to-language conversion: from C++ to VB, same semantics.
#include <cstdio> void divisor_count_and_sum(unsigned int n, unsigned int& divisor_count, unsigned int& divisor_sum) { divisor_count = 0; divisor_sum = 0; for (unsigned int i = 1;; i++) { unsigned int j = n / i; if (j < i) break; if (i * j != n) continue; divisor_sum += i; divisor_count += 1; if (i != j) { divisor_sum += j; divisor_count += 1; } } } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; n++) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, divisor_count, divisor_sum); unsigned int mean = divisor_sum / divisor_count; if (mean * divisor_count != divisor_sum) continue; arithmetic_count++; if (divisor_count > 2) composite_count++; if (arithmetic_count <= 100) { std::printf("%3u ", n); if (arithmetic_count % 10 == 0) std::printf("\n"); } if ((arithmetic_count == 1000) || (arithmetic_count == 10000) || (arithmetic_count == 100000) || (arithmetic_count == 1000000)) { std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
function isarit_compo(i) cnt=0 sum=0 for j=1 to sqr(i) if (i mod j)=0 then k=i\j if k=j then cnt=cnt+1:sum=sum+j else cnt=cnt+2:sum=sum+j+k end if end if next avg= sum/cnt isarit_compo= array((fix(avg)=avg),-(cnt>2)) end function function rpad(a,n) rpad=right(space(n)&a,n) :end function dim s1 sub print(s) s1=s1& rpad(s,4) if len(s1)=40 then wscript.stdout.writeline s1:s1="" end sub cntr=0 cntcompo=0 i=1 wscript.stdout.writeline "the first 100 arithmetic numbers are:" do a=isarit_compo(i) if a(0) then cntcompo=cntcompo+a(1) cntr=cntr+1 if cntr<=100 then print i if cntr=1000 then wscript.stdout.writeline vbcrlf&"1000th  : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6) if cntr=10000 then wscript.stdout.writeline vbcrlf& "10000th  : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6) if cntr=100000 then wscript.stdout.writeline vbcrlf &"100000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6):exit do end if i=i+1 loop
Transform the following C++ implementation into VB, maintaining the same output and logic.
#include <windows.h> #include <sstream> #include <tchar.h> using namespace std; const unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } void* getBits( void ) const { return pBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void* pBits; int width, height, wid; DWORD clr; }; class bmpNoise { public: bmpNoise() { QueryPerformanceFrequency( &_frequency ); _bmp.create( BMP_WID, BMP_HEI ); _frameTime = _fps = 0; _start = getTime(); _frames = 0; } void mainLoop() { float now = getTime(); if( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; } HDC wdc, dc = _bmp.getDC(); unsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() ); for( int y = 0; y < BMP_HEI; y++ ) { for( int x = 0; x < BMP_WID; x++ ) { if( rand() % 10 < 5 ) memset( bits, 255, 3 ); else memset( bits, 0, 3 ); bits++; } } ostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() ); wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); _frames++; _frameTime = getTime() - now; if( _frameTime > 1.0f ) _frameTime = 1.0f; } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: float getTime() { LARGE_INTEGER liTime; QueryPerformanceCounter( &liTime ); return liTime.QuadPart / ( float )_frequency.QuadPart; } myBitmap _bmp; HWND _hwnd; float _start, _fps, _frameTime; unsigned int _frames; LARGE_INTEGER _frequency; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _noise.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { _noise.mainLoop(); } } return UnregisterClass( "_MY_NOISE_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_NOISE_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_WID, BMP_HEI }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_NOISE_", ".: Noise image -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; bmpNoise _noise; }; wnd* wnd::_inst = 0; int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
Imports System.Drawing.Imaging Public Class frmSnowExercise Dim bRunning As Boolean = True Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _ Or ControlStyles.OptimizedDoubleBuffer, True) UpdateStyles() FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle MaximizeBox = False Width = 320 + Size.Width - ClientSize.Width Height = 240 + Size.Height - ClientSize.Height Show() Activate() Application.DoEvents() RenderLoop() Close() End Sub Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False End Sub Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _ System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing e.Cancel = bRunning bRunning = False End Sub Private Sub RenderLoop() Const cfPadding As Single = 5.0F Dim b As New Bitmap(ClientSize.Width, ClientSize.Width, PixelFormat.Format32bppArgb) Dim g As Graphics = Graphics.FromImage(b) Dim r As New Random(Now.Millisecond) Dim oBMPData As BitmapData = Nothing Dim oPixels() As Integer = Nothing Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb} Dim oStopwatch As New Stopwatch Dim fElapsed As Single = 0.0F Dim iLoops As Integer = 0 Dim sFPS As String = "0.0 FPS" Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font) Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height) g.Clear(Color.Black) oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb) Array.Resize(oPixels, b.Width * b.Height) Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0, oPixels, 0, oPixels.Length) b.UnlockBits(oBMPData) Do fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F oStopwatch.Reset() : oStopwatch.Start() iLoops += 1 If fElapsed >= 1.0F Then sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS" oFPSSize = g.MeasureString(sFPS, Font) oFPSBG = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height) fElapsed -= 1.0F iLoops = 0 End If For i As Integer = 0 To oPixels.GetUpperBound(0) oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length)) Next oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb) Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0, oPixels.Length) b.UnlockBits(oBMPData) g.FillRectangle(Brushes.Black, oFPSBG) g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top) BackgroundImage = b Invalidate(ClientRectangle) Application.DoEvents() Loop While bRunning End Sub End Class
Port the following code from C++ to VB with equivalent syntax and logic.
#include <conio.h> #include <iostream> using namespace std; int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N'); if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.") GraphicsWindow.KeyDown = OnKeyDown Sub OnKeyDown TextWindow.WriteLine(GraphicsWindow.LastKey) EndSub
Write the same code in VB as shown below in C++.
#include <conio.h> #include <iostream> using namespace std; int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N'); if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.") GraphicsWindow.KeyDown = OnKeyDown Sub OnKeyDown TextWindow.WriteLine(GraphicsWindow.LastKey) EndSub
Change the following C++ code into VB without altering its purpose.
#include <conio.h> #include <iostream> using namespace std; int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N'); if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.") GraphicsWindow.KeyDown = OnKeyDown Sub OnKeyDown TextWindow.WriteLine(GraphicsWindow.LastKey) EndSub
Convert this C++ block to VB, preserving its control flow and logic.
#include <iostream> using namespace std ; int divisor_sum( int number ) { int sum = 0 ; for ( int i = 1 ; i < number ; i++ ) if ( number % i == 0 ) sum += i ; return sum; } int main( ) { cout << "Perfect numbers from 1 to 33550337:\n" ; for ( int num = 1 ; num < 33550337 ; num++ ) { if (divisor_sum(num) == num) cout << num << '\n' ; } return 0 ; }
Private Function Factors(x As Long) As String Application.Volatile Dim i As Long Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors End If Next i If x <> 1 Then Factors = Factors & ", " & corresponding_factors End Function Private Function is_perfect(n As Long) fs = Split(Factors(n), ", ") Dim f() As Long ReDim f(UBound(fs)) For i = 0 To UBound(fs) f(i) = Val(fs(i)) Next i is_perfect = WorksheetFunction.Sum(f) - n = n End Function Public Sub main() Dim i As Long For i = 2 To 100000 If is_perfect(i) Then Debug.Print i Next i End Sub
Rewrite this program in VB while keeping its functionality equivalent to the C++ version.
#include <iostream> using namespace std ; int divisor_sum( int number ) { int sum = 0 ; for ( int i = 1 ; i < number ; i++ ) if ( number % i == 0 ) sum += i ; return sum; } int main( ) { cout << "Perfect numbers from 1 to 33550337:\n" ; for ( int num = 1 ; num < 33550337 ; num++ ) { if (divisor_sum(num) == num) cout << num << '\n' ; } return 0 ; }
Private Function Factors(x As Long) As String Application.Volatile Dim i As Long Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors End If Next i If x <> 1 Then Factors = Factors & ", " & corresponding_factors End Function Private Function is_perfect(n As Long) fs = Split(Factors(n), ", ") Dim f() As Long ReDim f(UBound(fs)) For i = 0 To UBound(fs) f(i) = Val(fs(i)) Next i is_perfect = WorksheetFunction.Sum(f) - n = n End Function Public Sub main() Dim i As Long For i = 2 To 100000 If is_perfect(i) Then Debug.Print i Next i End Sub
Preserve the algorithm and functionality while converting the code from C++ to VB.
#include <iostream> #include <vector> using std::cout; using std::vector; void distribute(int dist, vector<int> &List) { if (dist > List.size() ) List.resize(dist); for (int i=0; i < dist; i++) List[i]++; } vector<int> beadSort(int *myints, int n) { vector<int> list, list2, fifth (myints, myints + n); cout << "#1 Beads falling down: "; for (int i=0; i < fifth.size(); i++) distribute (fifth[i], list); cout << '\n'; cout << "\nBeads on their sides: "; for (int i=0; i < list.size(); i++) cout << " " << list[i]; cout << '\n'; cout << "#2 Beads right side up: "; for (int i=0; i < list.size(); i++) distribute (list[i], list2); cout << '\n'; return list2; } int main() { int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1}; vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int)); cout << "Sorted list/array: "; for(unsigned int i=0; i<sorted.size(); i++) cout << sorted[i] << ' '; }
Option Base 1 Private Function sq_add(arr As Variant, x As Double) As Variant Dim res() As Variant ReDim res(UBound(arr)) For i = 1 To UBound(arr) res(i) = arr(i) + x Next i sq_add = res End Function Private Function beadsort(ByVal a As Variant) As Variant Dim poles() As Variant ReDim poles(WorksheetFunction.Max(a)) For i = 1 To UBound(a) For j = 1 To a(i) poles(j) = poles(j) + 1 Next j Next i For j = 1 To UBound(a) a(j) = 0 Next j For i = 1 To UBound(poles) For j = 1 To poles(i) a(j) = a(j) + 1 Next j Next i beadsort = a End Function Public Sub main() Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ") End Sub
Convert the following code from C++ to VB, ensuring the logic remains intact.
#include <iostream> #include <boost/multiprecision/gmp.hpp> #include <string> namespace mp = boost::multiprecision; int main(int argc, char const *argv[]) { uint64_t tmpres = mp::pow(mp::mpz_int(4) , mp::pow(mp::mpz_int(3) , 2).convert_to<uint64_t>() ).convert_to<uint64_t>(); mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres); std::string s = res.str(); std::cout << s.substr(0, 20) << "..." << s.substr(s.length() - 20, 20) << std::endl; return 0; }
Imports System.Console Imports BI = System.Numerics.BigInteger Module Module1 Dim Implems() As String = {"Built-In", "Recursive", "Iterative"}, powers() As Integer = {5, 4, 3, 2} Function intPowR(val As BI, exp As BI) As BI If exp = 0 Then Return 1 Dim ne As BI, vs As BI = val * val If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val End Function Function intPowI(val As BI, exp As BI) As BI intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val val *= val : exp >>= 1 : End While End Function Sub DoOne(title As String, p() As Integer) Dim st As DateTime = DateTime.Now, res As BI, resStr As String Select Case (Array.IndexOf(Implems, title)) Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3)))))) Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3)))) Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3)))) End Select : resStr = res.ToString() Dim et As TimeSpan = DateTime.Now - st Debug.Assert(resStr.Length = 183231) Debug.Assert(resStr.StartsWith("62060698786608744707")) Debug.Assert(resStr.EndsWith("92256259918212890625")) WriteLine("n = {0}", String.Join("^", powers)) WriteLine("n = {0}...{1}", resStr.Substring(0, 20), resStr.Substring(resStr.Length - 20, 20)) WriteLine("n digits = {0}", resStr.Length) WriteLine("{0} elasped: {1} milliseconds." & vblf, title, et.TotalMilliseconds) End Sub Sub Main() For Each itm As String in Implems : DoOne(itm, powers) : Next If Debugger.IsAttached Then Console.ReadKey() End Sub End Module
Transform the following C++ implementation into VB, maintaining the same output and logic.
#include <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@") light = Array(30, 30, -50) Sub Normalize(v) length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2)) v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length End Sub Function Dot(x, y) d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2) If d < 0 Then Dot = -d Else Dot = 0 End If End Function Function Ceil(x) Ceil = Int(x) If Ceil <> x Then Ceil = Ceil + 1 End if End Function Sub DrawSphere(R, k, ambient) Dim i, j, intensity, inten, b, x, y Dim vec(3) For i = Int(-R) to Ceil(R) x = i + 0.5 line = "" For j = Int(-2*R) to Ceil(2*R) y = j / 2 + 0.5 If x * x + y * y <= R*R Then vec(0) = x vec(1) = y vec(2) = Sqr(R * R - x * x - y * y) Normalize vec b = dot(light, vec)^k + ambient intensity = Int((1 - b) * UBound(shades)) If intensity < 0 Then intensity = 0 End If If intensity >= UBound(shades) Then intensity = UBound(shades) End If line = line & shades(intensity) Else line = line & " " End If Next WScript.StdOut.WriteLine line Next End Sub Normalize light DrawSphere 20, 4, 0.1 DrawSphere 10,2,0.4
Port the following code from C++ to VB with equivalent syntax and logic.
#include <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@") light = Array(30, 30, -50) Sub Normalize(v) length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2)) v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length End Sub Function Dot(x, y) d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2) If d < 0 Then Dot = -d Else Dot = 0 End If End Function Function Ceil(x) Ceil = Int(x) If Ceil <> x Then Ceil = Ceil + 1 End if End Function Sub DrawSphere(R, k, ambient) Dim i, j, intensity, inten, b, x, y Dim vec(3) For i = Int(-R) to Ceil(R) x = i + 0.5 line = "" For j = Int(-2*R) to Ceil(2*R) y = j / 2 + 0.5 If x * x + y * y <= R*R Then vec(0) = x vec(1) = y vec(2) = Sqr(R * R - x * x - y * y) Normalize vec b = dot(light, vec)^k + ambient intensity = Int((1 - b) * UBound(shades)) If intensity < 0 Then intensity = 0 End If If intensity >= UBound(shades) Then intensity = UBound(shades) End If line = line & shades(intensity) Else line = line & " " End If Next WScript.StdOut.WriteLine line Next End Sub Normalize light DrawSphere 20, 4, 0.1 DrawSphere 10,2,0.4
Convert the following code from C++ to VB, ensuring the logic remains intact.
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
Function gcd(u As Long, v As Long) As Long Dim t As Long Do While v t = u u = v v = t Mod v Loop gcd = u End Function Function lcm(m As Long, n As Long) As Long lcm = Abs(m * n) / gcd(m, n) End Function
Port the provided C++ code into VB while preserving the original functionality.
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
Function gcd(u As Long, v As Long) As Long Dim t As Long Do While v t = u u = v v = t Mod v Loop gcd = u End Function Function lcm(m As Long, n As Long) As Long lcm = Abs(m * n) / gcd(m, n) End Function
Rewrite this program in VB while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <ctime> #include <cstdlib> int main(){ srand(time(NULL)); while(true){ const int a = rand() % 20; std::cout << a << std::endl; if(a == 10) break; const int b = rand() % 20; std::cout << b << std::endl; } return 0; }
Public Sub LoopsBreak() Dim value As Integer Randomize Do While True value = Int(20 * Rnd) Debug.Print value If value = 10 Then Exit Do Debug.Print Int(20 * Rnd) Loop End Sub
Generate a VB translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <vector> #include <algorithm> enum { EMPTY, WALL, WATER }; auto fill(const std::vector<int> b) { auto water = 0; const auto rows = *std::max_element(std::begin(b), std::end(b)); const auto cols = std::size(b); std::vector<std::vector<int>> g(rows); for (auto& r : g) { for (auto i = 0; i < cols; ++i) { r.push_back(EMPTY); } } for (auto c = 0; c < cols; ++c) { for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) { g[r][c] = WALL; } } for (auto c = 0; c < cols - 1; ++c) { auto start_row = rows - b[c]; while (start_row < rows) { if (g[start_row][c] == EMPTY) break; auto c2 = c + 1; bool hitWall = false; while (c2 < cols) { if (g[start_row][c2] == WALL) { hitWall = true; break; } ++c2; } if (hitWall) { for (auto i = c + 1; i < c2; ++i) { g[start_row][i] = WATER; ++water; } } ++start_row; } } return water; } int main() { std::vector<std::vector<int>> b = { { 1, 5, 3, 7, 2 }, { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, { 5, 5, 5, 5 }, { 5, 6, 7, 8 }, { 8, 7, 7, 6 }, { 6, 7, 10, 7, 6 } }; for (const auto v : b) { auto water = fill(v); std::cout << water << " water drops." << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
Module Module1 Sub Main(Args() As String) Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1 Dim wta As Integer()() = { New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8}, New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}} Dim blk As String, lf As String = vbLf, tb = "██", wr = "≈≈", mt = " " For i As Integer = 0 To wta.Length - 1 Dim bpf As Integer blk = "" Do bpf = 0 : Dim floor As String = "" For j As Integer = 0 To wta(i).Length - 1 If wta(i)(j) > 0 Then floor &= tb : wta(i)(j) -= 1 : bpf += 1 Else floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt) End If Next If bpf > 0 Then blk = floor & lf & blk Loop Until bpf = 0 While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While If shoTow Then Console.Write("{0}{1}", lf, blk) Console.Write("Block {0} retains {1,2} water units.{2}", i + 1, (blk.Length - blk.Replace(wr, "").Length) \ 2, lf) Next End Sub End Module
Convert this C++ block to VB, preserving its control flow and logic.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; bool square_free(integer n) { if (n % 4 == 0) return false; for (integer p = 3; p * p <= n; p += 2) { integer count = 0; for (; n % p == 0; n /= p) { if (++count > 1) return false; } } return true; } void print_square_free_numbers(integer from, integer to) { std::cout << "Square-free numbers between " << from << " and " << to << ":\n"; std::string line; for (integer i = from; i <= to; ++i) { if (square_free(i)) { if (!line.empty()) line += ' '; line += std::to_string(i); if (line.size() >= 80) { std::cout << line << '\n'; line.clear(); } } } if (!line.empty()) std::cout << line << '\n'; } void print_square_free_count(integer from, integer to) { integer count = 0; for (integer i = from; i <= to; ++i) { if (square_free(i)) ++count; } std::cout << "Number of square-free numbers between " << from << " and " << to << ": " << count << '\n'; } int main() { print_square_free_numbers(1, 145); print_square_free_numbers(1000000000000LL, 1000000000145LL); print_square_free_count(1, 100); print_square_free_count(1, 1000); print_square_free_count(1, 10000); print_square_free_count(1, 100000); print_square_free_count(1, 1000000); return 0; }
Module Module1 Function Sieve(limit As Long) As List(Of Long) Dim primes As New List(Of Long) From {2} Dim c(limit + 1) As Boolean Dim p = 3L While True Dim p2 = p * p If p2 > limit Then Exit While End If For i = p2 To limit Step 2 * p c(i) = True Next While True p += 2 If Not c(p) Then Exit While End If End While End While For i = 3 To limit Step 2 If Not c(i) Then primes.Add(i) End If Next Return primes End Function Function SquareFree(from As Long, to_ As Long) As List(Of Long) Dim limit = CType(Math.Sqrt(to_), Long) Dim primes = Sieve(limit) Dim results As New List(Of Long) Dim i = from While i <= to_ For Each p In primes Dim p2 = p * p If p2 > i Then Exit For End If If (i Mod p2) = 0 Then i += 1 Continue While End If Next results.Add(i) i += 1 End While Return results End Function ReadOnly TRILLION As Long = 1_000_000_000_000 Sub Main() Console.WriteLine("Square-free integers from 1 to 145:") Dim sf = SquareFree(1, 145) For index = 0 To sf.Count - 1 Dim v = sf(index) If index > 1 AndAlso (index Mod 20) = 0 Then Console.WriteLine() End If Console.Write("{0,4}", v) Next Console.WriteLine() Console.WriteLine() Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145) sf = SquareFree(TRILLION, TRILLION + 145) For index = 0 To sf.Count - 1 Dim v = sf(index) If index > 1 AndAlso (index Mod 5) = 0 Then Console.WriteLine() End If Console.Write("{0,14}", v) Next Console.WriteLine() Console.WriteLine() Console.WriteLine("Number of square-free integers:") For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000} Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count) Next End Sub End Module
Rewrite this program in VB while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <iostream> #include <string> double jaro(const std::string s1, const std::string s2) { const uint l1 = s1.length(), l2 = s2.length(); if (l1 == 0) return l2 == 0 ? 1.0 : 0.0; const uint match_distance = std::max(l1, l2) / 2 - 1; bool s1_matches[l1]; bool s2_matches[l2]; std::fill(s1_matches, s1_matches + l1, false); std::fill(s2_matches, s2_matches + l2, false); uint matches = 0; for (uint i = 0; i < l1; i++) { const int end = std::min(i + match_distance + 1, l2); for (int k = std::max(0u, i - match_distance); k < end; k++) if (!s2_matches[k] && s1[i] == s2[k]) { s1_matches[i] = true; s2_matches[k] = true; matches++; break; } } if (matches == 0) return 0.0; double t = 0.0; uint k = 0; for (uint i = 0; i < l1; i++) if (s1_matches[i]) { while (!s2_matches[k]) k++; if (s1[i] != s2[k]) t += 0.5; k++; } const double m = matches; return (m / l1 + m / l2 + (m - t) / m) / 3.0; } int main() { using namespace std; cout << jaro("MARTHA", "MARHTA") << endl; cout << jaro("DIXON", "DICKSONX") << endl; cout << jaro("JELLYFISH", "SMELLYFISH") << endl; return 0; }
Option Explicit Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double Dim dummyChar, match1, match2 As String Dim i, f, t, j, m, l, s1, s2, limit As Integer i = 1 Do dummyChar = Chr(i) i = i + 1 Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0 s1 = Len(text1) s2 = Len(text2) limit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1) match1 = String(s1, dummyChar) match2 = String(s2, dummyChar) For l = 1 To WorksheetFunction.Min(4, s1, s2) If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For Next l l = l - 1 For i = 1 To s1 f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2) t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2) j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare) If j > 0 Then m = m + 1 text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j) match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1) match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j) End If Next i match1 = Replace(match1, dummyChar, "", 1, -1, vbTextCompare) match2 = Replace(match2, dummyChar, "", 1, -1, vbTextCompare) t = 0 For i = 1 To m If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1 Next i JaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3 JaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p) End Function
Convert the following code from C++ to VB, ensuring the logic remains intact.
#include <iostream> #include <vector> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { printf("Base %2d:", base); for (int i = 0; i < count; i++) { int t = turn(base, i); printf(" %2d", t); } printf("\n"); } void turnCount(int base, int count) { std::vector<int> cnt(base, 0); for (int i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } int minTurn = INT_MAX; int maxTurn = INT_MIN; int portion = 0; for (int i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(" With %d people: ", base); if (0 == minTurn) { printf("Only %d have a turn\n", portion); } else if (minTurn == maxTurn) { printf("%d\n", minTurn); } else { printf("%d or %d\n", minTurn, maxTurn); } } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf("How many times does each get a turn in 50000 iterations?\n"); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
Module Module1 Function Turn(base As Integer, n As Integer) As Integer Dim sum = 0 While n <> 0 Dim re = n Mod base n \= base sum += re End While Return sum Mod base End Function Sub Fairshare(base As Integer, count As Integer) Console.Write("Base {0,2}:", base) For i = 1 To count Dim t = Turn(base, i - 1) Console.Write(" {0,2}", t) Next Console.WriteLine() End Sub Sub TurnCount(base As Integer, count As Integer) Dim cnt(base) As Integer For i = 1 To base cnt(i - 1) = 0 Next For i = 1 To count Dim t = Turn(base, i - 1) cnt(t) += 1 Next Dim minTurn = Integer.MaxValue Dim maxTurn = Integer.MinValue Dim portion = 0 For i = 1 To base Dim num = cnt(i - 1) If num > 0 Then portion += 1 End If If num < minTurn Then minTurn = num End If If num > maxTurn Then maxTurn = num End If Next Console.Write(" With {0} people: ", base) If 0 = minTurn Then Console.WriteLine("Only {0} have a turn", portion) ElseIf minTurn = maxTurn Then Console.WriteLine(minTurn) Else Console.WriteLine("{0} or {1}", minTurn, maxTurn) End If End Sub Sub Main() Fairshare(2, 25) Fairshare(3, 25) Fairshare(5, 25) Fairshare(11, 25) Console.WriteLine("How many times does each get a turn in 50000 iterations?") TurnCount(191, 50000) TurnCount(1377, 50000) TurnCount(49999, 50000) TurnCount(50000, 50000) TurnCount(50001, 50000) End Sub End Module
Can you help me rewrite this code in VB instead of C++, keeping it the same logically?
#include <ciso646> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> using std::vector; using std::string; #include <exception> #include <stdexcept> template <typename...Args> std::runtime_error error( Args...args ) { return std::runtime_error( (std::ostringstream{} << ... << args).str() ); }; template <typename T> struct stack : public std::vector <T> { using base_type = std::vector <T> ; T push ( const T& x ) { base_type::push_back( x ); return x; } const T& top () { return base_type::back(); } T pop () { T x = std::move( top() ); base_type::pop_back(); return x; } bool empty() { return base_type::empty(); } }; using Number = double; using Operator_Name = string; using Precedence = int; enum class Associates { none, left_to_right, right_to_left }; struct Operator_Info { Precedence precedence; Associates associativity; }; std::unordered_map <Operator_Name, Operator_Info> Operators = { { "^", { 4, Associates::right_to_left } }, { "*", { 3, Associates::left_to_right } }, { "/", { 3, Associates::left_to_right } }, { "+", { 2, Associates::left_to_right } }, { "-", { 2, Associates::left_to_right } }, }; Precedence precedence ( const Operator_Name& op ) { return Operators[ op ].precedence; } Associates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; } using Token = string; bool is_number ( const Token& t ) { return regex_match( t, std::regex{ R"z((\d+(\.\d*)?|\.\d+)([Ee][\+\-]?\d+)?)z" } ); } bool is_operator ( const Token& t ) { return Operators.count( t ); } bool is_open_parenthesis ( const Token& t ) { return t == "("; } bool is_close_parenthesis( const Token& t ) { return t == ")"; } bool is_parenthesis ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); } template <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs ) { std::size_t n = 0; for (auto x : xs) outs << (n++ ? " " : "") << x; return outs; } #include <iomanip> struct Progressive_Display { string token_name; string token_type; Progressive_Display() { std::cout << "\n" " INPUT │ TYPE │ ACTION │ STACK │ OUTPUT\n" "────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\n"; } Progressive_Display& operator () ( const Token& token ) { token_name = token; token_type = is_operator ( token ) ? "op" : is_parenthesis( token ) ? "()" : is_number ( token ) ? "num" : ""; return *this; } Progressive_Display& operator () ( const string & description, const stack <Token> & stack, const vector <Token> & output ) { std::cout << std::right << std::setw( 7 ) << token_name << " │ " << std::left << std::setw( 4 ) << token_type << " │ " << std::setw( 16 ) << description << " │ " << std::setw( 12 ) << (std::ostringstream{} << stack).str() << " │ " << output << "\n"; return operator () ( "" ); } }; vector <Token> parse( const vector <Token> & tokens ) { vector <Token> output; stack <Token> stack; Progressive_Display display; for (auto token : tokens) if (is_number( token )) { output.push_back( token ); display( token )( "num --> output", stack, output ); } else if (is_operator( token ) or is_parenthesis( token )) { display( token ); if (!is_open_parenthesis( token )) { while (!stack.empty() and ( (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() )) or (precedence( stack.top() ) > precedence( token )) or ( (precedence( stack.top() ) == precedence( token )) and (associativity( token ) == Associates::left_to_right)))) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } if (is_close_parenthesis( token )) { stack.pop(); display( "pop", stack, output ); } } if (!is_close_parenthesis( token )) { stack.push( token ); display( "push op", stack, output ); } } else throw error( "unexpected token: ", token ); display( "END" ); while (!stack.empty()) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } return output; } int main( int argc, char** argv ) try { auto tokens = vector <Token> ( argv+1, argv+argc ); auto rpn_expr = parse( tokens ); std::cout << "\nInfix = " << tokens << "\nRPN = " << rpn_expr << "\n"; } catch (std::exception e) { std::cerr << "error: " << e.what() << "\n"; return 1; }
Module Module1 Class SymbolType Public ReadOnly symbol As String Public ReadOnly precedence As Integer Public ReadOnly rightAssociative As Boolean Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean) Me.symbol = symbol Me.precedence = precedence Me.rightAssociative = rightAssociative End Sub End Class ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From { {"^", New SymbolType("^", 4, True)}, {"*", New SymbolType("*", 3, False)}, {"/", New SymbolType("/", 3, False)}, {"+", New SymbolType("+", 2, False)}, {"-", New SymbolType("-", 2, False)} } Function ToPostfix(infix As String) As String Dim tokens = infix.Split(" ") Dim stack As New Stack(Of String) Dim output As New List(Of String) Dim Print = Sub(action As String) Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {String.Join(" ", stack.Reverse())} ]", $"out[ {String.Join(" ", output)} ]") For Each token In tokens Dim iv As Integer Dim op1 As SymbolType Dim op2 As SymbolType If Integer.TryParse(token, iv) Then output.Add(token) Print(token) ElseIf Operators.TryGetValue(token, op1) Then While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2) Dim c = op1.precedence.CompareTo(op2.precedence) If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then output.Add(stack.Pop()) Else Exit While End If End While stack.Push(token) Print(token) ElseIf token = "(" Then stack.Push(token) Print(token) ElseIf token = ")" Then Dim top = "" While stack.Count > 0 top = stack.Pop() If top <> "(" Then output.Add(top) Else Exit While End If End While If top <> "(" Then Throw New ArgumentException("No matching left parenthesis.") End If Print(token) End If Next While stack.Count > 0 Dim top = stack.Pop() If Not Operators.ContainsKey(top) Then Throw New ArgumentException("No matching right parenthesis.") End If output.Add(top) End While Print("pop") Return String.Join(" ", output) End Function Sub Main() Dim infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" Console.WriteLine(ToPostfix(infix)) End Sub End Module
Generate a VB translation of this C++ snippet without changing its computational steps.
#include <cassert> #include <chrono> #include <iomanip> #include <iostream> #include <numeric> #include <vector> bool is_prime(unsigned int n) { assert(n > 0 && n < 64); return (1ULL << n) & 0x28208a20a08a28ac; } template <typename Iterator> bool prime_triangle_row(Iterator begin, Iterator end) { if (std::distance(begin, end) == 2) return is_prime(*begin + *(begin + 1)); for (auto i = begin + 1; i + 1 != end; ++i) { if (is_prime(*begin + *i)) { std::iter_swap(i, begin + 1); if (prime_triangle_row(begin + 1, end)) return true; std::iter_swap(i, begin + 1); } } return false; } template <typename Iterator> void prime_triangle_count(Iterator begin, Iterator end, int& count) { if (std::distance(begin, end) == 2) { if (is_prime(*begin + *(begin + 1))) ++count; return; } for (auto i = begin + 1; i + 1 != end; ++i) { if (is_prime(*begin + *i)) { std::iter_swap(i, begin + 1); prime_triangle_count(begin + 1, end, count); std::iter_swap(i, begin + 1); } } } template <typename Iterator> void print(Iterator begin, Iterator end) { if (begin == end) return; auto i = begin; std::cout << std::setw(2) << *i++; for (; i != end; ++i) std::cout << ' ' << std::setw(2) << *i; std::cout << '\n'; } int main() { auto start = std::chrono::high_resolution_clock::now(); for (unsigned int n = 2; n < 21; ++n) { std::vector<unsigned int> v(n); std::iota(v.begin(), v.end(), 1); if (prime_triangle_row(v.begin(), v.end())) print(v.begin(), v.end()); } std::cout << '\n'; for (unsigned int n = 2; n < 21; ++n) { std::vector<unsigned int> v(n); std::iota(v.begin(), v.end(), 1); int count = 0; prime_triangle_count(v.begin(), v.end(), count); if (n > 2) std::cout << ' '; std::cout << count; } std::cout << '\n'; auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "\nElapsed time: " << duration.count() << " seconds\n"; }
Option Strict On Option Explicit On Imports System.IO Module vMain Public Const maxNumber As Integer = 20 Dim prime(2 * maxNumber) As Boolean Public Function countArrangements(ByVal n As Integer) As Integer If n < 2 Then Return 0 ElseIf n < 4 Then For i As Integer = 1 To n Console.Out.Write(i.ToString.PadLeft(3)) Next i Console.Out.WriteLine() Return 1 Else Dim printSolution As Boolean = true Dim used(n) As Boolean Dim number(n) As Integer For i As Integer = 0 To n - 1 number(i) = i Mod 2 Next i used(1) = True number(n) = n used(n) = True Dim count As Integer = 0 Dim p As Integer = 2 Do While p > 0 Dim p1 As Integer = number(p - 1) Dim current As Integer = number(p) Dim [next] As Integer = current + 2 Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next])) [next] += 2 Loop If [next] >= n Then [next] = 0 End If If p = n - 1 Then If [next] <> 0 Then If prime([next] + n) Then count += 1 If printSolution Then For i As Integer = 1 To n - 2 Console.Out.Write(number(i).ToString.PadLeft(3)) Next i Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3)) printSolution = False End If End If [next] = 0 End If p -= 1 End If If [next] <> 0 Then used(current) = False used([next]) = True number(p) = [next] p += 1 ElseIf p <= 2 Then p = 0 Else used(number(p)) = False number(p) = p Mod 2 p -= 1 End If Loop Return count End If End Function Public Sub Main prime(2) = True For i As Integer = 3 To UBound(prime) Step 2 prime(i) = True Next i For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2 If prime(i) Then For s As Integer = i * i To Ubound(prime) Step i + i prime(s) = False Next s End If Next i Dim arrangements(maxNumber) As Integer For n As Integer = 2 To UBound(arrangements) arrangements(n) = countArrangements(n) Next n For n As Integer = 2 To UBound(arrangements) Console.Out.Write(" " & arrangements(n)) Next n Console.Out.WriteLine() End Sub End Module
Keep all operations the same but rewrite the snippet in VB.
#include <iostream> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> int main( ) { std::vector<double> input( 11 ) , results( 11 ) ; std::cout << "Please enter 11 numbers!\n" ; for ( int i = 0 ; i < input.size( ) ; i++ ) std::cin >> input[i]; std::transform( input.begin( ) , input.end( ) , results.begin( ) , [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ; for ( int i = 10 ; i > -1 ; i-- ) { std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ; if ( results[ i ] > 400 ) std::cout << "too large!" ; else std::cout << results[ i ] << " !" ; std::cout << std::endl ; } return 0 ; }
Function tpk(s) arr = Split(s," ") For i = UBound(arr) To 0 Step -1 n = fx(CDbl(arr(i))) If n > 400 Then WScript.StdOut.WriteLine arr(i) & " = OVERFLOW" Else WScript.StdOut.WriteLine arr(i) & " = " & n End If Next End Function Function fx(x) fx = Sqr(Abs(x))+5*x^3 End Function WScript.StdOut.Write "Please enter a series of numbers:" list = WScript.StdIn.ReadLine tpk(list)
Please provide an equivalent version of this C++ code in VB.
#include <iostream> std::string middleThreeDigits(int n) { auto number = std::to_string(std::abs(n)); auto length = number.size(); if (length < 3) { return "less than three digits"; } else if (length % 2 == 0) { return "even number of digits"; } else { return number.substr(length / 2 - 1, 3); } } int main() { auto values {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}; for (auto&& v : values) { std::cout << "middleThreeDigits(" << v << "): " << middleThreeDigits(v) << "\n"; } }
Option Explicit Sub Main_Middle_three_digits() Dim Numbers, i& Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _ 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) For i = 0 To 16 Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i))) Next End Sub Function Middle3digits(strNb As String) As String If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1) If Len(strNb) < 3 Then Middle3digits = "Error ! Number of digits must be >= 3" ElseIf Len(strNb) Mod 2 = 0 Then Middle3digits = "Error ! Number of digits must be odd" Else Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3) End If End Function
Rewrite the snippet below in VB so it works the same as the original C++ code.
#include <iostream> #include <cctype> #include <functional> using namespace std; bool odd() { function<void ()> prev = []{}; while(true) { int c = cin.get(); if (!isalpha(c)) { prev(); cout.put(c); return c != '.'; } prev = [=] { cout.put(c); prev(); }; } } bool even() { while(true) { int c; cout.put(c = cin.get()); if (!isalpha(c)) return c != '.'; } } int main() { bool e = false; while( e ? odd() : even() ) e = !e; return 0; }
Private Function OddWordFirst(W As String) As String Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String count = 1 Do flag = Not flag l = FindNextPunct(i, W) - count + 1 If flag Then temp = temp & ExtractWord(W, count, l) Else temp = temp & ReverseWord(W, count, l) End If Loop While count < Len(W) OddWordFirst = temp End Function Private Function FindNextPunct(d As Integer, W As String) As Integer Const PUNCT As String = ",;:." Do d = d + 1 Loop While InStr(PUNCT, Mid(W, d, 1)) = 0 FindNextPunct = d End Function Private Function ExtractWord(W As String, c As Integer, i As Integer) As String ExtractWord = Mid(W, c, i) c = c + Len(ExtractWord) End Function Private Function ReverseWord(W As String, c As Integer, i As Integer) As String Dim temp As String, sep As String temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1) sep = Right(Mid(W, c, i), 1) ReverseWord = StrReverse(temp) & sep c = c + Len(ReverseWord) End Function
Change the programming language of this snippet from C++ to VB without modifying what it does.
#include <iostream> #include <iomanip> #include <algorithm> #include <vector> unsigned gcd( unsigned i, unsigned j ) { return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j; } void createSequence( std::vector<unsigned>& seq, int c ) { if( 1500 == seq.size() ) return; unsigned t = seq.at( c ) + seq.at( c + 1 ); seq.push_back( t ); seq.push_back( seq.at( c + 1 ) ); createSequence( seq, c + 1 ); } int main( int argc, char* argv[] ) { std::vector<unsigned> seq( 2, 1 ); createSequence( seq, 0 ); std::cout << "First fifteen members of the sequence:\n "; for( unsigned x = 0; x < 15; x++ ) { std::cout << seq[x] << " "; } std::cout << "\n\n"; for( unsigned x = 1; x < 11; x++ ) { std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x ); if( i != seq.end() ) { std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } } std::cout << "\n"; std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 ); if( i != seq.end() ) { std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } std::cout << "\n"; unsigned g; bool f = false; for( int x = 0, y = 1; x < 1000; x++, y++ ) { g = gcd( seq[x], seq[y] ); if( g != 1 ) f = true; std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", " << seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" ); } std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n"; return 0; }
Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Dim l As List(Of Integer) = {1, 1}.ToList() Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b) End Function Sub Main(ByVal args As String()) Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1, selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1 Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last() Console.Write("The first {0} items In the Stern-Brocot sequence: ", take) Console.WriteLine("{0}" & vbLf, String.Join(", ", l.Take(take))) Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:") For Each ii As Integer In selection Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1 Console.WriteLine("{0,3}: {1:n0}", ii, j) Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For Next Console.WriteLine("The greatest common divisor of all the two consecutive items of the" & " series up to the {0}th item is {1}always one.", max, If(good, "", "not ")) End Sub End Module
Port the provided C++ code into VB while preserving the original functionality.
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { double x, y; friend std::ostream& operator<<(std::ostream& os, const Point& p); }; std::ostream& operator<<(std::ostream& os, const Point& p) { auto f(std::cout.flags()); os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' '; std::cout.flags(f); return os; } struct Turtle { private: Point pos; double theta; bool tracing; public: Turtle() : theta(0.0), tracing(false) { pos.x = 0.0; pos.y = 0.0; } Turtle(double x, double y) : theta(0.0), tracing(false) { pos.x = x; pos.y = y; } Point position() { return pos; } void position(const Point& p) { pos = p; } double heading() { return theta; } void heading(double angle) { theta = angle; } void forward(double dist) { auto dx = dist * cos(theta); auto dy = dist * sin(theta); pos.x += dx; pos.y += dy; if (tracing) { std::cout << pos; } } void right(double angle) { theta -= angle; } void begin_fill() { if (!tracing) { std::cout << "<polygon points=\""; tracing = true; } } void end_fill() { if (tracing) { std::cout << "\"/>\n"; tracing = false; } } }; void pentagon(Turtle& turtle, double size) { turtle.right(degrees(36)); turtle.begin_fill(); for (size_t i = 0; i < 5; i++) { turtle.forward(size); turtle.right(degrees(72)); } turtle.end_fill(); } void sierpinski(int order, Turtle& turtle, double size) { turtle.heading(0.0); auto new_size = size * side_ratio; if (order-- > 1) { for (size_t j = 0; j < 4; j++) { turtle.right(degrees(36)); double small = size * side_ratio / part_ratio; auto distList = { small, size, size, small }; auto dist = *(distList.begin() + j); Turtle spawn{ turtle.position().x, turtle.position().y }; spawn.heading(turtle.heading()); spawn.forward(dist); sierpinski(order, spawn, new_size); } sierpinski(order, turtle, new_size); } else { pentagon(turtle, size); } if (order > 0) { std::cout << '\n'; } } int main() { const int order = 5; double size = 500; Turtle turtle{ size / 2.0, size }; std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n"; std::cout << "<!DOCTYPE svg PUBLIC \" - std::cout << " \"http: std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n"; std::cout << " version=\"1.1\" xmlns=\"http: size *= part_ratio; sierpinski(order, turtle, size); std::cout << "</svg>"; }
Private Sub sierpinski(Order_ As Integer, Side As Double) Dim Circumradius As Double, Inradius As Double Dim Height As Double, Diagonal As Double, HeightDiagonal As Double Dim Pi As Double, p(5) As String, Shp As Shape Circumradius = Sqr(50 + 10 * Sqr(5)) / 10 Inradius = Sqr(25 + 10 * Sqr(5)) / 10 Height = Circumradius + Inradius Diagonal = (1 + Sqr(5)) / 2 HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4 Pi = WorksheetFunction.Pi Ratio = Height / (2 * Height + HeightDiagonal) Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _ 2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side) p(0) = Shp.Name Shp.Rotation = 180 Shp.Line.Weight = 0 For j = 1 To Order_ For i = 0 To 4 Set Shp = Shp.Duplicate p(i + 1) = Shp.Name If i = 0 Then Shp.Rotation = 0 Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5) Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5) Shp.Visible = msoTrue Next i Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group p(0) = Shp.Name If j < Order_ Then Shp.ScaleHeight Ratio, False Shp.ScaleWidth Ratio, False Shp.Rotation = 180 Shp.Left = 2 * Side Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side End If Next j End Sub Public Sub main() sierpinski Order_:=5, Side:=200 End Sub
Rewrite this program in VB while keeping its functionality equivalent to the C++ version.
#include <string> #include <vector> #include <boost/regex.hpp> bool is_repstring( const std::string & teststring , std::string & repunit ) { std::string regex( "^(.+)\\1+(.*)$" ) ; boost::regex e ( regex ) ; boost::smatch what ; if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) { std::string firstbracket( what[1 ] ) ; std::string secondbracket( what[ 2 ] ) ; if ( firstbracket.length( ) >= secondbracket.length( ) && firstbracket.find( secondbracket ) != std::string::npos ) { repunit = firstbracket ; } } return !repunit.empty( ) ; } int main( ) { std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" , "1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ; std::string theRep ; for ( std::string myString : teststrings ) { if ( is_repstring( myString , theRep ) ) { std::cout << myString << " is a rep string! Here is a repeating string:\n" ; std::cout << theRep << " " ; } else { std::cout << myString << " is no rep string!" ; } theRep.clear( ) ; std::cout << std::endl ; } return 0 ; }
Function rep_string(s) max_len = Int(Len(s)/2) tmp = "" If max_len = 0 Then rep_string = "No Repeating String" Exit Function End If For i = 1 To max_len If InStr(i+1,s,tmp & Mid(s,i,1))Then tmp = tmp & Mid(s,i,1) Else Exit For End If Next Do While Len(tmp) > 0 If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then rep_string = tmp Exit Do Else tmp = Mid(tmp,1,Len(tmp)-1) End If Loop If Len(tmp) > 0 Then rep_string = tmp Else rep_string = "No Repeating String" End If End Function arr = Array("1001110011","1110111011","0010010010","1010101010",_ "1111111111","0100101101","0100100","101","11","00","1") For n = 0 To UBound(arr) WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n)) WScript.StdOut.WriteLine Next
Generate an equivalent VB version of this C++ code.
auto strA = R"(this is a newline-separated raw string)";
Debug.Print "Tom said, ""The fox ran away.""" Debug.Print "Tom said,
Port the provided C++ code into VB while preserving the original functionality.
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
Enum fruits apple banana cherry End Enum Enum fruits2 pear = 5 mango = 10 kiwi = 20 pineapple = 20 End Enum Sub test() Dim f As fruits f = apple Debug.Print "apple equals "; f Debug.Print "kiwi equals "; kiwi Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple End Sub
Can you help me rewrite this code in VB instead of C++, keeping it the same logically?
#include <boost/asio/ip/address.hpp> #include <cstdint> #include <iostream> #include <iomanip> #include <limits> #include <string> using boost::asio::ip::address; using boost::asio::ip::address_v4; using boost::asio::ip::address_v6; using boost::asio::ip::make_address; using boost::asio::ip::make_address_v4; using boost::asio::ip::make_address_v6; template<typename uint> bool parse_int(const std::string& str, int base, uint& n) { try { size_t pos = 0; unsigned long u = stoul(str, &pos, base); if (pos != str.length() || u > std::numeric_limits<uint>::max()) return false; n = static_cast<uint>(u); return true; } catch (const std::exception& ex) { return false; } } void parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) { size_t pos = input.rfind(':'); if (pos != std::string::npos && pos > 1 && pos + 1 < input.length() && parse_int(input.substr(pos + 1), 10, port) && port > 0) { if (input[0] == '[' && input[pos - 1] == ']') { addr = make_address_v6(input.substr(1, pos - 2)); return; } else { try { addr = make_address_v4(input.substr(0, pos)); return; } catch (const std::exception& ex) { } } } port = 0; addr = make_address(input); } void print_address_and_port(const address& addr, uint16_t port) { std::cout << std::hex << std::uppercase << std::setfill('0'); if (addr.is_v4()) { address_v4 addr4 = addr.to_v4(); std::cout << "address family: IPv4\n"; std::cout << "address number: " << std::setw(8) << addr4.to_uint() << '\n'; } else if (addr.is_v6()) { address_v6 addr6 = addr.to_v6(); address_v6::bytes_type bytes(addr6.to_bytes()); std::cout << "address family: IPv6\n"; std::cout << "address number: "; for (unsigned char byte : bytes) std::cout << std::setw(2) << static_cast<unsigned int>(byte); std::cout << '\n'; } if (port != 0) std::cout << "port: " << std::dec << port << '\n'; else std::cout << "port not specified\n"; } void test(const std::string& input) { std::cout << "input: " << input << '\n'; try { address addr; uint16_t port = 0; parse_ip_address_and_port(input, addr, port); print_address_and_port(addr, port); } catch (const std::exception& ex) { std::cout << "parsing failed\n"; } std::cout << '\n'; } int main(int argc, char** argv) { test("127.0.0.1"); test("127.0.0.1:80"); test("::ffff:127.0.0.1"); test("::1"); test("[::1]:80"); test("1::80"); test("2605:2700:0:3::4713:93e3"); test("[2605:2700:0:3::4713:93e3]:80"); return 0; }
Function parse_ip(addr) Set ipv4_pattern = New RegExp ipv4_pattern.Global = True ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}" Set ipv6_pattern = New RegExp ipv6_pattern.Global = True ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}" If ipv4_pattern.Test(addr) Then port = Split(addr,":") octet = Split(port(0),".") ipv4_hex = "" For i = 0 To UBound(octet) If octet(i) <= 255 And octet(i) >= 0 Then ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2) Else ipv4_hex = "Erroneous Address" Exit For End If Next parse_ip = "Test Case: " & addr & vbCrLf &_ "Address: " & ipv4_hex & vbCrLf If UBound(port) = 1 Then If port(1) <= 65535 And port(1) >= 0 Then parse_ip = parse_ip & "Port: " & port(1) & vbCrLf Else parse_ip = parse_ip & "Port: Invalid" & vbCrLf End If End If End If If ipv6_pattern.Test(addr) Then parse_ip = "Test Case: " & addr & vbCrLf port_v6 = "Port: " ipv6_hex = "" If InStr(1,addr,"[") Then port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1))) addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1)) End If word = Split(addr,":") word_count = 0 For i = 0 To UBound(word) If word(i) = "" Then If i < UBound(word) Then If Int((7-(i+1))/2) = 1 Then k = 1 ElseIf UBound(word) < 6 Then k = Int((7-(i+1))/2) ElseIf UBound(word) >= 6 Then k = Int((7-(i+1))/2)-1 End If For j = 0 To k ipv6_hex = ipv6_hex & "0000" word_count = word_count + 1 Next Else For j = 0 To (7-word_count) ipv6_hex = ipv6_hex & "0000" Next End If Else ipv6_hex = ipv6_hex & Right("0000" & word(i),4) word_count = word_count + 1 End If Next parse_ip = parse_ip & "Address: " & ipv6_hex &_ vbCrLf & port_v6 & vbCrLf End If If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then parse_ip = "Test Case: " & addr & vbCrLf &_ "Address: Invalid Address" & vbCrLf End If End Function ip_arr = Array("127.0.0.1","127.0.0.1:80","::1",_ "[::1]:80","2605:2700:0:3::4713:93e3","[2605:2700:0:3::4713:93e3]:80","RosettaCode") For n = 0 To UBound(ip_arr) WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf Next
Port the provided C++ code into VB while preserving the original functionality.
#include <fstream> #include <iostream> #include <unordered_map> #include <vector> struct Textonym_Checker { private: int total; int elements; int textonyms; int max_found; std::vector<std::string> max_strings; std::unordered_map<std::string, std::vector<std::string>> values; int get_mapping(std::string &result, const std::string &input) { static std::unordered_map<char, char> mapping = { {'A', '2'}, {'B', '2'}, {'C', '2'}, {'D', '3'}, {'E', '3'}, {'F', '3'}, {'G', '4'}, {'H', '4'}, {'I', '4'}, {'J', '5'}, {'K', '5'}, {'L', '5'}, {'M', '6'}, {'N', '6'}, {'O', '6'}, {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'}, {'T', '8'}, {'U', '8'}, {'V', '8'}, {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'} }; result = input; for (char &c : result) { if (!isalnum(c)) return 0; if (isalpha(c)) c = mapping[toupper(c)]; } return 1; } public: Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { } ~Textonym_Checker() { } void add(const std::string &str) { std::string mapping; total++; if (!get_mapping(mapping, str)) return; const int num_strings = values[mapping].size(); if (num_strings == 1) textonyms++; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.push_back(mapping); max_found = num_strings; } else if (num_strings == max_found) max_strings.push_back(mapping); values[mapping].push_back(str); } void results(const std::string &filename) { std::cout << "Read " << total << " words from " << filename << "\n\n"; std::cout << "There are " << elements << " words in " << filename; std::cout << " which can be represented by the digit key mapping.\n"; std::cout << "They require " << values.size() << " digit combinations to represent them.\n"; std::cout << textonyms << " digit combinations represent Textonyms.\n\n"; std::cout << "The numbers mapping to the most words map to "; std::cout << max_found + 1 << " words each:\n"; for (auto it1 : max_strings) { std::cout << '\t' << it1 << " maps to: "; for (auto it2 : values[it1]) std::cout << it2 << " "; std::cout << '\n'; } std::cout << '\n'; } void match(const std::string &str) { auto match = values.find(str); if (match == values.end()) { std::cout << "Key '" << str << "' not found\n"; } else { std::cout << "Key '" << str << "' matches: "; for (auto it : values[str]) std::cout << it << " "; std::cout << '\n'; } } }; int main() { auto filename = "unixdict.txt"; std::ifstream input(filename); Textonym_Checker tc; if (input.is_open()) { std::string line; while (getline(input, line)) tc.add(line); } input.close(); tc.results(filename); tc.match("001"); tc.match("228"); tc.match("27484247"); tc.match("7244967473642"); }
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1) Set objKeyMap = CreateObject("Scripting.Dictionary") With objKeyMap .Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5" .Add "MNO", "6" : .Add "PQRS", "7" : .Add "TUV", "8" : .Add "WXYZ", "9" End With TotalWords = 0 UniqueCombinations = 0 Set objUniqueWords = CreateObject("Scripting.Dictionary") Set objMoreThanOneWord = CreateObject("Scripting.Dictionary") Do Until objInFile.AtEndOfStream Word = objInFile.ReadLine c = 0 Num = "" If Word <> "" Then For i = 1 To Len(Word) For Each Key In objKeyMap.Keys If InStr(1,Key,Mid(Word,i,1),1) > 0 Then Num = Num & objKeyMap.Item(Key) c = c + 1 End If Next Next If c = Len(Word) Then TotalWords = TotalWords + 1 If objUniqueWords.Exists(Num) = False Then objUniqueWords.Add Num, "" UniqueCombinations = UniqueCombinations + 1 Else If objMoreThanOneWord.Exists(Num) = False Then objMoreThanOneWord.Add Num, "" End If End If End If End If Loop WScript.Echo "There are " & TotalWords & " words in ""unixdict.txt"" which can be represented by the digit key mapping." & vbCrLf &_ "They require " & UniqueCombinations & " digit combinations to represent them." & vbCrLf &_ objMoreThanOneWord.Count & " digit combinations represent Textonyms." objInFile.Close
Preserve the algorithm and functionality while converting the code from C++ to VB.
#include <iostream> #include <iterator> #include <cstddef> template<typename InIter> void extract_ranges(InIter begin, InIter end, std::ostream& os) { if (begin == end) return; int current = *begin++; os << current; int count = 1; while (begin != end) { int next = *begin++; if (next == current+1) ++count; else { if (count > 2) os << '-'; else os << ','; if (count > 1) os << current << ','; os << next; count = 1; } current = next; } if (count > 1) os << (count > 2? '-' : ',') << current; } template<typename T, std::size_t n> T* end(T (&array)[n]) { return array+n; } int main() { int data[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; extract_ranges(data, end(data), std::cout); std::cout << std::endl; }
Public Function RangeExtraction(AList) As String Const RangeDelim = "-" Dim result As String Dim InRange As Boolean Dim Posn, ub, lb, rangestart, rangelen As Integer result = "" ub = UBound(AList) lb = LBound(AList) Posn = lb While Posn < ub rangestart = Posn rangelen = 0 InRange = True While InRange rangelen = rangelen + 1 If Posn = ub Then InRange = False Else InRange = (AList(Posn + 1) = AList(Posn) + 1) Posn = Posn + 1 End If Wend If rangelen > 2 Then result = result & "," & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1)) Else For i = rangestart To rangestart + rangelen - 1 result = result & "," & Format$(AList(i)) Next End If Posn = rangestart + rangelen Wend RangeExtraction = Mid$(result, 2) End Function Public Sub RangeTest() Dim MyList As Variant MyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39) Debug.Print "a) "; RangeExtraction(MyList) Dim MyOtherList(1 To 20) As Integer MyOtherList(1) = -6 MyOtherList(2) = -3 MyOtherList(3) = -2 MyOtherList(4) = -1 MyOtherList(5) = 0 MyOtherList(6) = 1 MyOtherList(7) = 3 MyOtherList(8) = 4 MyOtherList(9) = 5 MyOtherList(10) = 7 MyOtherList(11) = 8 MyOtherList(12) = 9 MyOtherList(13) = 10 MyOtherList(14) = 11 MyOtherList(15) = 14 MyOtherList(16) = 15 MyOtherList(17) = 17 MyOtherList(18) = 18 MyOtherList(19) = 19 MyOtherList(20) = 20 Debug.Print "b) "; RangeExtraction(MyOtherList) End Sub
Convert this C++ snippet to VB and keep its semantics consistent.
#include <iostream> template <typename T> auto typeString(const T&) { return typeid(T).name(); } class C {}; struct S {}; int main() { std::cout << typeString(1) << '\n'; std::cout << typeString(1L) << '\n'; std::cout << typeString(1.0f) << '\n'; std::cout << typeString(1.0) << '\n'; std::cout << typeString('c') << '\n'; std::cout << typeString("string") << '\n'; std::cout << typeString(C{}) << '\n'; std::cout << typeString(S{}) << '\n'; std::cout << typeString(nullptr) << '\n'; }
Public Sub main() Dim c(1) As Currency Dim d(1) As Double Dim dt(1) As Date Dim a(1) As Integer Dim l(1) As Long Dim s(1) As Single Dim e As Variant Dim o As Object Set o = New Application Debug.Print TypeName(o) Debug.Print TypeName(1 = 1) Debug.Print TypeName(CByte(1)) Set o = New Collection Debug.Print TypeName(o) Debug.Print TypeName(1@) Debug.Print TypeName(c) Debug.Print TypeName(CDate(1)) Debug.Print TypeName(dt) Debug.Print TypeName(CDec(1)) Debug.Print TypeName(1#) Debug.Print TypeName(d) Debug.Print TypeName(e) Debug.Print TypeName(CVErr(1)) Debug.Print TypeName(1) Debug.Print TypeName(a) Debug.Print TypeName(1&) Debug.Print TypeName(l) Set o = Nothing Debug.Print TypeName(o) Debug.Print TypeName([A1]) Debug.Print TypeName(1!) Debug.Print TypeName(s) Debug.Print TypeName(CStr(1)) Debug.Print TypeName(Worksheets(1)) End Sub
Write a version of this C++ function in VB with identical behavior.
#include <iostream> int main( int argc, char* argv[] ) { int triangle[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; const int size = sizeof( triangle ) / sizeof( int ); const int tn = static_cast<int>(sqrt(2.0 * size)); assert(tn * (tn + 1) == 2 * size); for (int n = tn - 1; n > 0; --n) for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]); std::cout << "Maximum total: " << triangle[0] << "\n\n"; }
Set objfso = CreateObject("Scripting.FileSystemObject") Set objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\triangle.txt",1,False) row = Split(objinfile.ReadAll,vbCrLf) For i = UBound(row) To 0 Step -1 row(i) = Split(row(i)," ") If i < UBound(row) Then For j = 0 To UBound(row(i)) If (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j)) Else row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1)) End If Next End If Next WScript.Echo row(0)(0) objinfile.Close Set objfso = Nothing
Change the following C++ code into VB without altering its purpose.
#include <iostream> #include <string> #include <sstream> #include <valarray> const std::string input { "................................" ".#########.......########......." ".###...####.....####..####......" ".###....###.....###....###......" ".###...####.....###............." ".#########......###............." ".###.####.......###....###......" ".###..####..###.####..####.###.." ".###...####.###..########..###.." "................................" }; const std::string input2 { ".........................................................." ".#################...................#############........" ".##################...............################........" ".###################............##################........" ".########.....#######..........###################........" "...######.....#######.........#######.......######........" "...######.....#######........#######......................" "...#################.........#######......................" "...################..........#######......................" "...#################.........#######......................" "...######.....#######........#######......................" "...######.....#######........#######......................" "...######.....#######.........#######.......######........" ".########.....#######..........###################........" ".########.....#######.######....##################.######." ".########.....#######.######......################.######." ".########.....#######.######.........#############.######." ".........................................................." }; class ZhangSuen; class Image { public: friend class ZhangSuen; using pixel_t = char; static const pixel_t BLACK_PIX; static const pixel_t WHITE_PIX; Image(unsigned width = 1, unsigned height = 1) : width_{width}, height_{height}, data_( '\0', width_ * height_) {} Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_} {} Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)} {} ~Image() = default; Image& operator=(const Image& i) { if (this != &i) { width_ = i.width_; height_ = i.height_; data_ = i.data_; } return *this; } Image& operator=(Image&& i) { if (this != &i) { width_ = i.width_; height_ = i.height_; data_ = std::move(i.data_); } return *this; } size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; } bool operator()(unsigned x, unsigned y) { return data_[idx(x, y)]; } friend std::ostream& operator<<(std::ostream& o, const Image& i) { o << i.width_ << " x " << i.height_ << std::endl; size_t px = 0; for(const auto& e : i.data_) { o << (e?Image::BLACK_PIX:Image::WHITE_PIX); if (++px % i.width_ == 0) o << std::endl; } return o << std::endl; } friend std::istream& operator>>(std::istream& in, Image& img) { auto it = std::begin(img.data_); const auto end = std::end(img.data_); Image::pixel_t tmp; while(in && it != end) { in >> tmp; if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX) throw "Bad character found in image"; *it = (tmp == Image::BLACK_PIX)?1:0; ++it; } return in; } unsigned width() const noexcept { return width_; } unsigned height() const noexcept { return height_; } struct Neighbours { Neighbours(const Image& img, unsigned p1_x, unsigned p1_y) : img_{img} , p1_{img.idx(p1_x, p1_y)} , p2_{p1_ - img.width()} , p3_{p2_ + 1} , p4_{p1_ + 1} , p5_{p4_ + img.width()} , p6_{p5_ - 1} , p7_{p6_ - 1} , p8_{p1_ - 1} , p9_{p2_ - 1} {} const Image& img_; const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; } const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; } const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; } const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; } const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; } const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; } const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; } const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; } const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; } const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_; }; Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); } private: unsigned height_ { 0 }; unsigned width_ { 0 }; std::valarray<pixel_t> data_; }; constexpr const Image::pixel_t Image::BLACK_PIX = '#'; constexpr const Image::pixel_t Image::WHITE_PIX = '.'; class ZhangSuen { public: unsigned transitions_white_black(const Image::Neighbours& a) const { unsigned sum = 0; sum += (a.p9() == 0) && a.p2(); sum += (a.p2() == 0) && a.p3(); sum += (a.p3() == 0) && a.p4(); sum += (a.p8() == 0) && a.p9(); sum += (a.p4() == 0) && a.p5(); sum += (a.p7() == 0) && a.p8(); sum += (a.p6() == 0) && a.p7(); sum += (a.p5() == 0) && a.p6(); return sum; } unsigned black_pixels(const Image::Neighbours& a) const { unsigned sum = 0; sum += a.p9(); sum += a.p2(); sum += a.p3(); sum += a.p8(); sum += a.p4(); sum += a.p7(); sum += a.p6(); sum += a.p5(); return sum; } const Image& operator()(const Image& img) { tmp_a_ = img; size_t changed_pixels = 0; do { changed_pixels = 0; tmp_b_ = tmp_a_; for(size_t y = 1; y < tmp_a_.height() - 1; ++y) { for(size_t x = 1; x < tmp_a_.width() - 1; ++x) { if (tmp_a_.data_[tmp_a_.idx(x, y)]) { auto n = tmp_a_.neighbours(x, y); auto bp = black_pixels(n); if (bp >= 2 && bp <= 6) { auto tr = transitions_white_black(n); if ( tr == 1 && (n.p2() * n.p4() * n.p6() == 0) && (n.p4() * n.p6() * n.p8() == 0) ) { tmp_b_.data_[n.p1_] = 0; ++changed_pixels; } } } } } tmp_a_ = tmp_b_; for(size_t y = 1; y < tmp_b_.height() - 1; ++y) { for(size_t x = 1; x < tmp_b_.width() - 1; ++x) { if (tmp_b_.data_[tmp_b_.idx(x, y)]) { auto n = tmp_b_.neighbours(x, y); auto bp = black_pixels(n); if (bp >= 2 && bp <= 6) { auto tr = transitions_white_black(n); if ( tr == 1 && (n.p2() * n.p4() * n.p8() == 0) && (n.p2() * n.p6() * n.p8() == 0) ) { tmp_a_.data_[n.p1_] = 0; ++changed_pixels; } } } } } } while(changed_pixels > 0); return tmp_a_; } private: Image tmp_a_; Image tmp_b_; }; int main(int argc, char const *argv[]) { using namespace std; Image img(32, 10); istringstream iss{input}; iss >> img; cout << img; cout << "ZhangSuen" << endl; ZhangSuen zs; Image res = std::move(zs(img)); cout << res << endl; Image img2(58,18); istringstream iss2{input2}; iss2 >> img2; cout << img2; cout << "ZhangSuen with big image" << endl; Image res2 = std::move(zs(img2)); cout << res2 << endl; return 0; }
Public n As Variant Private Sub init() n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}] End Sub Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant Dim wtb As Integer Dim bn As Integer Dim prev As String: prev = "#" Dim next_ As String Dim p2468 As String For i = 1 To UBound(n) next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1) wtb = wtb - (prev = "." And next_ <= "#") bn = bn - (i > 1 And next_ <= "#") If (i And 1) = 0 Then p2468 = p2468 & prev prev = next_ Next i If step = 2 Then p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2) End If Dim ret(2) As Variant ret(0) = wtb ret(1) = bn ret(2) = p2468 AB = ret End Function Private Sub Zhang_Suen(text As Variant) Dim wtb As Integer Dim bn As Integer Dim changed As Boolean, changes As Boolean Dim p2468 As String Dim x As Integer, y As Integer, step As Integer Do While True changed = False For step = 1 To 2 changes = False For y = 1 To UBound(text) - 1 For x = 2 To Len(text(y)) - 1 If Mid(text(y), x, 1) = "#" Then ret = AB(text, y, x, step) wtb = ret(0) bn = ret(1) p2468 = ret(2) If wtb = 1 _ And bn >= 2 And bn <= 6 _ And InStr(1, Mid(p2468, 1, 3), ".") _ And InStr(1, Mid(p2468, 2, 3), ".") Then changes = True text(y) = Left(text(y), x - 1) & "!" & Right(text(y), Len(text(y)) - x) End If End If Next x Next y If changes Then For y = 1 To UBound(text) - 1 text(y) = Replace(text(y), "!", ".") Next y changed = True End If Next step If Not changed Then Exit Do Loop Debug.Print Join(text, vbCrLf) End Sub Public Sub main() init Dim Small_rc(9) As String Small_rc(0) = "................................" Small_rc(1) = ".#########.......########......." Small_rc(2) = ".###...####.....####..####......" Small_rc(3) = ".###....###.....###....###......" Small_rc(4) = ".###...####.....###............." Small_rc(5) = ".#########......###............." Small_rc(6) = ".###.####.......###....###......" Small_rc(7) = ".###..####..###.####..####.###.." Small_rc(8) = ".###...####.###..########..###.." Small_rc(9) = "................................" Zhang_Suen (Small_rc) End Sub
Ensure the translated VB code behaves exactly like the original C++ snippet.
#include <array> #include <iostream> int main() { constexpr std::array s {1,2,2,3,4,4,5}; if(!s.empty()) { int previousValue = s[0]; for(size_t i = 1; i < s.size(); ++i) { const int currentValue = s[i]; if(i > 0 && previousValue == currentValue) { std::cout << i << "\n"; } previousValue = currentValue; } } }
Option Strict On Option Explicit On Imports System.IO Module vMain Public Sub Main Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5} For i As Integer = 0 To Ubound(s) Dim curr As Integer = s(i) Dim prev As Integer If i > 1 AndAlso curr = prev Then Console.Out.WriteLine(i) End If prev = curr Next i End Sub End Module
Convert this C++ block to VB, preserving its control flow and logic.
#include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; struct point { double x; double y; }; std::vector<point> koch_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(4*(size - 1) + 1); double x0, y0, x1, y1; size_t j = 0; for (size_t i = 0; i + 1 < size; ++i) { x0 = points[i].x; y0 = points[i].y; x1 = points[i + 1].x; y1 = points[i + 1].y; double dy = y1 - y0; double dx = x1 - x0; output[j++] = {x0, y0}; output[j++] = {x0 + dx/3, y0 + dy/3}; output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3}; output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3}; } output[j] = {x1, y1}; return output; } std::vector<point> koch_points(int size, int iterations) { double length = size * sqrt3_2 * 0.95; double x = (size - length)/2; double y = size/2 - length * sqrt3_2/3; std::vector<point> points{ {x, y}, {x + length/2, y + length * sqrt3_2}, {x + length, y}, {x, y} }; for (int i = 0; i < iterations; ++i) points = koch_next(points); return points; } void koch_curve_svg(std::ostream& out, int size, int iterations) { out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << "<path stroke-width='1' stroke='white' fill='none' d='"; auto points(koch_points(size, iterations)); for (size_t i = 0, n = points.size(); i < n; ++i) out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n'; out << "z'/>\n</svg>\n"; } int main() { std::ofstream out("koch_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } koch_curve_svg(out, 600, 5); return EXIT_SUCCESS; }
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public property let iangle(n):iang= n*pi180 :end property public sub pd() : pdown=true: end sub public sub pu() :pdown=FALSE :end sub public sub rt(i) ori=ori - i*iang: if ori<0 then ori = ori+pi*2 end sub public sub lt(i): ori=(ori + i*iang) if ori>(pi*2) then ori=ori-pi*2 end sub public sub bw(l) x= x+ cos(ori+pi)*l*incr y= y+ sin(ori+pi)*l*incr end sub public sub fw(l) dim x1,y1 x1=x + cos(ori)*l*incr y1=y + sin(ori)*l*incr if pdown then line x,y,x1,y1 x=x1:y=y1 end sub Private Sub Class_Initialize() setlocale "us" initsvg pdown=true end sub Private Sub Class_Terminate() disply end sub private sub line (x,y,x1,y1) svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>" end sub private sub disply() dim shell svg.WriteLine "</svg></body></html>" svg.close Set shell = CreateObject("Shell.Application") shell.ShellExecute fn,1,False end sub private sub initsvg() dim scriptpath Set fso = CreateObject ("Scripting.Filesystemobject") ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) fn=Scriptpath & "SIERP.HTML" Set svg = fso.CreateTextFile(fn,True) if SVG IS nothing then wscript.echo "Can svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>" svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>" svg.writeline "</head>"&vbcrlf & "<body>" svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" end sub end class sub koch (n,le) if n=0 then x.fw le :exit sub koch n-1, le/3 x.lt 1 koch n-1, le/3 x.rt 2 koch n-1, le/3 x.lt 1 koch n-1, le/3 end sub dim x,i set x=new turtle x.iangle=60 x.orient=0 x.incr=3 x.x=100:x.y=300 for i=0 to 3 koch 7,100 x.rt 2 next set x=nothing
Convert the following code from C++ to VB, ensuring the logic remains intact.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int main(int argc, char** argv) { const int min_length = 9; const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string line; std::vector<std::string> words; while (getline(in, line)) { if (line.size() >= min_length) words.push_back(line); } std::sort(words.begin(), words.end()); std::string previous_word; int count = 0; for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) { std::string word; word.reserve(min_length); for (size_t j = 0; j < min_length; ++j) word += words[i + j][j]; if (previous_word == word) continue; auto w = std::lower_bound(words.begin(), words.end(), word); if (w != words.end() && *w == word) std::cout << std::setw(2) << ++count << ". " << word << '\n'; previous_word = word; } return EXIT_SUCCESS; }
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) set d=createobject("scripting.dictionary") redim b(ubound(a)) i=0 for each x in a s=trim(x) if len(s)>=9 then if len(s)= 9 then d.add s,"" b(i)=s i=i+1 end if next redim preserve b(i-1) wscript.echo i j=1 for i=0 to ubound(b)-9 s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_ mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1) if d.exists(s9) then wscript.echo j,s9 d.remove(s9) j=j+1 end if next
Convert this C++ snippet to VB and keep its semantics consistent.
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr( int d ) { while( d % 4 > 0 ) { d++; } sz = d; sqr = new int[sz * sz]; fillSqr(); } ~magicSqr() { delete [] sqr; } void display() const { cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) { cout << setw( l + 2 ) << sqr[yy + x]; } cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } }; int i = 0; for( int curRow = 0; curRow < sz; curRow++ ) { for( int curCol = 0; curCol < sz; curCol++ ) { sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i; i++; } } } int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s( 8 ); s.display(); return 0; }
n=8 pattern="1001011001101001" size=n*n: w=len(size) mult=n\4 wscript.echo "Magic square : " & n & " x " & n i=0 For r=0 To n-1 l="" For c=0 To n-1 bit=Mid(pattern, c\mult+(r\mult)*4+1, 1) If bit="1" Then t=i+1 Else t=size-i l=l & Right(Space(w) & t, w) & " " i=i+1 Next wscript.echo l Next wscript.echo "Magic constant=" & (n*n+1)*n/2
Maintain the same structure and functionality when rewriting this code in VB.
#include <iostream> #include <iterator> #include <sstream> #include <vector> using namespace std; class MTF { public: string encode( string str ) { fillSymbolTable(); vector<int> output; for( string::iterator it = str.begin(); it != str.end(); it++ ) { for( int i = 0; i < 26; i++ ) { if( *it == symbolTable[i] ) { output.push_back( i ); moveToFront( i ); break; } } } string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { ostringstream ss; ss << *it; r += ss.str() + " "; } return r; } string decode( string str ) { fillSymbolTable(); istringstream iss( str ); vector<int> output; copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) ); string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { r.append( 1, symbolTable[*it] ); moveToFront( *it ); } return r; } private: void moveToFront( int i ) { char t = symbolTable[i]; for( int z = i - 1; z >= 0; z-- ) symbolTable[z + 1] = symbolTable[z]; symbolTable[0] = t; } void fillSymbolTable() { for( int x = 0; x < 26; x++ ) symbolTable[x] = x + 'a'; } char symbolTable[26]; }; int main() { MTF mtf; string a, str[] = { "broood", "bananaaa", "hiphophiphop" }; for( int x = 0; x < 3; x++ ) { a = str[x]; cout << a << " -> encoded = "; a = mtf.encode( a ); cout << a << "; decoded = " << mtf.decode( a ) << endl; } return 0; }
Function mtf_encode(s) Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 symbol_table.Add Chr(j) Next output = "" For i = 1 To Len(s) char = Mid(s,i,1) If i = Len(s) Then output = output & symbol_table.IndexOf(char,0) symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char Else output = output & symbol_table.IndexOf(char,0) & " " symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char End If Next mtf_encode = output End Function Function mtf_decode(s) code = Split(s," ") Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 symbol_table.Add Chr(j) Next output = "" For i = 0 To UBound(code) char = symbol_table(code(i)) output = output & char If code(i) <> 0 Then symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char End If Next mtf_decode = output End Function wordlist = Array("broood","bananaaa","hiphophiphop") For Each word In wordlist WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_ mtf_decode(mtf_encode(word)) & "." WScript.StdOut.WriteBlankLines(1) Next
Port the following code from C++ to VB with equivalent syntax and logic.
#include <vector> #include <list> #include <algorithm> #include <iostream> template <typename T> struct Node { T value; Node* prev_node; }; template <typename Container> Container lis(const Container& values) { using E = typename Container::value_type; using NodePtr = Node<E>*; using ConstNodePtr = const NodePtr; std::vector<NodePtr> pileTops; std::vector<Node<E>> nodes(values.size()); auto cur_node = std::begin(nodes); for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node) { auto node = &*cur_node; node->value = *cur_value; auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node, [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; }); if (lb != pileTops.begin()) node->prev_node = *std::prev(lb); if (lb == pileTops.end()) pileTops.push_back(node); else *lb = node; } Container result(pileTops.size()); auto r = std::rbegin(result); for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r) *r = node->value; return result; } template <typename Container> void show_lis(const Container& values) { auto&& result = lis(values); for (auto& r : result) { std::cout << r << ' '; } std::cout << std::endl; } int main() { show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 }); show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }); }
Function LIS(arr) n = UBound(arr) Dim p() ReDim p(n) Dim m() ReDim m(n) l = 0 For i = 0 To n lo = 1 hi = l Do While lo <= hi middle = Int((lo+hi)/2) If arr(m(middle)) < arr(i) Then lo = middle + 1 Else hi = middle - 1 End If Loop newl = lo p(i) = m(newl-1) m(newl) = i If newL > l Then l = newl End If Next Dim s() ReDim s(l) k = m(l) For i = l-1 To 0 Step - 1 s(i) = arr(k) k = p(k) Next LIS = Join(s,",") End Function WScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1)) WScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))
Rewrite this program in VB while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> namespace detail { template <typename ForwardIterator> class tokenizer { ForwardIterator _tbegin, _tend, _end; public: tokenizer(ForwardIterator begin, ForwardIterator end) : _tbegin(begin), _tend(begin), _end(end) { } template <typename Lambda> bool next(Lambda istoken) { if (_tbegin == _end) { return false; } _tbegin = _tend; for (; _tend != _end && !istoken(*_tend); ++_tend) { if (*_tend == '\\' && std::next(_tend) != _end) { ++_tend; } } if (_tend == _tbegin) { _tend++; } return _tbegin != _end; } ForwardIterator begin() const { return _tbegin; } ForwardIterator end() const { return _tend; } bool operator==(char c) { return *_tbegin == c; } }; template <typename List> void append_all(List & lista, const List & listb) { if (listb.size() == 1) { for (auto & a : lista) { a += listb.back(); } } else { List tmp; for (auto & a : lista) { for (auto & b : listb) { tmp.push_back(a + b); } } lista = std::move(tmp); } } template <typename String, typename List, typename Tokenizer> List expand(Tokenizer & token) { std::vector<List> alts{ { String() } }; while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) { if (token == '{') { append_all(alts.back(), expand<String, List>(token)); } else if (token == ',') { alts.push_back({ String() }); } else if (token == '}') { if (alts.size() == 1) { for (auto & a : alts.back()) { a = '{' + a + '}'; } return alts.back(); } else { for (std::size_t i = 1; i < alts.size(); i++) { alts.front().insert(alts.front().end(), std::make_move_iterator(std::begin(alts[i])), std::make_move_iterator(std::end(alts[i]))); } return std::move(alts.front()); } } else { for (auto & a : alts.back()) { a.append(token.begin(), token.end()); } } } List result{ String{ '{' } }; append_all(result, alts.front()); for (std::size_t i = 1; i < alts.size(); i++) { for (auto & a : result) { a += ','; } append_all(result, alts[i]); } return result; } } template < typename ForwardIterator, typename String = std::basic_string< typename std::iterator_traits<ForwardIterator>::value_type >, typename List = std::vector<String> > List expand(ForwardIterator begin, ForwardIterator end) { detail::tokenizer<ForwardIterator> token(begin, end); List list{ String() }; while (token.next([](char c) { return c == '{'; })) { if (token == '{') { detail::append_all(list, detail::expand<String, List>(token)); } else { for (auto & a : list) { a.append(token.begin(), token.end()); } } } return list; } template < typename Range, typename String = std::basic_string<typename Range::value_type>, typename List = std::vector<String> > List expand(const Range & range) { using Iterator = typename Range::const_iterator; return expand<Iterator, String, List>(std::begin(range), std::end(range)); } int main() { for (std::string string : { R"(~/{Downloads,Pictures}/*.{jpg,gif,png})", R"(It{{em,alic}iz,erat}e{d,}, please.)", R"({,{,gotta have{ ,\, again\, }}more }cowbell!)", R"({}} some {\\{edge,edgy} }{ cases, here\\\})", R"(a{b{1,2}c)", R"(a{1,2}b}c)", R"(a{1,{2},3}b)", R"(a{b{1,2}c{}})", R"(more{ darn{ cowbell,},})", R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)", R"({a,{\,b}c)", R"(a{b,{{c}})", R"({a{\}b,c}d)", R"({a,b{{1,2}e}f)", R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})", R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)", }) { std::cout << string << '\n'; for (auto expansion : expand(string)) { std::cout << " " << expansion << '\n'; } std::cout << '\n'; } return 0; }
Module Module1 Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String) Dim out As New List(Of String) Dim comma = False While Not String.IsNullOrEmpty(s) Dim gs = GetItem(s, depth) Dim g = gs.Item1 s = gs.Item2 If String.IsNullOrEmpty(s) Then Exit While End If out.AddRange(g) If s(0) = "}" Then If comma Then Return Tuple.Create(out, s.Substring(1)) End If Return Tuple.Create(out.Select(Function(a) "{" + a + "}").ToList(), s.Substring(1)) End If If s(0) = "," Then comma = True s = s.Substring(1) End If End While Return Nothing End Function Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String) Dim out As New List(Of String) From {""} While Not String.IsNullOrEmpty(s) Dim c = s(0) If depth > 0 AndAlso (c = "," OrElse c = "}") Then Return Tuple.Create(out, s) End If If c = "{" Then Dim x = GetGroup(s.Substring(1), depth + 1) If Not IsNothing(x) Then Dim tout As New List(Of String) For Each a In out For Each b In x.Item1 tout.Add(a + b) Next Next out = tout s = x.Item2 Continue While End If End If If c = "\" AndAlso s.Length > 1 Then c += s(1) s = s.Substring(1) End If out = out.Select(Function(a) a + c).ToList() s = s.Substring(1) End While Return Tuple.Create(out, s) End Function Sub Main() For Each s In { "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\, again\, }}more }cowbell!", "{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}" } Dim fmt = "{0}" + vbNewLine + vbTab + "{1}" Dim parts = GetItem(s) Dim res = String.Join(vbNewLine + vbTab, parts.Item1) Console.WriteLine(fmt, s, res) Next End Sub End Module
Convert this C++ block to VB, preserving its control flow and logic.
#ifndef INTERACTION_H #define INTERACTION_H #include <QWidget> class QPushButton ; class QLineEdit ; class QVBoxLayout ; class MyWidget : public QWidget { Q_OBJECT public : MyWidget( QWidget *parent = 0 ) ; private : QLineEdit *entryField ; QPushButton *increaseButton ; QPushButton *randomButton ; QVBoxLayout *myLayout ; private slots : void doIncrement( ) ; void findRandomNumber( ) ; } ; #endif
VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 2265 ClientLeft = 60 ClientTop = 600 ClientWidth = 2175 LinkTopic = "Form1" ScaleHeight = 2265 ScaleWidth = 2175 StartUpPosition = 3 Begin VB.CommandButton cmdRnd Caption = "Random" Height = 495 Left = 120 TabIndex = 2 Top = 1680 Width = 1215 End Begin VB.CommandButton cmdInc Caption = "Increment" Height = 495 Left = 120 TabIndex = 1 Top = 1080 Width = 1215 End Begin VB.TextBox txtValue Height = 495 Left = 120 TabIndex = 0 Text = "0" Top = 240 Width = 1215 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private Sub Form_Load() Randomize Timer End Sub Private Sub cmdRnd_Click() If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11) End Sub Private Sub cmdInc_Click() If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1 End Sub Private Sub txtValue_KeyPress(KeyAscii As Integer) Select Case KeyAscii Case 8, 43, 45, 48 To 57 Case Else KeyAscii = 0 End Select End Sub
Produce a functionally identical VB code for the snippet given in C++.
#ifndef INTERACTION_H #define INTERACTION_H #include <QWidget> class QPushButton ; class QLineEdit ; class QVBoxLayout ; class MyWidget : public QWidget { Q_OBJECT public : MyWidget( QWidget *parent = 0 ) ; private : QLineEdit *entryField ; QPushButton *increaseButton ; QPushButton *randomButton ; QVBoxLayout *myLayout ; private slots : void doIncrement( ) ; void findRandomNumber( ) ; } ; #endif
VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 2265 ClientLeft = 60 ClientTop = 600 ClientWidth = 2175 LinkTopic = "Form1" ScaleHeight = 2265 ScaleWidth = 2175 StartUpPosition = 3 Begin VB.CommandButton cmdRnd Caption = "Random" Height = 495 Left = 120 TabIndex = 2 Top = 1680 Width = 1215 End Begin VB.CommandButton cmdInc Caption = "Increment" Height = 495 Left = 120 TabIndex = 1 Top = 1080 Width = 1215 End Begin VB.TextBox txtValue Height = 495 Left = 120 TabIndex = 0 Text = "0" Top = 240 Width = 1215 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private Sub Form_Load() Randomize Timer End Sub Private Sub cmdRnd_Click() If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11) End Sub Private Sub cmdInc_Click() If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1 End Sub Private Sub txtValue_KeyPress(KeyAscii As Integer) Select Case KeyAscii Case 8, 43, 45, 48 To 57 Case Else KeyAscii = 0 End Select End Sub
Ensure the translated VB code behaves exactly like the original C++ snippet.
#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'; }
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
Maintain the same structure and functionality when rewriting this code in VB.
#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; }
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
Preserve the algorithm and functionality while converting the code from C++ to VB.
#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; }
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"
Preserve the algorithm and functionality while converting the code from C++ to VB.
#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; }
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
Change the following C++ code into VB without altering its purpose.
template <typename Function> void repeat(Function f, unsigned int n) { for(unsigned int i=n; 0<i; i--) f(); }
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
Please provide an equivalent version of this C++ code in VB.
#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; }
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
Convert this C++ block to VB, preserving its control flow and logic.
#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; }
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
Port the following code from C++ to VB with equivalent syntax and logic.
#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; }
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
Produce a functionally identical VB code for the snippet given in C++.
#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; }
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
Change the following C++ code into VB without altering its purpose.
#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; }
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
Convert this C++ snippet to VB and keep its semantics consistent.
#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; }
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
Write the same code in VB as shown below in C++.
#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; }
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
Produce a language-to-language conversion: from C++ to VB, same semantics.
#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; }
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
Keep all operations the same but rewrite the snippet in VB.
#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'; }
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
Convert this C++ snippet to VB and keep its semantics consistent.
#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'; }
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
Change the following C++ code into VB without altering its purpose.
#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; }
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
Convert this C++ snippet to VB and keep its semantics consistent.
#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"; }
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
Transform the following C++ implementation into VB, maintaining the same output and logic.
#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; }
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
Rewrite the snippet below in VB so it works the same as the original C++ code.
#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; }
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
Rewrite the snippet below in VB so it works the same as the original C++ code.
#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; }
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
Translate the given C++ code snippet into VB without altering its behavior.
#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; }
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
Translate the given C++ code snippet into VB without altering its behavior.
#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; }
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
Port the following code from C++ to VB with equivalent syntax and logic.
#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; }
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
Convert this C++ snippet to VB and keep its semantics consistent.
#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; }
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
Convert this C++ snippet to VB and keep its semantics consistent.
#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; }
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
Can you help me rewrite this code in VB instead of C++, keeping it the same logically?
#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; }
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
Write the same algorithm in VB as shown in this C++ implementation.
#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; }
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
Produce a language-to-language conversion: from C++ to VB, same semantics.
#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; }
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
Write a version of this C++ function in VB with identical behavior.
#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; }
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
Ensure the translated VB code behaves exactly like the original C++ snippet.
#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; }
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
Preserve the algorithm and functionality while converting the code from C++ to VB.
#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; }
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
Rewrite this program in VB while keeping its functionality equivalent to the C++ version.
#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; }
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
Please provide an equivalent version of this C++ code in VB.
#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; }
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
Translate this program into VB but keep the logic exactly as in C++.
#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; };
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
Translate the given C++ code snippet into VB without altering its behavior.
#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; }
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
Change the following C++ code into VB without altering its purpose.
#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; }
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
Port the provided C++ code into VB while preserving the original functionality.
#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; }
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
Keep all operations the same but rewrite the snippet in VB.
#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; }
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
Can you help me rewrite this code in VB instead of C++, keeping it the same logically?
#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; }
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
Translate the given C++ code snippet into VB without altering its behavior.
#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; }
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
Write the same algorithm in VB as shown in this C++ implementation.
#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" ); }
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
Write a version of this C++ function in VB with identical behavior.
#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" ); }
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
Convert the following code from C++ to VB, ensuring the logic remains intact.
#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" ); }
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
Change the programming language of this snippet from C++ to VB without modifying what it does.
#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; }
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
Convert the following code from C++ to VB, ensuring the logic remains intact.
int i; void* address_of_i = &i;
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)