Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <windows.h> #include <string> #include <math.h> using namespace std; const float PI = 3.1415926536f; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; void *pBits; 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 setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD* dwpBits; DWORD wb; HANDLE file; GetObject( bmp, sizeof( bitmap ), &bitmap ); 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 ); file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() { return hdc; } int getWidth() { return width; } int getHeight() { return height; } private: HBITMAP bmp; HDC hdc; HPEN pen; int width, height; }; class vector2 { public: vector2() { x = y = 0; } vector2( int a, int b ) { x = a; y = b; } void set( int a, int b ) { x = a; y = b; } void rotate( float angle_r ) { float _x = static_cast<float>( x ), _y = static_cast<float>( y ), s = sinf( angle_r ), c = cosf( angle_r ), a = _x * c - _y * s, b = _x * s + _y * c; x = static_cast<int>( a ); y = static_cast<int>( b ); } int x, y; }; class fractalTree { public: fractalTree() { _ang = DegToRadian( 24.0f ); } float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); } void create( myBitmap* bmp ) { _bmp = bmp; float line_len = 130.0f; vector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 ); MoveToEx( _bmp->getDC(), sp.x, sp.y, NULL ); sp.y -= static_cast<int>( line_len ); LineTo( _bmp->getDC(), sp.x, sp.y); drawRL( &sp, line_len, 0, true ); drawRL( &sp, line_len, 0, false ); } private: void drawRL( vector2* sp, float line_len, float a, bool rg ) { line_len *= .75f; if( line_len < 2.0f ) return; MoveToEx( _bmp->getDC(), sp->x, sp->y, NULL ); vector2 r( 0, static_cast<int>( line_len ) ); if( rg ) a -= _ang; else a += _ang; r.rotate( a ); r.x += sp->x; r.y = sp->y - r.y; LineTo( _bmp->getDC(), r.x, r.y ); drawRL( &r, line_len, a, true ); drawRL( &r, line_len, a, false ); } myBitmap* _bmp; float _ang; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); myBitmap bmp; bmp.create( 640, 512 ); bmp.setPenColor( RGB( 255, 255, 0 ) ); fractalTree tree; tree.create( &bmp ); BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY ); bmp.saveBitmap( "f: system( "pause" ); return 0; }
package main import ( "math" "raster" ) const ( width = 400 height = 300 depth = 8 angle = 12 length = 50 frac = .8 ) func main() { g := raster.NewGrmap(width, height) ftree(g, width/2, height*9/10, length, 0, depth) g.Bitmap().WritePpmFile("ftree.ppm") } func ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) { x2 := x + distance*math.Sin(direction*math.Pi/180) y2 := y - distance*math.Cos(direction*math.Pi/180) g.AaLine(x, y, x2, y2) if depth > 0 { ftree(g, x2, y2, distance*frac, direction-angle, depth-1) ftree(g, x2, y2, distance*frac, direction+angle, depth-1) } }
Write the same algorithm in Go as shown in this C++ implementation.
#include <windows.h> class pinstripe { public: pinstripe() { createColors(); } void setDimensions( int x, int y ) { _mw = x; _mh = y; } void createColors() { colors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 ); colors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); colors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); colors[7] = RGB( 255, 255, 255 ); } void draw( HDC dc ) { HPEN pen; int lh = _mh / 4, row, cp; for( int lw = 1; lw < 5; lw++ ) { cp = 0; row = ( lw - 1 ) * lh; for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw ) { pen = CreatePen( PS_SOLID, lw, colors[cp] ); ++cp %= 8; SelectObject( dc, pen ); MoveToEx( dc, x, row, NULL ); LineTo( dc, x, row + lh ); DeleteObject( pen ); } } } private: int _mw, _mh; DWORD colors[8]; }; pinstripe pin; void PaintWnd( HWND hWnd ) { PAINTSTRUCT ps; HDC hdc = BeginPaint( hWnd, &ps ); pin.draw( hdc ); EndPaint( hWnd, &ps ); } LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_PAINT: PaintWnd( hWnd ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll( HINSTANCE hInstance ) { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_CLR_PS_"; RegisterClassEx( &wcex ); return CreateWindow( "_CLR_PS_", ".: Clr Pinstripe -- PJorenteΒ :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL ); } int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); HWND hwnd = InitAll( hInstance ); if( !hwnd ) return -1; int mw = GetSystemMetrics( SM_CXSCREEN ), mh = GetSystemMetrics( SM_CYSCREEN ); pin.setDimensions( mw, mh ); RECT rc = { 0, 0, mw, mh }; AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 ); int w = rc.right - rc.left, h = rc.bottom - rc.top; int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ), posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 ); SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER ); ShowWindow( hwnd, nCmdShow ); UpdateWindow( hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } return UnregisterClass( "_CLR_PS_", hInstance ); }
package main import "github.com/fogleman/gg" var palette = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func pinstripe(dc *gg.Context) { w := dc.Width() h := dc.Height() / 4 for b := 1; b <= 4; b++ { for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 { dc.SetHexColor(palette[ci%8]) y := h * (b - 1) dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h)) dc.Fill() } } } func main() { dc := gg.NewContext(900, 600) pinstripe(dc) dc.SavePNG("color_pinstripe.png") }
Write a version of this C++ function in Go with identical behavior.
#include <iostream> #include <cstdint> struct Date { std::uint16_t year; std::uint8_t month; std::uint8_t day; }; constexpr bool leap(int year) { return year%4==0 && (year%100!=0 || year%400==0); } const std::string& weekday(const Date& date) { static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const std::string days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned const c = date.year/100, r = date.year%100; unsigned const s = r/12, t = r%12; unsigned const c_anchor = (5 * (c%4) + 2) % 7; unsigned const doom = (s + t + t/4 + c_anchor) % 7; unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const std::string months[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; for (const Date& d : dates) { std::cout << months[d.month] << " " << (int)d.day << ", " << d.year; std::cout << (d.year > 2021 ? " will be " : " was "); std::cout << "on a " << weekday(d) << std::endl; } return 0; }
package main import ( "fmt" "strconv" ) var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} func anchorDay(y int) int { return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7 } func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) } var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} func main() { dates := []string{ "1800-01-06", "1875-03-29", "1915-12-07", "1970-12-23", "2043-05-14", "2077-02-12", "2101-04-02", } fmt.Println("Days of week given by Doomsday rule:") for _, date := range dates { y, _ := strconv.Atoi(date[0:4]) m, _ := strconv.Atoi(date[5:7]) m-- d, _ := strconv.Atoi(date[8:10]) a := anchorDay(y) f := firstDaysCommon[m] if isLeapYear(y) { f = firstDaysLeap[m] } w := d - f if w < 0 { w = 7 + w } dow := (a + w) % 7 fmt.Printf("%s -> %s\n", date, days[dow]) } }
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <iostream> #include <cstdint> struct Date { std::uint16_t year; std::uint8_t month; std::uint8_t day; }; constexpr bool leap(int year) { return year%4==0 && (year%100!=0 || year%400==0); } const std::string& weekday(const Date& date) { static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const std::string days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned const c = date.year/100, r = date.year%100; unsigned const s = r/12, t = r%12; unsigned const c_anchor = (5 * (c%4) + 2) % 7; unsigned const doom = (s + t + t/4 + c_anchor) % 7; unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const std::string months[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; for (const Date& d : dates) { std::cout << months[d.month] << " " << (int)d.day << ", " << d.year; std::cout << (d.year > 2021 ? " will be " : " was "); std::cout << "on a " << weekday(d) << std::endl; } return 0; }
package main import ( "fmt" "strconv" ) var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} func anchorDay(y int) int { return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7 } func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) } var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} func main() { dates := []string{ "1800-01-06", "1875-03-29", "1915-12-07", "1970-12-23", "2043-05-14", "2077-02-12", "2101-04-02", } fmt.Println("Days of week given by Doomsday rule:") for _, date := range dates { y, _ := strconv.Atoi(date[0:4]) m, _ := strconv.Atoi(date[5:7]) m-- d, _ := strconv.Atoi(date[8:10]) a := anchorDay(y) f := firstDaysCommon[m] if isLeapYear(y) { f = firstDaysLeap[m] } w := d - f if w < 0 { w = 7 + w } dow := (a + w) % 7 fmt.Printf("%s -> %s\n", date, days[dow]) } }
Port the following code from C++ to Go with equivalent syntax and logic.
#include <algorithm> #include <cassert> #include <iostream> #include <iterator> #include <vector> template <typename iterator> void cocktail_shaker_sort(iterator begin, iterator end) { if (begin == end) return; for (--end; begin < end; ) { iterator new_begin = end; iterator new_end = begin; for (iterator i = begin; i < end; ++i) { iterator j = i + 1; if (*j < *i) { std::iter_swap(i, j); new_end = i; } } end = new_end; for (iterator i = end; i > begin; --i) { iterator j = i - 1; if (*i < *j) { std::iter_swap(i, j); new_begin = i; } } begin = new_begin; } } template <typename iterator> void print(iterator begin, iterator end) { if (begin == end) return; std::cout << *begin++; while (begin != end) std::cout << ' ' << *begin++; std::cout << '\n'; } int main() { std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15}; std::cout << "before: "; print(v.begin(), v.end()); cocktail_shaker_sort(v.begin(), v.end()); assert(std::is_sorted(v.begin(), v.end())); std::cout << "after: "; print(v.begin(), v.end()); return 0; }
package main import ( "fmt" "math/rand" "time" ) func cocktailShakerSort(a []int) { var begin = 0 var end = len(a) - 2 for begin <= end { newBegin := end newEnd := begin for i := begin; i <= end; i++ { if a[i] > a[i+1] { a[i+1], a[i] = a[i], a[i+1] newEnd = i } } end = newEnd - 1 for i := end; i >= begin; i-- { if a[i] > a[i+1] { a[i+1], a[i] = a[i], a[i+1] newBegin = i } } begin = newBegin + 1 } } func cocktailSort(a []int) { last := len(a) - 1 for { swapped := false for i := 0; i < last; i++ { if a[i] > a[i+1] { a[i], a[i+1] = a[i+1], a[i] swapped = true } } if !swapped { return } swapped = false for i := last - 1; i >= 0; i-- { if a[i] > a[i+1] { a[i], a[i+1] = a[i+1], a[i] swapped = true } } if !swapped { return } } } func main() { a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170} fmt.Println("Original array:", a) b := make([]int, len(a)) copy(b, a) cocktailSort(a) fmt.Println("Cocktail sortΒ :", a) cocktailShakerSort(b) fmt.Println("C/Shaker sortΒ :", b) rand.Seed(time.Now().UnixNano()) fmt.Println("\nRelative speed of the two sorts") fmt.Println(" N x faster (CSS v CS)") fmt.Println("----- -------------------") const runs = 10 for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} { sum := 0.0 for i := 1; i <= runs; i++ { nums := make([]int, n) for i := 0; i < n; i++ { rn := rand.Intn(100000) if i%2 == 1 { rn = -rn } nums[i] = rn } nums2 := make([]int, n) copy(nums2, nums) start := time.Now() cocktailSort(nums) elapsed := time.Since(start) start2 := time.Now() cocktailShakerSort(nums2) elapsed2 := time.Since(start2) sum += float64(elapsed) / float64(elapsed2) } fmt.Printf(" %2dk %0.3f\n", n/1000, sum/runs) } }
Rewrite this program in Go while keeping its functionality equivalent to the C++ version.
#ifndef __wxPendulumDlg_h__ #define __wxPendulumDlg_h__ #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include <wx/wx.h> #include <wx/dialog.h> #else #include <wx/wxprec.h> #endif #include <wx/timer.h> #include <wx/dcbuffer.h> #include <cmath> class wxPendulumDlgApp : public wxApp { public: bool OnInit(); int OnExit(); }; class wxPendulumDlg : public wxDialog { public: wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("wxPendulum"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX); virtual ~wxPendulumDlg(); void wxPendulumDlgPaint(wxPaintEvent& event); void wxPendulumDlgSize(wxSizeEvent& event); void OnTimer(wxTimerEvent& event); private: wxTimer *m_timer; unsigned int m_uiLength; double m_Angle; double m_AngleVelocity; enum wxIDs { ID_WXTIMER1 = 1001, ID_DUMMY_VALUE_ }; void OnClose(wxCloseEvent& event); void CreateGUIControls(); DECLARE_EVENT_TABLE() }; #endif
package main import ( "github.com/google/gxui" "github.com/google/gxui/drivers/gl" "github.com/google/gxui/math" "github.com/google/gxui/themes/dark" omath "math" "time" ) const ( ANIMATION_WIDTH int = 480 ANIMATION_HEIGHT int = 320 BALL_RADIUS float32 = 25.0 METER_PER_PIXEL float64 = 1.0 / 20.0 PHI_ZERO float64 = omath.Pi * 0.5 ) var ( l float64 = float64(ANIMATION_HEIGHT) * 0.5 freq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL)) ) type Pendulum interface { GetPhi() float64 } type mathematicalPendulum struct { start time.Time } func (p *mathematicalPendulum) GetPhi() float64 { if (p.start == time.Time{}) { p.start = time.Now() } t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9) return PHI_ZERO * omath.Cos(t*freq) } type numericalPendulum struct { currentPhi float64 angAcc float64 angVel float64 lastTime time.Time } func (p *numericalPendulum) GetPhi() float64 { dt := 0.0 if (p.lastTime != time.Time{}) { dt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9) } p.lastTime = time.Now() p.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi) p.angVel += p.angAcc * dt p.currentPhi += p.angVel * dt return p.currentPhi } func draw(p Pendulum, canvas gxui.Canvas, x, y int) { attachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y} phi := p.GetPhi() ball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))} line := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}} canvas.DrawLines(line, gxui.DefaultPen) m := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)} rect := math.Rect{ball.Sub(m), ball.Add(m)} canvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow)) } func appMain(driver gxui.Driver) { theme := dark.CreateTheme(driver) window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum") window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50)) image := theme.CreateImage() ticker := time.NewTicker(time.Millisecond * 15) pendulum := &mathematicalPendulum{} pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}} go func() { for _ = range ticker.C { canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT}) canvas.Clear(gxui.White) draw(pendulum, canvas, 0, 0) draw(pendulum2, canvas, 0, ANIMATION_HEIGHT) canvas.Complete() driver.Call(func() { image.SetCanvas(canvas) }) } }() window.AddChild(image) window.OnClose(ticker.Stop) window.OnClose(driver.Terminate) } func main() { gl.StartDriver(appMain) }
Maintain the same structure and functionality when rewriting this code in Go.
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
Can you help me rewrite this code in Go instead of C++, keeping it the same logically?
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <iostream> #include <fstream> #if defined(_WIN32) || defined(WIN32) constexpr auto FILENAME = "tape.file"; #else constexpr auto FILENAME = "/dev/tape"; #endif int main() { std::filebuf fb; fb.open(FILENAME,std::ios::out); std::ostream os(&fb); os << "Hello World\n"; fb.close(); return 0; }
package main import ( "archive/tar" "compress/gzip" "flag" "io" "log" "os" "time" ) func main() { filename := flag.String("file", "TAPE.FILE", "filename within TAR") data := flag.String("data", "", "data for file") outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)") gzipFlag := flag.Bool("gzip", false, "use gzip compression") flag.Parse() var w io.Writer = os.Stdout if *outfile != "" { f, err := os.Create(*outfile) if err != nil { log.Fatalf("opening/creating %q: %v", *outfile, err) } defer f.Close() w = f } if *gzipFlag { zw := gzip.NewWriter(w) defer zw.Close() w = zw } tw := tar.NewWriter(w) defer tw.Close() w = tw tw.WriteHeader(&tar.Header{ Name: *filename, Mode: 0660, Size: int64(len(*data)), ModTime: time.Now(), Typeflag: tar.TypeReg, Uname: "guest", Gname: "guest", }) _, err := w.Write([]byte(*data)) if err != nil { log.Fatal("writing data:", err) } }
Convert this C++ block to Go, preserving its control flow and logic.
#include <iostream> #include <fstream> #if defined(_WIN32) || defined(WIN32) constexpr auto FILENAME = "tape.file"; #else constexpr auto FILENAME = "/dev/tape"; #endif int main() { std::filebuf fb; fb.open(FILENAME,std::ios::out); std::ostream os(&fb); os << "Hello World\n"; fb.close(); return 0; }
package main import ( "archive/tar" "compress/gzip" "flag" "io" "log" "os" "time" ) func main() { filename := flag.String("file", "TAPE.FILE", "filename within TAR") data := flag.String("data", "", "data for file") outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)") gzipFlag := flag.Bool("gzip", false, "use gzip compression") flag.Parse() var w io.Writer = os.Stdout if *outfile != "" { f, err := os.Create(*outfile) if err != nil { log.Fatalf("opening/creating %q: %v", *outfile, err) } defer f.Close() w = f } if *gzipFlag { zw := gzip.NewWriter(w) defer zw.Close() w = zw } tw := tar.NewWriter(w) defer tw.Close() w = tw tw.WriteHeader(&tar.Header{ Name: *filename, Mode: 0660, Size: int64(len(*data)), ModTime: time.Now(), Typeflag: tar.TypeReg, Uname: "guest", Gname: "guest", }) _, err := w.Write([]byte(*data)) if err != nil { log.Fatal("writing data:", err) } }
Write a version of this C++ function in Go with identical behavior.
#include <algorithm> #include <iterator> #include <iostream> template<typename RandomAccessIterator> void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) { std::make_heap(begin, end); std::sort_heap(begin, end); } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; heap_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
package main import ( "sort" "container/heap" "fmt" ) type HeapHelper struct { container sort.Interface length int } func (self HeapHelper) Len() int { return self.length } func (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) } func (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) } func (self *HeapHelper) Push(x interface{}) { panic("impossible") } func (self *HeapHelper) Pop() interface{} { self.length-- return nil } func heapSort(a sort.Interface) { helper := HeapHelper{ a, a.Len() } heap.Init(&helper) for helper.length > 0 { heap.Pop(&helper) } } func main() { a := []int{170, 45, 75, -90, -802, 24, 2, 66} fmt.Println("before:", a) heapSort(sort.IntSlice(a)) fmt.Println("after: ", a) }
Change the programming language of this snippet from C++ to Go without modifying what it does.
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; enum { unique_count = pip_count * suite_count }; card(suite_type s, pip_type p): value(s + suite_count * p) {} explicit card(unsigned char v = 0): value(v) {} pip_type pip() { return pip_type(value / suite_count); } suite_type suite() { return suite_type(value % suite_count); } private: unsigned char value; }; const char* const pip_names[] = { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace" }; std::ostream& operator<<(std::ostream& os, card::pip_type pip) { return os << pip_names[pip]; } const char* const suite_names[] = { "hearts", "spades", "diamonds", "clubs" }; std::ostream& operator<<(std::ostream& os, card::suite_type suite) { return os << suite_names[suite]; } std::ostream& operator<<(std::ostream& os, card c) { return os << c.pip() << " of " << c.suite(); } class deck { public: deck() { for (int i = 0; i < card::unique_count; ++i) { cards.push_back(card(i)); } } void shuffle() { std::random_shuffle(cards.begin(), cards.end()); } card deal() { card c = cards.front(); cards.pop_front(); return c; } typedef std::deque<card>::const_iterator const_iterator; const_iterator begin() const { return cards.cbegin(); } const_iterator end() const { return cards.cend(); } private: std::deque<card> cards; }; inline std::ostream& operator<<(std::ostream& os, const deck& d) { std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n")); return os; } }
package cards import ( "math/rand" ) type Suit uint8 const ( Spade Suit = 3 Heart Suit = 2 Diamond Suit = 1 Club Suit = 0 ) func (s Suit) String() string { const suites = "CDHS" return suites[s : s+1] } type Rank uint8 const ( Ace Rank = 1 Two Rank = 2 Three Rank = 3 Four Rank = 4 Five Rank = 5 Six Rank = 6 Seven Rank = 7 Eight Rank = 8 Nine Rank = 9 Ten Rank = 10 Jack Rank = 11 Queen Rank = 12 King Rank = 13 ) func (r Rank) String() string { const ranks = "A23456789TJQK" return ranks[r-1 : r] } type Card uint8 func NewCard(r Rank, s Suit) Card { return Card(13*uint8(s) + uint8(r-1)) } func (c Card) RankSuit() (Rank, Suit) { return Rank(c%13 + 1), Suit(c / 13) } func (c Card) Rank() Rank { return Rank(c%13 + 1) } func (c Card) Suit() Suit { return Suit(c / 13) } func (c Card) String() string { return c.Rank().String() + c.Suit().String() } type Deck []Card func NewDeck() Deck { d := make(Deck, 52) for i := range d { d[i] = Card(i) } return d } func (d Deck) String() string { s := "" for i, c := range d { switch { case i == 0: case i%13 == 0: s += "\n" default: s += " " } s += c.String() } return s } func (d Deck) Shuffle() { for i := range d { j := rand.Intn(i + 1) d[i], d[j] = d[j], d[i] } } func (d Deck) Contains(tc Card) bool { for _, c := range d { if c == tc { return true } } return false } func (d *Deck) AddDeck(decks ...Deck) { for _, o := range decks { *d = append(*d, o...) } } func (d *Deck) AddCard(c Card) { *d = append(*d, c) } func (d *Deck) Draw(n int) Deck { old := *d *d = old[n:] return old[:n:n] } func (d *Deck) DrawCard() (Card, bool) { if len(*d) == 0 { return 0, false } old := *d *d = old[1:] return old[0], true } func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) { for i := 0; i < cards; i++ { for j := range hands { if len(*d) == 0 { return hands, false } hands[j] = append(hands[j], (*d)[0]) *d = (*d)[1:] } } return hands, true }
Write a version of this C++ function in Go with identical behavior.
#include <array> #include <vector> #include <algorithm> #include <iostream> #include <iterator> #include <string> template <typename Array> void demonstrate(Array& array) { array[2] = "Three"; array.at(1) = "Two"; std::reverse(begin(array), end(array)); std::for_each(begin(array), end(array), [](typename Array::value_type const& element) { std::cout << element << ' '; }); std::cout << '\n'; } int main() { auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" }; auto dynamic_array = std::vector<std::string>{ "One", "Four" }; dynamic_array.push_back("Eight"); demonstrate(fixed_size_array); demonstrate(dynamic_array); }
package main import ( "fmt" ) func main() { var a [5]int fmt.Println("len(a) =", len(a)) fmt.Println("a =", a) a[0] = 3 fmt.Println("a =", a) fmt.Println("a[0] =", a[0]) s := a[:4] fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s)) s = s[:5] fmt.Println("s =", s) a[0] = 22 fmt.Println("a =", a) fmt.Println("s =", s) s = append(s, 4, 5, 6) fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s)) a[4] = -1 fmt.Println("a =", a) fmt.Println("s =", s) s = make([]int, 8) fmt.Println("s =", s) fmt.Println("len(s) =", len(s), " cap(s) =", cap(s)) }
Change the following C++ code into Go without altering its purpose.
#include <cstdint> #include <cstdlib> #include <cstdio> static constexpr int32_t bct_low_bits = 0x55555555; static int32_t bct_decrement(int32_t v) { --v; return v ^ (v & (v>>1) & bct_low_bits); } int main (int argc, char *argv[]) { const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3; if (n < 0 || 9 < n) { std::printf("N out of range (use 0..9): %ld\n", long(n)); return 1; } const int32_t size_bct = 1<<(n*2); int32_t y = size_bct; do { y = bct_decrement(y); int32_t x = size_bct; do { x = bct_decrement(x); std::putchar((x & y & bct_low_bits) ? ' ' : '#'); } while (0 < x); std::putchar('\n'); } while (0 < y); return 0; }
package main import ( "fmt" "strings" "unicode/utf8" ) var order = 3 var grain = "#" func main() { carpet := []string{grain} for ; order > 0; order-- { hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0])) middle := make([]string, len(carpet)) for i, s := range carpet { middle[i] = s + hole + s carpet[i] = strings.Repeat(s, 3) } carpet = append(append(carpet, middle...), carpet...) } for _, r := range carpet { fmt.Println(r) } }
Maintain the same structure and functionality when rewriting this code in Go.
#include <algorithm> #include <iostream> #include <iterator> #include <random> template <typename RandomAccessIterator, typename Predicate> void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end, Predicate p) { std::random_device rd; std::mt19937 generator(rd()); while (!std::is_sorted(begin, end, p)) { std::shuffle(begin, end, generator); } } template <typename RandomAccessIterator> void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) { bogo_sort( begin, end, std::less< typename std::iterator_traits<RandomAccessIterator>::value_type>()); } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bogo_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
package main import ( "fmt" "math/rand" "sort" "time" ) func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} rand.Seed(time.Now().UnixNano()) fmt.Println("unsorted:", list) temp := make([]int, len(list)) copy(temp, list) for !sort.IntsAreSorted(temp) { for i, v := range rand.Perm(len(list)) { temp[i] = list[v] } } fmt.Println("sorted! ", temp) }
Port the provided C++ code into Go while preserving the original functionality.
#include <iostream> #include <optional> #include <ranges> #include <string> #include <vector> using namespace std; struct Patient { string ID; string LastName; }; struct Visit { string PatientID; string Date; optional<float> Score; }; int main(void) { auto patients = vector<Patient> { {"1001", "Hopper"}, {"4004", "Wirth"}, {"3003", "Kemeny"}, {"2002", "Gosling"}, {"5005", "Kurtz"}}; auto visits = vector<Visit> { {"2002", "2020-09-10", 6.8}, {"1001", "2020-09-17", 5.5}, {"4004", "2020-09-24", 8.4}, {"2002", "2020-10-08", }, {"1001", "" , 6.6}, {"3003", "2020-11-12", }, {"4004", "2020-11-05", 7.0}, {"1001", "2020-11-19", 5.3}}; sort(patients.begin(), patients.end(), [](const auto& a, const auto&b){ return a.ID < b.ID;}); cout << "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n"; for(const auto& patient : patients) { string lastVisit; float sum = 0; int numScores = 0; auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;}; for(const auto& visit : visits | views::filter( patientFilter )) { if(visit.Score) { sum += *visit.Score; numScores++; } lastVisit = max(lastVisit, visit.Date); } cout << "| " << patient.ID << " | "; cout.width(8); cout << patient.LastName << " | "; cout.width(10); cout << lastVisit << " | "; if(numScores > 0) { cout.width(9); cout << sum << " | "; cout.width(9); cout << (sum / float(numScores)); } else cout << " | "; cout << " |\n"; } }
package main import ( "fmt" "math" "sort" ) type Patient struct { id int lastName string } var patientDir = make(map[int]string) var patientIds []int func patientNew(id int, lastName string) Patient { patientDir[id] = lastName patientIds = append(patientIds, id) sort.Ints(patientIds) return Patient{id, lastName} } type DS struct { dates []string scores []float64 } type Visit struct { id int date string score float64 } var visitDir = make(map[int]DS) func visitNew(id int, date string, score float64) Visit { if date == "" { date = "0000-00-00" } v, ok := visitDir[id] if ok { v.dates = append(v.dates, date) v.scores = append(v.scores, score) visitDir[id] = DS{v.dates, v.scores} } else { visitDir[id] = DS{[]string{date}, []float64{score}} } return Visit{id, date, score} } type Merge struct{ id int } func (m Merge) lastName() string { return patientDir[m.id] } func (m Merge) dates() []string { return visitDir[m.id].dates } func (m Merge) scores() []float64 { return visitDir[m.id].scores } func (m Merge) lastVisit() string { dates := m.dates() dates2 := make([]string, len(dates)) copy(dates2, dates) sort.Strings(dates2) return dates2[len(dates2)-1] } func (m Merge) scoreSum() float64 { sum := 0.0 for _, score := range m.scores() { if score != -1 { sum += score } } return sum } func (m Merge) scoreAvg() float64 { count := 0 for _, score := range m.scores() { if score != -1 { count++ } } return m.scoreSum() / float64(count) } func mergePrint(merges []Merge) { fmt.Println("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |") f := "| %d |Β %-7s | %s | %4s | %4s |\n" for _, m := range merges { _, ok := visitDir[m.id] if ok { lv := m.lastVisit() if lv == "0000-00-00" { lv = " " } scoreSum := m.scoreSum() ss := fmt.Sprintf("%4.1f", scoreSum) if scoreSum == 0 { ss = " " } scoreAvg := m.scoreAvg() sa := " " if !math.IsNaN(scoreAvg) { sa = fmt.Sprintf("%4.2f", scoreAvg) } fmt.Printf(f, m.id, m.lastName(), lv, ss, sa) } else { fmt.Printf(f, m.id, m.lastName(), " ", " ", " ") } } } func main() { patientNew(1001, "Hopper") patientNew(4004, "Wirth") patientNew(3003, "Kemeny") patientNew(2002, "Gosling") patientNew(5005, "Kurtz") visitNew(2002, "2020-09-10", 6.8) visitNew(1001, "2020-09-17", 5.5) visitNew(4004, "2020-09-24", 8.4) visitNew(2002, "2020-10-08", -1) visitNew(1001, "", 6.6) visitNew(3003, "2020-11-12", -1) visitNew(4004, "2020-11-05", 7.0) visitNew(1001, "2020-11-19", 5.3) merges := make([]Merge, len(patientIds)) for i, id := range patientIds { merges[i] = Merge{id} } mergePrint(merges) }
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <iomanip> #include <iostream> typedef double F(double,double); void euler(F f, double y0, double a, double b, double h) { double y = y0; for (double t = a; t < b; t += h) { std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n"; y += h * f(t, y); } std::cout << "done\n"; } double newtonCoolingLaw(double, double t) { return -0.07 * (t - 20); } int main() { euler(newtonCoolingLaw, 100, 0, 100, 2); euler(newtonCoolingLaw, 100, 0, 100, 5); euler(newtonCoolingLaw, 100, 0, 100, 10); }
package main import ( "fmt" "math" ) type fdy func(float64, float64) float64 func eulerStep(f fdy, x, y, h float64) float64 { return y + h*f(x, y) } func newCoolingRate(k float64) func(float64) float64 { return func(deltaTemp float64) float64 { return -k * deltaTemp } } func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 { return func(time float64) float64 { return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time) } } func newCoolingRateDy(k, ambientTemp float64) fdy { crf := newCoolingRate(k) return func(_, objectTemp float64) float64 { return crf(objectTemp - ambientTemp) } } func main() { k := .07 tempRoom := 20. tempObject := 100. fcr := newCoolingRateDy(k, tempRoom) analytic := newTempFunc(k, tempRoom, tempObject) for _, deltaTime := range []float64{2, 5, 10} { fmt.Printf("Step size =Β %.1f\n", deltaTime) fmt.Println(" Time Euler's Analytic") temp := tempObject for time := 0.; time <= 100; time += deltaTime { fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time)) temp = eulerStep(fcr, time, temp, deltaTime) } fmt.Println() } }
Write a version of this C++ function in Go with identical behavior.
#include <iostream> #include <algorithm> #include <vector> #include <cmath> #include <boost/bind.hpp> #include <iterator> double nextNumber( double number ) { return number + floor( 0.5 + sqrt( number ) ) ; } int main( ) { std::vector<double> non_squares ; typedef std::vector<double>::iterator SVI ; non_squares.reserve( 1000000 ) ; for ( double i = 1.0 ; i < 100001.0 ; i += 1 ) non_squares.push_back( nextNumber( i ) ) ; std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 , std::ostream_iterator<double>(std::cout, " " ) ) ; std::cout << '\n' ; SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) , boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ; if ( found != non_squares.end( ) ) { std::cout << "Found a square number in the sequence!\n" ; std::cout << "It is " << *found << "Β !\n" ; } else { std::cout << "Up to 1000000, found no square number in the sequence!\n" ; } return 0 ; }
package main import ( "fmt" "math" ) func remarkable(n int) int { return n + int(.5+math.Sqrt(float64(n))) } func main() { fmt.Println(" n r(n)") fmt.Println("--- ---") for n := 1; n <= 22; n++ { fmt.Printf("%3d %3d\n", n, remarkable(n)) } const limit = 1e6 fmt.Println("\nChecking for squares for n <", limit) next := 2 nextSq := 4 for n := 1; n < limit; n++ { r := remarkable(n) switch { case r == nextSq: panic(n) case r > nextSq: fmt.Println(nextSq, "didn't occur") next++ nextSq = next * next } } fmt.Println("No squares occur for n <", limit) }
Write the same code in Go as shown below in C++.
#include <iostream> #include <string> int main() { std::string s = "0123456789"; int const n = 3; int const m = 4; char const c = '2'; std::string const sub = "456"; std::cout << s.substr(n, m)<< "\n"; std::cout << s.substr(n) << "\n"; std::cout << s.substr(0, s.size()-1) << "\n"; std::cout << s.substr(s.find(c), m) << "\n"; std::cout << s.substr(s.find(sub), m) << "\n"; }
package main import ( "fmt" "strings" ) func main() { s := "ABCDEFGH" n, m := 2, 3 fmt.Println("Index: ", "01234567") fmt.Println("String:", s) fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m]) fmt.Printf("Start %d, to end: %s\n", n, s[n:]) fmt.Printf("All but last: %s\n", s[:len(s)-1]) dx := strings.IndexByte(s, 'D') fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m]) sx := strings.Index(s, "DE") fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m]) }
Generate a Go translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <string> int main() { std::string s = "0123456789"; int const n = 3; int const m = 4; char const c = '2'; std::string const sub = "456"; std::cout << s.substr(n, m)<< "\n"; std::cout << s.substr(n) << "\n"; std::cout << s.substr(0, s.size()-1) << "\n"; std::cout << s.substr(s.find(c), m) << "\n"; std::cout << s.substr(s.find(sub), m) << "\n"; }
package main import ( "fmt" "strings" ) func main() { s := "ABCDEFGH" n, m := 2, 3 fmt.Println("Index: ", "01234567") fmt.Println("String:", s) fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m]) fmt.Printf("Start %d, to end: %s\n", n, s[n:]) fmt.Printf("All but last: %s\n", s[:len(s)-1]) dx := strings.IndexByte(s, 'D') fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m]) sx := strings.Index(s, "DE") fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m]) }
Produce a language-to-language conversion: from C++ to Go, same semantics.
#include <algorithm> #include <string> #include <iostream> #include <iterator> class jortSort { public: template<class T> bool jort_sort( T* o, size_t s ) { T* n = copy_array( o, s ); sort_array( n, s ); bool r = false; if( n ) { r = check( o, n, s ); delete [] n; } return r; } private: template<class T> T* copy_array( T* o, size_t s ) { T* z = new T[s]; memcpy( z, o, s * sizeof( T ) ); return z; } template<class T> void sort_array( T* n, size_t s ) { std::sort( n, n + s ); } template<class T> bool check( T* n, T* o, size_t s ) { for( size_t x = 0; x < s; x++ ) if( n[x] != o[x] ) return false; return true; } }; jortSort js; template<class T> void displayTest( T* o, size_t s ) { std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) ); std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n"; } int main( int argc, char* argv[] ) { const size_t s = 5; std::string oStr[] = { "5", "A", "D", "R", "S" }; displayTest( oStr, s ); std::swap( oStr[0], oStr[1] ); displayTest( oStr, s ); int oInt[] = { 1, 2, 3, 4, 5 }; displayTest( oInt, s ); std::swap( oInt[0], oInt[1] ); displayTest( oInt, s ); return 0; }
package main import ( "log" "sort" ) func main() { log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) log.Println(jortSort([]int{0, 1, 0, 0, 0, 0})) log.Println(jortSort([]int{1, 2, 4, 11, 22, 22})) log.Println(jortSort([]int{0, 0, 0, 1, 2, 2})) } func jortSort(a []int) bool { c := make([]int, len(a)) copy(c, a) sort.Ints(a) for k, v := range c { if v == a[k] { continue } else { return false } } return true }
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <iostream> bool is_leap_year(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } int main() { for (auto year : {1900, 1994, 1996, 1997, 2000}) { std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n"; } }
func isLeap(year int) bool { return year%400 == 0 || year%4 == 0 && year%100 != 0 }
Produce a language-to-language conversion: from C++ to Go, same semantics.
#include <boost/multiprecision/gmp.hpp> #include <iostream> using namespace boost::multiprecision; mpz_int p(uint n, uint p) { mpz_int r = 1; mpz_int k = n - p; while (n > k) r *= n--; return r; } mpz_int c(uint n, uint k) { mpz_int r = p(n, k); while (k) r /= k--; return r; } int main() { for (uint i = 1u; i < 12u; i++) std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl; for (uint i = 10u; i < 60u; i += 10u) std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl; return 0; }
package main import ( "fmt" "math/big" ) func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10; n < 61; n += 10 { p = n / 3 fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of permutations from 5 to 15000:\n") nArr := [...]int64{5, 50, 500, 1000, 5000, 15000} for _, n = range nArr { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 100 to 1000:\n") for n = 100; n < 1001; n += 100 { p = n / 3 fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) } } func fact(n *big.Int) *big.Int { if n.Sign() < 1 { return big.NewInt(0) } r := big.NewInt(1) i := big.NewInt(2) for i.Cmp(n) < 1 { r.Mul(r, i) i.Add(i, big.NewInt(1)) } return r } func perm(n, k *big.Int) *big.Int { r := fact(n) r.Div(r, fact(n.Sub(n, k))) return r } func comb(n, r *big.Int) *big.Int { if r.Cmp(n) == 1 { return big.NewInt(0) } if r.Cmp(n) == 0 { return big.NewInt(1) } c := fact(n) den := fact(n.Sub(n, r)) den.Mul(den, fact(r)) c.Div(c, den) return c }
Translate this program into Go but keep the logic exactly as in C++.
#include <boost/multiprecision/gmp.hpp> #include <iostream> using namespace boost::multiprecision; mpz_int p(uint n, uint p) { mpz_int r = 1; mpz_int k = n - p; while (n > k) r *= n--; return r; } mpz_int c(uint n, uint k) { mpz_int r = p(n, k); while (k) r /= k--; return r; } int main() { for (uint i = 1u; i < 12u; i++) std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl; for (uint i = 10u; i < 60u; i += 10u) std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl; return 0; }
package main import ( "fmt" "math/big" ) func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10; n < 61; n += 10 { p = n / 3 fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of permutations from 5 to 15000:\n") nArr := [...]int64{5, 50, 500, 1000, 5000, 15000} for _, n = range nArr { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 100 to 1000:\n") for n = 100; n < 1001; n += 100 { p = n / 3 fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) } } func fact(n *big.Int) *big.Int { if n.Sign() < 1 { return big.NewInt(0) } r := big.NewInt(1) i := big.NewInt(2) for i.Cmp(n) < 1 { r.Mul(r, i) i.Add(i, big.NewInt(1)) } return r } func perm(n, k *big.Int) *big.Int { r := fact(n) r.Div(r, fact(n.Sub(n, k))) return r } func comb(n, r *big.Int) *big.Int { if r.Cmp(n) == 1 { return big.NewInt(0) } if r.Cmp(n) == 0 { return big.NewInt(1) } c := fact(n) den := fact(n.Sub(n, r)) den.Mul(den, fact(r)) c.Div(c, den) return c }
Port the provided C++ code into Go while preserving the original functionality.
#include <algorithm> #include <iostream> #include <numeric> #include <string> #include <vector> void lexicographical_sort(std::vector<int>& numbers) { std::vector<std::string> strings(numbers.size()); std::transform(numbers.begin(), numbers.end(), strings.begin(), [](int i) { return std::to_string(i); }); std::sort(strings.begin(), strings.end()); std::transform(strings.begin(), strings.end(), numbers.begin(), [](const std::string& s) { return std::stoi(s); }); } std::vector<int> lexicographically_sorted_vector(int n) { std::vector<int> numbers(n >= 1 ? n : 2 - n); std::iota(numbers.begin(), numbers.end(), std::min(1, n)); lexicographical_sort(numbers); return numbers; } template <typename T> void print_vector(std::ostream& out, const std::vector<T>& v) { out << '['; if (!v.empty()) { auto i = v.begin(); out << *i++; for (; i != v.end(); ++i) out << ',' << *i; } out << "]\n"; } int main(int argc, char** argv) { for (int i : { 0, 5, 13, 21, -22 }) { std::cout << i << ": "; print_vector(std::cout, lexicographically_sorted_vector(i)); } return 0; }
package main import ( "fmt" "sort" "strconv" ) func lexOrder(n int) []int { first, last, k := 1, n, n if n < 1 { first, last, k = n, 1, 2-n } strs := make([]string, k) for i := first; i <= last; i++ { strs[i-first] = strconv.Itoa(i) } sort.Strings(strs) ints := make([]int, k) for i := 0; i < k; i++ { ints[i], _ = strconv.Atoi(strs[i]) } return ints } func main() { fmt.Println("In lexicographical order:\n") for _, n := range []int{0, 5, 13, 21, -22} { fmt.Printf("%3d: %v\n", n, lexOrder(n)) } }
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <string> #include <iostream> using std::string; const char* smallNumbers[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; string spellHundreds(unsigned n) { string res; if (n > 99) { res = smallNumbers[n/100]; res += " hundred"; n %= 100; if (n) res += " and "; } if (n >= 20) { static const char* Decades[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; res += Decades[n/10]; n %= 10; if (n) res += "-"; } if (n < 20 && n > 0) res += smallNumbers[n]; return res; } const char* thousandPowers[] = { " billion", " million", " thousand", "" }; typedef unsigned long Spellable; string spell(Spellable n) { if (n < 20) return smallNumbers[n]; string res; const char** pScaleName = thousandPowers; Spellable scaleFactor = 1000000000; while (scaleFactor > 0) { if (n >= scaleFactor) { Spellable h = n / scaleFactor; res += spellHundreds(h) + *pScaleName; n %= scaleFactor; if (n) res += ", "; } scaleFactor /= 1000; ++pScaleName; } return res; } int main() { #define SPELL_IT(x) std::cout << #x " " << spell(x) << std::endl; SPELL_IT( 99); SPELL_IT( 300); SPELL_IT( 310); SPELL_IT( 1501); SPELL_IT( 12609); SPELL_IT( 512609); SPELL_IT(43112609); SPELL_IT(1234567890); return 0; }
package main import "fmt" func main() { for _, n := range []int64{12, 1048576, 9e18, -2, 0} { fmt.Println(say(n)) } } var small = [...]string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} var tens = [...]string{"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"} var illions = [...]string{"", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion"} func say(n int64) string { var t string if n < 0 { t = "negative " n = -n } switch { case n < 20: t += small[n] case n < 100: t += tens[n/10] s := n % 10 if s > 0 { t += "-" + small[s] } case n < 1000: t += small[n/100] + " hundred" s := n % 100 if s > 0 { t += " " + say(s) } default: sx := "" for i := 0; n > 0; i++ { p := n % 1000 n /= 1000 if p > 0 { ix := say(p) + illions[i] if sx != "" { ix += " " + sx } sx = ix } } t += sx } return t }
Convert the following code from C++ to Go, ensuring the logic remains intact.
#include <iostream> #include <algorithm> #include <string> #include <list> using namespace std; bool cmp(const string& a, const string& b) { return b.length() < a.length(); } void compareAndReportStringsLength(list<string> listOfStrings) { if (!listOfStrings.empty()) { char Q = '"'; string has_length(" has length "); string predicate_max(" and is the longest string"); string predicate_min(" and is the shortest string"); string predicate_ave(" and is neither the longest nor the shortest string"); list<string> ls(listOfStrings); ls.sort(cmp); int max = ls.front().length(); int min = ls.back().length(); for (list<string>::iterator s = ls.begin(); s != ls.end(); s++) { int length = s->length(); string* predicate; if (length == max) predicate = &predicate_max; else if (length == min) predicate = &predicate_min; else predicate = &predicate_ave; cout << Q << *s << Q << has_length << length << *predicate << endl; } } } int main(int argc, char* argv[]) { list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(listOfStrings); return EXIT_SUCCESS; }
package main import ( "fmt" "os" "sort" ) func main() { if len(os.Args) == 1 { compareStrings("abcd", "123456789", "abcdef", "1234567") } else { strings := os.Args[1:] compareStrings(strings...) } } func compareStrings(strings ...string) { sort.SliceStable(strings, func(i, j int) bool { return len(strings[i]) > len(strings[j]) }) for _, s := range strings { fmt.Printf("%d: %s\n", len(s), s) } }
Ensure the translated Go code behaves exactly like the original C++ snippet.
#include <time.h> #include <iostream> using namespace std; const int MAX = 126; class shell { public: shell() { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; } void sort( int* a, int count ) { _cnt = count; for( int x = 0; x < 9; x++ ) if( count > _gap[x] ) { _idx = x; break; } sortIt( a ); } private: void sortIt( int* arr ) { bool sorted = false; while( true ) { sorted = true; int st = 0; for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] ) { if( arr[st] > arr[x] ) { swap( arr[st], arr[x] ); sorted = false; } st = x; } if( ++_idx >= 8 ) _idx = 8; if( sorted && _idx == 8 ) break; } } void swap( int& a, int& b ) { int t = a; a = b; b = t; } int _gap[9], _idx, _cnt; }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX]; for( int x = 0; x < MAX; x++ ) arr[x] = rand() % MAX - rand() % MAX; cout << " Before: \n=========\n"; for( int x = 0; x < 7; x++ ) { for( int a = 0; a < 18; a++ ) { cout << arr[x * 18 + a] << " "; } cout << endl; } cout << endl; shell s; s.sort( arr, MAX ); cout << " After: \n========\n"; for( int x = 0; x < 7; x++ ) { for( int a = 0; a < 18; a++ ) { cout << arr[x * 18 + a] << " "; } cout << endl; } cout << endl << endl; return system( "pause" ); }
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 { for i := inc; i < len(a); i++ { j, temp := i, a[i] for ; j >= inc && a[j-inc] > temp; j -= inc { a[j] = a[j-inc] } a[j] = temp } } fmt.Println("after: ", a) }
Maintain the same structure and functionality when rewriting this code in Go.
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; numbers.insert(numbers.begin(), 9); numbers.insert(numbers.end(), 4); auto it = std::next(numbers.begin(), numbers.size() / 2); numbers.insert(it, 6); for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
type dlNode struct { int next, prev *dlNode } type dlList struct { members map[*dlNode]int head, tail **dlNode }
Ensure the translated Go code behaves exactly like the original C++ snippet.
#include <fstream> #include <iostream> int main() { std::ifstream input("filename.txt", std::ios_base::binary); if (!input) { std::cerr << "error: can't open file\n"; return -1; } size_t count[256]; std::fill_n(count, 256, 0); for (char c; input.get(c); ++count[uint8_t(c)]) ; for (size_t i = 0; i < 256; ++i) { if (count[i] && isgraph(i)) { std::cout << char(i) << " = " << count[i] << '\n'; } } }
package main import ( "fmt" "io/ioutil" "sort" "unicode" ) const file = "unixdict.txt" func main() { bs, err := ioutil.ReadFile(file) if err != nil { fmt.Println(err) return } m := make(map[rune]int) for _, r := range string(bs) { m[r]++ } lfs := make(lfList, 0, len(m)) for l, f := range m { lfs = append(lfs, &letterFreq{l, f}) } sort.Sort(lfs) fmt.Println("file:", file) fmt.Println("letter frequency") for _, lf := range lfs { if unicode.IsGraphic(lf.rune) { fmt.Printf(" %c %7d\n", lf.rune, lf.freq) } else { fmt.Printf("%U %7d\n", lf.rune, lf.freq) } } } type letterFreq struct { rune freq int } type lfList []*letterFreq func (lfs lfList) Len() int { return len(lfs) } func (lfs lfList) Less(i, j int) bool { switch fd := lfs[i].freq - lfs[j].freq; { case fd < 0: return false case fd > 0: return true } return lfs[i].rune < lfs[j].rune } func (lfs lfList) Swap(i, j int) { lfs[i], lfs[j] = lfs[j], lfs[i] }
Ensure the translated Go code behaves exactly like the original C++ snippet.
#include<iostream> #include<vector> #include<numeric> #include<functional> class { public: int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);} private: int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); } int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);} }combinations; int main() { static constexpr int treatment = 9; const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 }; int treated = std::accumulate(data.begin(), data.begin() + treatment, 0); std::function<int (int, int, int)> pick; pick = [&](int n, int from, int accumulated) { if(n == 0) return accumulated > treated ? 1 : 0; else return pick(n - 1, from - 1, accumulated + data[from - 1]) + (from > n ? pick(n, from - 1, accumulated) : 0); }; int total = combinations(data.size(), treatment); int greater = pick(treatment, data.size(), 0); int lesser = total - greater; std::cout << "<=Β : " << 100.0 * lesser / total << "% " << lesser << std::endl << " >Β : " << 100.0 * greater / total << "% " << greater << std::endl; }
package main import "fmt" var tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97} var ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98} func main() { all := make([]int, len(tr)+len(ct)) copy(all, tr) copy(all[len(tr):], ct) var sumAll int for _, r := range all { sumAll += r } sd := func(trc []int) int { var sumTr int for _, x := range trc { sumTr += all[x] } return sumTr*len(ct) - (sumAll-sumTr)*len(tr) } a := make([]int, len(tr)) for i, _ := range a { a[i] = i } sdObs := sd(a) var nLe, nGt int comb(len(all), len(tr), func(c []int) { if sd(c) > sdObs { nGt++ } else { nLe++ } }) pc := 100 / float64(nLe+nGt) fmt.Printf("differences <= observed: %f%%\n", float64(nLe)*pc) fmt.Printf("differences > observed: %f%%\n", float64(nGt)*pc) } func comb(n, m int, emit func([]int)) { s := make([]int, m) last := m - 1 var rc func(int, int) rc = func(i, next int) { for j := next; j < n; j++ { s[i] = j if i == last { emit(s) } else { rc(i+1, j+1) } } return } rc(0, 0) }
Maintain the same structure and functionality when rewriting this code in Go.
#include <iomanip> #include <iostream> #include <vector> constexpr int MU_MAX = 1'000'000; std::vector<int> MU; int mobiusFunction(int n) { if (!MU.empty()) { return MU[n]; } MU.resize(MU_MAX + 1, 1); int root = sqrt(MU_MAX); for (int i = 2; i <= root; i++) { if (MU[i] == 1) { for (int j = i; j <= MU_MAX; j += i) { MU[j] *= -i; } for (int j = i * i; j <= MU_MAX; j += i * i) { MU[j] = 0; } } } for (int i = 2; i <= MU_MAX; i++) { if (MU[i] == i) { MU[i] = 1; } else if (MU[i] == -i) { MU[i] = -1; } else if (MU[i] < 0) { MU[i] = 1; } else if (MU[i] > 0) { MU[i] = -1; } } return MU[n]; } int main() { std::cout << "First 199 terms of the mΓΆbius function are as follows:\n "; for (int n = 1; n < 200; n++) { std::cout << std::setw(2) << mobiusFunction(n) << " "; if ((n + 1) % 20 == 0) { std::cout << '\n'; } } return 0; }
package main import "fmt" func mΓΆbius(to int) []int { if to < 1 { to = 1 } mobs := make([]int, to+1) primes := []int{2} for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { if p > j { break } if j%p == 0 { j /= p cp++ } if j%p == 0 { spf = true break } } if cp == 0 && i > 2 { cp = 1 primes = append(primes, i) } if !spf { if cp%2 == 0 { mobs[i] = 1 } else { mobs[i] = -1 } } } return mobs } func main() { mobs := mΓΆbius(199) fmt.Println("MΓΆbius sequence - First 199 terms:") for i := 0; i < 200; i++ { if i == 0 { fmt.Print(" ") continue } if i%20 == 0 { fmt.Println() } fmt.Printf(" Β % d", mobs[i]) } }
Convert this C++ snippet to Go and keep its semantics consistent.
#include <cstdlib> #include <string> #include <sstream> std::string s = "12345"; int i; std::istringstream(s) >> i; i++; std::ostringstream oss; if (oss << i) s = oss.str();
package main import "fmt" import "strconv" func main() { i, _ := strconv.Atoi("1234") fmt.Println(strconv.Itoa(i + 1)) }
Rewrite this program in Go while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <iostream> #include <string> std::string stripchars(std::string str, const std::string &chars) { str.erase( std::remove_if(str.begin(), str.end(), [&](char c){ return chars.find(c) != std::string::npos; }), str.end() ); return str; } int main() { std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n'; return 0; }
package main import ( "fmt" "strings" ) func stripchars(str, chr string) string { return strings.Map(func(r rune) rune { if strings.IndexRune(chr, r) < 0 { return r } return -1 }, str) } func main() { fmt.Println(stripchars("She was a soul stripper. She took my heart!", "aei")) }
Translate the given C++ code snippet into Go without altering its behavior.
#include <algorithm> template<typename ForwardIterator> void permutation_sort(ForwardIterator begin, ForwardIterator end) { while (std::next_permutation(begin, end)) { } }
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) if len(a) > 1 && !recurse(len(a) - 1) { panic("sorted permutation not found!") } fmt.Println("after: ", a) } func recurse(last int) bool { if last <= 0 { for i := len(a) - 1; a[i] >= a[i-1]; i-- { if i == 1 { return true } } return false } for i := 0; i <= last; i++ { a[i], a[last] = a[last], a[i] if recurse(last - 1) { return true } a[i], a[last] = a[last], a[i] } return false }
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <vector> double mean(const std::vector<double>& numbers) { if (numbers.size() == 0) return 0; double sum = 0; for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++) sum += *i; return sum / numbers.size(); }
package main import ( "fmt" "math" ) func mean(v []float64) (m float64, ok bool) { if len(v) == 0 { return } var parts []float64 for _, x := range v { var i int for _, p := range parts { sum := p + x var err float64 switch ax, ap := math.Abs(x), math.Abs(p); { case ax < ap: err = x - (sum - p) case ap < ax: err = p - (sum - x) } if err != 0 { parts[i] = err i++ } x = sum } parts = append(parts[:i], x) } var sum float64 for _, x := range parts { sum += x } return sum / float64(len(v)), true } func main() { for _, v := range [][]float64{ []float64{}, []float64{math.Inf(1), math.Inf(1)}, []float64{math.Inf(1), math.Inf(-1)}, []float64{3, 1, 4, 1, 5, 9}, []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20}, []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11}, []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2}, } { fmt.Println("Vector:", v) if m, ok := mean(v); ok { fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m) } else { fmt.Println("Mean undefined\n") } } }
Write the same code in Go as shown below in C++.
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } bool parse_integer(const std::string& word, int& value) { try { size_t pos; int i = std::stoi(word, &pos, 10); if (pos < word.length()) return false; value = i; return true; } catch (const std::exception& ex) { return false; } } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::istringstream is(table); std::string word; std::vector<std::string> words; while (is >> word) { uppercase(word); words.push_back(word); } for (size_t i = 0, n = words.size(); i < n; ++i) { word = words[i]; int len = word.length(); if (i + 1 < n && parse_integer(words[i + 1], len)) ++i; commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
package main import ( "io" "os" "strconv" "strings" "text/tabwriter" ) func readTable(table string) ([]string, []int) { fields := strings.Fields(table) var commands []string var minLens []int for i, max := 0, len(fields); i < max; { cmd := fields[i] cmdLen := len(cmd) i++ if i < max { num, err := strconv.Atoi(fields[i]) if err == nil && 1 <= num && num < cmdLen { cmdLen = num i++ } } commands = append(commands, cmd) minLens = append(minLens, cmdLen) } return commands, minLens } func validateCommands(commands []string, minLens []int, words []string) []string { var results []string for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func printResults(words []string, results []string) { wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0) io.WriteString(wr, "user words:") for _, word := range words { io.WriteString(wr, "\t"+word) } io.WriteString(wr, "\n") io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n") wr.Flush() } func main() { const table = "" + "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" commands, minLens := readTable(table) words := strings.Fields(sentence) results := validateCommands(commands, minLens, words) printResults(words, results) }
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } bool parse_integer(const std::string& word, int& value) { try { size_t pos; int i = std::stoi(word, &pos, 10); if (pos < word.length()) return false; value = i; return true; } catch (const std::exception& ex) { return false; } } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::istringstream is(table); std::string word; std::vector<std::string> words; while (is >> word) { uppercase(word); words.push_back(word); } for (size_t i = 0, n = words.size(); i < n; ++i) { word = words[i]; int len = word.length(); if (i + 1 < n && parse_integer(words[i + 1], len)) ++i; commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
package main import ( "io" "os" "strconv" "strings" "text/tabwriter" ) func readTable(table string) ([]string, []int) { fields := strings.Fields(table) var commands []string var minLens []int for i, max := 0, len(fields); i < max; { cmd := fields[i] cmdLen := len(cmd) i++ if i < max { num, err := strconv.Atoi(fields[i]) if err == nil && 1 <= num && num < cmdLen { cmdLen = num i++ } } commands = append(commands, cmd) minLens = append(minLens, cmdLen) } return commands, minLens } func validateCommands(commands []string, minLens []int, words []string) []string { var results []string for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func printResults(words []string, results []string) { wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0) io.WriteString(wr, "user words:") for _, word := range words { io.WriteString(wr, "\t"+word) } io.WriteString(wr, "\n") io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n") wr.Flush() } func main() { const table = "" + "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" commands, minLens := readTable(table) words := strings.Fields(sentence) results := validateCommands(commands, minLens, words) printResults(words, results) }
Convert this C++ snippet to Go and keep its semantics consistent.
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } bool parse_integer(const std::string& word, int& value) { try { size_t pos; int i = std::stoi(word, &pos, 10); if (pos < word.length()) return false; value = i; return true; } catch (const std::exception& ex) { return false; } } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::istringstream is(table); std::string word; std::vector<std::string> words; while (is >> word) { uppercase(word); words.push_back(word); } for (size_t i = 0, n = words.size(); i < n; ++i) { word = words[i]; int len = word.length(); if (i + 1 < n && parse_integer(words[i + 1], len)) ++i; commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
package main import ( "io" "os" "strconv" "strings" "text/tabwriter" ) func readTable(table string) ([]string, []int) { fields := strings.Fields(table) var commands []string var minLens []int for i, max := 0, len(fields); i < max; { cmd := fields[i] cmdLen := len(cmd) i++ if i < max { num, err := strconv.Atoi(fields[i]) if err == nil && 1 <= num && num < cmdLen { cmdLen = num i++ } } commands = append(commands, cmd) minLens = append(minLens, cmdLen) } return commands, minLens } func validateCommands(commands []string, minLens []int, words []string) []string { var results []string for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func printResults(words []string, results []string) { wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0) io.WriteString(wr, "user words:") for _, word := range words { io.WriteString(wr, "\t"+word) } io.WriteString(wr, "\n") io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n") wr.Flush() } func main() { const table = "" + "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" commands, minLens := readTable(table) words := strings.Fields(sentence) results := validateCommands(commands, minLens, words) printResults(words, results) }
Maintain the same structure and functionality when rewriting this code in Go.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> double log2( double number ) { return log( number ) / log( 2 ) ; } int main( int argc , char *argv[ ] ) { std::string teststring( argv[ 1 ] ) ; std::map<char , int> frequencies ; for ( char c : teststring ) frequencies[ c ] ++ ; int numlen = teststring.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent -= freq * log2( freq ) ; } std::cout << "The information content of " << teststring << " is " << infocontent << std::endl ; return 0 ; }
package main import ( "fmt" "math" "strings" ) func main(){ fmt.Println(H("1223334444")) } func H(data string) (entropy float64) { if data == "" { return 0 } for i := 0; i < 256; i++ { px := float64(strings.Count(data, string(byte(i)))) / float64(len(data)) if px > 0 { entropy += -px * math.Log2(px) } } return entropy }
Port the provided C++ code into Go while preserving the original functionality.
#include <iostream> #include <stdexcept> #include <string> #include <vector> using namespace std; vector<string> tokenize(const string& input, char seperator, char escape) { vector<string> output; string token; bool inEsc = false; for (char ch : input) { if (inEsc) { inEsc = false; } else if (ch == escape) { inEsc = true; continue; } else if (ch == seperator) { output.push_back(token); token = ""; continue; } token += ch; } if (inEsc) throw new invalid_argument("Invalid terminal escape"); output.push_back(token); return output; } int main() { string sample = "one^|uno||three^^^^|four^^^|^cuatro|"; cout << sample << endl; cout << '['; for (auto t : tokenize(sample, '|', '^')) { cout << '"' << t << "\", "; } cout << ']' << endl; return 0; }
package main import ( "errors" "fmt" ) func TokenizeString(s string, sep, escape rune) (tokens []string, err error) { var runes []rune inEscape := false for _, r := range s { switch { case inEscape: inEscape = false fallthrough default: runes = append(runes, r) case r == escape: inEscape = true case r == sep: tokens = append(tokens, string(runes)) runes = runes[:0] } } tokens = append(tokens, string(runes)) if inEscape { err = errors.New("invalid terminal escape") } return tokens, err } func main() { const sample = "one^|uno||three^^^^|four^^^|^cuatro|" const separator = '|' const escape = '^' fmt.Printf("Input: %q\n", sample) tokens, err := TokenizeString(sample, separator, escape) if err != nil { fmt.Println("error:", err) } else { fmt.Printf("Tokens: %q\n", tokens) } }
Translate the given C++ code snippet into Go without altering its behavior.
#include <iostream> int main () { std::cout << "Hello world!" << std::endl; }
package main import "fmt" func main() { fmt.Println("Hello world!") }
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <array> #include <iostream> #include <vector> #include <boost/circular_buffer.hpp> #include "prime_sieve.hpp" int main() { using std::cout; using std::vector; using boost::circular_buffer; using group_buffer = circular_buffer<vector<int>>; const int max = 1000035; const int max_group_size = 5; const int diff = 6; const int array_size = max + diff; const int max_groups = 5; const int max_unsexy = 10; prime_sieve sieve(array_size); std::array<int, max_group_size> group_count{0}; vector<group_buffer> groups(max_group_size, group_buffer(max_groups)); int unsexy_count = 0; circular_buffer<int> unsexy_primes(max_unsexy); vector<int> group; for (int p = 2; p < max; ++p) { if (!sieve.is_prime(p)) continue; if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) { ++unsexy_count; unsexy_primes.push_back(p); } else { group.clear(); group.push_back(p); for (int group_size = 1; group_size < max_group_size; group_size++) { int next_p = p + group_size * diff; if (next_p >= max || !sieve.is_prime(next_p)) break; group.push_back(next_p); ++group_count[group_size]; groups[group_size].push_back(group); } } } for (int size = 1; size < max_group_size; ++size) { cout << "number of groups of size " << size + 1 << " is " << group_count[size] << '\n'; cout << "last " << groups[size].size() << " groups of size " << size + 1 << ":"; for (const vector<int>& group : groups[size]) { cout << " ("; for (size_t i = 0; i < group.size(); ++i) { if (i > 0) cout << ' '; cout << group[i]; } cout << ")"; } cout << "\n\n"; } cout << "number of unsexy primes is " << unsexy_count << '\n'; cout << "last " << unsexy_primes.size() << " unsexy primes:"; for (int prime : unsexy_primes) cout << ' ' << prime; cout << '\n'; return 0; }
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func printHelper(cat string, le, lim, max int) (int, int, string) { cle, clim := commatize(le), commatize(lim) if cat != "unsexy primes" { cat = "sexy prime " + cat } fmt.Printf("Number of %s less than %s = %s\n", cat, clim, cle) last := max if le < last { last = le } verb := "are" if last == 1 { verb = "is" } return le, last, verb } func main() { lim := 1000035 sv := sieve(lim - 1) var pairs [][2]int var trips [][3]int var quads [][4]int var quins [][5]int var unsexy = []int{2, 3} for i := 3; i < lim; i += 2 { if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] { unsexy = append(unsexy, i) continue } if i < lim-6 && !sv[i] && !sv[i+6] { pair := [2]int{i, i + 6} pairs = append(pairs, pair) } else { continue } if i < lim-12 && !sv[i+12] { trip := [3]int{i, i + 6, i + 12} trips = append(trips, trip) } else { continue } if i < lim-18 && !sv[i+18] { quad := [4]int{i, i + 6, i + 12, i + 18} quads = append(quads, quad) } else { continue } if i < lim-24 && !sv[i+24] { quin := [5]int{i, i + 6, i + 12, i + 18, i + 24} quins = append(quins, quin) } } le, n, verb := printHelper("pairs", len(pairs), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, pairs[le-n:]) le, n, verb = printHelper("triplets", len(trips), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, trips[le-n:]) le, n, verb = printHelper("quadruplets", len(quads), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quads[le-n:]) le, n, verb = printHelper("quintuplets", len(quins), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quins[le-n:]) le, n, verb = printHelper("unsexy primes", len(unsexy), lim, 10) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, unsexy[le-n:]) }
Rewrite this program in Go while keeping its functionality equivalent to the C++ version.
#include <vector> #include <iterator> #include <algorithm> template<typename InputIterator, typename OutputIterator> OutputIterator forward_difference(InputIterator first, InputIterator last, OutputIterator dest) { if (first == last) return dest; typedef typename std::iterator_traits<InputIterator>::value_type value_type; value_type temp = *first++; while (first != last) { value_type temp2 = *first++; *dest++ = temp2 - temp; temp = temp2; } return dest; } template<typename InputIterator, typename OutputIterator> OutputIterator nth_forward_difference(int order, InputIterator first, InputIterator last, OutputIterator dest) { if (order == 0) return std::copy(first, last, dest); if (order == 1) return forward_difference(first, last, dest); typedef typename std::iterator_traits<InputIterator>::value_type value_type; std::vector<value_type> temp_storage; forward_difference(first, last, std::back_inserter(temp_storage)); typename std::vector<value_type>::iterator begin = temp_storage.begin(), end = temp_storage.end(); for (int i = 1; i < order-1; ++i) end = forward_difference(begin, end, begin); return forward_difference(begin, end, dest); } #include <iostream> int main() { double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 }; std::vector<double> dest; nth_forward_difference(1, array, array+10, std::back_inserter(dest)); std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; double* end = nth_forward_difference(3, array, array+10, array); for (double* p = array; p < end; ++p) std::cout << *p << " "; std::cout << std::endl; return 0; }
package main import "fmt" func main() { a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73} fmt.Println(a) fmt.Println(fd(a, 9)) } func fd(a []int, ord int) []int { for i := 0; i < ord; i++ { for j := 0; j < len(a)-i-1; j++ { a[j] = a[j+1] - a[j] } } return a[:len(a)-ord] }
Maintain the same structure and functionality when rewriting this code in Go.
#include <cmath> bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false; return true; }
func IsPrime(n int) bool { if n < 0 { n = -n } switch { case n == 2: return true case n < 2 || n % 2 == 0: return false default: for i = 3; i*i <= n; i += 2 { if n % i == 0 { return false } } } return true }
Please provide an equivalent version of this C++ code in Go.
#include <cmath> bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false; return true; }
func IsPrime(n int) bool { if n < 0 { n = -n } switch { case n == 2: return true case n < 2 || n % 2 == 0: return false default: for i = 3; i*i <= n; i += 2 { if n % i == 0 { return false } } } return true }
Convert the following code from C++ to Go, ensuring the logic remains intact.
double Factorial(double nValue) { double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; } double binomialCoefficient(double n, double k) { if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0; if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n; return Factorial(n) /(Factorial(k)*Factorial((n - k))); }
package main import "fmt" import "math/big" func main() { fmt.Println(new(big.Int).Binomial(5, 3)) fmt.Println(new(big.Int).Binomial(60, 30)) }
Write a version of this C++ function in Go with identical behavior.
int a[5]; a[0] = 1; int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; #include <string> std::string strings[4];
package main import "fmt" func main() { var a []interface{} a = append(a, 3) a = append(a, "apples", "oranges") fmt.Println(a) }
Convert the following code from C++ to Go, ensuring the logic remains intact.
#include <iostream> #include <forward_list> int main() { std::forward_list<int> list{1, 2, 3, 4, 5}; for (int e : list) std::cout << e << std::endl; }
start := &Ele{"tacos", nil} end := start.Append("burritos") end = end.Append("fajitas") end = end.Append("enchilatas") for iter := start; iter != nil; iter = iter.Next { fmt.Println(iter) }
Keep all operations the same but rewrite the snippet in Go.
#include <iostream> #include <forward_list> int main() { std::forward_list<int> list{1, 2, 3, 4, 5}; for (int e : list) std::cout << e << std::endl; }
start := &Ele{"tacos", nil} end := start.Append("burritos") end = end.Append("fajitas") end = end.Append("enchilatas") for iter := start; iter != nil; iter = iter.Next { fmt.Println(iter) }
Convert this C++ block to Go, preserving its control flow and logic.
#include <fstream> #include <cstdio> int main() { constexpr auto dimx = 800u, dimy = 800u; using namespace std; ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256); ofs.close(); return EXIT_SUCCESS; }
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <cstdio> #include <direct.h> int main() { remove( "input.txt" ); remove( "/input.txt" ); _rmdir( "docs" ); _rmdir( "/docs" ); return 0; }
package main import "os" func main() { os.Remove("input.txt") os.Remove("/input.txt") os.Remove("docs") os.Remove("/docs") os.RemoveAll("docs") os.RemoveAll("/docs") }
Write the same code in Go as shown below in C++.
#include <cstdio> #include <direct.h> int main() { remove( "input.txt" ); remove( "/input.txt" ); _rmdir( "docs" ); _rmdir( "/docs" ); return 0; }
package main import "os" func main() { os.Remove("input.txt") os.Remove("/input.txt") os.Remove("docs") os.Remove("/docs") os.RemoveAll("docs") os.RemoveAll("/docs") }
Write a version of this C++ function in Go with identical behavior.
#include <iostream> #include <algorithm> #include <vector> #include <sstream> #include <iterator> using namespace std; class myTuple { public: void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; } bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; } string second() { return t.second; } private: pair<pair<int, int>, string> t; }; class discordian { public: discordian() { myTuple t; t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t ); t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t ); t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t ); t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t ); t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t ); t.set( 8, 12, "Afflux" ); holyday.push_back( t ); seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" ); seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" ); wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" ); wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" ); } void convert( int d, int m, int y ) { if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { cout << "\nThis is not a date!"; return; } vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); int dd = d, day, wday, sea, yr = y + 1166; for( int x = 1; x < m; x++ ) dd += getMaxDay( x, 1 ); day = dd % 73; if( !day ) day = 73; wday = dd % 5; sea = ( dd - 1 ) / 73; if( d == 29 && m == 2 && isLeap( y ) ) { cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr; return; } cout << wdays[wday] << " " << seasons[sea] << " " << day; if( day > 10 && day < 14 ) cout << "th"; else switch( day % 10) { case 1: cout << "st"; break; case 2: cout << "nd"; break; case 3: cout << "rd"; break; default: cout << "th"; } cout << ", Year of Our Lady of Discord " << yr; if( f != holyday.end() ) cout << " - " << ( *f ).second(); } private: int getMaxDay( int m, int y ) { int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; } bool isLeap( int y ) { bool l = false; if( !( y % 4 ) ) { if( y % 100 ) l = true; else if( !( y % 400 ) ) l = true; } return l; } vector<myTuple> holyday; vector<string> seasons, wdays; }; int main( int argc, char* argv[] ) { string date; discordian disc; while( true ) { cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break; if( date.length() == 10 ) { istringstream iss( date ); vector<string> vc; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) ); disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); cout << "\n\n\n"; } else cout << "\nIs this a date?!\n\n"; } return 0; }
package ddate import ( "strconv" "strings" "time" ) const ( DefaultFmt = "Pungenday, Discord 5, 3131 YOLD" OldFmt = `Today is Pungenday, the 5th day of Discord in the YOLD 3131 Celebrate Mojoday` ) const ( protoLongSeason = "Discord" protoShortSeason = "Dsc" protoLongDay = "Pungenday" protoShortDay = "PD" protoOrdDay = "5" protoCardDay = "5th" protoHolyday = "Mojoday" protoYear = "3131" ) var ( longDay = []string{"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"} shortDay = []string{"SM", "BT", "PD", "PP", "SO"} longSeason = []string{ "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"} shortSeason = []string{"Chs", "Dsc", "Cfn", "Bcy", "Afm"} holyday = [][]string{{"Mungday", "Chaoflux"}, {"Mojoday", "Discoflux"}, {"Syaday", "Confuflux"}, {"Zaraday", "Bureflux"}, {"Maladay", "Afflux"}} ) type DiscDate struct { StTibs bool Dayy int Year int } func New(eris time.Time) DiscDate { t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(), eris.Second(), eris.Nanosecond(), eris.Location()) bob := int(eris.Sub(t).Hours()) / 24 raw := eris.Year() hastur := DiscDate{Year: raw + 1166} if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) { if bob > 59 { bob-- } else if bob == 59 { hastur.StTibs = true return hastur } } hastur.Dayy = bob return hastur } func (dd DiscDate) Format(f string) (r string) { var st, snarf string var dateElement bool f6 := func(proto, wibble string) { if !dateElement { snarf = r dateElement = true } if st > "" { r = "" } else { r += wibble } f = f[len(proto):] } f4 := func(proto, wibble string) { if dd.StTibs { st = "St. Tib's Day" } f6(proto, wibble) } season, day := dd.Dayy/73, dd.Dayy%73 for f > "" { switch { case strings.HasPrefix(f, protoLongDay): f4(protoLongDay, longDay[dd.Dayy%5]) case strings.HasPrefix(f, protoShortDay): f4(protoShortDay, shortDay[dd.Dayy%5]) case strings.HasPrefix(f, protoCardDay): funkychickens := "th" if day/10 != 1 { switch day % 10 { case 0: funkychickens = "st" case 1: funkychickens = "nd" case 2: funkychickens = "rd" } } f4(protoCardDay, strconv.Itoa(day+1)+funkychickens) case strings.HasPrefix(f, protoOrdDay): f4(protoOrdDay, strconv.Itoa(day+1)) case strings.HasPrefix(f, protoLongSeason): f6(protoLongSeason, longSeason[season]) case strings.HasPrefix(f, protoShortSeason): f6(protoShortSeason, shortSeason[season]) case strings.HasPrefix(f, protoHolyday): if day == 4 { r += holyday[season][0] } else if day == 49 { r += holyday[season][1] } f = f[len(protoHolyday):] case strings.HasPrefix(f, protoYear): r += strconv.Itoa(dd.Year) f = f[4:] default: r += f[:1] f = f[1:] } } if st > "" { r = snarf + st + r } return }
Port the provided C++ code into Go while preserving the original functionality.
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var n int = 3 var moves int = 0 a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } } b := make([][]int, len(a)) for i := range a { b[i] = make([]int, len(a[i])) copy(b[i], a[i]) } for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- { b = flipCol(b, rand.Intn(n) + 1) b = flipRow(b, rand.Intn(n) + 1) } fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) var rc rune var num int for { for{ fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n) _, err := fmt.Scanf("%c%d", &rc, &num) if err != nil { fmt.Println(err) continue } if num < 1 || num > n { fmt.Println("Wrong command!") continue } break } switch rc { case 'c': fmt.Printf("Column %v will be flipped\n", num) flipCol(b, num) case 'r': fmt.Printf("Row %v will be flipped\n", num) flipRow(b, num) default: fmt.Println("Wrong command!") continue } moves++ fmt.Println("\nMoves taken: ", moves) fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) if compareSlices(a, b) { fmt.Printf("Finished. You win with %d moves!\n", moves) break } } } func drawBoard (m [][]int) { fmt.Print(" ") for i := range m { fmt.Printf("%d ", i+1) } for i := range m { fmt.Println() fmt.Printf("%d ", i+1) for _, val := range m[i] { fmt.Printf(" %d", val) } } fmt.Print("\n") } func flipRow(m [][]int, row int) ([][]int) { for j := range m { m[row-1][j] ^= 1 } return m } func flipCol(m [][]int, col int) ([][]int) { for j := range m { m[j][col-1] ^= 1 } return m } func compareSlices(m [][]int, n[][]int) bool { o := true for i := range m { for j := range m { if m[i][j] != n[i][j] { o = false } } } return o }
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var n int = 3 var moves int = 0 a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } } b := make([][]int, len(a)) for i := range a { b[i] = make([]int, len(a[i])) copy(b[i], a[i]) } for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- { b = flipCol(b, rand.Intn(n) + 1) b = flipRow(b, rand.Intn(n) + 1) } fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) var rc rune var num int for { for{ fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n) _, err := fmt.Scanf("%c%d", &rc, &num) if err != nil { fmt.Println(err) continue } if num < 1 || num > n { fmt.Println("Wrong command!") continue } break } switch rc { case 'c': fmt.Printf("Column %v will be flipped\n", num) flipCol(b, num) case 'r': fmt.Printf("Row %v will be flipped\n", num) flipRow(b, num) default: fmt.Println("Wrong command!") continue } moves++ fmt.Println("\nMoves taken: ", moves) fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) if compareSlices(a, b) { fmt.Printf("Finished. You win with %d moves!\n", moves) break } } } func drawBoard (m [][]int) { fmt.Print(" ") for i := range m { fmt.Printf("%d ", i+1) } for i := range m { fmt.Println() fmt.Printf("%d ", i+1) for _, val := range m[i] { fmt.Printf(" %d", val) } } fmt.Print("\n") } func flipRow(m [][]int, row int) ([][]int) { for j := range m { m[row-1][j] ^= 1 } return m } func flipCol(m [][]int, col int) ([][]int) { for j := range m { m[j][col-1] ^= 1 } return m } func compareSlices(m [][]int, n[][]int) bool { o := true for i := range m { for j := range m { if m[i][j] != n[i][j] { o = false } } } return o }
Convert this C++ block to Go, preserving its control flow and logic.
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator = ln_two; for(int n = 1; n <= 17; n++) { decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; decfloat tenths_dig = floor((h - floor(h)) * 10); std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; } }
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
Can you help me rewrite this code in Go instead of C++, keeping it the same logically?
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator = ln_two; for(int n = 1; n <= 17; n++) { decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; decfloat tenths_dig = floor((h - floor(h)) * 10); std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; } }
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
Keep all operations the same but rewrite the snippet in Go.
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
Convert this C++ snippet to Go and keep its semantics consistent.
#include <string> #include <iostream> int main( ) { std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , replacement ( "little" ) ; std::string newString = original.replace( original.find( "X" ) , toBeReplaced.length( ) , replacement ) ; std::cout << "String after replacement: " << newString << " \n" ; return 0 ; }
package main import ( "fmt" ) func main() { str := "Mary had a %s lamb" txt := "little" out := fmt.Sprintf(str, txt) fmt.Println(out) }
Translate the given C++ code snippet into Go without altering its behavior.
#include <string> #include <iostream> int main( ) { std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , replacement ( "little" ) ; std::string newString = original.replace( original.find( "X" ) , toBeReplaced.length( ) , replacement ) ; std::cout << "String after replacement: " << newString << " \n" ; return 0 ; }
package main import ( "fmt" ) func main() { str := "Mary had a %s lamb" txt := "little" out := fmt.Sprintf(str, txt) fmt.Println(out) }
Generate an equivalent Go version of this C++ code.
#include <iostream> #include <vector> #include <stack> #include <iterator> #include <algorithm> #include <cassert> template <class E> struct pile_less { bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const { return pile1.top() < pile2.top(); } }; template <class E> struct pile_greater { bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const { return pile1.top() > pile2.top(); } }; template <class Iterator> void patience_sort(Iterator first, Iterator last) { typedef typename std::iterator_traits<Iterator>::value_type E; typedef std::stack<E> Pile; std::vector<Pile> piles; for (Iterator it = first; it != last; it++) { E& x = *it; Pile newPile; newPile.push(x); typename std::vector<Pile>::iterator i = std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>()); if (i != piles.end()) i->push(x); else piles.push_back(newPile); } std::make_heap(piles.begin(), piles.end(), pile_greater<E>()); for (Iterator it = first; it != last; it++) { std::pop_heap(piles.begin(), piles.end(), pile_greater<E>()); Pile &smallPile = piles.back(); *it = smallPile.top(); smallPile.pop(); if (smallPile.empty()) piles.pop_back(); else std::push_heap(piles.begin(), piles.end(), pile_greater<E>()); } assert(piles.empty()); } int main() { int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1}; patience_sort(a, a+sizeof(a)/sizeof(*a)); std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; return 0; }
package main import ( "fmt" "container/heap" "sort" ) type IntPile []int func (self IntPile) Top() int { return self[len(self)-1] } func (self *IntPile) Pop() int { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x } type IntPilesHeap []IntPile func (self IntPilesHeap) Len() int { return len(self) } func (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() } func (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] } func (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) } func (self *IntPilesHeap) Pop() interface{} { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x } func patience_sort (n []int) { var piles []IntPile for _, x := range n { j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x }) if j != len(piles) { piles[j] = append(piles[j], x) } else { piles = append(piles, IntPile{ x }) } } hp := IntPilesHeap(piles) heap.Init(&hp) for i, _ := range n { smallPile := heap.Pop(&hp).(IntPile) n[i] = smallPile.Pop() if len(smallPile) != 0 { heap.Push(&hp, smallPile) } } if len(hp) != 0 { panic("something went wrong") } } func main() { a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1} patience_sort(a) fmt.Println(a) }
Rewrite this program in Go while keeping its functionality equivalent to the C++ version.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT" func mutate(dna string, w [3]int) string { le := len(dna) p := rand.Intn(le) r := rand.Intn(300) bytes := []byte(dna) switch { case r < w[0]: base := bases[rand.Intn(4)] fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base) bytes[p] = base case r < w[0]+w[1]: fmt.Printf(" Delete @%3d %q\n", p, bytes[p]) copy(bytes[p:], bytes[p+1:]) bytes = bytes[0 : le-1] default: base := bases[rand.Intn(4)] bytes = append(bytes, 0) copy(bytes[p+1:], bytes[p:]) fmt.Printf(" Insert @%3d %q\n", p, base) bytes[p] = base } return string(bytes) } func generate(le int) string { bytes := make([]byte, le) for i := 0; i < le; i++ { bytes[i] = bases[rand.Intn(4)] } return string(bytes) } func prettyPrint(dna string, rowLen int) { fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += rowLen { k := i + rowLen if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Ξ£:", le) fmt.Println(" ======\n") } func wstring(w [3]int) string { return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2]) } func main() { rand.Seed(time.Now().UnixNano()) dna := generate(250) prettyPrint(dna, 50) muts := 10 w := [3]int{100, 100, 100} fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w)) fmt.Printf("MUTATIONS (%d):\n", muts) for i := 0; i < muts; i++ { dna = mutate(dna, w) } fmt.Println() prettyPrint(dna, 50) }
Translate the given C++ code snippet into Go without altering its behavior.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT" func mutate(dna string, w [3]int) string { le := len(dna) p := rand.Intn(le) r := rand.Intn(300) bytes := []byte(dna) switch { case r < w[0]: base := bases[rand.Intn(4)] fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base) bytes[p] = base case r < w[0]+w[1]: fmt.Printf(" Delete @%3d %q\n", p, bytes[p]) copy(bytes[p:], bytes[p+1:]) bytes = bytes[0 : le-1] default: base := bases[rand.Intn(4)] bytes = append(bytes, 0) copy(bytes[p+1:], bytes[p:]) fmt.Printf(" Insert @%3d %q\n", p, base) bytes[p] = base } return string(bytes) } func generate(le int) string { bytes := make([]byte, le) for i := 0; i < le; i++ { bytes[i] = bases[rand.Intn(4)] } return string(bytes) } func prettyPrint(dna string, rowLen int) { fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += rowLen { k := i + rowLen if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Ξ£:", le) fmt.Println(" ======\n") } func wstring(w [3]int) string { return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2]) } func main() { rand.Seed(time.Now().UnixNano()) dna := generate(250) prettyPrint(dna, 50) muts := 10 w := [3]int{100, 100, 100} fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w)) fmt.Printf("MUTATIONS (%d):\n", muts) for i := 0; i < muts; i++ { dna = mutate(dna, w) } fmt.Println() prettyPrint(dna, 50) }
Produce a language-to-language conversion: from C++ to Go, same semantics.
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } int main() { const unsigned int limit = 100; std::cout << "The first " << limit << " tau numbers are:\n"; unsigned int count = 0; for (unsigned int n = 1; count < limit; ++n) { if (n % divisor_count(n) == 0) { std::cout << std::setw(6) << n; ++count; if (count % 10 == 0) std::cout << '\n'; } } }
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } return count } func main() { fmt.Println("The first 100 tau numbers are:") count := 0 i := 1 for count < 100 { tf := countDivisors(i) if i%tf == 0 { fmt.Printf("%4d ", i) count++ if count%10 == 0 { fmt.Println() } } i++ } }
Convert this C++ block to Go, preserving its control flow and logic.
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, Οƒ := range p { pr *= m[i][Οƒ] } d += float64(s) * pr } return } func permanent(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, Οƒ := range p { pr *= m[i][Οƒ] } d += pr } return } var m2 = [][]float64{ {1, 2}, {3, 4}} var m3 = [][]float64{ {2, 9, 4}, {7, 5, 3}, {6, 1, 8}} func main() { fmt.Println(determinant(m2), permanent(m2)) fmt.Println(determinant(m3), permanent(m3)) }
Write the same algorithm in Go as shown in this C++ implementation.
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, Οƒ := range p { pr *= m[i][Οƒ] } d += float64(s) * pr } return } func permanent(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, Οƒ := range p { pr *= m[i][Οƒ] } d += pr } return } var m2 = [][]float64{ {1, 2}, {3, 4}} var m3 = [][]float64{ {2, 9, 4}, {7, 5, 3}, {6, 1, 8}} func main() { fmt.Println(determinant(m2), permanent(m2)) fmt.Println(determinant(m3), permanent(m3)) }
Translate the given C++ code snippet into Go without altering its behavior.
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; j = (k * (3*k + 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; } } return p[n]; } int main() { auto start = std::chrono::steady_clock::now(); auto result = partitions(6666); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> ms(end - start); std::cout << result << '\n'; std::cout << "elapsed time: " << ms.count() << " milliseconds\n"; }
package main import ( "fmt" "math/big" "time" ) var p []*big.Int var pd []int func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 } func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] } func partitionsP(n int) { if n < 2 { return } psum := new(big.Int) for i := 1; i <= n; i++ { pdi := partDiff(i) if pdi > n { break } sign := int64(-1) if (i-1)%4 < 2 { sign = 1 } t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign)) psum.Add(psum, t) } p[n] = psum } func main() { start := time.Now() const N = 6666 p = make([]*big.Int, N+1) pd = make([]int, N+1) p[0], pd[0] = big.NewInt(1), 1 p[1], pd[1] = big.NewInt(1), 1 for n := 2; n <= N; n++ { partitionsP(n) } fmt.Printf("p[%d)] = %d\n", N, p[N]) fmt.Printf("Took %s\n", time.Since(start)) }
Port the following code from C++ to Go with equivalent syntax and logic.
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; j = (k * (3*k + 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; } } return p[n]; } int main() { auto start = std::chrono::steady_clock::now(); auto result = partitions(6666); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> ms(end - start); std::cout << result << '\n'; std::cout << "elapsed time: " << ms.count() << " milliseconds\n"; }
package main import ( "fmt" "math/big" "time" ) var p []*big.Int var pd []int func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 } func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] } func partitionsP(n int) { if n < 2 { return } psum := new(big.Int) for i := 1; i <= n; i++ { pdi := partDiff(i) if pdi > n { break } sign := int64(-1) if (i-1)%4 < 2 { sign = 1 } t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign)) psum.Add(psum, t) } p[n] = psum } func main() { start := time.Now() const N = 6666 p = make([]*big.Int, N+1) pd = make([]int, N+1) p[0], pd[0] = big.NewInt(1), 1 p[1], pd[1] = big.NewInt(1), 1 for n := 2; n <= N; n++ { partitionsP(n) } fmt.Printf("p[%d)] = %d\n", N, p[N]) fmt.Printf("Took %s\n", time.Since(start)) }
Rewrite this program in Go while keeping its functionality equivalent to the C++ version.
#include <ggi/ggi.h> #include <set> #include <map> #include <utility> #include <iostream> #include <fstream> #include <string> #include <unistd.h> enum cell_type { none, wire, head, tail }; class display { public: display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors); ~display() { ggiClose(visual); ggiExit(); } void flush(); bool keypressed() { return ggiKbhit(visual); } void clear(); void putpixel(int x, int y, cell_type c); private: ggi_visual_t visual; int size_x, size_y; int pixel_size_x, pixel_size_y; ggi_pixel pixels[4]; }; display::display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors): pixel_size_x(pixsizex), pixel_size_y(pixsizey) { if (ggiInit() < 0) { std::cerr << "couldn't open ggi\n"; exit(1); } visual = ggiOpen(NULL); if (!visual) { ggiPanic("couldn't open visual\n"); } ggi_mode mode; if (ggiCheckGraphMode(visual, sizex, sizey, GGI_AUTO, GGI_AUTO, GT_4BIT, &mode) != 0) { if (GT_DEPTH(mode.graphtype) < 2) ggiPanic("low-color displays are not supported!\n"); } if (ggiSetMode(visual, &mode) != 0) { ggiPanic("couldn't set graph mode\n"); } ggiAddFlags(visual, GGIFLAG_ASYNC); size_x = mode.virt.x; size_y = mode.virt.y; for (int i = 0; i < 4; ++i) pixels[i] = ggiMapColor(visual, colors+i); } void display::flush() { ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual)); ggiFlush(visual); ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual)); } void display::clear() { ggiSetGCForeground(visual, pixels[0]); ggiDrawBox(visual, 0, 0, size_x, size_y); } void display::putpixel(int x, int y, cell_type cell) { ggiSetGCForeground(visual, pixels[cell]); ggiDrawBox(visual, x*pixel_size_x, y*pixel_size_y, pixel_size_x, pixel_size_y); } class wireworld { public: void set(int posx, int posy, cell_type type); void draw(display& destination); void step(); private: typedef std::pair<int, int> position; typedef std::set<position> position_set; typedef position_set::iterator positer; position_set wires, heads, tails; }; void wireworld::set(int posx, int posy, cell_type type) { position p(posx, posy); wires.erase(p); heads.erase(p); tails.erase(p); switch(type) { case head: heads.insert(p); break; case tail: tails.insert(p); break; case wire: wires.insert(p); break; } } void wireworld::draw(display& destination) { destination.clear(); for (positer i = heads.begin(); i != heads.end(); ++i) destination.putpixel(i->first, i->second, head); for (positer i = tails.begin(); i != tails.end(); ++i) destination.putpixel(i->first, i->second, tail); for (positer i = wires.begin(); i != wires.end(); ++i) destination.putpixel(i->first, i->second, wire); destination.flush(); } void wireworld::step() { std::map<position, int> new_heads; for (positer i = heads.begin(); i != heads.end(); ++i) for (int dx = -1; dx <= 1; ++dx) for (int dy = -1; dy <= 1; ++dy) { position pos(i->first + dx, i->second + dy); if (wires.count(pos)) new_heads[pos]++; } wires.insert(tails.begin(), tails.end()); tails.swap(heads); heads.clear(); for (std::map<position, int>::iterator i = new_heads.begin(); i != new_heads.end(); ++i) { if (i->second < 3) { wires.erase(i->first); heads.insert(i->first); } } } ggi_color colors[4] = {{ 0x0000, 0x0000, 0x0000 }, { 0x8000, 0x8000, 0x8000 }, { 0xffff, 0xffff, 0x0000 }, { 0xffff, 0x0000, 0x0000 }}; int main(int argc, char* argv[]) { int display_x = 800; int display_y = 600; int pixel_x = 5; int pixel_y = 5; if (argc < 2) { std::cerr << "No file name given!\n"; return 1; } std::ifstream f(argv[1]); wireworld w; std::string line; int line_number = 0; while (std::getline(f, line)) { for (int col = 0; col < line.size(); ++col) { switch (line[col]) { case 'h': case 'H': w.set(col, line_number, head); break; case 't': case 'T': w.set(col, line_number, tail); break; case 'w': case 'W': case '.': w.set(col, line_number, wire); break; default: std::cerr << "unrecognized character: " << line[col] << "\n"; return 1; case ' ': ; } } ++line_number; } display d(display_x, display_y, pixel_x, pixel_y, colors); w.draw(d); while (!d.keypressed()) { usleep(100000); w.step(); w.draw(d); } std::cout << std::endl; }
package main import ( "bytes" "fmt" "io/ioutil" "strings" ) var rows, cols int var rx, cx int var mn []int func main() { src, err := ioutil.ReadFile("ww.config") if err != nil { fmt.Println(err) return } srcRows := bytes.Split(src, []byte{'\n'}) rows = len(srcRows) for _, r := range srcRows { if len(r) > cols { cols = len(r) } } rx, cx = rows+2, cols+2 mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1} odd := make([]byte, rx*cx) even := make([]byte, rx*cx) for ri, r := range srcRows { copy(odd[(ri+1)*cx+1:], r) } for { print(odd) step(even, odd) fmt.Scanln() print(even) step(odd, even) fmt.Scanln() } } func print(grid []byte) { fmt.Println(strings.Repeat("__", cols)) fmt.Println() for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { if grid[r*cx+c] == 0 { fmt.Print(" ") } else { fmt.Printf(" %c", grid[r*cx+c]) } } fmt.Println() } } func step(dst, src []byte) { for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { x := r*cx + c dst[x] = src[x] switch dst[x] { case 'H': dst[x] = 't' case 't': dst[x] = '.' case '.': var nn int for _, n := range mn { if src[x+n] == 'H' { nn++ } } if nn == 1 || nn == 2 { dst[x] = 'H' } } } } }
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <algorithm> #include <cstdlib> #include <iomanip> #include <iostream> #include <limits> using namespace std; const double epsilon = numeric_limits<float>().epsilon(); const numeric_limits<double> DOUBLE; const double MIN = DOUBLE.min(); const double MAX = DOUBLE.max(); struct Point { const double x, y; }; struct Edge { const Point a, b; bool operator()(const Point& p) const { if (a.y > b.y) return Edge{ b, a }(p); if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon }); if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false; if (p.x < min(a.x, b.x)) return true; auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX; auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX; return blue >= red; } }; struct Figure { const string name; const initializer_list<Edge> edges; bool contains(const Point& p) const { auto c = 0; for (auto e : edges) if (e(p)) c++; return c % 2 != 0; } template<unsigned char W = 3> void check(const initializer_list<Point>& points, ostream& os) const { os << "Is point inside figure " << name << '?' << endl; for (auto p : points) os << " (" << setw(W) << p.x << ',' << setw(W) << p.y << "): " << boolalpha << contains(p) << endl; os << endl; } }; int main() { const initializer_list<Point> points = { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} }; const Figure square = { "Square", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} } }; const Figure square_hole = { "Square hole", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}}, {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}} } }; const Figure strange = { "Strange", { {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}}, {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}} } }; const Figure exagon = { "Exagon", { {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}}, {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}} } }; for(auto f : {square, square_hole, strange, exagon}) f.check(points, cout); return EXIT_SUCCESS; }
package main import ( "fmt" "math" ) type xy struct { x, y float64 } type seg struct { p1, p2 xy } type poly struct { name string sides []seg } func inside(pt xy, pg poly) (i bool) { for _, side := range pg.sides { if rayIntersectsSegment(pt, side) { i = !i } } return } func rayIntersectsSegment(p xy, s seg) bool { var a, b xy if s.p1.y < s.p2.y { a, b = s.p1, s.p2 } else { a, b = s.p2, s.p1 } for p.y == a.y || p.y == b.y { p.y = math.Nextafter(p.y, math.Inf(1)) } if p.y < a.y || p.y > b.y { return false } if a.x > b.x { if p.x > a.x { return false } if p.x < b.x { return true } } else { if p.x > b.x { return false } if p.x < a.x { return true } } return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x) } var ( p1 = xy{0, 0} p2 = xy{10, 0} p3 = xy{10, 10} p4 = xy{0, 10} p5 = xy{2.5, 2.5} p6 = xy{7.5, 2.5} p7 = xy{7.5, 7.5} p8 = xy{2.5, 7.5} p9 = xy{0, 5} p10 = xy{10, 5} p11 = xy{3, 0} p12 = xy{7, 0} p13 = xy{7, 10} p14 = xy{3, 10} ) var tpg = []poly{ {"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}}, {"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}, {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}}, {"strange", []seg{{p1, p5}, {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}}, {"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13}, {p13, p14}, {p14, p9}, {p9, p11}}}, } var tpt = []xy{ {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10}, {1, 2}, {2, 1}, } func main() { for _, pg := range tpg { fmt.Printf("%s:\n", pg.name) for _, pt := range tpt { fmt.Println(pt, inside(pt, pg)) } } }
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { return; } if(m_y == 0) { *this = EllipticPoint(); } else { double L = (3 * m_x * m_x) / (2 * m_y); double newX = L * L - 2 * m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } } public: friend std::ostream& operator<<(std::ostream&, const EllipticPoint&); constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {} explicit EllipticPoint(double yCoordinate) noexcept { m_y = yCoordinate; m_x = cbrt(m_y * m_y - B); } bool IsZero() const noexcept { bool isNotZero = abs(m_y) < ZeroThreshold; return !isNotZero; } EllipticPoint operator-() const noexcept { EllipticPoint negPt; negPt.m_x = m_x; negPt.m_y = -m_y; return negPt; } EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept { if(IsZero()) { *this = rhs; } else if (rhs.IsZero()) { } else { double L = (rhs.m_y - m_y) / (rhs.m_x - m_x); if(isfinite(L)) { double newX = L * L - m_x - rhs.m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } else { if(signbit(m_y) != signbit(rhs.m_y)) { *this = EllipticPoint(); } else { Double(); } } } return *this; } EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept { *this+= -rhs; return *this; } EllipticPoint& operator*=(int rhs) noexcept { EllipticPoint r; EllipticPoint p = *this; if(rhs < 0) { rhs = -rhs; p = -p; } for (int i = 1; i <= rhs; i <<= 1) { if (i & rhs) r += p; p.Double(); } *this = r; return *this; } }; inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += rhs; return lhs; } inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += -rhs; return lhs; } inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept { lhs *= rhs; return lhs; } inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept { rhs *= lhs; return rhs; } ostream& operator<<(ostream& os, const EllipticPoint& pt) { if(pt.IsZero()) cout << "(Zero)\n"; else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n"; return os; } int main(void) { const EllipticPoint a(1), b(2); cout << "a = " << a; cout << "b = " << b; const EllipticPoint c = a + b; cout << "c = a + b = " << c; cout << "a + b - c = " << a + b - c; cout << "a + b - (b + a) = " << a + b - (b + a) << "\n"; cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a; cout << "a * 12345 = " << a * 12345; cout << "a * -12345 = " << a * -12345; cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345; cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345); cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n"; const EllipticPoint zero; EllipticPoint g; cout << "g = zero = " << g; cout << "g += a = " << (g+=a); cout << "g += zero = " << (g+=zero); cout << "g += b = " << (g+=b); cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n"; EllipticPoint special(0); cout << "special = " << special; cout << "special *= 2 = " << (special*=2); return 0; }
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f,Β %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
Produce a functionally identical Go code for the snippet given in C++.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { return; } if(m_y == 0) { *this = EllipticPoint(); } else { double L = (3 * m_x * m_x) / (2 * m_y); double newX = L * L - 2 * m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } } public: friend std::ostream& operator<<(std::ostream&, const EllipticPoint&); constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {} explicit EllipticPoint(double yCoordinate) noexcept { m_y = yCoordinate; m_x = cbrt(m_y * m_y - B); } bool IsZero() const noexcept { bool isNotZero = abs(m_y) < ZeroThreshold; return !isNotZero; } EllipticPoint operator-() const noexcept { EllipticPoint negPt; negPt.m_x = m_x; negPt.m_y = -m_y; return negPt; } EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept { if(IsZero()) { *this = rhs; } else if (rhs.IsZero()) { } else { double L = (rhs.m_y - m_y) / (rhs.m_x - m_x); if(isfinite(L)) { double newX = L * L - m_x - rhs.m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } else { if(signbit(m_y) != signbit(rhs.m_y)) { *this = EllipticPoint(); } else { Double(); } } } return *this; } EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept { *this+= -rhs; return *this; } EllipticPoint& operator*=(int rhs) noexcept { EllipticPoint r; EllipticPoint p = *this; if(rhs < 0) { rhs = -rhs; p = -p; } for (int i = 1; i <= rhs; i <<= 1) { if (i & rhs) r += p; p.Double(); } *this = r; return *this; } }; inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += rhs; return lhs; } inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += -rhs; return lhs; } inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept { lhs *= rhs; return lhs; } inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept { rhs *= lhs; return rhs; } ostream& operator<<(ostream& os, const EllipticPoint& pt) { if(pt.IsZero()) cout << "(Zero)\n"; else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n"; return os; } int main(void) { const EllipticPoint a(1), b(2); cout << "a = " << a; cout << "b = " << b; const EllipticPoint c = a + b; cout << "c = a + b = " << c; cout << "a + b - c = " << a + b - c; cout << "a + b - (b + a) = " << a + b - (b + a) << "\n"; cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a; cout << "a * 12345 = " << a * 12345; cout << "a * -12345 = " << a * -12345; cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345; cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345); cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n"; const EllipticPoint zero; EllipticPoint g; cout << "g = zero = " << g; cout << "g += a = " << (g+=a); cout << "g += zero = " << (g+=zero); cout << "g += b = " << (g+=b); cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n"; EllipticPoint special(0); cout << "special = " << special; cout << "special *= 2 = " << (special*=2); return 0; }
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f,Β %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
Convert this C++ snippet to Go and keep its semantics consistent.
#include <iostream> #include <string> int countSubstring(const std::string& str, const std::string& sub) { if (sub.length() == 0) return 0; int count = 0; for (size_t offset = str.find(sub); offset != std::string::npos; offset = str.find(sub, offset + sub.length())) { ++count; } return count; } int main() { std::cout << countSubstring("the three truths", "th") << '\n'; std::cout << countSubstring("ababababab", "abab") << '\n'; std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n'; return 0; }
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.Count("the three truths", "th")) fmt.Println(strings.Count("ababababab", "abab")) }
Keep all operations the same but rewrite the snippet in Go.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
Keep all operations the same but rewrite the snippet in Go.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
Convert this C++ block to Go, preserving its control flow and logic.
#include <algorithm> #include <iostream> #include <sstream> #include <string> template <typename T> void demo_compare(const T &a, const T &b, const std::string &semantically) { std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ") << "exactly " << semantically << " equal." << std::endl; std::cout << a << " and " << b << " are " << ((a != b) ? "" : "not ") << semantically << "inequal." << std::endl; std::cout << a << " is " << ((a < b) ? "" : "not ") << semantically << " ordered before " << b << '.' << std::endl; std::cout << a << " is " << ((a > b) ? "" : "not ") << semantically << " ordered after " << b << '.' << std::endl; } int main(int argc, char *argv[]) { std::string a((argc > 1) ? argv[1] : "1.2.Foo"); std::string b((argc > 2) ? argv[2] : "1.3.Bar"); demo_compare<std::string>(a, b, "lexically"); std::transform(a.begin(), a.end(), a.begin(), ::tolower); std::transform(b.begin(), b.end(), b.begin(), ::tolower); demo_compare<std::string>(a, b, "lexically"); double numA, numB; std::istringstream(a) >> numA; std::istringstream(b) >> numB; demo_compare<double>(numA, numB, "numerically"); return (a == b); }
package main import ( "fmt" "strings" ) func main() { c := "cat" d := "dog" if c == d { fmt.Println(c, "is bytewise identical to", d) } if c != d { fmt.Println(c, "is bytewise different from", d) } if c > d { fmt.Println(c, "is lexically bytewise greater than", d) } if c < d { fmt.Println(c, "is lexically bytewise less than", d) } if c >= d { fmt.Println(c, "is lexically bytewise greater than or equal to", d) } if c <= d { fmt.Println(c, "is lexically bytewise less than or equal to", d) } eqf := `when interpreted as UTF-8 and compared under Unicode simple case folding rules.` if strings.EqualFold(c, d) { fmt.Println(c, "equal to", d, eqf) } else { fmt.Println(c, "not equal to", d, eqf) } }
Transform the following C++ implementation into Go, maintaining the same output and logic.
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
package main import ( "fmt" "io" "os" "strings" "time" ) func addNote(fn string, note string) error { f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return err } _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n") if cErr := f.Close(); err == nil { err = cErr } return err } func showNotes(w io.Writer, fn string) error { f, err := os.Open(fn) if err != nil { if os.IsNotExist(err) { return nil } return err } _, err = io.Copy(w, f) f.Close() return err } func main() { const fn = "NOTES.TXT" var err error if len(os.Args) > 1 { err = addNote(fn, strings.Join(os.Args[1:], " ")) } else { err = showNotes(os.Stdout, fn) } if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
Convert this C++ block to Go, preserving its control flow and logic.
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
package main import ( "fmt" "io" "os" "strings" "time" ) func addNote(fn string, note string) error { f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return err } _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n") if cErr := f.Close(); err == nil { err = cErr } return err } func showNotes(w io.Writer, fn string) error { f, err := os.Open(fn) if err != nil { if os.IsNotExist(err) { return nil } return err } _, err = io.Copy(w, f) f.Close() return err } func main() { const fn = "NOTES.TXT" var err error if len(os.Args) > 1 { err = addNote(fn, strings.Join(os.Args[1:], " ")) } else { err = showNotes(os.Stdout, fn) } if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
Rewrite the snippet below in Go so it works the same as the original C++ code.
#include <cmath> #include <iostream> #include <iomanip> #include <string.h> constexpr unsigned int N = 32u; double xval[N], t_sin[N], t_cos[N], t_tan[N]; constexpr unsigned int N2 = N * (N - 1u) / 2u; double r_sin[N2], r_cos[N2], r_tan[N2]; double ρ(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; unsigned int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, unsigned int n) { return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } inline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); } inline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); } inline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); } int main() { constexpr double step = .05; for (auto i = 0u; i < N; i++) { xval[i] = i * step; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (auto i = 0u; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = NAN; std::cout << std::setw(16) << std::setprecision(25) << 6 * i_sin(.5) << std::endl << 3 * i_cos(.5) << std::endl << 4 * i_tan(1.) << std::endl; return 0; }
package main import ( "fmt" "math" ) func main() { const nn = 32 const step = .05 xVal := make([]float64, nn) tSin := make([]float64, nn) tCos := make([]float64, nn) tTan := make([]float64, nn) for i := range xVal { xVal[i] = float64(i) * step tSin[i], tCos[i] = math.Sincos(xVal[i]) tTan[i] = tSin[i] / tCos[i] } iSin := thieleInterpolator(tSin, xVal) iCos := thieleInterpolator(tCos, xVal) iTan := thieleInterpolator(tTan, xVal) fmt.Printf("%16.14f\n", 6*iSin(.5)) fmt.Printf("%16.14f\n", 3*iCos(.5)) fmt.Printf("%16.14f\n", 4*iTan(1)) } func thieleInterpolator(x, y []float64) func(float64) float64 { n := len(x) ρ := make([][]float64, n) for i := range ρ { ρ[i] = make([]float64, n-i) ρ[i][0] = y[i] } for i := 0; i < n-1; i++ { ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]) } for i := 2; i < n; i++ { for j := 0; j < n-i; j++ { ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2] } } ρ0 := ρ[0] return func(xin float64) float64 { var a float64 for i := n - 1; i > 1; i-- { a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a) } return y[0] + (xin-x[0])/(ρ0[1]+a) } }
Ensure the translated Go code behaves exactly like the original C++ snippet.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s Β %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d Β %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d Β %.16f\n", n, len(s), entropy(s)) } }
Port the following code from C++ to Go with equivalent syntax and logic.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s Β %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d Β %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d Β %.16f\n", n, len(s), entropy(s)) } }
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s Β %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d Β %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d Β %.16f\n", n, len(s), entropy(s)) } }
Port the provided C++ code into Go while preserving the original functionality.
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(double a) { return normalize<double>(a, 400); } inline double m2m(double a) { return normalize<double>(a, 6400); } inline double r2r(double a) { return normalize<double>(a, 2*M_PI); } double d2g(double a) { return g2g(a * 10 / 9); } double d2m(double a) { return m2m(a * 160 / 9); } double d2r(double a) { return r2r(a * M_PI / 180); } double g2d(double a) { return d2d(a * 9 / 10); } double g2m(double a) { return m2m(a * 16); } double g2r(double a) { return r2r(a * M_PI / 200); } double m2d(double a) { return d2d(a * 9 / 160); } double m2g(double a) { return g2g(a / 16); } double m2r(double a) { return r2r(a * M_PI / 3200); } double r2d(double a) { return d2d(a * 180 / M_PI); } double r2g(double a) { return g2g(a * 200 / M_PI); } double r2m(double a) { return m2m(a * 3200 / M_PI); } void print(const std::vector<double> &values, const char *s, std::function<double(double)> f) { using namespace std; ostringstream out; out << " β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”\n"; out << " β”‚ " << setw(17) << s << " β”‚\n"; out << "β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€\n"; for (double i : values) out << "β”‚ " << setw(15) << fixed << i << defaultfloat << " β”‚ " << setw(17) << fixed << f(i) << defaultfloat << " β”‚\n"; out << "β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜\n"; auto str = out.str(); boost::algorithm::replace_all(str, ".000000", " "); cout << str; } int main() { std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 }; print(values, "normalized (deg)", d2d); print(values, "normalized (grad)", g2g); print(values, "normalized (mil)", m2m); print(values, "normalized (rad)", r2r); print(values, "deg -> grad ", d2g); print(values, "deg -> mil ", d2m); print(values, "deg -> rad ", d2r); print(values, "grad -> deg ", g2d); print(values, "grad -> mil ", g2m); print(values, "grad -> rad ", g2r); print(values, "mil -> deg ", m2d); print(values, "mil -> grad ", m2g); print(values, "mil -> rad ", m2r); print(values, "rad -> deg ", r2d); print(values, "rad -> grad ", r2g); print(values, "rad -> mil ", r2m); return 0; }
package main import ( "fmt" "math" "strconv" "strings" ) func d2d(d float64) float64 { return math.Mod(d, 360) } func g2g(g float64) float64 { return math.Mod(g, 400) } func m2m(m float64) float64 { return math.Mod(m, 6400) } func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) } func d2g(d float64) float64 { return d2d(d) * 400 / 360 } func d2m(d float64) float64 { return d2d(d) * 6400 / 360 } func d2r(d float64) float64 { return d2d(d) * math.Pi / 180 } func g2d(g float64) float64 { return g2g(g) * 360 / 400 } func g2m(g float64) float64 { return g2g(g) * 6400 / 400 } func g2r(g float64) float64 { return g2g(g) * math.Pi / 200 } func m2d(m float64) float64 { return m2m(m) * 360 / 6400 } func m2g(m float64) float64 { return m2m(m) * 400 / 6400 } func m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 } func r2d(r float64) float64 { return r2r(r) * 180 / math.Pi } func r2g(r float64) float64 { return r2r(r) * 200 / math.Pi } func r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi } func s(f float64) string { wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), ".") if len(wf) == 1 { return fmt.Sprintf("%7s ", wf[0]) } le := len(wf[1]) if le > 7 { le = 7 } return fmt.Sprintf("%7s.%-7s", wf[0], wf[1][:le]) } func main() { angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ft := "%s %s %s %s %s\n" fmt.Printf(ft, " degrees ", "normalized degs", " gradians ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a))) } fmt.Printf(ft, "\n gradians ", "normalized grds", " degrees ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a))) } fmt.Printf(ft, "\n mils ", "normalized mils", " degrees ", " gradians ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a))) } fmt.Printf(ft, "\n radians ", "normalized rads", " degrees ", " gradians ", " mils ") for _, a := range angles { fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a))) } }
Please provide an equivalent version of this C++ code in Go.
#include <algorithm> #include <iostream> #include <string> #include <vector> std::string longestPath( const std::vector<std::string> & , char ) ; int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std::vector<std::string> myDirs ( dirs , dirs + 3 ) ; std::cout << "The longest common path of the given directories is " << longestPath( myDirs , '/' ) << "!\n" ; return 0 ; } std::string longestPath( const std::vector<std::string> & dirs , char separator ) { std::vector<std::string>::const_iterator vsi = dirs.begin( ) ; int maxCharactersCommon = vsi->length( ) ; std::string compareString = *vsi ; for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) { std::pair<std::string::const_iterator , std::string::const_iterator> p = std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ; if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) maxCharactersCommon = p.first - compareString.begin( ) ; } std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ; return compareString.substr( 0 , found ) ; }
package main import ( "fmt" "os" "path" ) func CommonPrefix(sep byte, paths ...string) string { switch len(paths) { case 0: return "" case 1: return path.Clean(paths[0]) } c := []byte(path.Clean(paths[0])) c = append(c, sep) for _, v := range paths[1:] { v = path.Clean(v) + string(sep) if len(v) < len(c) { c = c[:len(v)] } for i := 0; i < len(c); i++ { if v[i] != c[i] { c = c[:i] break } } } for i := len(c) - 1; i >= 0; i-- { if c[i] == sep { c = c[:i] break } } return string(c) } func main() { c := CommonPrefix(os.PathSeparator, "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", "/home "/home/user1/././tmp/covertly/foo", "/home/bob/../user1/tmp/coved/bar", ) if c == "" { fmt.Println("No common path") } else { fmt.Println("Common path:", c) } }
Produce a language-to-language conversion: from C++ to Go, same semantics.
#include <map> #include <iostream> #include <cmath> template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist; for (int i = 0; i < calls; ++i) ++dist[f()]; double mean = 1.0/dist.size(); bool good = true; for (distmap::iterator i = dist.begin(); i != dist.end(); ++i) { if (std::abs((1.0 * i->second)/calls - mean) > delta) { std::cout << "Relative frequency " << i->second/(1.0*calls) << " of result " << i->first << " deviates by more than " << delta << " from the expected value " << mean << "\n"; good = false; } } return good; }
package main import ( "fmt" "math" "math/rand" "time" ) func dice5() int { return rand.Intn(5) + 1 } func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break } } return (i / 3) - 1 } func distCheck(f func() int, n int, repeats int, delta float64) (max float64, flatEnough bool) { count := make([]int, n) for i := 0; i < repeats; i++ { count[f()-1]++ } expected := float64(repeats) / float64(n) for _, c := range count { max = math.Max(max, math.Abs(float64(c)-expected)) } return max, max < delta } func main() { rand.Seed(time.Now().UnixNano()) const calls = 1000000 max, flatEnough := distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) max, flatEnough = distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) }
Write the same algorithm in Go as shown in this C++ implementation.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
Keep all operations the same but rewrite the snippet in Go.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
Please provide an equivalent version of this C++ code in Go.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
Generate an equivalent Go version of this C++ code.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
Translate the given C++ code snippet into Go without altering its behavior.
#include <string> int main() { int* p; p = new int; delete p; p = new int(2); delete p; std::string* p2; p2 = new std::string; delete p2; p = new int[10]; delete[] p; p2 = new std::string[10]; delete[] p2; }
func inc(n int) { x := n + 1 println(x) }
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <windows.h> #include <iostream> #include <string> using namespace std; enum players { Computer, Human, Draw, None }; const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } }; class ttt { public: ttt() { _p = rand() % 2; reset(); } void play() { int res = Draw; while( true ) { drawGrid(); while( true ) { if( _p ) getHumanMove(); else getComputerMove(); drawGrid(); res = checkVictory(); if( res != None ) break; ++_p %= 2; } if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!"; else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!"; else cout << "It's a draw!"; cout << endl << endl; string r; cout << "Play again( Y / N )? "; cin >> r; if( r != "Y" && r != "y" ) return; ++_p %= 2; reset(); } } private: void reset() { for( int x = 0; x < 9; x++ ) _field[x] = None; } void drawGrid() { system( "cls" ); COORD c = { 0, 2 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); cout << " 1 | 2 | 3 " << endl; cout << "---+---+---" << endl; cout << " 4 | 5 | 6 " << endl; cout << "---+---+---" << endl; cout << " 7 | 8 | 9 " << endl << endl << endl; int f = 0; for( int y = 0; y < 5; y += 2 ) for( int x = 1; x < 11; x += 4 ) { if( _field[f] != None ) { COORD c = { x, 2 + y }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); string o = _field[f] == Computer ? "X" : "O"; cout << o; } f++; } c.Y = 9; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); } int checkVictory() { for( int i = 0; i < 8; i++ ) { if( _field[iWin[i][0]] != None && _field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] ) { return _field[iWin[i][0]]; } } int i = 0; for( int f = 0; f < 9; f++ ) { if( _field[f] != None ) i++; } if( i == 9 ) return Draw; return None; } void getHumanMove() { int m; cout << "Enter your move ( 1 - 9 ) "; while( true ) { m = 0; do { cin >> m; } while( m < 1 && m > 9 ); if( _field[m - 1] != None ) cout << "Invalid move. Try again!" << endl; else break; } _field[m - 1] = Human; } void getComputerMove() { int move = 0; do{ move = rand() % 9; } while( _field[move] != None ); for( int i = 0; i < 8; i++ ) { int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2]; if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None ) { move = try3; if( _field[try1] == Computer ) break; } if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) { move = try2; if( _field[try1] == Computer ) break; } if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None ) { move = try1; if( _field[try2] == Computer ) break; } } _field[move] = Computer; } int _p; int _field[9]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); ttt tic; tic.play(); return 0; }
package main import ( "bufio" "fmt" "math/rand" "os" "strings" ) var b []byte func printBoard() { fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9]) } var pScore, cScore int var pMark, cMark byte = 'X', 'O' var in = bufio.NewReader(os.Stdin) func main() { b = make([]byte, 9) fmt.Println("Play by entering a digit.") for { for i := range b { b[i] = '1' + byte(i) } computerStart := cMark == 'X' if computerStart { fmt.Println("I go first, playing X's") } else { fmt.Println("You go first, playing X's") } TakeTurns: for { if !computerStart { if !playerTurn() { return } if gameOver() { break TakeTurns } } computerStart = false computerTurn() if gameOver() { break TakeTurns } } fmt.Println("Score: you", pScore, "me", cScore) fmt.Println("\nLet's play again.") } } func playerTurn() bool { var pm string var err error for i := 0; i < 3; i++ { printBoard() fmt.Printf("%c's move? ", pMark) if pm, err = in.ReadString('\n'); err != nil { fmt.Println(err) return false } pm = strings.TrimSpace(pm) if pm >= "1" && pm <= "9" && b[pm[0]-'1'] == pm[0] { x := pm[0] - '1' b[x] = pMark return true } } fmt.Println("You're not playing right.") return false } var choices = make([]int, 9) func computerTurn() { printBoard() var x int defer func() { fmt.Println("My move:", x+1) b[x] = cMark }() block := -1 for _, l := range lines { var mine, yours int x = -1 for _, sq := range l { switch b[sq] { case cMark: mine++ case pMark: yours++ default: x = sq } } if mine == 2 && x >= 0 { return } if yours == 2 && x >= 0 { block = x } } if block >= 0 { x = block return } choices = choices[:0] for i, sq := range b { if sq == '1'+byte(i) { choices = append(choices, i) } } x = choices[rand.Intn(len(choices))] } func gameOver() bool { for _, l := range lines { if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] { printBoard() if b[l[0]] == cMark { fmt.Println("I win!") cScore++ pMark, cMark = 'X', 'O' } else { fmt.Println("You win!") pScore++ pMark, cMark = 'O', 'X' } return true } } for i, sq := range b { if sq == '1'+byte(i) { return false } } fmt.Println("Cat game.") pMark, cMark = cMark, pMark return true } var lines = [][]int{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}, }
Produce a functionally identical Go code for the snippet given in C++.
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
Preserve the algorithm and functionality while converting the code from C++ to Go.
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
Change the following C++ code into Go without altering its purpose.
#include <iostream> #include <fstream> #include <cmath> using namespace std; string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; } double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; } int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
package main import ( "fmt" "io/ioutil" "log" "math" "os" "runtime" ) func main() { _, src, _, _ := runtime.Caller(0) fmt.Println("Source file entropy:", entropy(src)) fmt.Println("Binary file entropy:", entropy(os.Args[0])) } func entropy(file string) float64 { d, err := ioutil.ReadFile(file) if err != nil { log.Fatal(err) } var f [256]float64 for _, b := range d { f[b]++ } hm := 0. for _, c := range f { if c > 0 { hm += c * math.Log2(c) } } l := float64(len(d)) return math.Log2(l) - hm/l }
Generate a Go translation of this PHP snippet without changing its computational steps.
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
package main import "fmt" func bitwise(a, b int16) { fmt.Printf("a: %016b\n", uint16(a)) fmt.Printf("b: %016b\n", uint16(b)) fmt.Printf("and: %016b\n", uint16(a&b)) fmt.Printf("or: %016b\n", uint16(a|b)) fmt.Printf("xor: %016b\n", uint16(a^b)) fmt.Printf("not: %016b\n", uint16(^a)) if b < 0 { fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).") return } ua := uint16(a) ub := uint32(b) fmt.Printf("shl: %016b\n", uint16(ua<<ub)) fmt.Printf("shr: %016b\n", uint16(ua>>ub)) fmt.Printf("las: %016b\n", uint16(a<<ub)) fmt.Printf("ras: %016b\n", uint16(a>>ub)) fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub)))) fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub))) } func main() { var a, b int16 = -460, 6 bitwise(a, b) }
Transform the following PHP implementation into Go, maintaining the same output and logic.
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
package main import "fmt" func bitwise(a, b int16) { fmt.Printf("a: %016b\n", uint16(a)) fmt.Printf("b: %016b\n", uint16(b)) fmt.Printf("and: %016b\n", uint16(a&b)) fmt.Printf("or: %016b\n", uint16(a|b)) fmt.Printf("xor: %016b\n", uint16(a^b)) fmt.Printf("not: %016b\n", uint16(^a)) if b < 0 { fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).") return } ua := uint16(a) ub := uint32(b) fmt.Printf("shl: %016b\n", uint16(ua<<ub)) fmt.Printf("shr: %016b\n", uint16(ua>>ub)) fmt.Printf("las: %016b\n", uint16(a<<ub)) fmt.Printf("ras: %016b\n", uint16(a>>ub)) fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub)))) fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub))) } func main() { var a, b int16 = -460, 6 bitwise(a, b) }
Port the provided PHP code into Go while preserving the original functionality.
<?php $file = fopen(__FILE__, 'r'); // read current file while ($line = fgets($file)) { $line = rtrim($line); // removes linebreaks and spaces at end echo strrev($line) . "\n"; // reverse line and upload it }
package main import ( "bufio" "fmt" "log" "os" ) func init() { log.SetFlags(log.Lshortfile) } func main() { inputFile, err := os.Open("byline.go") if err != nil { log.Fatal("Error opening input file:", err) } defer inputFile.Close() scanner := bufio.NewScanner(inputFile) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(scanner.Err()) } }