Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate an equivalent Python version of this C++ code. | #include <windows.h>
#include <math.h>
#include <string>
const int BMP_SIZE = 240, MY_TIMER = 987654;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
DWORD* bits() { return ( DWORD* )pBits; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class plasma
{
public:
plasma() {
currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;
_bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();
plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
int i, j, dst = 0;
double temp;
for( j = 0; j < BMP_SIZE * 2; j++ ) {
for( i = 0; i < BMP_SIZE * 2; i++ ) {
plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );
plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) +
( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );
dst++;
}
}
}
void update() {
DWORD dst;
BYTE a, c1,c2, c3;
currentTime += ( double )( rand() % 2 + 1 );
int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ),
x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ),
x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),
y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ),
y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ),
y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );
int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;
DWORD* bits = _bmp.bits();
for( int j = 0; j < BMP_SIZE; j++ ) {
dst = j * BMP_SIZE;
for( int i= 0; i < BMP_SIZE; i++ ) {
a = plasma2[src1] + plasma1[src2] + plasma2[src3];
c1 = a << 1; c2 = a << 2; c3 = a << 3;
bits[dst + i] = RGB( c1, c2, c3 );
src1++; src2++; src3++;
}
src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;
}
draw();
}
void setHWND( HWND hwnd ) { _hwnd = hwnd; }
private:
void draw() {
HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );
BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );
ReleaseDC( _hwnd, wdc );
}
myBitmap _bmp; HWND _hwnd; float _ang;
BYTE *plasma1, *plasma2;
double currentTime; int _WD, _WV;
};
class wnd
{
public:
wnd() { _inst = this; }
int wnd::Run( HINSTANCE hInst ) {
_hInst = hInst; _hwnd = InitAll();
SetTimer( _hwnd, MY_TIMER, 15, NULL );
_plasma.setHWND( _hwnd );
ShowWindow( _hwnd, SW_SHOW );
UpdateWindow( _hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT ) {
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return UnregisterClass( "_MY_PLASMA_", _hInst );
}
private:
void wnd::doPaint( HDC dc ) { _plasma.update(); }
void wnd::doTimer() { _plasma.update(); }
static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
switch( msg ) {
case WM_PAINT: {
PAINTSTRUCT ps;
_inst->doPaint( BeginPaint( hWnd, &ps ) );
EndPaint( hWnd, &ps );
return 0;
}
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_TIMER: _inst->doTimer(); break;
default: return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
HWND InitAll() {
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ( WNDPROC )WndProc;
wcex.hInstance = _hInst;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_MY_PLASMA_";
RegisterClassEx( &wcex );
RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };
AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );
int w = rc.right - rc.left, h = rc.bottom - rc.top;
return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );
}
static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;
};
wnd* wnd::_inst = 0;
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {
wnd myWnd;
return myWnd.Run( hInstance );
}
|
pal = [0] * 128
r = 42
g = 84
b = 126
rd = gd = bd = False
def setup():
global buffer
size(600, 600)
frameRate(25)
buffer = [None] * width * height
for x in range(width):
for y in range(width):
value = int(((128 + (128 * sin(x / 32.0)))
+ (128 + (128 * cos(y / 32.0)))
+ (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)
buffer[x + y * width] = value
def draw():
global r, g, b, rd, gd, bd
if r > 128: rd = True
if not rd: r += 1
else: r-=1
if r < 0: rd = False
if g > 128: gd = True
if not gd: g += 1
else: g- = 1
if r < 0: gd = False
if b > 128: bd = True
if not bd: b += 1
else: b- = 1
if b < 0: bd = False
for i in range(128):
s_1 = sin(i * PI / 25)
s_2 = sin(i * PI / 50 + PI / 4)
pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)
loadPixels()
for i, b in enumerate(buffer):
pixels[i] = pal[(b + frameCount) % 127]
updatePixels()
|
Write the same code in Python as shown below in C++. | #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);
public:
abelian_sandpile();
explicit abelian_sandpile(std::initializer_list<int> init);
void stabilize();
bool is_stable() const;
void topple();
abelian_sandpile& operator+=(const abelian_sandpile&);
bool operator==(const abelian_sandpile&);
private:
int& cell_value(size_t row, size_t column) {
return cells_[cell_index(row, column)];
}
static size_t cell_index(size_t row, size_t column) {
return row * sp_columns + column;
}
static size_t row_index(size_t cell_index) {
return cell_index/sp_columns;
}
static size_t column_index(size_t cell_index) {
return cell_index % sp_columns;
}
std::array<int, sp_cells> cells_;
};
abelian_sandpile::abelian_sandpile() {
cells_.fill(0);
}
abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {
assert(init.size() == sp_cells);
std::copy(init.begin(), init.end(), cells_.begin());
}
abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {
for (size_t i = 0; i < sp_cells; ++i)
cells_[i] += other.cells_[i];
stabilize();
return *this;
}
bool abelian_sandpile::operator==(const abelian_sandpile& other) {
return cells_ == other.cells_;
}
bool abelian_sandpile::is_stable() const {
return std::none_of(cells_.begin(), cells_.end(),
[](int a) { return a >= sp_limit; });
}
void abelian_sandpile::topple() {
for (size_t i = 0; i < sp_cells; ++i) {
if (cells_[i] >= sp_limit) {
cells_[i] -= sp_limit;
size_t row = row_index(i);
size_t column = column_index(i);
if (row > 0)
++cell_value(row - 1, column);
if (row + 1 < sp_rows)
++cell_value(row + 1, column);
if (column > 0)
++cell_value(row, column - 1);
if (column + 1 < sp_columns)
++cell_value(row, column + 1);
break;
}
}
}
void abelian_sandpile::stabilize() {
while (!is_stable())
topple();
}
abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {
abelian_sandpile c(a);
c += b;
return c;
}
std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {
for (size_t i = 0; i < sp_cells; ++i) {
if (i > 0)
out << (as.column_index(i) == 0 ? '\n' : ' ');
out << as.cells_[i];
}
return out << '\n';
}
int main() {
std::cout << std::boolalpha;
std::cout << "Avalanche:\n";
abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};
while (!sp.is_stable()) {
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
sp.topple();
}
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
std::cout << "Commutativity:\n";
abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};
abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};
abelian_sandpile sum1(s1 + s2);
abelian_sandpile sum2(s2 + s1);
std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n";
std::cout << "s1 + s2 = \n" << sum1;
std::cout << "\ns2 + s1 = \n" << sum2;
std::cout << '\n';
std::cout << "Identity:\n";
abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};
abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};
abelian_sandpile sum3(s3 + s3_id);
abelian_sandpile sum4(s3_id + s3_id);
std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n';
std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n";
std::cout << "s3 + s3_id = \n" << sum3;
std::cout << "\ns3_id + s3_id = \n" << sum4;
return 0;
}
| from itertools import product
from collections import defaultdict
class Sandpile():
def __init__(self, gridtext):
array = [int(x) for x in gridtext.strip().split()]
self.grid = defaultdict(int,
{(i //3, i % 3): x
for i, x in enumerate(array)})
_border = set((r, c)
for r, c in product(range(-1, 4), repeat=2)
if not 0 <= r <= 2 or not 0 <= c <= 2
)
_cell_coords = list(product(range(3), repeat=2))
def topple(self):
g = self.grid
for r, c in self._cell_coords:
if g[(r, c)] >= 4:
g[(r - 1, c)] += 1
g[(r + 1, c)] += 1
g[(r, c - 1)] += 1
g[(r, c + 1)] += 1
g[(r, c)] -= 4
return True
return False
def stabilise(self):
while self.topple():
pass
g = self.grid
for row_col in self._border.intersection(g.keys()):
del g[row_col]
return self
__pos__ = stabilise
def __eq__(self, other):
g = self.grid
return all(g[row_col] == other.grid[row_col]
for row_col in self._cell_coords)
def __add__(self, other):
g = self.grid
ans = Sandpile("")
for row_col in self._cell_coords:
ans.grid[row_col] = g[row_col] + other.grid[row_col]
return ans.stabilise()
def __str__(self):
g, txt = self.grid, []
for row in range(3):
txt.append(' '.join(str(g[(row, col)])
for col in range(3)))
return '\n'.join(txt)
def __repr__(self):
return f'{self.__class__.__name__}()'
unstable = Sandpile()
s1 = Sandpile()
s2 = Sandpile()
s3 = Sandpile("3 3 3 3 3 3 3 3 3")
s3_id = Sandpile("2 1 2 1 0 1 2 1 2")
|
Convert this C++ snippet to Python and keep its semantics consistent. | #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostream&, const abelian_sandpile&);
public:
abelian_sandpile();
explicit abelian_sandpile(std::initializer_list<int> init);
void stabilize();
bool is_stable() const;
void topple();
abelian_sandpile& operator+=(const abelian_sandpile&);
bool operator==(const abelian_sandpile&);
private:
int& cell_value(size_t row, size_t column) {
return cells_[cell_index(row, column)];
}
static size_t cell_index(size_t row, size_t column) {
return row * sp_columns + column;
}
static size_t row_index(size_t cell_index) {
return cell_index/sp_columns;
}
static size_t column_index(size_t cell_index) {
return cell_index % sp_columns;
}
std::array<int, sp_cells> cells_;
};
abelian_sandpile::abelian_sandpile() {
cells_.fill(0);
}
abelian_sandpile::abelian_sandpile(std::initializer_list<int> init) {
assert(init.size() == sp_cells);
std::copy(init.begin(), init.end(), cells_.begin());
}
abelian_sandpile& abelian_sandpile::operator+=(const abelian_sandpile& other) {
for (size_t i = 0; i < sp_cells; ++i)
cells_[i] += other.cells_[i];
stabilize();
return *this;
}
bool abelian_sandpile::operator==(const abelian_sandpile& other) {
return cells_ == other.cells_;
}
bool abelian_sandpile::is_stable() const {
return std::none_of(cells_.begin(), cells_.end(),
[](int a) { return a >= sp_limit; });
}
void abelian_sandpile::topple() {
for (size_t i = 0; i < sp_cells; ++i) {
if (cells_[i] >= sp_limit) {
cells_[i] -= sp_limit;
size_t row = row_index(i);
size_t column = column_index(i);
if (row > 0)
++cell_value(row - 1, column);
if (row + 1 < sp_rows)
++cell_value(row + 1, column);
if (column > 0)
++cell_value(row, column - 1);
if (column + 1 < sp_columns)
++cell_value(row, column + 1);
break;
}
}
}
void abelian_sandpile::stabilize() {
while (!is_stable())
topple();
}
abelian_sandpile operator+(const abelian_sandpile& a, const abelian_sandpile& b) {
abelian_sandpile c(a);
c += b;
return c;
}
std::ostream& operator<<(std::ostream& out, const abelian_sandpile& as) {
for (size_t i = 0; i < sp_cells; ++i) {
if (i > 0)
out << (as.column_index(i) == 0 ? '\n' : ' ');
out << as.cells_[i];
}
return out << '\n';
}
int main() {
std::cout << std::boolalpha;
std::cout << "Avalanche:\n";
abelian_sandpile sp{4,3,3, 3,1,2, 0,2,3};
while (!sp.is_stable()) {
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
sp.topple();
}
std::cout << sp << "stable? " << sp.is_stable() << "\n\n";
std::cout << "Commutativity:\n";
abelian_sandpile s1{1,2,0, 2,1,1, 0,1,3};
abelian_sandpile s2{2,1,3, 1,0,1, 0,1,0};
abelian_sandpile sum1(s1 + s2);
abelian_sandpile sum2(s2 + s1);
std::cout << "s1 + s2 equals s2 + s1? " << (sum1 == sum2) << "\n\n";
std::cout << "s1 + s2 = \n" << sum1;
std::cout << "\ns2 + s1 = \n" << sum2;
std::cout << '\n';
std::cout << "Identity:\n";
abelian_sandpile s3{3,3,3, 3,3,3, 3,3,3};
abelian_sandpile s3_id{2,1,2, 1,0,1, 2,1,2};
abelian_sandpile sum3(s3 + s3_id);
abelian_sandpile sum4(s3_id + s3_id);
std::cout << "s3 + s3_id equals s3? " << (sum3 == s3) << '\n';
std::cout << "s3_id + s3_id equals s3_id? " << (sum4 == s3_id) << "\n\n";
std::cout << "s3 + s3_id = \n" << sum3;
std::cout << "\ns3_id + s3_id = \n" << sum4;
return 0;
}
| from itertools import product
from collections import defaultdict
class Sandpile():
def __init__(self, gridtext):
array = [int(x) for x in gridtext.strip().split()]
self.grid = defaultdict(int,
{(i //3, i % 3): x
for i, x in enumerate(array)})
_border = set((r, c)
for r, c in product(range(-1, 4), repeat=2)
if not 0 <= r <= 2 or not 0 <= c <= 2
)
_cell_coords = list(product(range(3), repeat=2))
def topple(self):
g = self.grid
for r, c in self._cell_coords:
if g[(r, c)] >= 4:
g[(r - 1, c)] += 1
g[(r + 1, c)] += 1
g[(r, c - 1)] += 1
g[(r, c + 1)] += 1
g[(r, c)] -= 4
return True
return False
def stabilise(self):
while self.topple():
pass
g = self.grid
for row_col in self._border.intersection(g.keys()):
del g[row_col]
return self
__pos__ = stabilise
def __eq__(self, other):
g = self.grid
return all(g[row_col] == other.grid[row_col]
for row_col in self._cell_coords)
def __add__(self, other):
g = self.grid
ans = Sandpile("")
for row_col in self._cell_coords:
ans.grid[row_col] = g[row_col] + other.grid[row_col]
return ans.stabilise()
def __str__(self):
g, txt = self.grid, []
for row in range(3):
txt.append(' '.join(str(g[(row, col)])
for col in range(3)))
return '\n'.join(txt)
def __repr__(self):
return f'{self.__class__.__name__}()'
unstable = Sandpile()
s1 = Sandpile()
s2 = Sandpile()
s3 = Sandpile("3 3 3 3 3 3 3 3 3")
s3_id = Sandpile("2 1 2 1 0 1 2 1 2")
|
Convert the following code from C++ to Python, ensuring the logic remains intact. | #include <iostream>
int main() {
using namespace std;
cout << "Hello, World!" << endl;
return 0;
}
| print "Goodbye, World!"
|
Change the following C++ code into Python without altering its purpose. | #include <iostream>
int main() {
using namespace std;
cout << "Hello, World!" << endl;
return 0;
}
| print "Goodbye, World!"
|
Write the same code in Python as shown below in C++. | #include <cstdio>
#include <cstdlib>
class Point {
protected:
int x, y;
public:
Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}
Point(const Point &p) : x(p.x), y(p.y) {}
virtual ~Point() {}
const Point& operator=(const Point &p) {
if (this != &p) {
x = p.x;
y = p.y;
}
return *this;
}
int getX() { return x; }
int getY() { return y; }
void setX(int x0) { x = x0; }
void setY(int y0) { y = y0; }
virtual void print() { printf("Point\n"); }
};
class Circle: public Point {
private:
int r;
public:
Circle(Point p, int r0 = 0) : Point(p), r(r0) {}
Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}
virtual ~Circle() {}
const Circle& operator=(const Circle &c) {
if (this != &c) {
x = c.x;
y = c.y;
r = c.r;
}
return *this;
}
int getR() { return r; }
void setR(int r0) { r = r0; }
virtual void print() { printf("Circle\n"); }
};
int main() {
Point *p = new Point();
Point *c = new Circle();
p->print();
c->print();
delete p;
delete c;
return EXIT_SUCCESS;
}
| class Point(object):
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __repr__(self):
return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)
class Circle(object):
def __init__(self, center=None, radius=1.0):
self.center = center or Point()
self.radius = radius
def __repr__(self):
return '<Circle 0x%x x: %f y: %f radius: %f>' % (
id(self), self.center.x, self.center.y, self.radius)
|
Change the programming language of this snippet from C++ to Python without modifying what it does. | #include <gmpxx.h>
#include <primesieve.hpp>
#include <iostream>
using big_int = mpz_class;
std::string to_string(const big_int& num, size_t n) {
std::string str = num.get_str();
size_t len = str.size();
if (len > n) {
str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
str += " (";
str += std::to_string(len);
str += " digits)";
}
return str;
}
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}
int main() {
const big_int one(1);
primesieve::iterator pi;
pi.next_prime();
for (int i = 0; i < 24;) {
uint64_t p = pi.next_prime();
big_int n = ((one << p) + 1) / 3;
if (is_probably_prime(n))
std::cout << ++i << ": " << p << " - " << to_string(n, 30) << '\n';
}
}
|
from sympy import isprime
def wagstaff(N):
pri, wcount = 1, 0
while wcount < N:
pri += 2
if isprime(pri):
wag = (2**pri + 1) // 3
if isprime(wag):
wcount += 1
print(f'{wcount: 3}: {pri: 5} => ',
f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')
wagstaff(24)
|
Translate this program into Python but keep the logic exactly as in C++. | #include <gmpxx.h>
#include <primesieve.hpp>
#include <iostream>
using big_int = mpz_class;
std::string to_string(const big_int& num, size_t n) {
std::string str = num.get_str();
size_t len = str.size();
if (len > n) {
str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
str += " (";
str += std::to_string(len);
str += " digits)";
}
return str;
}
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}
int main() {
const big_int one(1);
primesieve::iterator pi;
pi.next_prime();
for (int i = 0; i < 24;) {
uint64_t p = pi.next_prime();
big_int n = ((one << p) + 1) / 3;
if (is_probably_prime(n))
std::cout << ++i << ": " << p << " - " << to_string(n, 30) << '\n';
}
}
|
from sympy import isprime
def wagstaff(N):
pri, wcount = 1, 0
while wcount < N:
pri += 2
if isprime(pri):
wag = (2**pri + 1) // 3
if isprime(wag):
wcount += 1
print(f'{wcount: 3}: {pri: 5} => ',
f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')
wagstaff(24)
|
Translate the given C++ code snippet into Python without altering its behavior. | #include <iostream>
#include <map>
#include <utility>
using namespace std;
template<typename T>
class FixedMap : private T
{
T m_defaultValues;
public:
FixedMap(T map)
: T(map), m_defaultValues(move(map)){}
using T::cbegin;
using T::cend;
using T::empty;
using T::find;
using T::size;
using T::at;
using T::begin;
using T::end;
auto& operator[](typename T::key_type&& key)
{
return this->at(forward<typename T::key_type>(key));
}
void erase(typename T::key_type&& key)
{
T::operator[](key) = m_defaultValues.at(key);
}
void clear()
{
T::operator=(m_defaultValues);
}
};
auto PrintMap = [](const auto &map)
{
for(auto &[key, value] : map)
{
cout << "{" << key << " : " << value << "} ";
}
cout << "\n\n";
};
int main(void)
{
cout << "Map intialized with values\n";
FixedMap<map<string, int>> fixedMap ({
{"a", 1},
{"b", 2}});
PrintMap(fixedMap);
cout << "Change the values of the keys\n";
fixedMap["a"] = 55;
fixedMap["b"] = 56;
PrintMap(fixedMap);
cout << "Reset the 'a' key\n";
fixedMap.erase("a");
PrintMap(fixedMap);
cout << "Change the values the again\n";
fixedMap["a"] = 88;
fixedMap["b"] = 99;
PrintMap(fixedMap);
cout << "Reset all keys\n";
fixedMap.clear();
PrintMap(fixedMap);
try
{
cout << "Try to add a new key\n";
fixedMap["newKey"] = 99;
}
catch (exception &ex)
{
cout << "error: " << ex.what();
}
}
| from collections import UserDict
import copy
class Dict(UserDict):
def __init__(self, dict=None, **kwargs):
self.__init = True
super().__init__(dict, **kwargs)
self.default = copy.deepcopy(self.data)
self.__init = False
def __delitem__(self, key):
if key in self.default:
self.data[key] = self.default[key]
else:
raise NotImplementedError
def __setitem__(self, key, item):
if self.__init:
super().__setitem__(key, item)
elif key in self.data:
self.data[key] = item
else:
raise KeyError
def __repr__(self):
return "%s(%s)" % (type(self).__name__, super().__repr__())
def fromkeys(cls, iterable, value=None):
if self.__init:
super().fromkeys(cls, iterable, value)
else:
for key in iterable:
if key in self.data:
self.data[key] = value
else:
raise KeyError
def clear(self):
self.data.update(copy.deepcopy(self.default))
def pop(self, key, default=None):
raise NotImplementedError
def popitem(self):
raise NotImplementedError
def update(self, E, **F):
if self.__init:
super().update(E, **F)
else:
haskeys = False
try:
keys = E.keys()
haskeys = Ture
except AttributeError:
pass
if haskeys:
for key in keys:
self[key] = E[key]
else:
for key, val in E:
self[key] = val
for key in F:
self[key] = F[key]
def setdefault(self, key, default=None):
if key not in self.data:
raise KeyError
else:
return super().setdefault(key, default)
|
Write a version of this C++ function in Python with identical behavior. | #include <array>
#include <iostream>
#include <numeric>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::uint128_t;
class magic_number_generator {
public:
magic_number_generator() : magic_(10) {
std::iota(magic_.begin(), magic_.end(), 0);
}
bool next(uint128_t& n);
public:
std::vector<uint128_t> magic_;
size_t index_ = 0;
int digits_ = 2;
};
bool magic_number_generator::next(uint128_t& n) {
if (index_ == magic_.size()) {
std::vector<uint128_t> magic;
for (uint128_t m : magic_) {
if (m == 0)
continue;
uint128_t n = 10 * m;
for (int d = 0; d < 10; ++d, ++n) {
if (n % digits_ == 0)
magic.push_back(n);
}
}
index_ = 0;
++digits_;
magic_ = std::move(magic);
}
if (magic_.empty())
return false;
n = magic_[index_++];
return true;
}
std::array<int, 10> get_digits(uint128_t n) {
std::array<int, 10> result = {};
for (; n > 0; n /= 10)
++result[static_cast<int>(n % 10)];
return result;
}
int main() {
int count = 0, dcount = 0;
uint128_t magic = 0, p = 10;
std::vector<int> digit_count;
std::array<int, 10> digits0 = {1,1,1,1,1,1,1,1,1,1};
std::array<int, 10> digits1 = {0,1,1,1,1,1,1,1,1,1};
std::vector<uint128_t> pandigital0, pandigital1;
for (magic_number_generator gen; gen.next(magic);) {
if (magic >= p) {
p *= 10;
digit_count.push_back(dcount);
dcount = 0;
}
auto digits = get_digits(magic);
if (digits == digits0)
pandigital0.push_back(magic);
else if (digits == digits1)
pandigital1.push_back(magic);
++count;
++dcount;
}
digit_count.push_back(dcount);
std::cout << "There are " << count << " magic numbers.\n\n";
std::cout << "The largest magic number is " << magic << ".\n\n";
std::cout << "Magic number count by digits:\n";
for (int i = 0; i < digit_count.size(); ++i)
std::cout << i + 1 << '\t' << digit_count[i] << '\n';
std::cout << "\nMagic numbers that are minimally pandigital in 1-9:\n";
for (auto m : pandigital1)
std::cout << m << '\n';
std::cout << "\nMagic numbers that are minimally pandigital in 0-9:\n";
for (auto m : pandigital0)
std::cout << m << '\n';
}
| from itertools import groupby
def magic_numbers(base):
hist = []
n = l = i = 0
while True:
l += 1
hist.extend((n + digit, l) for digit in range(-n % l, base, l))
i += 1
if i == len(hist):
return hist
n, l = hist[i]
n *= base
mn = magic_numbers(10)
print("found", len(mn), "magic numbers")
print("the largest one is", mn[-1][0])
print("count by number of digits:")
print(*(f"{l}:{sum(1 for _ in g)}" for l, g in groupby(l for _, l in mn)))
print(end="minimally pandigital in 1..9: ")
print(*(m for m, l in mn if l == 9 == len(set(str(m)) - {"0"})))
print(end="minimally pandigital in 0..9: ")
print(*(m for m, l in mn if l == 10 == len(set(str(m)))))
|
Change the following C++ code into Python without altering its purpose. | #include <iostream>
#include <list>
#include <string>
#include <vector>
using namespace std;
void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel)
{
for(auto it = start; it != sentinel; ++it)
{
cout << *it << " ";
}
cout << "\n";
}
void FirstFourthFifth(input_iterator auto it)
{
cout << *it;
advance(it, 3);
cout << ", " << *it;
advance(it, 1);
cout << ", " << *it;
cout << "\n";
}
int main()
{
vector<string> days{"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
list<string> colors{"Red", "Orange", "Yellow", "Green", "Blue", "Purple"};
cout << "All elements:\n";
PrintContainer(days.begin(), days.end());
PrintContainer(colors.begin(), colors.end());
cout << "\nFirst, fourth, and fifth elements:\n";
FirstFourthFifth(days.begin());
FirstFourthFifth(colors.begin());
cout << "\nReverse first, fourth, and fifth elements:\n";
FirstFourthFifth(days.rbegin());
FirstFourthFifth(colors.rbegin());
}
|
from collections import deque
from typing import Iterable
from typing import Iterator
from typing import Reversible
days = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
]
colors = deque(
[
"red",
"yellow",
"pink",
"green",
"purple",
"orange",
"blue",
]
)
class MyIterable:
class MyIterator:
def __init__(self) -> None:
self._day = -1
def __iter__(self):
return self
def __next__(self):
if self._day >= 6:
raise StopIteration
self._day += 1
return days[self._day]
class MyReversedIterator:
def __init__(self) -> None:
self._day = 7
def __iter__(self):
return self
def __next__(self):
if self._day <= 0:
raise StopIteration
self._day -= 1
return days[self._day]
def __iter__(self):
return self.MyIterator()
def __reversed__(self):
return self.MyReversedIterator()
def print_elements(container: Iterable[object]) -> None:
for element in container:
print(element, end=" ")
print("")
def _drop(it: Iterator[object], n: int) -> None:
try:
for _ in range(n):
next(it)
except StopIteration:
pass
def print_first_fourth_fifth(container: Iterable[object]) -> None:
it = iter(container)
print(next(it), end=" ")
_drop(it, 2)
print(next(it), end=" ")
print(next(it))
def print_reversed_first_fourth_fifth(container: Reversible[object]) -> None:
it = reversed(container)
print(next(it), end=" ")
_drop(it, 2)
print(next(it), end=" ")
print(next(it))
def main() -> None:
my_iterable = MyIterable()
print("All elements:")
print_elements(days)
print_elements(colors)
print_elements(my_iterable)
print("\nFirst, fourth, fifth:")
print_first_fourth_fifth(days)
print_first_fourth_fifth(colors)
print_first_fourth_fifth(my_iterable)
print("\nLast, fourth to last, fifth to last:")
print_reversed_first_fourth_fifth(days)
print_reversed_first_fourth_fifth(colors)
print_reversed_first_fourth_fifth(my_iterable)
if __name__ == "__main__":
main()
|
Rewrite this program in Python while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <list>
#include <string>
#include <vector>
using namespace std;
void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel)
{
for(auto it = start; it != sentinel; ++it)
{
cout << *it << " ";
}
cout << "\n";
}
void FirstFourthFifth(input_iterator auto it)
{
cout << *it;
advance(it, 3);
cout << ", " << *it;
advance(it, 1);
cout << ", " << *it;
cout << "\n";
}
int main()
{
vector<string> days{"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
list<string> colors{"Red", "Orange", "Yellow", "Green", "Blue", "Purple"};
cout << "All elements:\n";
PrintContainer(days.begin(), days.end());
PrintContainer(colors.begin(), colors.end());
cout << "\nFirst, fourth, and fifth elements:\n";
FirstFourthFifth(days.begin());
FirstFourthFifth(colors.begin());
cout << "\nReverse first, fourth, and fifth elements:\n";
FirstFourthFifth(days.rbegin());
FirstFourthFifth(colors.rbegin());
}
|
from collections import deque
from typing import Iterable
from typing import Iterator
from typing import Reversible
days = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
]
colors = deque(
[
"red",
"yellow",
"pink",
"green",
"purple",
"orange",
"blue",
]
)
class MyIterable:
class MyIterator:
def __init__(self) -> None:
self._day = -1
def __iter__(self):
return self
def __next__(self):
if self._day >= 6:
raise StopIteration
self._day += 1
return days[self._day]
class MyReversedIterator:
def __init__(self) -> None:
self._day = 7
def __iter__(self):
return self
def __next__(self):
if self._day <= 0:
raise StopIteration
self._day -= 1
return days[self._day]
def __iter__(self):
return self.MyIterator()
def __reversed__(self):
return self.MyReversedIterator()
def print_elements(container: Iterable[object]) -> None:
for element in container:
print(element, end=" ")
print("")
def _drop(it: Iterator[object], n: int) -> None:
try:
for _ in range(n):
next(it)
except StopIteration:
pass
def print_first_fourth_fifth(container: Iterable[object]) -> None:
it = iter(container)
print(next(it), end=" ")
_drop(it, 2)
print(next(it), end=" ")
print(next(it))
def print_reversed_first_fourth_fifth(container: Reversible[object]) -> None:
it = reversed(container)
print(next(it), end=" ")
_drop(it, 2)
print(next(it), end=" ")
print(next(it))
def main() -> None:
my_iterable = MyIterable()
print("All elements:")
print_elements(days)
print_elements(colors)
print_elements(my_iterable)
print("\nFirst, fourth, fifth:")
print_first_fourth_fifth(days)
print_first_fourth_fifth(colors)
print_first_fourth_fifth(my_iterable)
print("\nLast, fourth to last, fifth to last:")
print_reversed_first_fourth_fifth(days)
print_reversed_first_fourth_fifth(colors)
print_reversed_first_fourth_fifth(my_iterable)
if __name__ == "__main__":
main()
|
Port the provided C++ code into Python while preserving the original functionality. |
#include <functional>
#include <bitset>
#include <cmath>
using namespace std;
using Z2 = optional<long long>; using Z1 = function<Z2()>;
constexpr auto pow10 = [] { array <long long, 19> n {1}; for (int j{0}, i{1}; i < 19; j = i++) n[i] = n[j] * 10; return n; } ();
long long acc, l;
bool izRev(int n, unsigned long long i, unsigned long long g) {
return (i / pow10[n - 1] != g % 10) ? false : n < 2 ? true : izRev(n - 1, i % pow10[n - 1], g / 10);
}
const Z1 fG(Z1 n, int start, int end, int reset, const long long step, long long &l) {
return [n, i{step * start}, g{step * end}, e{step * reset}, &l, step] () mutable {
while (i<g){i+=step; return Z2(l+=step);}
l-=g-(i=e); return n();};
}
struct nLH {
vector<unsigned long long>even{}, odd{};
nLH(const Z1 a, const vector<long long> b, long long llim){while (auto i = a()) for (auto ng : b)
if(ng>0 | *i>llim){unsigned long long sq{ng+ *i}, r{sqrt(sq)}; if (r*r == sq) ng&1 ? odd.push_back(sq) : even.push_back(sq);}}
};
const double fac = 3.94;
const int mbs = (int)sqrt(fac * pow10[9]), mbt = (int)sqrt(fac * fac * pow10[9]) >> 3;
const bitset<100000>bs {[]{bitset<100000>n{false}; for(int g{3};g<mbs;++g) n[(g*g)%100000]=true; return n;}()};
constexpr array<const int, 7>li{1,3,0,0,1,1,1},lin{0,-7,0,0,-8,-3,-9},lig{0,9,0,0,8,7,9},lil{0,2,0,0,2,10,2};
const nLH makeL(const int n){
constexpr int r{9}; acc=0; Z1 g{[]{return Z2{};}}; int s{-r}, q{(n>11)*5}; vector<long long> w{};
for (int i{1};i<n/2-q+1;++i){l=pow10[n-i-q]-pow10[i+q-1]; s-=i==n/2-q; g=fG(g,s,r,-r,l,acc+=l*s);}
if(q){long long g0{0}, g1{0}, g2{0}, g3{0}, g4{0}, l3{pow10[n-5]}; while (g0<7){const long long g{-10000*g4-1000*g3-100*g2-10*g1-g0};
if (bs[(g+1000000000000LL)%100000]) w.push_back(l3*(g4+g3*10+g2*100+g1*1000+g0*10000)+g);
if(g4<r) ++g4; else{g4= -r; if(g3<r) ++g3; else{g3= -r; if(g2<r) ++g2; else{g2= -r; if(g1<lig[g0]) g1+=lil[g0]; else {g0+=li[g0];g1=lin[g0];}}}}}}
return q ? nLH(g,w,0) : nLH(g,{0},0);
}
const bitset<100000>bt {[]{bitset<100000>n{false}; for(int g{11};g<mbt;++g) n[(g*g)%100000]=true; return n;}()};
constexpr array<const int, 17>lu{0,0,0,0,2,0,4,0,0,0,1,4,0,0,0,1,1},lun{0,0,0,0,0,0,1,0,0,0,9,1,0,0,0,1,0},lug{0,0,0,0,18,0,17,0,0,0,9,17,0,0,0,11,18},lul{0,0,0,0,2,0,2,0,0,0,0,2,0,0,0,10,2};
const nLH makeH(const int n){
acc= -pow10[n>>1]-pow10[(n-1)>>1]; Z1 g{[]{ return Z2{};}}; int q{(n>11)*5}; vector<long long> w {};
for (int i{1}; i<(n>>1)-q+1; ++i) g = fG(g,0,18,0,pow10[n-i-q]+pow10[i+q-1], acc);
if (n & 1){l=pow10[n>>1]<<1; g=fG(g,0,9,0,l,acc+=l);}
if(q){long long g0{4}, g1{0}, g2{0}, g3{0}, g4{0},l3{pow10[n-5]}; while (g0<17){const long long g{g4*10000+g3*1000+g2*100+g1*10+g0};
if (bt[g%100000]) w.push_back(l3*(g4+g3*10+g2*100+g1*1000+g0*10000)+g);
if (g4<18) ++g4; else{g4=0; if(g3<18) ++g3; else{g3=0; if(g2<18) ++g2; else{g2=0; if(g1<lug[g0]) g1+=lul[g0]; else{g0+=lu[g0];g1=lun[g0];}}}}}}
return q ? nLH(g,w,0) : nLH(g,{0},pow10[n-1]<<2);
}
#include <chrono>
using namespace chrono; using VU = vector<unsigned long long>; using VS = vector<string>;
template <typename T>
vector<T>& operator +=(vector<T>& v, const vector<T>& w) { v.insert(v.end(), w.begin(), w.end()); return v; }
int c{0};
auto st{steady_clock::now()}, st0{st}, tmp{st};
string dFmt(duration<double> et, int digs) {
string res{""}; double dt{et.count()};
if (dt > 60.0) { int m = (int)(dt / 60.0); dt -= m * 60.0; res = to_string(m) + "m"; }
res += to_string(dt); return res.substr(0, digs - 1) + 's';
}
VS dump(int nd, VU lo, VU hi) {
VS res {};
for (auto l : lo) for (auto h : hi) {
auto r { (h - l) >> 1 }, z { h - r };
if (izRev(nd, r, z)) {
char buf[99]; sprintf(buf, "%20llu %11lu %10lu", z, (long long)sqrt(h), (long long)sqrt(l));
res.push_back(buf); } } return res;
}
void doOne(int n, nLH L, nLH H) {
VS lines = dump(n, L.even, H.even); lines += dump(n, L.odd , H.odd); sort(lines.begin(), lines.end());
duration<double> tet = (tmp = steady_clock::now()) - st; int ls = lines.size();
if (ls-- > 0)
for (int i{0}; i <= ls; ++i)
printf("%3d %s%s", ++c, lines[i].c_str(), i == ls ? "" : "\n");
else printf("%s", string(47, ' ').c_str());
printf(" %2d: %s %s\n", n, dFmt(tmp - st0, 8).c_str(), dFmt(tet, 8).c_str()); st0 = tmp;
}
void Rare(int n) { doOne(n, makeL(n), makeH(n)); }
int main(int argc, char *argv[]) {
int max{argc > 1 ? stoi(argv[1]) : 19}; if (max < 2) max = 2; if (max > 19 ) max = 19;
printf("%4s %19s %11s %10s %5s %11s %9s\n", "nth", "forward", "rt.sum", "rt.diff", "digs", "block.et", "total.et");
for (int nd{2}; nd <= max; ++nd) Rare(nd);
}
|
from math import floor, sqrt
from datetime import datetime
def main():
start = datetime.now()
for i in xrange(1, 10 ** 11):
if rare(i):
print "found a rare:", i
end = datetime.now()
print "time elapsed:", end - start
def is_square(n):
s = floor(sqrt(n + 0.5))
return s * s == n
def reverse(n):
return int(str(n)[::-1])
def is_palindrome(n):
return n == reverse(n)
def rare(n):
r = reverse(n)
return (
not is_palindrome(n) and
n > r and
is_square(n+r) and is_square(n-r)
)
if __name__ == '__main__':
main()
|
Transform the following C++ implementation into Python, maintaining the same output and logic. | #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
size_t consonants(const std::string& word) {
std::bitset<26> bits;
size_t bit = 0;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
if (ch < 'a' || ch > 'z')
continue;
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
bit = ch - 'a';
if (bits.test(bit))
return 0;
bits.set(bit);
break;
}
}
return bits.count();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
std::map<size_t, std::vector<std::string>, std::greater<int>> map;
while (getline(in, word)) {
if (word.size() <= 10)
continue;
size_t count = consonants(word);
if (count != 0)
map[count].push_back(word);
}
const int columns = 4;
for (const auto& p : map) {
std::cout << p.first << " consonants (" << p.second.size() << "):\n";
int n = 0;
for (const auto& word : p.second) {
std::cout << std::left << std::setw(18) << word;
++n;
if (n % columns == 0)
std::cout << '\n';
}
if (n % columns != 0)
std::cout << '\n';
std::cout << '\n';
}
return EXIT_SUCCESS;
}
| print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in
(x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)
for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]
if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)
|
Can you help me rewrite this code in Python instead of C++, keeping it the same logically? | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
| for i in range(65,123):
check = 1
for j in range(2,i):
if i%j == 0:
check = 0
if check==1:
print(chr(i),end='')
|
Write a version of this C++ function in Python with identical behavior. | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
| for i in range(65,123):
check = 1
for j in range(2,i):
if i%j == 0:
check = 0
if check==1:
print(chr(i),end='')
|
Rewrite the snippet below in Python so it works the same as the original C++ code. | #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include "prime_sieve.hpp"
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
prime_sieve sieve(UCHAR_MAX);
auto is_prime = [&sieve](unsigned char c){ return sieve.is_prime(c); };
int n = 0;
while (getline(in, line)) {
if (std::all_of(line.begin(), line.end(), is_prime)) {
++n;
std::cout << std::right << std::setw(2) << n << ": "
<< std::left << std::setw(10) << line;
if (n % 4 == 0)
std::cout << '\n';
}
}
return EXIT_SUCCESS;
}
| for i in range(65,123):
check = 1
for j in range(2,i):
if i%j == 0:
check = 0
if check==1:
print(chr(i),end='')
|
Ensure the translated Python code behaves exactly like the original C++ snippet. | #include <iomanip>
#include <iostream>
#include <gmpxx.h>
using big_int = mpz_class;
class riordan_number_generator {
public:
big_int next();
private:
big_int a0_ = 1;
big_int a1_ = 0;
int n_ = 0;
};
big_int riordan_number_generator::next() {
int n = n_++;
if (n == 0)
return a0_;
if (n == 1)
return a1_;
big_int a = (n - 1) * (2 * a1_ + 3 * a0_) / (n + 1);
a0_ = a1_;
a1_ = a;
return a;
}
std::string to_string(const big_int& num, size_t n) {
std::string str = num.get_str();
size_t len = str.size();
if (len > n)
str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
return str;
}
int main() {
riordan_number_generator rng;
std::cout << "First 32 Riordan numbers:\n";
int i = 1;
for (; i <= 32; ++i) {
std::cout << std::setw(14) << rng.next()
<< (i % 4 == 0 ? '\n' : ' ');
}
for (; i < 1000; ++i)
rng.next();
auto num = rng.next();
++i;
std::cout << "\nThe 1000th is " << to_string(num, 40) << " ("
<< num.get_str().size() << " digits).\n";
for (; i < 10000; ++i)
rng.next();
num = rng.next();
std::cout << "The 10000th is " << to_string(num, 40) << " ("
<< num.get_str().size() << " digits).\n";
}
| def Riordan(N):
a = [1, 0, 1]
for n in range(3, N):
a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1))
return a
rios = Riordan(10_000)
for i in range(32):
print(f'{rios[i] : 18,}', end='\n' if (i + 1) % 4 == 0 else '')
print(f'The 1,000th Riordan has {len(str(rios[999]))} digits.')
print(f'The 10,000th Rirdan has {len(str(rios[9999]))} digits.')
|
Convert this C++ block to Python, preserving its control flow and logic. | #include <iomanip>
#include <iostream>
#include <gmpxx.h>
using big_int = mpz_class;
class riordan_number_generator {
public:
big_int next();
private:
big_int a0_ = 1;
big_int a1_ = 0;
int n_ = 0;
};
big_int riordan_number_generator::next() {
int n = n_++;
if (n == 0)
return a0_;
if (n == 1)
return a1_;
big_int a = (n - 1) * (2 * a1_ + 3 * a0_) / (n + 1);
a0_ = a1_;
a1_ = a;
return a;
}
std::string to_string(const big_int& num, size_t n) {
std::string str = num.get_str();
size_t len = str.size();
if (len > n)
str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2);
return str;
}
int main() {
riordan_number_generator rng;
std::cout << "First 32 Riordan numbers:\n";
int i = 1;
for (; i <= 32; ++i) {
std::cout << std::setw(14) << rng.next()
<< (i % 4 == 0 ? '\n' : ' ');
}
for (; i < 1000; ++i)
rng.next();
auto num = rng.next();
++i;
std::cout << "\nThe 1000th is " << to_string(num, 40) << " ("
<< num.get_str().size() << " digits).\n";
for (; i < 10000; ++i)
rng.next();
num = rng.next();
std::cout << "The 10000th is " << to_string(num, 40) << " ("
<< num.get_str().size() << " digits).\n";
}
| def Riordan(N):
a = [1, 0, 1]
for n in range(3, N):
a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1))
return a
rios = Riordan(10_000)
for i in range(32):
print(f'{rios[i] : 18,}', end='\n' if (i + 1) % 4 == 0 else '')
print(f'The 1,000th Riordan has {len(str(rios[999]))} digits.')
print(f'The 10,000th Rirdan has {len(str(rios[9999]))} digits.')
|
Write a version of this C++ function in Python with identical behavior. | #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() {
std::cout.imbue(std::locale(""));
std::cout << "First 50 numbers which are the cube roots of the products of "
"their proper divisors:\n";
for (unsigned int n = 1, count = 0; count < 50000; ++n) {
if (n == 1 || divisor_count(n) == 8) {
++count;
if (count <= 50)
std::cout << std::setw(3) << n
<< (count % 10 == 0 ? '\n' : ' ');
else if (count == 500 || count == 5000 || count == 50000)
std::cout << std::setw(6) << count << "th: " << n << '\n';
}
}
}
|
from functools import reduce
from sympy import divisors
FOUND = 0
for num in range(1, 1_000_000):
divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1
if num * num * num == divprod:
FOUND += 1
if FOUND <= 50:
print(f'{num:5}', end='\n' if FOUND % 10 == 0 else '')
if FOUND == 500:
print(f'\nFive hundreth: {num:,}')
if FOUND == 5000:
print(f'\nFive thousandth: {num:,}')
if FOUND == 50000:
print(f'\nFifty thousandth: {num:,}')
break
|
Produce a language-to-language conversion: from C++ to Python, same semantics. | #include <boost/spirit.hpp>
#include <boost/spirit/tree/ast.hpp>
#include <string>
#include <cassert>
#include <iostream>
#include <istream>
#include <ostream>
using boost::spirit::rule;
using boost::spirit::parser_tag;
using boost::spirit::ch_p;
using boost::spirit::real_p;
using boost::spirit::tree_node;
using boost::spirit::node_val_data;
struct parser: public boost::spirit::grammar<parser>
{
enum rule_ids { addsub_id, multdiv_id, value_id, real_id };
struct set_value
{
set_value(parser const& p): self(p) {}
void operator()(tree_node<node_val_data<std::string::iterator,
double> >& node,
std::string::iterator begin,
std::string::iterator end) const
{
node.value.value(self.tmp);
}
parser const& self;
};
mutable double tmp;
template<typename Scanner> struct definition
{
rule<Scanner, parser_tag<addsub_id> > addsub;
rule<Scanner, parser_tag<multdiv_id> > multdiv;
rule<Scanner, parser_tag<value_id> > value;
rule<Scanner, parser_tag<real_id> > real;
definition(parser const& self)
{
using namespace boost::spirit;
addsub = multdiv
>> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);
multdiv = value
>> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);
value = real | inner_node_d[('(' >> addsub >> ')')];
real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];
}
rule<Scanner, parser_tag<addsub_id> > const& start() const
{
return addsub;
}
};
};
template<typename TreeIter>
double evaluate(TreeIter const& i)
{
double op1, op2;
switch (i->value.id().to_long())
{
case parser::real_id:
return i->value.value();
case parser::value_id:
case parser::addsub_id:
case parser::multdiv_id:
op1 = evaluate(i->children.begin());
op2 = evaluate(i->children.begin()+1);
switch(*i->value.begin())
{
case '+':
return op1 + op2;
case '-':
return op1 - op2;
case '*':
return op1 * op2;
case '/':
return op1 / op2;
default:
assert(!"Should not happen");
}
default:
assert(!"Should not happen");
}
return 0;
}
int main()
{
parser eval;
std::string line;
while (std::cout << "Expression: "
&& std::getline(std::cin, line)
&& !line.empty())
{
typedef boost::spirit::node_val_data_factory<double> factory_t;
boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =
boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),
eval, boost::spirit::space_p);
if (info.full)
{
std::cout << "Result: " << evaluate(info.trees.begin()) << std::endl;
}
else
{
std::cout << "Error in expression." << std::endl;
}
}
};
| import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(self):
return self.v
class Yaccer(object):
def __init__(self):
self.operstak = []
self.nodestak =[]
self.__dict__.update(self.state1)
def v1( self, valStrg ):
self.nodestak.append( LeafNode(valStrg))
self.__dict__.update(self.state2)
def o2( self, operchar ):
def openParen(a,b):
return 0
opDict= { '+': ( operator.add, 2, 2 ),
'-': (operator.sub, 2, 2 ),
'*': (operator.mul, 3, 3 ),
'/': (operator.div, 3, 3 ),
'^': ( pow, 4, 5 ),
'(': ( openParen, 0, 8 )
}
operPrecidence = opDict[operchar][2]
self.redeuce(operPrecidence)
self.operstak.append(opDict[operchar])
self.__dict__.update(self.state1)
def syntaxErr(self, char ):
print 'parse error - near operator "%s"' %char
def pc2( self,operchar ):
self.redeuce( 1 )
if len(self.operstak)>0:
self.operstak.pop()
else:
print 'Error - no open parenthesis matches close parens.'
self.__dict__.update(self.state2)
def end(self):
self.redeuce(0)
return self.nodestak.pop()
def redeuce(self, precidence):
while len(self.operstak)>0:
tailOper = self.operstak[-1]
if tailOper[1] < precidence: break
tailOper = self.operstak.pop()
vrgt = self.nodestak.pop()
vlft= self.nodestak.pop()
self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))
state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }
state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }
def Lex( exprssn, p ):
bgn = None
cp = -1
for c in exprssn:
cp += 1
if c in '+-/*^()':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if c=='(': p.po(p, c)
elif c==')':p.pc(p, c)
else: p.o(p, c)
elif c in ' \t':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
elif c in '0123456789':
if bgn is None:
bgn = cp
else:
print 'Invalid character in expression'
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if bgn is not None:
p.v(p, exprssn[bgn:cp+1])
bgn = None
return p.end()
expr = raw_input("Expression:")
astTree = Lex( expr, Yaccer())
print expr, '=',astTree.eval()
|
Translate this program into Python but keep the logic exactly as in C++. | #include <boost/spirit.hpp>
#include <boost/spirit/tree/ast.hpp>
#include <string>
#include <cassert>
#include <iostream>
#include <istream>
#include <ostream>
using boost::spirit::rule;
using boost::spirit::parser_tag;
using boost::spirit::ch_p;
using boost::spirit::real_p;
using boost::spirit::tree_node;
using boost::spirit::node_val_data;
struct parser: public boost::spirit::grammar<parser>
{
enum rule_ids { addsub_id, multdiv_id, value_id, real_id };
struct set_value
{
set_value(parser const& p): self(p) {}
void operator()(tree_node<node_val_data<std::string::iterator,
double> >& node,
std::string::iterator begin,
std::string::iterator end) const
{
node.value.value(self.tmp);
}
parser const& self;
};
mutable double tmp;
template<typename Scanner> struct definition
{
rule<Scanner, parser_tag<addsub_id> > addsub;
rule<Scanner, parser_tag<multdiv_id> > multdiv;
rule<Scanner, parser_tag<value_id> > value;
rule<Scanner, parser_tag<real_id> > real;
definition(parser const& self)
{
using namespace boost::spirit;
addsub = multdiv
>> *((root_node_d[ch_p('+')] | root_node_d[ch_p('-')]) >> multdiv);
multdiv = value
>> *((root_node_d[ch_p('*')] | root_node_d[ch_p('/')]) >> value);
value = real | inner_node_d[('(' >> addsub >> ')')];
real = leaf_node_d[access_node_d[real_p[assign_a(self.tmp)]][set_value(self)]];
}
rule<Scanner, parser_tag<addsub_id> > const& start() const
{
return addsub;
}
};
};
template<typename TreeIter>
double evaluate(TreeIter const& i)
{
double op1, op2;
switch (i->value.id().to_long())
{
case parser::real_id:
return i->value.value();
case parser::value_id:
case parser::addsub_id:
case parser::multdiv_id:
op1 = evaluate(i->children.begin());
op2 = evaluate(i->children.begin()+1);
switch(*i->value.begin())
{
case '+':
return op1 + op2;
case '-':
return op1 - op2;
case '*':
return op1 * op2;
case '/':
return op1 / op2;
default:
assert(!"Should not happen");
}
default:
assert(!"Should not happen");
}
return 0;
}
int main()
{
parser eval;
std::string line;
while (std::cout << "Expression: "
&& std::getline(std::cin, line)
&& !line.empty())
{
typedef boost::spirit::node_val_data_factory<double> factory_t;
boost::spirit::tree_parse_info<std::string::iterator, factory_t> info =
boost::spirit::ast_parse<factory_t>(line.begin(), line.end(),
eval, boost::spirit::space_p);
if (info.full)
{
std::cout << "Result: " << evaluate(info.trees.begin()) << std::endl;
}
else
{
std::cout << "Error in expression." << std::endl;
}
}
};
| import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(self):
return self.v
class Yaccer(object):
def __init__(self):
self.operstak = []
self.nodestak =[]
self.__dict__.update(self.state1)
def v1( self, valStrg ):
self.nodestak.append( LeafNode(valStrg))
self.__dict__.update(self.state2)
def o2( self, operchar ):
def openParen(a,b):
return 0
opDict= { '+': ( operator.add, 2, 2 ),
'-': (operator.sub, 2, 2 ),
'*': (operator.mul, 3, 3 ),
'/': (operator.div, 3, 3 ),
'^': ( pow, 4, 5 ),
'(': ( openParen, 0, 8 )
}
operPrecidence = opDict[operchar][2]
self.redeuce(operPrecidence)
self.operstak.append(opDict[operchar])
self.__dict__.update(self.state1)
def syntaxErr(self, char ):
print 'parse error - near operator "%s"' %char
def pc2( self,operchar ):
self.redeuce( 1 )
if len(self.operstak)>0:
self.operstak.pop()
else:
print 'Error - no open parenthesis matches close parens.'
self.__dict__.update(self.state2)
def end(self):
self.redeuce(0)
return self.nodestak.pop()
def redeuce(self, precidence):
while len(self.operstak)>0:
tailOper = self.operstak[-1]
if tailOper[1] < precidence: break
tailOper = self.operstak.pop()
vrgt = self.nodestak.pop()
vlft= self.nodestak.pop()
self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))
state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }
state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }
def Lex( exprssn, p ):
bgn = None
cp = -1
for c in exprssn:
cp += 1
if c in '+-/*^()':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if c=='(': p.po(p, c)
elif c==')':p.pc(p, c)
else: p.o(p, c)
elif c in ' \t':
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
elif c in '0123456789':
if bgn is None:
bgn = cp
else:
print 'Invalid character in expression'
if bgn is not None:
p.v(p, exprssn[bgn:cp])
bgn = None
if bgn is not None:
p.v(p, exprssn[bgn:cp+1])
bgn = None
return p.end()
expr = raw_input("Expression:")
astTree = Lex( expr, Yaccer())
print expr, '=',astTree.eval()
|
Convert the following code from C++ to Python, ensuring the logic remains intact. | #include <array>
#include <iostream>
#include <primesieve.hpp>
class ormiston_triple_generator {
public:
ormiston_triple_generator() {
for (int i = 0; i < 2; ++i) {
primes_[i] = pi_.next_prime();
digits_[i] = get_digits(primes_[i]);
}
}
std::array<uint64_t, 3> next_triple() {
for (;;) {
uint64_t prime = pi_.next_prime();
auto digits = get_digits(prime);
bool is_triple = digits == digits_[0] && digits == digits_[1];
uint64_t prime0 = primes_[0];
primes_[0] = primes_[1];
primes_[1] = prime;
digits_[0] = digits_[1];
digits_[1] = digits;
if (is_triple)
return {prime0, primes_[0], primes_[1]};
}
}
private:
static std::array<int, 10> get_digits(uint64_t n) {
std::array<int, 10> result = {};
for (; n > 0; n /= 10)
++result[n % 10];
return result;
}
primesieve::iterator pi_;
std::array<uint64_t, 2> primes_;
std::array<std::array<int, 10>, 2> digits_;
};
int main() {
ormiston_triple_generator generator;
int count = 0;
std::cout << "Smallest members of first 25 Ormiston triples:\n";
for (; count < 25; ++count) {
auto primes = generator.next_triple();
std::cout << primes[0] << ((count + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (uint64_t limit = 1000000000; limit <= 10000000000; ++count) {
auto primes = generator.next_triple();
if (primes[2] > limit) {
std::cout << "Number of Ormiston triples < " << limit << ": "
<< count << '\n';
limit *= 10;
}
}
}
| import textwrap
from itertools import pairwise
from typing import Iterator
from typing import List
import primesieve
def primes() -> Iterator[int]:
it = primesieve.Iterator()
while True:
yield it.next_prime()
def triplewise(iterable):
for (a, _), (b, c) in pairwise(pairwise(iterable)):
yield a, b, c
def is_anagram(a: int, b: int, c: int) -> bool:
return sorted(str(a)) == sorted(str(b)) == sorted(str(c))
def up_to_one_billion() -> int:
count = 0
for triple in triplewise(primes()):
if is_anagram(*triple):
count += 1
if triple[2] >= 1_000_000_000:
break
return count
def up_to_ten_billion() -> int:
count = 0
for triple in triplewise(primes()):
if is_anagram(*triple):
count += 1
if triple[2] >= 10_000_000_000:
break
return count
def first_25() -> List[int]:
rv: List[int] = []
for triple in triplewise(primes()):
if is_anagram(*triple):
rv.append(triple[0])
if len(rv) >= 25:
break
return rv
if __name__ == "__main__":
print("Smallest members of first 25 Ormiston triples:")
print(textwrap.fill(" ".join(str(i) for i in first_25())), "\n")
print(up_to_one_billion(), "Ormiston triples before 1,000,000,000")
print(up_to_ten_billion(), "Ormiston triples before 10,000,000,000")
|
Write the same code in Python as shown below in C++. | #include <algorithm>
#include <iostream>
#include <vector>
std::vector<unsigned int> divisors(unsigned int n) {
std::vector<unsigned int> result{1};
unsigned int power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
result.push_back(power);
for (unsigned int p = 3; p * p <= n; p += 2) {
size_t size = result.size();
for (power = p; n % p == 0; power *= p, n /= p)
for (size_t i = 0; i != size; ++i)
result.push_back(power * result[i]);
}
if (n > 1) {
size_t size = result.size();
for (size_t i = 0; i != size; ++i)
result.push_back(n * result[i]);
}
return result;
}
unsigned long long modpow(unsigned long long base, unsigned int exp,
unsigned int mod) {
if (mod == 1)
return 0;
unsigned long long result = 1;
base %= mod;
for (; exp != 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;
base = (base * base) % mod;
}
return result;
}
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
return n == 5;
static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};
for (unsigned int p = 7;;) {
for (unsigned int w : wheel) {
if (p * p > n)
return true;
if (n % p == 0)
return false;
p += w;
}
}
}
bool is_poulet_number(unsigned int n) {
return modpow(2, n - 1, n) == 1 && !is_prime(n);
}
bool is_sp_num(unsigned int n) {
if (!is_poulet_number(n))
return false;
auto div = divisors(n);
return all_of(div.begin() + 1, div.end(),
[](unsigned int d) { return modpow(2, d, d) == 2; });
}
int main() {
std::cout.imbue(std::locale(""));
unsigned int n = 1, count = 0;
std::cout << "First 20 super-Poulet numbers:\n";
for (; count < 20; n += 2) {
if (is_sp_num(n)) {
++count;
std::cout << n << ' ';
}
}
std::cout << '\n';
for (unsigned int limit = 1000000; limit <= 10000000; limit *= 10) {
for (;;) {
n += 2;
if (is_sp_num(n)) {
++count;
if (n > limit)
break;
}
}
std::cout << "\nIndex and value of first super-Poulet greater than "
<< limit << ":\n#" << count << " is " << n << '\n';
}
}
| from sympy import isprime, divisors
def is_super_Poulet(n):
return not isprime(n) and 2**(n - 1) % n == 1 and all((2**d - 2) % d == 0 for d in divisors(n))
spoulets = [n for n in range(1, 1_100_000) if is_super_Poulet(n)]
print('The first 20 super-Poulet numbers are:', spoulets[:20])
idx1m, val1m = next((i, v) for i, v in enumerate(spoulets) if v > 1_000_000)
print(f'The first super-Poulet number over 1 million is the {idx1m}th one, which is {val1m}')
|
Write the same algorithm in Python as shown in this C++ implementation. | #include <iostream>
struct SpecialVariables
{
int i = 0;
SpecialVariables& operator++()
{
this->i++;
return *this;
}
};
int main()
{
SpecialVariables sv;
auto sv2 = ++sv;
std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n";
}
| names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
|
Rewrite this program in Python while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <string>
#include <windows.h>
using namespace std;
typedef unsigned char byte;
enum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR };
class fieldData
{
public:
fieldData() : value( CLOSED ), open( false ) {}
byte value;
bool open, mine;
};
class game
{
public:
~game()
{ if( field ) delete [] field; }
game( int x, int y )
{
go = false; wid = x; hei = y;
field = new fieldData[x * y];
memset( field, 0, x * y * sizeof( fieldData ) );
oMines = ( ( 22 - rand() % 11 ) * x * y ) / 100;
mMines = 0;
int mx, my, m = 0;
for( ; m < oMines; m++ )
{
do
{ mx = rand() % wid; my = rand() % hei; }
while( field[mx + wid * my].mine );
field[mx + wid * my].mine = true;
}
graphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*';
graphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X';
}
void gameLoop()
{
string c, r, a;
int col, row;
while( !go )
{
drawBoard();
cout << "Enter column, row and an action( c r a ):\nActions: o => open, f => flag, ? => unknown\n";
cin >> c >> r >> a;
if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32;
col = c[0] - 65; row = r[0] - 49;
makeMove( col, row, a );
}
}
private:
void makeMove( int x, int y, string a )
{
fieldData* fd = &field[wid * y + x];
if( fd->open && fd->value < CLOSED )
{
cout << "This cell is already open!";
Sleep( 3000 ); return;
}
if( a[0] == 'O' ) openCell( x, y );
else if( a[0] == 'F' )
{
fd->open = true;
fd->value = FLAG;
mMines++;
checkWin();
}
else
{
fd->open = true;
fd->value = UNKNOWN;
}
}
bool openCell( int x, int y )
{
if( !isInside( x, y ) ) return false;
if( field[x + y * wid].mine ) boom();
else
{
if( field[x + y * wid].value == FLAG )
{
field[x + y * wid].value = CLOSED;
field[x + y * wid].open = false;
mMines--;
}
recOpen( x, y );
checkWin();
}
return true;
}
void drawBoard()
{
system( "cls" );
cout << "Marked mines: " << mMines << " from " << oMines << "\n\n";
for( int x = 0; x < wid; x++ )
cout << " " << ( char )( 65 + x ) << " ";
cout << "\n"; int yy;
for( int y = 0; y < hei; y++ )
{
yy = y * wid;
for( int x = 0; x < wid; x++ )
cout << "+---";
cout << "+\n"; fieldData* fd;
for( int x = 0; x < wid; x++ )
{
fd = &field[x + yy]; cout<< "| ";
if( !fd->open ) cout << ( char )graphs[1] << " ";
else
{
if( fd->value > 9 )
cout << ( char )graphs[fd->value - 9] << " ";
else
{
if( fd->value < 1 ) cout << " ";
else cout << ( char )(fd->value + 48 ) << " ";
}
}
}
cout << "| " << y + 1 << "\n";
}
for( int x = 0; x < wid; x++ )
cout << "+---";
cout << "+\n\n";
}
void checkWin()
{
int z = wid * hei - oMines, yy;
fieldData* fd;
for( int y = 0; y < hei; y++ )
{
yy = wid * y;
for( int x = 0; x < wid; x++ )
{
fd = &field[x + yy];
if( fd->open && fd->value != FLAG ) z--;
}
}
if( !z ) lastMsg( "Congratulations, you won the game!");
}
void boom()
{
int yy; fieldData* fd;
for( int y = 0; y < hei; y++ )
{
yy = wid * y;
for( int x = 0; x < wid; x++ )
{
fd = &field[x + yy];
if( fd->value == FLAG )
{
fd->open = true;
fd->value = fd->mine ? MINE : ERR;
}
else if( fd->mine )
{
fd->open = true;
fd->value = MINE;
}
}
}
lastMsg( "B O O O M M M M M !" );
}
void lastMsg( string s )
{
go = true; drawBoard();
cout << s << "\n\n";
}
bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); }
void recOpen( int x, int y )
{
if( !isInside( x, y ) || field[x + y * wid].open ) return;
int bc = getMineCount( x, y );
field[x + y * wid].open = true;
field[x + y * wid].value = bc;
if( bc ) return;
for( int yy = -1; yy < 2; yy++ )
for( int xx = -1; xx < 2; xx++ )
{
if( xx == 0 && yy == 0 ) continue;
recOpen( x + xx, y + yy );
}
}
int getMineCount( int x, int y )
{
int m = 0;
for( int yy = -1; yy < 2; yy++ )
for( int xx = -1; xx < 2; xx++ )
{
if( xx == 0 && yy == 0 ) continue;
if( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++;
}
return m;
}
int wid, hei, mMines, oMines;
fieldData* field; bool go;
int graphs[6];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
game g( 4, 6 ); g.gameLoop();
return system( "pause" );
}
|
gridsize = (6, 4)
minerange = (0.2, 0.6)
try:
raw_input
except:
raw_input = input
import random
from itertools import product
from pprint import pprint as pp
def gridandmines(gridsize=gridsize, minerange=minerange):
xgrid, ygrid = gridsize
minmines, maxmines = minerange
minecount = xgrid * ygrid
minecount = random.randint(int(minecount*minmines), int(minecount*maxmines))
grid = set(product(range(xgrid), range(ygrid)))
mines = set(random.sample(grid, minecount))
show = {xy:'.' for xy in grid}
return grid, mines, show
def printgrid(show, gridsize=gridsize):
xgrid, ygrid = gridsize
grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid))
for y in range(ygrid))
print( grid )
def resign(showgrid, mines, markedmines):
for m in mines:
showgrid[m] = 'Y' if m in markedmines else 'N'
def clear(x,y, showgrid, grid, mines, markedmines):
if showgrid[(x, y)] == '.':
xychar = str(sum(1
for xx in (x-1, x, x+1)
for yy in (y-1, y, y+1)
if (xx, yy) in mines ))
if xychar == '0': xychar = '.'
showgrid[(x,y)] = xychar
for xx in (x-1, x, x+1):
for yy in (y-1, y, y+1):
xxyy = (xx, yy)
if ( xxyy != (x, y)
and xxyy in grid
and xxyy not in mines | markedmines ):
clear(xx, yy, showgrid, grid, mines, markedmines)
if __name__ == '__main__':
grid, mines, showgrid = gridandmines()
markedmines = set([])
print( __doc__ )
print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) )
printgrid(showgrid)
while markedmines != mines:
inp = raw_input('m x y/c x y/p/r: ').strip().split()
if inp:
if inp[0] == 'm':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in markedmines:
markedmines.remove((x,y))
showgrid[(x,y)] = '.'
else:
markedmines.add((x,y))
showgrid[(x,y)] = '?'
elif inp[0] == 'p':
printgrid(showgrid)
elif inp[0] == 'c':
x, y = [int(i)-1 for i in inp[1:3]]
if (x,y) in mines | markedmines:
print( '\nKLABOOM!! You hit a mine.\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
clear(x,y, showgrid, grid, mines, markedmines)
printgrid(showgrid)
elif inp[0] == 'r':
print( '\nResigning!\n' )
resign(showgrid, mines, markedmines)
printgrid(showgrid)
break
print( '\nYou got %i and missed %i of the %i mines'
% (len(mines.intersection(markedmines)),
len(markedmines.difference(mines)),
len(mines)) )
|
Write a version of this C++ function in Python with identical behavior. | #include <iostream>
#include <iomanip>
#include <string>
class oo {
public:
void evolve( int l, int rule ) {
std::string cells = "O";
std::cout << " Rule #" << rule << ":\n";
for( int x = 0; x < l; x++ ) {
addNoCells( cells );
std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << "\n";
step( cells, rule );
}
}
private:
void step( std::string& cells, int rule ) {
int bin;
std::string newCells;
for( size_t i = 0; i < cells.length() - 2; i++ ) {
bin = 0;
for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) {
bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b );
}
newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' );
}
cells = newCells;
}
void addNoCells( std::string& s ) {
char l = s.at( 0 ) == 'O' ? '.' : 'O',
r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O';
s = l + s + r;
s = l + s + r;
}
};
int main( int argc, char* argv[] ) {
oo o;
o.evolve( 35, 90 );
std::cout << "\n";
return 0;
}
| def _notcell(c):
return '0' if c == '1' else '1'
def eca_infinite(cells, rule):
lencells = len(cells)
rulebits = '{0:08b}'.format(rule)
neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}
c = cells
while True:
yield c
c = _notcell(c[0])*2 + c + _notcell(c[-1])*2
c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1))
if __name__ == '__main__':
lines = 25
for rule in (90, 30):
print('\nRule: %i' % rule)
for i, c in zip(range(lines), eca_infinite('1', rule)):
print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '
|
Produce a language-to-language conversion: from C++ to Python, same semantics. | #include <fstream>
#include <iostream>
#include <sstream>
#include <streambuf>
#include <string>
#include <stdlib.h>
using namespace std;
void fatal_error(string errtext, char *argv[])
{
cout << "%" << errtext << endl;
cout << "usage: " << argv[0] << " [filename.cp]" << endl;
exit(1);
}
string& ltrim(string& str, const string& chars = "\t\n\v\f\r ")
{
str.erase(0, str.find_first_not_of(chars));
return str;
}
string& rtrim(string& str, const string& chars = "\t\n\v\f\r ")
{
str.erase(str.find_last_not_of(chars) + 1);
return str;
}
string& trim(string& str, const string& chars = "\t\n\v\f\r ")
{
return ltrim(rtrim(str, chars), chars);
}
int main(int argc, char *argv[])
{
string fname = "";
string source = "";
try
{
fname = argv[1];
ifstream t(fname);
t.seekg(0, ios::end);
source.reserve(t.tellg());
t.seekg(0, ios::beg);
source.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
}
catch(const exception& e)
{
fatal_error("error while trying to read from specified file", argv);
}
string clipboard = "";
int loc = 0;
string remaining = source;
string line = "";
string command = "";
stringstream ss;
while(remaining.find("\n") != string::npos)
{
line = remaining.substr(0, remaining.find("\n"));
command = trim(line);
remaining = remaining.substr(remaining.find("\n") + 1);
try
{
if(line == "Copy")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
clipboard += line;
}
else if(line == "CopyFile")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
if(line == "TheF*ckingCode")
clipboard += source;
else
{
string filetext = "";
ifstream t(line);
t.seekg(0, ios::end);
filetext.reserve(t.tellg());
t.seekg(0, ios::beg);
filetext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
clipboard += filetext;
}
}
else if(line == "Duplicate")
{
line = remaining.substr(0, remaining.find("\n"));
remaining = remaining.substr(remaining.find("\n") + 1);
int amount = stoi(line);
string origClipboard = clipboard;
for(int i = 0; i < amount - 1; i++) {
clipboard += origClipboard;
}
}
else if(line == "Pasta!")
{
cout << clipboard << endl;
return 0;
}
else
{
ss << (loc + 1);
fatal_error("unknown command '" + command + "' encounter on line " + ss.str(), argv);
}
}
catch(const exception& e)
{
ss << (loc + 1);
fatal_error("error while executing command '" + command + "' on line " + ss.str(), argv);
}
loc += 2;
}
return 0;
}
| import sys
def fatal_error(errtext):
print("%" + errtext)
print("usage: " + sys.argv[0] + " [filename.cp]")
sys.exit(1)
fname = None
source = None
try:
fname = sys.argv[1]
source = open(fname).read()
except:
fatal_error("error while trying to read from specified file")
lines = source.split("\n")
clipboard = ""
loc = 0
while(loc < len(lines)):
command = lines[loc].strip()
try:
if(command == "Copy"):
clipboard += lines[loc + 1]
elif(command == "CopyFile"):
if(lines[loc + 1] == "TheF*ckingCode"):
clipboard += source
else:
filetext = open(lines[loc+1]).read()
clipboard += filetext
elif(command == "Duplicate"):
clipboard += clipboard * ((int(lines[loc + 1])) - 1)
elif(command == "Pasta!"):
print(clipboard)
sys.exit(0)
else:
fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1))
except Exception as e:
fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e)
loc += 2
|
Convert the following code from C++ to Python, ensuring the logic remains intact. | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(int limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (sieve[p]) {
for (int q = sq; q < limit; q += p << 1)
sieve[q] = false;
}
sq += (p + 1) << 2;
}
return sieve;
}
void print_non_twin_prime_sums(const std::vector<bool>& sums) {
int count = 0;
for (size_t i = 2; i < sums.size(); i += 2) {
if (!sums[i]) {
++count;
std::cout << std::setw(4) << i << (count % 10 == 0 ? '\n' : ' ');
}
}
std::cout << "\nFound " << count << '\n';
}
int main() {
const int limit = 100001;
std::vector<bool> sieve = prime_sieve(limit + 2);
for (size_t i = 0; i < limit; ++i) {
if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))
sieve[i] = false;
}
std::vector<bool> twin_prime_sums(limit, false);
for (size_t i = 0; i < limit; ++i) {
if (sieve[i]) {
for (size_t j = i; i + j < limit; ++j) {
if (sieve[j])
twin_prime_sums[i + j] = true;
}
}
}
std::cout << "Non twin prime sums:\n";
print_non_twin_prime_sums(twin_prime_sums);
sieve[1] = true;
for (size_t i = 1; i + 1 < limit; ++i) {
if (sieve[i])
twin_prime_sums[i + 1] = true;
}
std::cout << "\nNon twin prime sums (including 1):\n";
print_non_twin_prime_sums(twin_prime_sums);
}
|
from sympy import sieve
def nonpairsums(include1=False, limit=20_000):
tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve)
for i in range(limit+2)]
if include1:
tpri[1] = True
twinsums = [False] * (limit * 2)
for i in range(limit):
for j in range(limit-i+1):
if tpri[i] and tpri[j]:
twinsums[i + j] = True
return [i for i in range(2, limit+1, 2) if not twinsums[i]]
print('Non twin prime sums:')
for k, p in enumerate(nonpairsums()):
print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')
print('\n\nNon twin prime sums (including 1):')
for k, p in enumerate(nonpairsums(include1=True)):
print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')
|
Rewrite this program in Python while keeping its functionality equivalent to the C++ version. | #include <functional>
#include <iostream>
#include <ostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[";
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << "]";
}
std::vector<int> kosaraju(std::vector<std::vector<int>>& g) {
auto size = g.size();
std::vector<bool> vis(size);
std::vector<int> l(size);
auto x = size;
std::vector<std::vector<int>> t(size);
std::function<void(int)> visit;
visit = [&](int u) {
if (!vis[u]) {
vis[u] = true;
for (auto v : g[u]) {
visit(v);
t[v].push_back(u);
}
l[--x] = u;
}
};
for (int i = 0; i < g.size(); ++i) {
visit(i);
}
std::vector<int> c(size);
std::function<void(int, int)> assign;
assign = [&](int u, int root) {
if (vis[u]) {
vis[u] = false;
c[u] = root;
for (auto v : t[u]) {
assign(v, root);
}
}
};
for (auto u : l) {
assign(u, u);
}
return c;
}
std::vector<std::vector<int>> g = {
{1},
{2},
{0},
{1, 2, 4},
{3, 5},
{2, 6},
{5},
{4, 6, 7},
};
int main() {
using namespace std;
cout << kosaraju(g) << endl;
return 0;
}
| def kosaraju(g):
class nonlocal: pass
size = len(g)
vis = [False]*size
l = [0]*size
nonlocal.x = size
t = [[]]*size
def visit(u):
if not vis[u]:
vis[u] = True
for v in g[u]:
visit(v)
t[v] = t[v] + [u]
nonlocal.x = nonlocal.x - 1
l[nonlocal.x] = u
for u in range(len(g)):
visit(u)
c = [0]*size
def assign(u, root):
if vis[u]:
vis[u] = False
c[u] = root
for v in t[u]:
assign(v, root)
for u in l:
assign(u, u)
return c
g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]
print kosaraju(g)
|
Convert this C++ block to Python, preserving its control flow and logic. | int a;
|
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"
example1 = "goodbye"
|
Convert the following code from C++ to Python, ensuring the logic remains intact. |
#include <cstring>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <ctime>
void Extend (uint32_t w[], uint32_t &w_end, uint32_t &length, uint32_t n, bool d[], uint32_t &w_end_max) {
uint32_t i, j, x;
i = 0; j = w_end;
x = length + 1;
while (x <= n) {
w[++j] = x;
d[x] = false;
x = length + w[++i];
}
length = n; w_end = j;
if (w_end > w_end_max) w_end_max = w_end;
}
void Delete (uint32_t w[], uint32_t length, uint32_t p, bool d[], uint32_t &imaxf) {
uint32_t i, x;
i = 0;
x = p;
while (x <= length) {
d[x] = true;
x = p*w[++i];
}
imaxf = i-1;
}
void Compress(uint32_t w[], bool d[], uint32_t to, uint32_t &w_end) {
uint32_t i, j;
j = 0;
for (i=1; i <= to; i++) {
if (!d[w[i]]) {
w[++j] = w[i];
}
}
if (to == w_end) {
w_end = j;
} else {
for (uint32_t k=j+1; k <= to; k++) w[k] = 0;
}
}
void Sift(uint32_t N, bool printPrimes, uint32_t &nrPrimes, uint32_t &vBound) {
uint32_t *w = new uint32_t[N/4+5];
bool *d = new bool[N+1];
uint32_t w_end, length;
uint32_t w_end_max, p, imaxf;
w_end = 0; w[0] = 1;
w_end_max = 0;
length = 2;
nrPrimes = 1;
if (printPrimes) printf("%d", 2);
p = 3;
while (p*p <= N) {
nrPrimes++;
if (printPrimes) printf(" %d", p);
if (length < N) {
Extend (w, w_end, length, std::min(p*length,N), d, w_end_max);
}
Delete(w, length, p, d, imaxf);
Compress(w, d, (length < N ? w_end : imaxf), w_end);
p = w[1];
if (p == 0) break;
}
if (length < N) {
Extend (w, w_end, length, N, d, w_end_max);
}
for (uint32_t i=1; i <= w_end; i++) {
if (w[i] == 0 || d[w[i]]) continue;
if (printPrimes) printf(" %d", w[i]);
nrPrimes++;
}
vBound = w_end_max+1;
}
int main (int argc, char *argw[]) {
bool error = false;
bool printPrimes = false;
uint32_t N, nrPrimes, vBound;
if (argc == 3) {
if (strcmp(argw[2], "-p") == 0) {
printPrimes = true;
argc--;
} else {
error = true;
}
}
if (argc == 2) {
N = atoi(argw[1]);
if (N < 2 || N > 1000000000) error = true;
} else {
error = true;
}
if (error) {
printf("call with: %s N -p where 2 <= N <= 1000000000 and -p to print the primes is optional \n", argw[0]);
exit(1);
}
int start_s = clock();
Sift(N, printPrimes, nrPrimes, vBound);
int stop_s=clock();
printf("\n%d primes up to %lu found in %.3f ms using array w[%d]\n", nrPrimes,
(unsigned long)N, (stop_s-start_s)*1E3/double(CLOCKS_PER_SEC), vBound);
}
|
from numpy import ndarray
from math import isqrt
def pritchard(limit):
members = ndarray(limit + 1, dtype=bool)
members.fill(False)
members[1] = True
steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2
primes = []
while prime <= rtlim:
if steplength < limit:
for w in range(1, len(members)):
if members[w]:
n = w + steplength
while n <= nlimit:
members[n] = True
n += steplength
steplength = nlimit
np = 5
mcpy = members.copy()
for w in range(1, len(members)):
if mcpy[w]:
if np == 5 and w > prime:
np = w
n = prime * w
if n > nlimit:
break
members[n] = False
if np < prime:
break
primes.append(prime)
prime = 3 if prime == 2 else np
nlimit = min(steplength * prime, limit)
newprimes = [i for i in range(2, len(members)) if members[i]]
return sorted(primes + newprimes)
print(pritchard(150))
print('Number of primes up to 1,000,000:', len(pritchard(1000000)))
|
Can you help me rewrite this code in Python instead of C++, keeping it the same logically? | #include <cmath>
#include <iostream>
#include <string>
using namespace std;
struct LoggingMonad
{
double Value;
string Log;
};
auto operator>>(const LoggingMonad& monad, auto f)
{
auto result = f(monad.Value);
return LoggingMonad{result.Value, monad.Log + "\n" + result.Log};
}
auto Root = [](double x){ return sqrt(x); };
auto AddOne = [](double x){ return x + 1; };
auto Half = [](double x){ return x / 2.0; };
auto MakeWriter = [](auto f, string message)
{
return [=](double x){return LoggingMonad(f(x), message);};
};
auto writerRoot = MakeWriter(Root, "Taking square root");
auto writerAddOne = MakeWriter(AddOne, "Adding 1");
auto writerHalf = MakeWriter(Half, "Dividing by 2");
int main()
{
auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf;
cout << result.Log << "\nResult: " << result.Value;
}
|
from __future__ import annotations
import functools
import math
import os
from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Writer(Generic[T]):
def __init__(self, value: Union[T, Writer[T]], *msgs: str):
if isinstance(value, Writer):
self.value: T = value.value
self.msgs: List[str] = value.msgs + list(msgs)
else:
self.value = value
self.msgs = list(f"{msg}: {self.value}" for msg in msgs)
def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
writer = func(self.value)
return Writer(writer, *self.msgs)
def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
return self.bind(func)
def __str__(self):
return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"
def __repr__(self):
return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"
def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
@functools.wraps(func)
def wrapped(value):
return Writer(func(value), msg)
return wrapped
if __name__ == "__main__":
square_root = lift(math.sqrt, "square root")
add_one = lift(lambda x: x + 1, "add one")
half = lift(lambda x: x / 2, "div two")
print(Writer(5, "initial") >> square_root >> add_one >> half)
|
Convert this C++ block to Python, preserving its control flow and logic. | #include <iostream>
#include <set>
#include <tuple>
#include <vector>
using namespace std;
template<typename P>
void PrintPayloads(const P &payloads, int index, bool isLast)
{
if(index < 0 || index >= (int)size(payloads)) cout << "null";
else cout << "'" << payloads[index] << "'";
if (!isLast) cout << ", ";
}
template<typename P, typename... Ts>
void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)
{
std::apply
(
[&payloads, isLast](Ts const&... tupleArgs)
{
size_t n{0};
cout << "[";
(PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);
cout << "]";
cout << (isLast ? "\n" : ",\n");
}, nestedTuple
);
}
void FindUniqueIndexes(set<int> &indexes, int index)
{
indexes.insert(index);
}
template<typename... Ts>
void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)
{
std::apply
(
[&indexes](Ts const&... tupleArgs)
{
(FindUniqueIndexes(indexes, tupleArgs),...);
}, nestedTuple
);
}
template<typename P>
void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)
{
for(size_t i = 0; i < size(payloads); i++)
{
if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n";
}
}
int main()
{
vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"};
const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"};
auto tpl = make_tuple(make_tuple(
make_tuple(1, 2),
make_tuple(3, 4, 1),
5));
cout << "Mapping indexes to payloads:\n";
PrintPayloads(payloads, tpl);
cout << "\nFinding unused payloads:\n";
set<int> usedIndexes;
FindUniqueIndexes(usedIndexes, tpl);
PrintUnusedPayloads(usedIndexes, payloads);
cout << "\nMapping to some out of range payloads:\n";
PrintPayloads(shortPayloads, tpl);
return 0;
}
| from pprint import pprint as pp
class Template():
def __init__(self, structure):
self.structure = structure
self.used_payloads, self.missed_payloads = [], []
def inject_payload(self, id2data):
def _inject_payload(substruct, i2d, used, missed):
used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)
missed.extend(f'??
for x in substruct if type(x) is not tuple and x not in i2d)
return tuple(_inject_payload(x, i2d, used, missed)
if type(x) is tuple
else i2d.get(x, f'??
for x in substruct)
ans = _inject_payload(self.structure, id2data,
self.used_payloads, self.missed_payloads)
self.unused_payloads = sorted(set(id2data.values())
- set(self.used_payloads))
self.missed_payloads = sorted(set(self.missed_payloads))
return ans
if __name__ == '__main__':
index2data = {p: f'Payload
print("
print('\n '.join(list(index2data.values())))
for structure in [
(((1, 2),
(3, 4, 1),
5),),
(((1, 2),
(10, 4, 1),
5),)]:
print("\n\n
pp(structure, width=13)
print("\n TEMPLATE WITH PAYLOADS:")
t = Template(structure)
out = t.inject_payload(index2data)
pp(out)
print("\n UNUSED PAYLOADS:\n ", end='')
unused = t.unused_payloads
print('\n '.join(unused) if unused else '-')
print(" MISSING PAYLOADS:\n ", end='')
missed = t.missed_payloads
print('\n '.join(missed) if missed else '-')
|
Translate this program into Python but keep the logic exactly as in C++. | #include <iostream>
#include <set>
#include <tuple>
#include <vector>
using namespace std;
template<typename P>
void PrintPayloads(const P &payloads, int index, bool isLast)
{
if(index < 0 || index >= (int)size(payloads)) cout << "null";
else cout << "'" << payloads[index] << "'";
if (!isLast) cout << ", ";
}
template<typename P, typename... Ts>
void PrintPayloads(const P &payloads, tuple<Ts...> const& nestedTuple, bool isLast = true)
{
std::apply
(
[&payloads, isLast](Ts const&... tupleArgs)
{
size_t n{0};
cout << "[";
(PrintPayloads(payloads, tupleArgs, (++n == sizeof...(Ts)) ), ...);
cout << "]";
cout << (isLast ? "\n" : ",\n");
}, nestedTuple
);
}
void FindUniqueIndexes(set<int> &indexes, int index)
{
indexes.insert(index);
}
template<typename... Ts>
void FindUniqueIndexes(set<int> &indexes, std::tuple<Ts...> const& nestedTuple)
{
std::apply
(
[&indexes](Ts const&... tupleArgs)
{
(FindUniqueIndexes(indexes, tupleArgs),...);
}, nestedTuple
);
}
template<typename P>
void PrintUnusedPayloads(const set<int> &usedIndexes, const P &payloads)
{
for(size_t i = 0; i < size(payloads); i++)
{
if(usedIndexes.find(i) == usedIndexes.end() ) cout << payloads[i] << "\n";
}
}
int main()
{
vector payloads {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"};
const char *shortPayloads[] {"Payload#0", "Payload#1", "Payload#2", "Payload#3"};
auto tpl = make_tuple(make_tuple(
make_tuple(1, 2),
make_tuple(3, 4, 1),
5));
cout << "Mapping indexes to payloads:\n";
PrintPayloads(payloads, tpl);
cout << "\nFinding unused payloads:\n";
set<int> usedIndexes;
FindUniqueIndexes(usedIndexes, tpl);
PrintUnusedPayloads(usedIndexes, payloads);
cout << "\nMapping to some out of range payloads:\n";
PrintPayloads(shortPayloads, tpl);
return 0;
}
| from pprint import pprint as pp
class Template():
def __init__(self, structure):
self.structure = structure
self.used_payloads, self.missed_payloads = [], []
def inject_payload(self, id2data):
def _inject_payload(substruct, i2d, used, missed):
used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)
missed.extend(f'??
for x in substruct if type(x) is not tuple and x not in i2d)
return tuple(_inject_payload(x, i2d, used, missed)
if type(x) is tuple
else i2d.get(x, f'??
for x in substruct)
ans = _inject_payload(self.structure, id2data,
self.used_payloads, self.missed_payloads)
self.unused_payloads = sorted(set(id2data.values())
- set(self.used_payloads))
self.missed_payloads = sorted(set(self.missed_payloads))
return ans
if __name__ == '__main__':
index2data = {p: f'Payload
print("
print('\n '.join(list(index2data.values())))
for structure in [
(((1, 2),
(3, 4, 1),
5),),
(((1, 2),
(10, 4, 1),
5),)]:
print("\n\n
pp(structure, width=13)
print("\n TEMPLATE WITH PAYLOADS:")
t = Template(structure)
out = t.inject_payload(index2data)
pp(out)
print("\n UNUSED PAYLOADS:\n ", end='')
unused = t.unused_payloads
print('\n '.join(unused) if unused else '-')
print(" MISSING PAYLOADS:\n ", end='')
missed = t.missed_payloads
print('\n '.join(missed) if missed else '-')
|
Convert this C++ snippet to Python and keep its semantics consistent. | #include <iomanip>
#include <iostream>
#include <sstream>
#include <utility>
#include <primesieve.hpp>
uint64_t digit_sum(uint64_t n) {
uint64_t sum = 0;
for (; n > 0; n /= 10)
sum += n % 10;
return sum;
}
class honaker_prime_generator {
public:
std::pair<uint64_t, uint64_t> next();
private:
primesieve::iterator pi_;
uint64_t index_ = 0;
};
std::pair<uint64_t, uint64_t> honaker_prime_generator::next() {
for (;;) {
uint64_t prime = pi_.next_prime();
++index_;
if (digit_sum(index_) == digit_sum(prime))
return std::make_pair(index_, prime);
}
}
std::ostream& operator<<(std::ostream& os,
const std::pair<uint64_t, uint64_t>& p) {
std::ostringstream str;
str << '(' << p.first << ", " << p.second << ')';
return os << str.str();
}
int main() {
honaker_prime_generator hpg;
std::cout << "First 50 Honaker primes (index, prime):\n";
int i = 1;
for (; i <= 50; ++i)
std::cout << std::setw(11) << hpg.next() << (i % 5 == 0 ? '\n' : ' ');
for (; i < 10000; ++i)
hpg.next();
std::cout << "\nTen thousandth: " << hpg.next() << '\n';
}
|
from pyprimesieve import primes
def digitsum(num):
return sum(int(c) for c in str(num))
def generate_honaker(limit=5_000_000):
honaker = [(i + 1, p) for i, p in enumerate(primes(limit)) if digitsum(p) == digitsum(i + 1)]
for hcount, (ppi, pri) in enumerate(honaker):
yield hcount + 1, ppi, pri
print('First 50 Honaker primes:')
for p in generate_honaker():
if p[0] < 51:
print(f'{str(p):16}', end='\n' if p[0] % 5 == 0 else '')
elif p[0] == 10_000:
print(f'\nThe 10,000th Honaker prime is the {p[1]:,}th one, which is {p[2]:,}.')
break
|
Convert the following code from C++ to Python, ensuring the logic remains intact. | #include <iomanip>
#include <iostream>
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
bool is_depolignac_number(int n) {
for (int p = 1; p < n; p <<= 1) {
if (is_prime(n - p))
return false;
}
return true;
}
int main() {
std::cout.imbue(std::locale(""));
std::cout << "First 50 de Polignac numbers:\n";
for (int n = 1, count = 0; count < 10000; n += 2) {
if (is_depolignac_number(n)) {
++count;
if (count <= 50)
std::cout << std::setw(5) << n
<< (count % 10 == 0 ? '\n' : ' ');
else if (count == 1000)
std::cout << "\nOne thousandth: " << n << '\n';
else if (count == 10000)
std::cout << "\nTen thousandth: " << n << '\n';
}
}
}
|
from sympy import isprime
from math import log
from numpy import ndarray
max_value = 1_000_000
all_primes = [i for i in range(max_value + 1) if isprime(i)]
powers_of_2 = [2**i for i in range(int(log(max_value, 2)))]
allvalues = ndarray(max_value, dtype=bool)
allvalues[:] = True
for i in all_primes:
for j in powers_of_2:
if i + j < max_value:
allvalues[i + j] = False
dePolignac = [n for n in range(1, max_value) if n & 1 == 1 and allvalues[n]]
print('First fifty de Polignac numbers:')
for i, n in enumerate(dePolignac[:50]):
print(f'{n:5}', end='\n' if (i + 1) % 10 == 0 else '')
print(f'\nOne thousandth: {dePolignac[999]:,}')
print(f'\nTen thousandth: {dePolignac[9999]:,}')
|
Transform the following C++ implementation into Python, maintaining the same output and logic. | #include <iostream>
#include <algorithm>
#include <ctime>
#include <string>
#include <vector>
typedef std::vector<char> vecChar;
class master {
public:
master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {
std::string color = "ABCDEFGHIJKLMNOPQRST";
if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10;
if( !rpt && clr_count < code_len ) clr_count = code_len;
if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20;
if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;
codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;
for( size_t s = 0; s < colorsCnt; s++ ) {
colors.append( 1, color.at( s ) );
}
}
void play() {
bool win = false;
combo = getCombo();
while( guessCnt ) {
showBoard();
if( checkInput( getInput() ) ) {
win = true;
break;
}
guessCnt--;
}
if( win ) {
std::cout << "\n\n--------------------------------\n" <<
"Very well done!\nYou found the code: " << combo <<
"\n--------------------------------\n\n";
} else {
std::cout << "\n\n--------------------------------\n" <<
"I am sorry, you couldn't make it!\nThe code was: " << combo <<
"\n--------------------------------\n\n";
}
}
private:
void showBoard() {
vecChar::iterator y;
for( int x = 0; x < guesses.size(); x++ ) {
std::cout << "\n--------------------------------\n";
std::cout << x + 1 << ": ";
for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) {
std::cout << *y << " ";
}
std::cout << " : ";
for( y = results[x].begin(); y != results[x].end(); y++ ) {
std::cout << *y << " ";
}
int z = codeLen - results[x].size();
if( z > 0 ) {
for( int x = 0; x < z; x++ ) std::cout << "- ";
}
}
std::cout << "\n\n";
}
std::string getInput() {
std::string a;
while( true ) {
std::cout << "Enter your guess (" << colors << "): ";
a = ""; std::cin >> a;
std::transform( a.begin(), a.end(), a.begin(), ::toupper );
if( a.length() > codeLen ) a.erase( codeLen );
bool r = true;
for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {
if( colors.find( *x ) == std::string::npos ) {
r = false;
break;
}
}
if( r ) break;
}
return a;
}
bool checkInput( std::string a ) {
vecChar g;
for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {
g.push_back( *x );
}
guesses.push_back( g );
int black = 0, white = 0;
std::vector<bool> gmatch( codeLen, false );
std::vector<bool> cmatch( codeLen, false );
for( int i = 0; i < codeLen; i++ ) {
if( a.at( i ) == combo.at( i ) ) {
gmatch[i] = true;
cmatch[i] = true;
black++;
}
}
for( int i = 0; i < codeLen; i++ ) {
if (gmatch[i]) continue;
for( int j = 0; j < codeLen; j++ ) {
if (i == j || cmatch[j]) continue;
if( a.at( i ) == combo.at( j ) ) {
cmatch[j] = true;
white++;
break;
}
}
}
vecChar r;
for( int b = 0; b < black; b++ ) r.push_back( 'X' );
for( int w = 0; w < white; w++ ) r.push_back( 'O' );
results.push_back( r );
return ( black == codeLen );
}
std::string getCombo() {
std::string c, clr = colors;
int l, z;
for( size_t s = 0; s < codeLen; s++ ) {
z = rand() % ( int )clr.length();
c.append( 1, clr[z] );
if( !repeatClr ) clr.erase( z, 1 );
}
return c;
}
size_t codeLen, colorsCnt, guessCnt;
bool repeatClr;
std::vector<vecChar> guesses, results;
std::string colors, combo;
};
int main( int argc, char* argv[] ) {
srand( unsigned( time( 0 ) ) );
master m( 4, 8, 12, false );
m.play();
return 0;
}
| import random
def encode(correct, guess):
output_arr = [''] * len(correct)
for i, (correct_char, guess_char) in enumerate(zip(correct, guess)):
output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-'
return ''.join(output_arr)
def safe_int_input(prompt, min_val, max_val):
while True:
user_input = input(prompt)
try:
user_input = int(user_input)
except ValueError:
continue
if min_val <= user_input <= max_val:
return user_input
def play_game():
print("Welcome to Mastermind.")
print("You will need to guess a random code.")
print("For each guess, you will receive a hint.")
print("In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.")
print()
number_of_letters = safe_int_input("Select a number of possible letters for the code (2-20): ", 2, 20)
code_length = safe_int_input("Select a length for the code (4-10): ", 4, 10)
letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters]
code = ''.join(random.choices(letters, k=code_length))
guesses = []
while True:
print()
guess = input(f"Enter a guess of length {code_length} ({letters}): ").upper().strip()
if len(guess) != code_length or any([char not in letters for char in guess]):
continue
elif guess == code:
print(f"\nYour guess {guess} was correct!")
break
else:
guesses.append(f"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}")
for i_guess in guesses:
print("------------------------------------")
print(i_guess)
print("------------------------------------")
if __name__ == '__main__':
play_game()
|
Maintain the same structure and functionality when rewriting this code in Python. | #include <algorithm>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
std::vector<uint64_t> divisors(uint64_t n) {
std::vector<uint64_t> result{1};
uint64_t power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
result.push_back(power);
for (uint64_t p = 3; p * p <= n; p += 2) {
size_t size = result.size();
for (power = p; n % p == 0; power *= p, n /= p)
for (size_t i = 0; i != size; ++i)
result.push_back(power * result[i]);
}
if (n > 1) {
size_t size = result.size();
for (size_t i = 0; i != size; ++i)
result.push_back(n * result[i]);
}
sort(result.begin(), result.end());
return result;
}
uint64_t ipow(uint64_t base, uint64_t exp) {
if (exp == 0)
return 1;
if ((exp & 1) == 0)
return ipow(base * base, exp >> 1);
return base * ipow(base * base, (exp - 1) >> 1);
}
uint64_t zsigmondy(uint64_t n, uint64_t a, uint64_t b) {
auto p = ipow(a, n) - ipow(b, n);
auto d = divisors(p);
if (d.size() == 2)
return p;
std::vector<uint64_t> dms(n - 1);
for (uint64_t m = 1; m < n; ++m)
dms[m - 1] = ipow(a, m) - ipow(b, m);
for (auto i = d.rbegin(); i != d.rend(); ++i) {
uint64_t z = *i;
if (all_of(dms.begin(), dms.end(),
[z](uint64_t x) { return std::gcd(x, z) == 1; }))
return z;
}
return 1;
}
void test(uint64_t a, uint64_t b) {
std::cout << "Zsigmondy(n, " << a << ", " << b << "):\n";
for (uint64_t n = 1; n <= 20; ++n) {
std::cout << zsigmondy(n, a, b) << ' ';
}
std::cout << "\n\n";
}
int main() {
test(2, 1);
test(3, 1);
test(4, 1);
test(5, 1);
test(6, 1);
test(7, 1);
test(3, 2);
test(5, 3);
test(7, 3);
test(7, 5);
}
|
from math import gcd
from sympy import divisors
def zsig(num, aint, bint):
assert aint > bint
dexpms = [aint**i - bint**i for i in range(1, num)]
dexpn = aint**num - bint**num
return max([d for d in divisors(dexpn) if all(gcd(k, d) == 1 for k in dexpms)])
tests = [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1),
(7, 1), (3, 2), (5, 3), (7, 3), (7, 5)]
for (a, b) in tests:
print(f'\nZsigmondy(n, {a}, {b}):', ', '.join(
[str(zsig(n, a, b)) for n in range(1, 21)]))
|
Rewrite this program in Python while keeping its functionality equivalent to the C++ version. | #include <algorithm>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <set>
#include <sstream>
#include <string>
#include <vector>
using bigram = std::pair<char, char>;
std::multiset<bigram> bigrams(const std::string& phrase) {
std::multiset<bigram> result;
std::istringstream is(phrase);
std::string word;
while (is >> word) {
for (char& ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
}
size_t length = word.size();
if (length == 1) {
result.emplace(word[0], '\0');
} else {
for (size_t i = 0; i + 1 < length; ++i) {
result.emplace(word[i], word[i + 1]);
}
}
}
return result;
}
double sorensen(const std::string& s1, const std::string& s2) {
auto a = bigrams(s1);
auto b = bigrams(s2);
std::multiset<bigram> c;
std::set_intersection(a.begin(), a.end(), b.begin(), b.end(),
std::inserter(c, c.begin()));
return (2.0 * c.size()) / (a.size() + b.size());
}
int main() {
std::vector<std::string> tasks;
std::ifstream is("tasks.txt");
if (!is) {
std::cerr << "Cannot open tasks file.\n";
return EXIT_FAILURE;
}
std::string task;
while (getline(is, task)) {
tasks.push_back(task);
}
const size_t tc = tasks.size();
const std::string tests[] = {"Primordial primes",
"Sunkist-Giuliani formula",
"Sieve of Euripides", "Chowder numbers"};
std::vector<std::pair<double, size_t>> sdi(tc);
std::cout << std::fixed;
for (const std::string& test : tests) {
for (size_t i = 0; i != tc; ++i) {
sdi[i] = std::make_pair(sorensen(tasks[i], test), i);
}
std::partial_sort(sdi.begin(), sdi.begin() + 5, sdi.end(),
[](const std::pair<double, size_t>& a,
const std::pair<double, size_t>& b) {
return a.first > b.first;
});
std::cout << test << " >\n";
for (size_t i = 0; i < 5 && i < tc; ++i) {
std::cout << " " << sdi[i].first << ' ' << tasks[sdi[i].second]
<< '\n';
}
std::cout << '\n';
}
return EXIT_SUCCESS;
}
|
from multiset import Multiset
def tokenizetext(txt):
arr = []
for wrd in txt.lower().split(' '):
arr += ([wrd] if len(wrd) == 1 else [wrd[i:i+2]
for i in range(len(wrd)-1)])
return Multiset(arr)
def sorenson_dice(text1, text2):
bc1, bc2 = tokenizetext(text1), tokenizetext(text2)
return 2 * len(bc1 & bc2) / (len(bc1) + len(bc2))
with open('tasklist_sorenson.txt', 'r') as fd:
alltasks = fd.read().split('\n')
for testtext in ['Primordial primes', 'Sunkist-Giuliani formula',
'Sieve of Euripides', 'Chowder numbers']:
taskvalues = sorted([(sorenson_dice(testtext, t), t)
for t in alltasks], reverse=True)
print(f'\n{testtext}:')
for (val, task) in taskvalues[:5]:
print(f' {val:.6f} {task}')
|
Convert this C snippet to C# and keep its semantics consistent. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX_N 20
#define TIMES 1000000
double factorial(int n) {
double f = 1;
int i;
for (i = 1; i <= n; i++) f *= i;
return f;
}
double expected(int n) {
double sum = 0;
int i;
for (i = 1; i <= n; i++)
sum += factorial(n) / pow(n, i) / factorial(n - i);
return sum;
}
int randint(int n) {
int r, rmax = RAND_MAX / n * n;
while ((r = rand()) >= rmax);
return r / (RAND_MAX / n);
}
int test(int n, int times) {
int i, count = 0;
for (i = 0; i < times; i++) {
int x = 1, bits = 0;
while (!(bits & x)) {
count++;
bits |= x;
x = 1 << randint(n);
}
}
return count;
}
int main(void) {
srand(time(0));
puts(" n\tavg\texp.\tdiff\n-------------------------------");
int n;
for (n = 1; n <= MAX_N; n++) {
int cnt = test(n, TIMES);
double avg = (double)cnt / TIMES;
double theory = expected(n);
double diff = (avg / theory - 1) * 100;
printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff);
}
return 0;
}
| public class AverageLoopLength {
private static int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.Next(n);
}
var seen = new HashSet<double>(n);
int current = 0;
int length = 0;
while (seen.Add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void Main(string[] args) {
Console.WriteLine(" N average analytical (error)");
Console.WriteLine("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
var average = AverageLoopLength.average(i);
var analytical = AverageLoopLength.analytical(i);
Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100);
}
}
}
|
Generate an equivalent C# version of this C code. | #include <stdio.h>
int main() {
const char *extra = "little";
printf("Mary had a %s lamb.\n", extra);
return 0;
}
| class Program
{
static void Main()
{
string extra = "little";
string formatted = $"Mary had a {extra} lamb.";
System.Console.WriteLine(formatted);
}
}
|
Transform the following C implementation into C#, maintaining the same output and logic. | #include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <gmp.h>
mpz_t* partition(uint64_t n) {
mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));
mpz_init_set_ui(pn[0], 1);
mpz_init_set_ui(pn[1], 1);
for (uint64_t i = 2; i < n + 2; i ++) {
mpz_init(pn[i]);
for (uint64_t k = 1, penta; ; k++) {
penta = k * (3 * k - 1) >> 1;
if (penta >= i) break;
if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);
else mpz_sub(pn[i], pn[i], pn[i - penta]);
penta += k;
if (penta >= i) break;
if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);
else mpz_sub(pn[i], pn[i], pn[i - penta]);
}
}
mpz_t *tmp = &pn[n + 1];
for (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);
free(pn);
return tmp;
}
int main(int argc, char const *argv[]) {
clock_t start = clock();
mpz_t *p = partition(6666);
gmp_printf("%Zd\n", p);
printf("Elapsed time: %.04f seconds\n",
(double)(clock() - start) / (double)CLOCKS_PER_SEC);
return 0;
}
| using System;
class Program {
const long Lm = (long)1e18;
const string Fm = "D18";
struct LI { public long lo, ml, mh, hi, tp; }
static void inc(ref LI d, LI s) {
if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }
if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }
if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }
if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }
d.tp += s.tp;
}
static void dec(ref LI d, LI s) {
if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }
if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }
if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }
if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }
d.tp -= s.tp;
}
static LI set(long s) { LI d;
d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }
static string fmt(LI x) {
if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);
return x.lo.ToString();
}
static LI partcount(int n) {
var P = new LI[n + 1]; P[0] = set(1);
for (int i = 1; i <= n; i++) {
int k = 0, d = -2, j = i;
LI x = set(0);
while (true) {
if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;
if ((j -= ++k) >= 0) inc(ref x, P[j]); else break;
if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;
if ((j -= ++k) >= 0) dec(ref x, P[j]); else break;
}
P[i] = x;
}
return P[n];
}
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew ();
var res = partcount(6666); sw.Stop();
Console.Write("{0} {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds);
}
}
|
Write the same code in C# as shown below in C. | #include <stdbool.h>
#include <stdio.h>
bool primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
switch (r) {
case 2:
case 3:
case 5:
case 7:
break;
default:
return false;
}
n /= 10;
sum += r;
}
return sum == 13;
}
int main() {
int i, c;
c = 0;
for (i = 1; i < 1000000; i++) {
if (primeDigitsSum13(i)) {
printf("%6d ", i);
if (c++ == 10) {
c = 0;
printf("\n");
}
}
}
printf("\n");
return 0;
}
| #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; }
|
Convert this C snippet to C# and keep its semantics consistent. | #include <stdbool.h>
#include <stdio.h>
bool primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
switch (r) {
case 2:
case 3:
case 5:
case 7:
break;
default:
return false;
}
n /= 10;
sum += r;
}
return sum == 13;
}
int main() {
int i, c;
c = 0;
for (i = 1; i < 1000000; i++) {
if (primeDigitsSum13(i)) {
printf("%6d ", i);
if (c++ == 10) {
c = 0;
printf("\n");
}
}
}
printf("\n");
return 0;
}
| using System;
using static System.Console;
using LI = System.Collections.Generic.SortedSet<int>;
class Program {
static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {
if (lft == 0) res.Add(vlu);
else if (lft > 0) foreach (int itm in set)
res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);
return res; }
static void Main(string[] args) { WriteLine(string.Join(" ",
unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }
}
|
Rewrite the snippet below in C# so it works the same as the original C code. | #include <stdbool.h>
#include <stdio.h>
bool primeDigitsSum13(int n) {
int sum = 0;
while (n > 0) {
int r = n % 10;
switch (r) {
case 2:
case 3:
case 5:
case 7:
break;
default:
return false;
}
n /= 10;
sum += r;
}
return sum == 13;
}
int main() {
int i, c;
c = 0;
for (i = 1; i < 1000000; i++) {
if (primeDigitsSum13(i)) {
printf("%6d ", i);
if (c++ == 10) {
c = 0;
printf("\n");
}
}
}
printf("\n");
return 0;
}
| using System;
using static System.Console;
using LI = System.Collections.Generic.SortedSet<int>;
class Program {
static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {
if (lft == 0) res.Add(vlu);
else if (lft > 0) foreach (int itm in set)
res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);
return res; }
static void Main(string[] args) { WriteLine(string.Join(" ",
unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }
}
|
Can you help me rewrite this code in C# instead of C, keeping it the same logically? | #include <stdio.h>
#include <time.h>
#define note_file "NOTES.TXT"
int main(int argc, char**argv)
{
FILE *note = 0;
time_t tm;
int i;
char *p;
if (argc < 2) {
if ((note = fopen(note_file, "r")))
while ((i = fgetc(note)) != EOF)
putchar(i);
} else if ((note = fopen(note_file, "a"))) {
tm = time(0);
p = ctime(&tm);
while (*p) fputc(*p != '\n'?*p:'\t', note), p++;
for (i = 1; i < argc; i++)
fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n');
}
if (note) fclose(note);
return 0;
}
| using System;
using System.IO;
using System.Text;
namespace RosettaCode
{
internal class Program
{
private const string FileName = "NOTES.TXT";
private static void Main(string[] args)
{
if (args.Length==0)
{
string txt = File.ReadAllText(FileName);
Console.WriteLine(txt);
}
else
{
var sb = new StringBuilder();
sb.Append(DateTime.Now).Append("\n\t");
foreach (string s in args)
sb.Append(s).Append(" ");
sb.Append("\n");
if (File.Exists(FileName))
File.AppendAllText(FileName, sb.ToString());
else
File.WriteAllText(FileName, sb.ToString());
}
}
}
}
|
Ensure the translated C# code behaves exactly like the original C snippet. | #include <stdio.h>
#include <time.h>
#define note_file "NOTES.TXT"
int main(int argc, char**argv)
{
FILE *note = 0;
time_t tm;
int i;
char *p;
if (argc < 2) {
if ((note = fopen(note_file, "r")))
while ((i = fgetc(note)) != EOF)
putchar(i);
} else if ((note = fopen(note_file, "a"))) {
tm = time(0);
p = ctime(&tm);
while (*p) fputc(*p != '\n'?*p:'\t', note), p++;
for (i = 1; i < argc; i++)
fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n');
}
if (note) fclose(note);
return 0;
}
| using System;
using System.IO;
using System.Text;
namespace RosettaCode
{
internal class Program
{
private const string FileName = "NOTES.TXT";
private static void Main(string[] args)
{
if (args.Length==0)
{
string txt = File.ReadAllText(FileName);
Console.WriteLine(txt);
}
else
{
var sb = new StringBuilder();
sb.Append(DateTime.Now).Append("\n\t");
foreach (string s in args)
sb.Append(s).Append(" ");
sb.Append("\n");
if (File.Exists(FileName))
File.AppendAllText(FileName, sb.ToString());
else
File.WriteAllText(FileName, sb.ToString());
}
}
}
}
|
Convert this C snippet to C# and keep its semantics consistent. | #define PI 3.141592653589793
#define TWO_PI 6.283185307179586
double normalize2deg(double a) {
while (a < 0) a += 360;
while (a >= 360) a -= 360;
return a;
}
double normalize2grad(double a) {
while (a < 0) a += 400;
while (a >= 400) a -= 400;
return a;
}
double normalize2mil(double a) {
while (a < 0) a += 6400;
while (a >= 6400) a -= 6400;
return a;
}
double normalize2rad(double a) {
while (a < 0) a += TWO_PI;
while (a >= TWO_PI) a -= TWO_PI;
return a;
}
double deg2grad(double a) {return a * 10 / 9;}
double deg2mil(double a) {return a * 160 / 9;}
double deg2rad(double a) {return a * PI / 180;}
double grad2deg(double a) {return a * 9 / 10;}
double grad2mil(double a) {return a * 16;}
double grad2rad(double a) {return a * PI / 200;}
double mil2deg(double a) {return a * 9 / 160;}
double mil2grad(double a) {return a / 16;}
double mil2rad(double a) {return a * PI / 3200;}
double rad2deg(double a) {return a * 180 / PI;}
double rad2grad(double a) {return a * 200 / PI;}
double rad2mil(double a) {return a * 3200 / PI;}
| using System;
public static class Angles
{
public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);
public static void Print(params double[] angles) {
string[] names = { "Degrees", "Gradians", "Mils", "Radians" };
Func<double, double> rnd = a => Math.Round(a, 4);
Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };
Func<double, double>[,] convert = {
{ a => a, DegToGrad, DegToMil, DegToRad },
{ GradToDeg, a => a, GradToMil, GradToRad },
{ MilToDeg, MilToGrad, a => a, MilToRad },
{ RadToDeg, RadToGrad, RadToMil, a => a }
};
Console.WriteLine($@"{"Angle",-12}{"Normalized",-12}{"Unit",-12}{
"Degrees",-12}{"Gradians",-12}{"Mils",-12}{"Radians",-12}");
foreach (double angle in angles) {
for (int i = 0; i < 4; i++) {
double nAngle = normal[i](angle);
Console.WriteLine($@"{
rnd(angle),-12}{
rnd(nAngle),-12}{
names[i],-12}{
rnd(convert[i, 0](nAngle)),-12}{
rnd(convert[i, 1](nAngle)),-12}{
rnd(convert[i, 2](nAngle)),-12}{
rnd(convert[i, 3](nAngle)),-12}");
}
}
}
public static double NormalizeDeg(double angle) => Normalize(angle, 360);
public static double NormalizeGrad(double angle) => Normalize(angle, 400);
public static double NormalizeMil(double angle) => Normalize(angle, 6400);
public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);
private static double Normalize(double angle, double N) {
while (angle <= -N) angle += N;
while (angle >= N) angle -= N;
return angle;
}
public static double DegToGrad(double angle) => angle * 10 / 9;
public static double DegToMil(double angle) => angle * 160 / 9;
public static double DegToRad(double angle) => angle * Math.PI / 180;
public static double GradToDeg(double angle) => angle * 9 / 10;
public static double GradToMil(double angle) => angle * 16;
public static double GradToRad(double angle) => angle * Math.PI / 200;
public static double MilToDeg(double angle) => angle * 9 / 160;
public static double MilToGrad(double angle) => angle / 16;
public static double MilToRad(double angle) => angle * Math.PI / 3200;
public static double RadToDeg(double angle) => angle * 180 / Math.PI;
public static double RadToGrad(double angle) => angle * 200 / Math.PI;
public static double RadToMil(double angle) => angle * 3200 / Math.PI;
}
|
Translate the given C code snippet into C# without altering its behavior. | #include <stdio.h>
int common_len(const char *const *names, int n, char sep)
{
int i, pos;
for (pos = 0; ; pos++) {
for (i = 0; i < n; i++) {
if (names[i][pos] != '\0' &&
names[i][pos] == names[0][pos])
continue;
while (pos > 0 && names[0][--pos] != sep);
return pos;
}
}
return 0;
}
int main()
{
const char *names[] = {
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members",
};
int len = common_len(names, sizeof(names) / sizeof(const char*), '/');
if (!len) printf("No common path\n");
else printf("Common path: %.*s\n", len, names[0]);
return 0;
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaCodeTasks
{
class Program
{
static void Main ( string[ ] args )
{
FindCommonDirectoryPath.Test ( );
}
}
class FindCommonDirectoryPath
{
public static void Test ( )
{
Console.WriteLine ( "Find Common Directory Path" );
Console.WriteLine ( );
List<string> PathSet1 = new List<string> ( );
PathSet1.Add ( "/home/user1/tmp/coverage/test" );
PathSet1.Add ( "/home/user1/tmp/covert/operator" );
PathSet1.Add ( "/home/user1/tmp/coven/members" );
Console.WriteLine("Path Set 1 (All Absolute Paths):");
foreach ( string path in PathSet1 )
{
Console.WriteLine ( path );
}
Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) );
}
public static string FindCommonPath ( string Separator, List<string> Paths )
{
string CommonPath = String.Empty;
List<string> SeparatedPath = Paths
.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )
.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )
.ToList ( );
foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )
{
if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )
{
CommonPath = PathSegment;
}
else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )
{
CommonPath += Separator + PathSegment;
}
else
{
break;
}
}
return CommonPath;
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | #include <stdio.h>
#include <stdlib.h>
#include <gmodule.h>
typedef int bool;
int main() {
int i, n, k = 0, next, *a;
bool foundDup = FALSE;
gboolean alreadyUsed;
GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);
GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);
a = malloc(400000 * sizeof(int));
a[0] = 0;
g_hash_table_add(used, GINT_TO_POINTER(0));
g_hash_table_add(used1000, GINT_TO_POINTER(0));
for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {
next = a[n - 1] - n;
if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {
next += 2 * n;
}
alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));
a[n] = next;
if (!alreadyUsed) {
g_hash_table_add(used, GINT_TO_POINTER(next));
if (next >= 0 && next <= 1000) {
g_hash_table_add(used1000, GINT_TO_POINTER(next));
}
}
if (n == 14) {
printf("The first 15 terms of the Recaman's sequence are: ");
printf("[");
for (i = 0; i < 15; ++i) printf("%d ", a[i]);
printf("\b]\n");
}
if (!foundDup && alreadyUsed) {
printf("The first duplicated term is a[%d] = %d\n", n, next);
foundDup = TRUE;
}
k = g_hash_table_size(used1000);
if (k == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
}
g_hash_table_destroy(used);
g_hash_table_destroy(used1000);
free(a);
return 0;
}
| using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from C to C#. | #include <stdio.h>
#include <stdlib.h>
#include <gmodule.h>
typedef int bool;
int main() {
int i, n, k = 0, next, *a;
bool foundDup = FALSE;
gboolean alreadyUsed;
GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);
GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);
a = malloc(400000 * sizeof(int));
a[0] = 0;
g_hash_table_add(used, GINT_TO_POINTER(0));
g_hash_table_add(used1000, GINT_TO_POINTER(0));
for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {
next = a[n - 1] - n;
if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {
next += 2 * n;
}
alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));
a[n] = next;
if (!alreadyUsed) {
g_hash_table_add(used, GINT_TO_POINTER(next));
if (next >= 0 && next <= 1000) {
g_hash_table_add(used1000, GINT_TO_POINTER(next));
}
}
if (n == 14) {
printf("The first 15 terms of the Recaman's sequence are: ");
printf("[");
for (i = 0; i < 15; ++i) printf("%d ", a[i]);
printf("\b]\n");
}
if (!foundDup && alreadyUsed) {
printf("The first duplicated term is a[%d] = %d\n", n, next);
foundDup = TRUE;
}
k = g_hash_table_size(used1000);
if (k == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
}
g_hash_table_destroy(used);
g_hash_table_destroy(used1000);
free(a);
return 0;
}
| using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
}
|
Please provide an equivalent version of this C code in C#. | #include <stdio.h>
#include <stdlib.h>
#include <gmodule.h>
typedef int bool;
int main() {
int i, n, k = 0, next, *a;
bool foundDup = FALSE;
gboolean alreadyUsed;
GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal);
GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal);
a = malloc(400000 * sizeof(int));
a[0] = 0;
g_hash_table_add(used, GINT_TO_POINTER(0));
g_hash_table_add(used1000, GINT_TO_POINTER(0));
for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) {
next = a[n - 1] - n;
if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) {
next += 2 * n;
}
alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next));
a[n] = next;
if (!alreadyUsed) {
g_hash_table_add(used, GINT_TO_POINTER(next));
if (next >= 0 && next <= 1000) {
g_hash_table_add(used1000, GINT_TO_POINTER(next));
}
}
if (n == 14) {
printf("The first 15 terms of the Recaman's sequence are: ");
printf("[");
for (i = 0; i < 15; ++i) printf("%d ", a[i]);
printf("\b]\n");
}
if (!foundDup && alreadyUsed) {
printf("The first duplicated term is a[%d] = %d\n", n, next);
foundDup = TRUE;
}
k = g_hash_table_size(used1000);
if (k == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
}
}
g_hash_table_destroy(used);
g_hash_table_destroy(used1000);
free(a);
return 0;
}
| using System;
using System.Collections.Generic;
namespace RecamanSequence {
class Program {
static void Main(string[] args) {
List<int> a = new List<int>() { 0 };
HashSet<int> used = new HashSet<int>() { 0 };
HashSet<int> used1000 = new HashSet<int>() { 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.Count < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.Contains(next)) {
next += 2 * n;
}
bool alreadyUsed = used.Contains(next);
a.Add(next);
if (!alreadyUsed) {
used.Add(next);
if (0 <= next && next <= 1000) {
used1000.Add(next);
}
}
if (n == 14) {
Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
}
if (!foundDup && alreadyUsed) {
Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
foundDup = true;
}
if (used1000.Count == 1001) {
Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
}
n++;
}
}
}
}
|
Produce a language-to-language conversion: from C to C#, same semantics. | #include <stdlib.h>
#define SIZEOF_MEMB (sizeof(int))
#define NMEMB 100
int main()
{
int *ints = malloc(SIZEOF_MEMB*NMEMB);
ints = realloc(ints, sizeof(int)*(NMEMB+1));
int *int2 = calloc(NMEMB, SIZEOF_MEMB);
free(ints); free(int2);
return 0;
}
| using System;
using System.Runtime.InteropServices;
public unsafe class Program
{
public static unsafe void HeapMemory()
{
const int HEAP_ZERO_MEMORY = 0x00000008;
const int size = 1000;
int ph = GetProcessHeap();
void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);
if (pointer == null)
throw new OutOfMemoryException();
Console.WriteLine(HeapSize(ph, 0, pointer));
HeapFree(ph, 0, pointer);
}
public static unsafe void StackMemory()
{
byte* buffer = stackalloc byte[1000];
}
public static void Main(string[] args)
{
HeapMemory();
StackMemory();
}
[DllImport("kernel32")]
static extern void* HeapAlloc(int hHeap, int flags, int size);
[DllImport("kernel32")]
static extern bool HeapFree(int hHeap, int flags, void* block);
[DllImport("kernel32")]
static extern int GetProcessHeap();
[DllImport("kernel32")]
static extern int HeapSize(int hHeap, int flags, void* block);
}
|
Produce a functionally identical C# code for the snippet given in C. | #include <stdio.h>
#include <stdlib.h>
int b[3][3];
int check_winner()
{
int i;
for (i = 0; i < 3; i++) {
if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0])
return b[i][0];
if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i])
return b[0][i];
}
if (!b[1][1]) return 0;
if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0];
if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1];
return 0;
}
void showboard()
{
const char *t = "X O";
int i, j;
for (i = 0; i < 3; i++, putchar('\n'))
for (j = 0; j < 3; j++)
printf("%c ", t[ b[i][j] + 1 ]);
printf("-----\n");
}
#define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++)
int best_i, best_j;
int test_move(int val, int depth)
{
int i, j, score;
int best = -1, changed = 0;
if ((score = check_winner())) return (score == val) ? 1 : -1;
for_ij {
if (b[i][j]) continue;
changed = b[i][j] = val;
score = -test_move(-val, depth + 1);
b[i][j] = 0;
if (score <= best) continue;
if (!depth) {
best_i = i;
best_j = j;
}
best = score;
}
return changed ? best : 0;
}
const char* game(int user)
{
int i, j, k, move, win = 0;
for_ij b[i][j] = 0;
printf("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n");
printf("You have O, I have X.\n\n");
for (k = 0; k < 9; k++, user = !user) {
while(user) {
printf("your move: ");
if (!scanf("%d", &move)) {
scanf("%*s");
continue;
}
if (--move < 0 || move >= 9) continue;
if (b[i = move / 3][j = move % 3]) continue;
b[i][j] = 1;
break;
}
if (!user) {
if (!k) {
best_i = rand() % 3;
best_j = rand() % 3;
} else
test_move(-1, 0);
b[best_i][best_j] = -1;
printf("My move: %d\n", best_i * 3 + best_j + 1);
}
showboard();
if ((win = check_winner()))
return win == 1 ? "You win.\n\n": "I win.\n\n";
}
return "A draw.\n\n";
}
int main()
{
int first = 0;
while (1) printf("%s", game(first = !first));
return 0;
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RosettaTicTacToe
{
class Program
{
static string[][] Players = new string[][] {
new string[] { "COMPUTER", "X" },
new string[] { "HUMAN", "O" }
};
const int Unplayed = -1;
const int Computer = 0;
const int Human = 1;
static int[] GameBoard = new int[9];
static int[] corners = new int[] { 0, 2, 6, 8 };
static int[][] wins = new int[][] {
new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 },
new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 },
new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } };
static void Main(string[] args)
{
while (true)
{
Console.Clear();
Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#.");
initializeGameBoard();
displayGameBoard();
int currentPlayer = rnd.Next(0, 2);
Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer));
while (true)
{
int thisMove = getMoveFor(currentPlayer);
if (thisMove == Unplayed)
{
Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer));
break;
}
playMove(thisMove, currentPlayer);
displayGameBoard();
if (isGameWon())
{
Console.WriteLine("{0} has won the game!", playerName(currentPlayer));
break;
}
else if (isGameTied())
{
Console.WriteLine("Cat game ... we have a tie.");
break;
}
currentPlayer = getNextPlayer(currentPlayer);
}
if (!playAgain())
return;
}
}
static int getMoveFor(int player)
{
if (player == Human)
return getManualMove(player);
else
{
int selectedMove = getSemiRandomMove(player);
Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1);
return selectedMove;
}
}
static int getManualMove(int player)
{
while (true)
{
Console.Write("{0}, enter you move (number): ", playerName(player));
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine();
if (keyInfo.Key == ConsoleKey.Escape)
return Unplayed;
if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9)
{
int move = keyInfo.KeyChar - '1';
if (GameBoard[move] == Unplayed)
return move;
else
Console.WriteLine("Spot {0} is already taken, please select again.", move + 1);
}
else
Console.WriteLine("Illegal move, please select again.\n");
}
}
static int getRandomMove(int player)
{
int movesLeft = GameBoard.Count(position => position == Unplayed);
int x = rnd.Next(0, movesLeft);
for (int i = 0; i < GameBoard.Length; i++)
{
if (GameBoard[i] == Unplayed && x < 0)
return i;
x--;
}
return Unplayed;
}
static int getSemiRandomMove(int player)
{
int posToPlay;
if (checkForWinningMove(player, out posToPlay))
return posToPlay;
if (checkForBlockingMove(player, out posToPlay))
return posToPlay;
return getRandomMove(player);
}
static int getBestMove(int player)
{
return -1;
}
static bool checkForWinningMove(int player, out int posToPlay)
{
posToPlay = Unplayed;
foreach (var line in wins)
if (twoOfThreeMatchPlayer(player, line, out posToPlay))
return true;
return false;
}
static bool checkForBlockingMove(int player, out int posToPlay)
{
posToPlay = Unplayed;
foreach (var line in wins)
if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay))
return true;
return false;
}
static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay)
{
int cnt = 0;
posToPlay = int.MinValue;
foreach (int pos in line)
{
if (GameBoard[pos] == player)
cnt++;
else if (GameBoard[pos] == Unplayed)
posToPlay = pos;
}
return cnt == 2 && posToPlay >= 0;
}
static void playMove(int boardPosition, int player)
{
GameBoard[boardPosition] = player;
}
static bool isGameWon()
{
return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2]));
}
static bool takenBySamePlayer(int a, int b, int c)
{
return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c];
}
static bool isGameTied()
{
return !GameBoard.Any(spot => spot == Unplayed);
}
static Random rnd = new Random();
static void initializeGameBoard()
{
for (int i = 0; i < GameBoard.Length; i++)
GameBoard[i] = Unplayed;
}
static string playerName(int player)
{
return Players[player][0];
}
static string playerToken(int player)
{
return Players[player][1];
}
static int getNextPlayer(int player)
{
return (player + 1) % 2;
}
static void displayGameBoard()
{
Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2));
Console.WriteLine("---|---|---");
Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5));
Console.WriteLine("---|---|---");
Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8));
Console.WriteLine();
}
static string pieceAt(int boardPosition)
{
if (GameBoard[boardPosition] == Unplayed)
return (boardPosition + 1).ToString();
return playerToken(GameBoard[boardPosition]);
}
private static bool playAgain()
{
Console.WriteLine("\nDo you want to play again?");
return Console.ReadKey(false).Key == ConsoleKey.Y;
}
}
}
|
Can you help me rewrite this code in C# instead of C, keeping it the same logically? | #include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
| using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | #include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
| using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
|
Port the provided C code into C# while preserving the original functionality. | #include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
| using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
|
Change the following C code into C# without altering its purpose. | #include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main()
{
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
error = getaddrinfo("www.kame.net", NULL, &hints, &res0);
if (error) {
fprintf(stderr, "%s\n", gai_strerror(error));
exit(1);
}
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (error) {
fprintf(stderr, "%s\n", gai_strerror(error));
} else {
printf("%s\n", host);
}
}
freeaddrinfo(res0);
return 0;
}
| private string LookupDns(string s)
{
try
{
System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);
string result = ip.AddressList[0].ToString();
for (int i = 1; i < ip.AddressList.Length; ++i)
result += ", " + ip.AddressList[i].ToString();
return result;
}
catch (System.Net.Sockets.SocketException se)
{
return se.Message;
}
}
|
Preserve the algorithm and functionality while converting the code from C to C#. | int rand5()
{
int r, rand_max = RAND_MAX - (RAND_MAX % 5);
while ((r = rand()) >= rand_max);
return r / (rand_max / 5) + 1;
}
int rand5_7()
{
int r;
while ((r = rand5() * 5 + rand5()) >= 27);
return r / 3 - 1;
}
int main()
{
printf(check(rand5, 5, 1000000, .05) ? "flat\n" : "not flat\n");
printf(check(rand7, 7, 1000000, .05) ? "flat\n" : "not flat\n");
return 0;
}
| using System;
public class SevenSidedDice
{
Random random = new Random();
static void Main(string[] args)
{
SevenSidedDice sevenDice = new SevenSidedDice();
Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven());
Console.Read();
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*5-6;
return 1+v%7;
}
int five()
{
return 1 + random.Next(5);
}
}
|
Change the following C code into C# without altering its purpose. | #include <stdio.h>
#include <string.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
bool is_prime(ull n) {
ull d;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
d = 5;
while (d * d <= n) {
if (!(n % d)) return FALSE;
d += 2;
if (!(n % d)) return FALSE;
d += 4;
}
return TRUE;
}
void ord(char *res, int n) {
char suffix[3];
int m = n % 100;
if (m >= 4 && m <= 20) {
sprintf(res,"%dth", n);
return;
}
switch(m % 10) {
case 1:
strcpy(suffix, "st");
break;
case 2:
strcpy(suffix, "nd");
break;
case 3:
strcpy(suffix, "rd");
break;
default:
strcpy(suffix, "th");
break;
}
sprintf(res, "%d%s", n, suffix);
}
bool is_magnanimous(ull n) {
ull p, q, r;
if (n < 10) return TRUE;
for (p = 10; ; p *= 10) {
q = n / p;
r = n % p;
if (!is_prime(q + r)) return FALSE;
if (q < 10) break;
}
return TRUE;
}
void list_mags(int from, int thru, int digs, int per_line) {
ull i = 0;
int c = 0;
char res1[13], res2[13];
if (from < 2) {
printf("\nFirst %d magnanimous numbers:\n", thru);
} else {
ord(res1, from);
ord(res2, thru);
printf("\n%s through %s magnanimous numbers:\n", res1, res2);
}
for ( ; c < thru; ++i) {
if (is_magnanimous(i)) {
if (++c >= from) {
printf("%*llu ", digs, i);
if (!(c % per_line)) printf("\n");
}
}
}
}
int main() {
list_mags(1, 45, 3, 15);
list_mags(241, 250, 1, 10);
list_mags(391, 400, 1, 10);
return 0;
}
| using System; using static System.Console;
class Program {
static bool[] np;
static void ms(long lmt) {
np = new bool[lmt]; np[0] = np[1] = true;
for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n])
for (long k = n * n; k < lmt; k += n) np[k] = true; }
static bool is_Mag(long n) { long res, rem;
for (long p = 10; n >= p; p *= 10) {
res = Math.DivRem (n, p, out rem);
if (np[res + rem]) return false; } return true; }
static void Main(string[] args) { ms(100_009); string mn;
WriteLine("First 45{0}", mn = " magnanimous numbers:");
for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) {
if (c++ < 45 || (c > 240 && c <= 250) || c > 390)
Write(c <= 45 ? "{0,4} " : "{0,8:n0} ", l);
if (c < 45 && c % 15 == 0) WriteLine();
if (c == 240) WriteLine ("\n\n241st through 250th{0}", mn);
if (c == 390) WriteLine ("\n\n391st through 400th{0}", mn); } }
}
|
Port the following code from C to C# with equivalent syntax and logic. | #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
| class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}
| class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}
|
Please provide an equivalent version of this C code in C#. | #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int chinese_remainder(int *n, int *a, int len)
{
int p, i, prod = 1, sum = 0;
for (i = 0; i < len; i++) prod *= n[i];
for (i = 0; i < len; i++) {
p = prod / n[i];
sum += a[i] * mul_inv(p, n[i]) * p;
}
return sum % prod;
}
int main(void)
{
int n[] = { 3, 5, 7 };
int a[] = { 2, 3, 2 };
printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));
return 0;
}
| using System;
using System.Linq;
namespace ChineseRemainderTheorem
{
class Program
{
static void Main(string[] args)
{
int[] n = { 3, 5, 7 };
int[] a = { 2, 3, 2 };
int result = ChineseRemainderTheorem.Solve(n, a);
int counter = 0;
int maxCount = n.Length - 1;
while (counter <= maxCount)
{
Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})");
counter++;
}
}
}
public static class ChineseRemainderTheorem
{
public static int Solve(int[] n, int[] a)
{
int prod = n.Aggregate(1, (i, j) => i * j);
int p;
int sm = 0;
for (int i = 0; i < n.Length; i++)
{
p = prod / n[i];
sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;
}
return sm % prod;
}
private static int ModularMultiplicativeInverse(int a, int mod)
{
int b = a % mod;
for (int x = 1; x < mod; x++)
{
if ((b * x) % mod == 1)
{
return x;
}
}
return 1;
}
}
}
|
Port the provided C code into C# while preserving the original functionality. | #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int chinese_remainder(int *n, int *a, int len)
{
int p, i, prod = 1, sum = 0;
for (i = 0; i < len; i++) prod *= n[i];
for (i = 0; i < len; i++) {
p = prod / n[i];
sum += a[i] * mul_inv(p, n[i]) * p;
}
return sum % prod;
}
int main(void)
{
int n[] = { 3, 5, 7 };
int a[] = { 2, 3, 2 };
printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));
return 0;
}
| using System;
using System.Linq;
namespace ChineseRemainderTheorem
{
class Program
{
static void Main(string[] args)
{
int[] n = { 3, 5, 7 };
int[] a = { 2, 3, 2 };
int result = ChineseRemainderTheorem.Solve(n, a);
int counter = 0;
int maxCount = n.Length - 1;
while (counter <= maxCount)
{
Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})");
counter++;
}
}
}
public static class ChineseRemainderTheorem
{
public static int Solve(int[] n, int[] a)
{
int prod = n.Aggregate(1, (i, j) => i * j);
int p;
int sm = 0;
for (int i = 0; i < n.Length; i++)
{
p = prod / n[i];
sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;
}
return sm % prod;
}
private static int ModularMultiplicativeInverse(int a, int mod)
{
int b = a % mod;
for (int x = 1; x < mod; x++)
{
if ((b * x) % mod == 1)
{
return x;
}
}
return 1;
}
}
}
|
Generate an equivalent C# version of this C code. | #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int chinese_remainder(int *n, int *a, int len)
{
int p, i, prod = 1, sum = 0;
for (i = 0; i < len; i++) prod *= n[i];
for (i = 0; i < len; i++) {
p = prod / n[i];
sum += a[i] * mul_inv(p, n[i]) * p;
}
return sum % prod;
}
int main(void)
{
int n[] = { 3, 5, 7 };
int a[] = { 2, 3, 2 };
printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0])));
return 0;
}
| using System;
using System.Linq;
namespace ChineseRemainderTheorem
{
class Program
{
static void Main(string[] args)
{
int[] n = { 3, 5, 7 };
int[] a = { 2, 3, 2 };
int result = ChineseRemainderTheorem.Solve(n, a);
int counter = 0;
int maxCount = n.Length - 1;
while (counter <= maxCount)
{
Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})");
counter++;
}
}
}
public static class ChineseRemainderTheorem
{
public static int Solve(int[] n, int[] a)
{
int prod = n.Aggregate(1, (i, j) => i * j);
int p;
int sm = 0;
for (int i = 0; i < n.Length; i++)
{
p = prod / n[i];
sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;
}
return sm % prod;
}
private static int ModularMultiplicativeInverse(int a, int mod)
{
int b = a % mod;
for (int x = 1; x < mod; x++)
{
if ((b * x) % mod == 1)
{
return x;
}
}
return 1;
}
}
}
|
Rewrite this program in C# while keeping its functionality equivalent to the C version. | #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
mpz_t tmp1, tmp2, t5, t239, pows;
void actan(mpz_t res, unsigned long base, mpz_t pows)
{
int i, neg = 1;
mpz_tdiv_q_ui(res, pows, base);
mpz_set(tmp1, res);
for (i = 3; ; i += 2) {
mpz_tdiv_q_ui(tmp1, tmp1, base * base);
mpz_tdiv_q_ui(tmp2, tmp1, i);
if (mpz_cmp_ui(tmp2, 0) == 0) break;
if (neg) mpz_sub(res, res, tmp2);
else mpz_add(res, res, tmp2);
neg = !neg;
}
}
char * get_digits(int n, size_t* len)
{
mpz_ui_pow_ui(pows, 10, n + 20);
actan(t5, 5, pows);
mpz_mul_ui(t5, t5, 16);
actan(t239, 239, pows);
mpz_mul_ui(t239, t239, 4);
mpz_sub(t5, t5, t239);
mpz_ui_pow_ui(pows, 10, 20);
mpz_tdiv_q(t5, t5, pows);
*len = mpz_sizeinbase(t5, 10);
return mpz_get_str(0, 0, t5);
}
int main(int c, char **v)
{
unsigned long accu = 16384, done = 0;
size_t got;
char *s;
mpz_init(tmp1);
mpz_init(tmp2);
mpz_init(t5);
mpz_init(t239);
mpz_init(pows);
while (1) {
s = get_digits(accu, &got);
got -= 2;
while (s[got] == '0' || s[got] == '9') got--;
printf("%.*s", (int)(got - done), s + done);
free(s);
done = got;
accu *= 2;
}
return 0;
}
| using System;
using System.Numerics;
namespace PiCalc {
internal class Program {
private readonly BigInteger FOUR = new BigInteger(4);
private readonly BigInteger SEVEN = new BigInteger(7);
private readonly BigInteger TEN = new BigInteger(10);
private readonly BigInteger THREE = new BigInteger(3);
private readonly BigInteger TWO = new BigInteger(2);
private BigInteger k = BigInteger.One;
private BigInteger l = new BigInteger(3);
private BigInteger n = new BigInteger(3);
private BigInteger q = BigInteger.One;
private BigInteger r = BigInteger.Zero;
private BigInteger t = BigInteger.One;
public void CalcPiDigits() {
BigInteger nn, nr;
bool first = true;
while (true) {
if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
Console.Write(n);
if (first) {
Console.Write(".");
first = false;
}
nr = TEN*(r - (n*t));
n = TEN*(THREE*q + r)/t - (TEN*n);
q *= TEN;
r = nr;
} else {
nr = (TWO*q + r)*l;
nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
q *= k;
t *= l;
l += TWO;
k += BigInteger.One;
n = nn;
r = nr;
}
}
}
private static void Main(string[] args) {
new Program().CalcPiDigits();
}
}
}
|
Generate an equivalent C# version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
mpz_t tmp1, tmp2, t5, t239, pows;
void actan(mpz_t res, unsigned long base, mpz_t pows)
{
int i, neg = 1;
mpz_tdiv_q_ui(res, pows, base);
mpz_set(tmp1, res);
for (i = 3; ; i += 2) {
mpz_tdiv_q_ui(tmp1, tmp1, base * base);
mpz_tdiv_q_ui(tmp2, tmp1, i);
if (mpz_cmp_ui(tmp2, 0) == 0) break;
if (neg) mpz_sub(res, res, tmp2);
else mpz_add(res, res, tmp2);
neg = !neg;
}
}
char * get_digits(int n, size_t* len)
{
mpz_ui_pow_ui(pows, 10, n + 20);
actan(t5, 5, pows);
mpz_mul_ui(t5, t5, 16);
actan(t239, 239, pows);
mpz_mul_ui(t239, t239, 4);
mpz_sub(t5, t5, t239);
mpz_ui_pow_ui(pows, 10, 20);
mpz_tdiv_q(t5, t5, pows);
*len = mpz_sizeinbase(t5, 10);
return mpz_get_str(0, 0, t5);
}
int main(int c, char **v)
{
unsigned long accu = 16384, done = 0;
size_t got;
char *s;
mpz_init(tmp1);
mpz_init(tmp2);
mpz_init(t5);
mpz_init(t239);
mpz_init(pows);
while (1) {
s = get_digits(accu, &got);
got -= 2;
while (s[got] == '0' || s[got] == '9') got--;
printf("%.*s", (int)(got - done), s + done);
free(s);
done = got;
accu *= 2;
}
return 0;
}
| using System;
using System.Numerics;
namespace PiCalc {
internal class Program {
private readonly BigInteger FOUR = new BigInteger(4);
private readonly BigInteger SEVEN = new BigInteger(7);
private readonly BigInteger TEN = new BigInteger(10);
private readonly BigInteger THREE = new BigInteger(3);
private readonly BigInteger TWO = new BigInteger(2);
private BigInteger k = BigInteger.One;
private BigInteger l = new BigInteger(3);
private BigInteger n = new BigInteger(3);
private BigInteger q = BigInteger.One;
private BigInteger r = BigInteger.Zero;
private BigInteger t = BigInteger.One;
public void CalcPiDigits() {
BigInteger nn, nr;
bool first = true;
while (true) {
if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
Console.Write(n);
if (first) {
Console.Write(".");
first = false;
}
nr = TEN*(r - (n*t));
n = TEN*(THREE*q + r)/t - (TEN*n);
q *= TEN;
r = nr;
} else {
nr = (TWO*q + r)*l;
nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
q *= k;
t *= l;
l += TWO;
k += BigInteger.One;
n = nn;
r = nr;
}
}
}
private static void Main(string[] args) {
new Program().CalcPiDigits();
}
}
}
|
Produce a language-to-language conversion: from C to C#, same semantics. | #include <stdio.h>
#include <stdlib.h>
typedef struct func_t *func;
typedef struct func_t {
func (*fn) (func, func);
func _;
int num;
} func_t;
func new(func(*f)(func, func), func _) {
func x = malloc(sizeof(func_t));
x->fn = f;
x->_ = _;
x->num = 0;
return x;
}
func call(func f, func n) {
return f->fn(f, n);
}
func Y(func(*f)(func, func)) {
func g = new(f, 0);
g->_ = g;
return g;
}
func num(int n) {
func x = new(0, 0);
x->num = n;
return x;
}
func fac(func self, func n) {
int nn = n->num;
return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num)
: num(1);
}
func fib(func self, func n) {
int nn = n->num;
return nn > 1
? num( call(self->_, num(nn - 1))->num +
call(self->_, num(nn - 2))->num )
: num(1);
}
void show(func n) { printf(" %d", n->num); }
int main() {
int i;
func f = Y(fac);
printf("fac: ");
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf("\n");
f = Y(fib);
printf("fib: ");
for (i = 1; i < 10; i++)
show( call(f, num(i)) );
printf("\n");
return 0;
}
| using System;
static class YCombinator<T, TResult>
{
private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);
public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } =
f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x)));
}
static class Program
{
static void Main()
{
var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1));
var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2));
Console.WriteLine(fac(10));
Console.WriteLine(fib(10));
}
}
|
Port the provided C code into C# while preserving the original functionality. | #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
| using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
|
Please provide an equivalent version of this C code in C#. | #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
| using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
|
Port the following code from C to C# with equivalent syntax and logic. | #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
| using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
|
Change the programming language of this snippet from C to C# without modifying what it does. | #include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
const int max = 1000;
int *a = malloc(max * sizeof(int));
for (int n = 0; n < max - 1; n ++) {
for (int m = n - 1; m >= 0; m --) {
if (a[m] == a[n]) {
a[n+1] = n - m;
break;
}
}
}
printf("The first ten terms of the Van Eck sequence are:\n");
for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
printf("\n\nTerms 991 to 1000 of the sequence are:\n");
for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
putchar('\n');
return 0;
}
| using System.Linq; class Program { static void Main() {
int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
for (d = a, e = b - d, f = h[b]; e <= b; e++)
if (f == h[d--]) { h[c] = e; break; }
void sho(int i) { System.Console.WriteLine(string.Join(" ",
h.Skip(i).Take(10))); } sho(0); sho(990); } }
|
Convert this C block to C#, preserving its control flow and logic. | for(int i = 1;i <= 10; i++){
printf("%d", i);
if(i % 5 == 0){
printf("\n");
continue;
}
printf(", ");
}
| using System;
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
Console.Write(i);
if (i % 5 == 0) {
Console.WriteLine();
continue;
}
Console.Write(", ");
}
}
}
|
Change the following C code into C# without altering its purpose. | for(int i = 1;i <= 10; i++){
printf("%d", i);
if(i % 5 == 0){
printf("\n");
continue;
}
printf(", ");
}
| using System;
class Program {
static void Main(string[] args) {
for (int i = 1; i <= 10; i++) {
Console.Write(i);
if (i % 5 == 0) {
Console.WriteLine();
continue;
}
Console.Write(", ");
}
}
}
|
Preserve the algorithm and functionality while converting the code from C to C#. | #include <stdio.h>
#include <stdlib.h>
struct replace_info {
int n;
char *text;
};
int compare(const void *a, const void *b)
{
struct replace_info *x = (struct replace_info *) a;
struct replace_info *y = (struct replace_info *) b;
return x->n - y->n;
}
void generic_fizz_buzz(int max, struct replace_info *info, int info_length)
{
int i, it;
int found_word;
for (i = 1; i < max; ++i) {
found_word = 0;
for (it = 0; it < info_length; ++it) {
if (0 == i % info[it].n) {
printf("%s", info[it].text);
found_word = 1;
}
}
if (0 == found_word)
printf("%d", i);
printf("\n");
}
}
int main(void)
{
struct replace_info info[3] = {
{5, "Buzz"},
{7, "Baxx"},
{3, "Fizz"}
};
qsort(info, 3, sizeof(struct replace_info), compare);
generic_fizz_buzz(20, info, 3);
return 0;
}
| using System;
public class GeneralFizzBuzz
{
public static void Main()
{
int i;
int j;
int k;
int limit;
string iString;
string jString;
string kString;
Console.WriteLine("First integer:");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("First string:");
iString = Console.ReadLine();
Console.WriteLine("Second integer:");
j = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second string:");
jString = Console.ReadLine();
Console.WriteLine("Third integer:");
k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Third string:");
kString = Console.ReadLine();
Console.WriteLine("Limit (inclusive):");
limit = Convert.ToInt32(Console.ReadLine());
for(int n = 1; n<= limit; n++)
{
bool flag = true;
if(n%i == 0)
{
Console.Write(iString);
flag = false;
}
if(n%j == 0)
{
Console.Write(jString);
flag = false;
}
if(n%k == 0)
{
Console.Write(kString);
flag = false;
}
if(flag)
Console.Write(n);
Console.WriteLine();
}
}
}
|
Ensure the translated C# code behaves exactly like the original C snippet. | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. | #include <stdio.h>
#include <stdint.h>
void to_seq(uint64_t x, uint8_t *out)
{
int i, j;
for (i = 9; i > 0; i--) {
if (x & 127ULL << i * 7) break;
}
for (j = 0; j <= i; j++)
out[j] = ((x >> ((i - j) * 7)) & 127) | 128;
out[i] ^= 128;
}
uint64_t from_seq(uint8_t *in)
{
uint64_t r = 0;
do {
r = (r << 7) | (uint64_t)(*in & 127);
} while (*in++ & 128);
return r;
}
int main()
{
uint8_t s[10];
uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};
int i, j;
for (j = 0; j < sizeof(x)/8; j++) {
to_seq(x[j], s);
printf("seq from %llx: [ ", x[j]);
i = 0;
do { printf("%02x ", s[i]); } while ((s[i++] & 128));
printf("] back: %llx\n", from_seq(s));
}
return 0;
}
| namespace Vlq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class VarLenQuantity
{
public static ulong ToVlq(ulong integer)
{
var array = new byte[8];
var buffer = ToVlqCollection(integer)
.SkipWhile(b => b == 0)
.Reverse()
.ToArray();
Array.Copy(buffer, array, buffer.Length);
return BitConverter.ToUInt64(array, 0);
}
public static ulong FromVlq(ulong integer)
{
var collection = BitConverter.GetBytes(integer).Reverse();
return FromVlqCollection(collection);
}
public static IEnumerable<byte> ToVlqCollection(ulong integer)
{
if (integer > Math.Pow(2, 56))
throw new OverflowException("Integer exceeds max value.");
var index = 7;
var significantBitReached = false;
var mask = 0x7fUL << (index * 7);
while (index >= 0)
{
var buffer = (mask & integer);
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
buffer >>= index * 7;
if (index > 0)
buffer |= 0x80;
yield return (byte)buffer;
}
mask >>= 7;
index--;
}
}
public static ulong FromVlqCollection(IEnumerable<byte> vlq)
{
ulong integer = 0;
var significantBitReached = false;
using (var enumerator = vlq.GetEnumerator())
{
int index = 0;
while (enumerator.MoveNext())
{
var buffer = enumerator.Current;
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
integer <<= 7;
integer |= (buffer & 0x7fUL);
}
if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))
break;
}
}
return integer;
}
public static void Main()
{
var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };
foreach (var original in integers)
{
Console.WriteLine("Original: 0x{0:X}", original);
var seq = ToVlqCollection(original);
Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat));
var decoded = FromVlqCollection(seq);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
var encoded = ToVlq(original);
Console.WriteLine("Encoded: 0x{0:X}", encoded);
decoded = FromVlq(encoded);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
Console.WriteLine();
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
|
Convert this C snippet to C# and keep its semantics consistent. | #include <stdio.h>
#include <stdint.h>
void to_seq(uint64_t x, uint8_t *out)
{
int i, j;
for (i = 9; i > 0; i--) {
if (x & 127ULL << i * 7) break;
}
for (j = 0; j <= i; j++)
out[j] = ((x >> ((i - j) * 7)) & 127) | 128;
out[i] ^= 128;
}
uint64_t from_seq(uint8_t *in)
{
uint64_t r = 0;
do {
r = (r << 7) | (uint64_t)(*in & 127);
} while (*in++ & 128);
return r;
}
int main()
{
uint8_t s[10];
uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};
int i, j;
for (j = 0; j < sizeof(x)/8; j++) {
to_seq(x[j], s);
printf("seq from %llx: [ ", x[j]);
i = 0;
do { printf("%02x ", s[i]); } while ((s[i++] & 128));
printf("] back: %llx\n", from_seq(s));
}
return 0;
}
| namespace Vlq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class VarLenQuantity
{
public static ulong ToVlq(ulong integer)
{
var array = new byte[8];
var buffer = ToVlqCollection(integer)
.SkipWhile(b => b == 0)
.Reverse()
.ToArray();
Array.Copy(buffer, array, buffer.Length);
return BitConverter.ToUInt64(array, 0);
}
public static ulong FromVlq(ulong integer)
{
var collection = BitConverter.GetBytes(integer).Reverse();
return FromVlqCollection(collection);
}
public static IEnumerable<byte> ToVlqCollection(ulong integer)
{
if (integer > Math.Pow(2, 56))
throw new OverflowException("Integer exceeds max value.");
var index = 7;
var significantBitReached = false;
var mask = 0x7fUL << (index * 7);
while (index >= 0)
{
var buffer = (mask & integer);
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
buffer >>= index * 7;
if (index > 0)
buffer |= 0x80;
yield return (byte)buffer;
}
mask >>= 7;
index--;
}
}
public static ulong FromVlqCollection(IEnumerable<byte> vlq)
{
ulong integer = 0;
var significantBitReached = false;
using (var enumerator = vlq.GetEnumerator())
{
int index = 0;
while (enumerator.MoveNext())
{
var buffer = enumerator.Current;
if (buffer > 0 || significantBitReached)
{
significantBitReached = true;
integer <<= 7;
integer |= (buffer & 0x7fUL);
}
if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80))
break;
}
}
return integer;
}
public static void Main()
{
var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff };
foreach (var original in integers)
{
Console.WriteLine("Original: 0x{0:X}", original);
var seq = ToVlqCollection(original);
Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat));
var decoded = FromVlqCollection(seq);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
var encoded = ToVlq(original);
Console.WriteLine("Encoded: 0x{0:X}", encoded);
decoded = FromVlq(encoded);
Console.WriteLine("Decoded: 0x{0:X}", decoded);
Console.WriteLine();
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
|
Change the programming language of this snippet from C to C# without modifying what it does. |
#include <ctype.h>
#include <stdio.h>
void str_toupper(char *s)
{
while(*s)
{
*s=toupper(*s);
s++;
}
}
void str_tolower(char *s)
{
while(*s)
{
*s=tolower(*s);
s++;
}
}
int main(int argc, char *argv[])
{
char t[255]="alphaBETA";
str_toupper(t);
printf("uppercase: %s\n", t);
str_tolower(t);
printf("lowercase: %s\n", t);
return 0;
}
| using System;
namespace StringCase
{
class Program
{
public static void Main()
{
String input = scope .("alphaBETA");
input.ToUpper();
Console.WriteLine(input);
input.ToLower();
Console.WriteLine(input);
}
}
}
|
Write a version of this C function in C# with identical behavior. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
const char *string = "The quick brown fox jumped over the lazy dog's back";
int main()
{
int i;
unsigned char result[MD5_DIGEST_LENGTH];
MD5(string, strlen(string), result);
for(i = 0; i < MD5_DIGEST_LENGTH; i++)
printf("%02x", result[i]);
printf("\n");
return EXIT_SUCCESS;
}
| using System.Text;
using System.Security.Cryptography;
byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back");
byte[] hash = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());
|
Write a version of this C function in C# with identical behavior. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
struct tm ts;
time_t t;
const char *d = "March 7 2009 7:30pm EST";
strptime(d, "%B %d %Y %I:%M%p %Z", &ts);
t = mktime(&ts);
t += 12*60*60;
printf("%s", ctime(&t));
return EXIT_SUCCESS;
}
| class Program
{
static void Main(string[] args)
{
CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
string dateString = "March 7 2009 7:30pm EST";
string format = "MMMM d yyyy h:mmtt z";
DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST"));
Console.ReadLine();
}
}
|
Rewrite the snippet below in C# so it works the same as the original C code. | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
struct tm ts;
time_t t;
const char *d = "March 7 2009 7:30pm EST";
strptime(d, "%B %d %Y %I:%M%p %Z", &ts);
t = mktime(&ts);
t += 12*60*60;
printf("%s", ctime(&t));
return EXIT_SUCCESS;
}
| class Program
{
static void Main(string[] args)
{
CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
string dateString = "March 7 2009 7:30pm EST";
string format = "MMMM d yyyy h:mmtt z";
DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST"));
Console.ReadLine();
}
}
|
Generate an equivalent C# version of this C code. | >>>>>,----------[++++++++
++[->+>+<<]>+>[-<<+>>]+++
+++++[-<------>]>>+>,----
------<<+[->>>>>+<<<<<]>>
]>>>[<<<<[<<<[->>+<<[->+>
[-]<<]]>[-<+>]>[-<<<.>>>>
->>>>>[>>>>>]<-<<<<[<<<<<
]+<]<<<<]>>>>>[>>>>>]<]
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
class Program
{
static void ThreadStart(object item)
{
Thread.Sleep(1000 * (int)item);
Console.WriteLine(item);
}
static void SleepSort(IEnumerable<int> items)
{
foreach (var item in items)
{
new Thread(ThreadStart).Start(item);
}
}
static void Main(string[] arguments)
{
SleepSort(arguments.Select(int.Parse));
}
}
|
Generate a C# translation of this C snippet without changing its computational steps. | #include <stdlib.h>
#include <time.h>
#include <stdio.h>
int main() {
int a[10][10], i, j;
srand(time(NULL));
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
a[i][j] = rand() % 20 + 1;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf(" %d", a[i][j]);
if (a[i][j] == 20)
goto Done;
}
printf("\n");
}
Done:
printf("\n");
return 0;
}
| using System;
class Program {
static void Main(string[] args) {
int[,] a = new int[10, 10];
Random r = new Random();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a[i, j] = r.Next(0, 21) + 1;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Console.Write(" {0}", a[i, j]);
if (a[i, j] == 20) {
goto Done;
}
}
Console.WriteLine();
}
Done:
Console.WriteLine();
}
}
|
Write a version of this C function in C# with identical behavior. | #include <stdio.h>
#include <stdlib.h>
struct list_node {int x; struct list_node *next;};
typedef struct list_node node;
node * uniq(int *a, unsigned alen)
{if (alen == 0) return NULL;
node *start = malloc(sizeof(node));
if (start == NULL) exit(EXIT_FAILURE);
start->x = a[0];
start->next = NULL;
for (int i = 1 ; i < alen ; ++i)
{node *n = start;
for (;; n = n->next)
{if (a[i] == n->x) break;
if (n->next == NULL)
{n->next = malloc(sizeof(node));
n = n->next;
if (n == NULL) exit(EXIT_FAILURE);
n->x = a[i];
n->next = NULL;
break;}}}
return start;}
int main(void)
{int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};
for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)
printf("%d ", n->x);
puts("");
return 0;}
| int[] nums = { 1, 1, 2, 3, 4, 4 };
List<int> unique = new List<int>();
foreach (int n in nums)
if (!unique.Contains(n))
unique.Add(n);
|
Write the same algorithm in C# as shown in this C implementation. | #include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
}
return 0;
}
| using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
|
Write a version of this C function in C# with identical behavior. | #include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
}
return 0;
}
| using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
|
Please provide an equivalent version of this C code in C#. | #include <stdio.h>
#include <stdlib.h>
#define DECL_STACK_TYPE(type, name) \
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \
stk_##name stk_##name##_create(size_t init_size) { \
stk_##name s; if (!init_size) init_size = 4; \
s = malloc(sizeof(struct stk_##name##_t)); \
if (!s) return 0; \
s->buf = malloc(sizeof(type) * init_size); \
if (!s->buf) { free(s); return 0; } \
s->len = 0, s->alloc = init_size; \
return s; } \
int stk_##name##_push(stk_##name s, type item) { \
type *tmp; \
if (s->len >= s->alloc) { \
tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \
if (!tmp) return -1; s->buf = tmp; \
s->alloc *= 2; } \
s->buf[s->len++] = item; \
return s->len; } \
type stk_##name##_pop(stk_##name s) { \
type tmp; \
if (!s->len) abort(); \
tmp = s->buf[--s->len]; \
if (s->len * 2 <= s->alloc && s->alloc >= 8) { \
s->alloc /= 2; \
s->buf = realloc(s->buf, s->alloc * sizeof(type));} \
return tmp; } \
void stk_##name##_delete(stk_##name s) { \
free(s->buf); free(s); }
#define stk_empty(s) (!(s)->len)
#define stk_size(s) ((s)->len)
DECL_STACK_TYPE(int, int)
int main(void)
{
int i;
stk_int stk = stk_int_create(0);
printf("pushing: ");
for (i = 'a'; i <= 'z'; i++) {
printf(" %c", i);
stk_int_push(stk, i);
}
printf("\nsize now: %d", stk_size(stk));
printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");
printf("\npoppoing:");
while (stk_size(stk))
printf(" %c", stk_int_pop(stk));
printf("\nsize now: %d", stk_size(stk));
printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");
stk_int_delete(stk);
return 0;
}
|
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
bool isEmpty = stack.Count == 0;
object top = stack.Peek();
top = stack.Pop();
System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();
stack.Push(new Foo());
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek();
top = stack.Pop();
|
Produce a functionally identical C# code for the snippet given in C. |
#include<stdio.h>
int totient(int n){
int tot = n,i;
for(i=2;i*i<=n;i+=2){
if(n%i==0){
while(n%i==0)
n/=i;
tot-=tot/i;
}
if(i==2)
i=1;
}
if(n>1)
tot-=tot/n;
return tot;
}
int main()
{
int count = 0,n,tot;
printf(" n %c prime",237);
printf("\n---------------\n");
for(n=1;n<=25;n++){
tot = totient(n);
if(n-1 == tot)
count++;
printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False");
}
printf("\nNumber of primes up to %6d =%4d\n", 25,count);
for(n = 26; n <= 100000; n++){
tot = totient(n);
if(tot == n-1)
count++;
if(n == 100 || n == 1000 || n%10000 == 0){
printf("\nNumber of primes up to %6d = %4d\n", n, count);
}
}
return 0;
}
| using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int i = 1; i <= 25; i++) {
int t = Totient(i);
WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
}
WriteLine();
for (int i = 100; i <= 100_000; i *= 10) {
WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
}
}
static int Totient(int n) {
if (n < 3) return 1;
if (n == 3) return 2;
int totient = n;
if ((n & 1) == 0) {
totient >>= 1;
while (((n >>= 1) & 1) == 0) ;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
totient -= totient / i;
while ((n /= i) % i == 0) ;
}
}
if (n > 1) totient -= totient / n;
return totient;
}
}
|
Generate a C# translation of this C snippet without changing its computational steps. |
#include<stdio.h>
int totient(int n){
int tot = n,i;
for(i=2;i*i<=n;i+=2){
if(n%i==0){
while(n%i==0)
n/=i;
tot-=tot/i;
}
if(i==2)
i=1;
}
if(n>1)
tot-=tot/n;
return tot;
}
int main()
{
int count = 0,n,tot;
printf(" n %c prime",237);
printf("\n---------------\n");
for(n=1;n<=25;n++){
tot = totient(n);
if(n-1 == tot)
count++;
printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False");
}
printf("\nNumber of primes up to %6d =%4d\n", 25,count);
for(n = 26; n <= 100000; n++){
tot = totient(n);
if(tot == n-1)
count++;
if(n == 100 || n == 1000 || n%10000 == 0){
printf("\nNumber of primes up to %6d = %4d\n", n, count);
}
}
return 0;
}
| using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
for (int i = 1; i <= 25; i++) {
int t = Totient(i);
WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : ""));
}
WriteLine();
for (int i = 100; i <= 100_000; i *= 10) {
WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}");
}
}
static int Totient(int n) {
if (n < 3) return 1;
if (n == 3) return 2;
int totient = n;
if ((n & 1) == 0) {
totient >>= 1;
while (((n >>= 1) & 1) == 0) ;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
totient -= totient / i;
while ((n /= i) % i == 0) ;
}
}
if (n > 1) totient -= totient / n;
return totient;
}
}
|
Transform the following C implementation into C#, maintaining the same output and logic. | int a = 3;
if (a == 2) {
puts ("a is 2");
} else if (a == 3) {
puts ("a is 3");
} else {
puts("a is 4");
}
unless (a == 2) {
puts ("a is 2");
} else if (a == 3) {
puts ("a is 3");
} else {
puts("a is 4");
}
switch (a) {
case 2:
puts ("a is 2");
break;
case 3:
puts ("a is 3");
break;
case 4:
puts ("a is 4");
break;
default:
puts("is neither");
}
| if (condition)
{
}
if (condition)
{
}
else if (condition2)
{
}
else
{
}
|
Please provide an equivalent version of this C code in C#. | #include <stdlib.h>
#include <string.h>
#include <strings.h>
int mycmp(const void *s1, const void *s2)
{
const char *l = *(const char **)s1, *r = *(const char **)s2;
size_t ll = strlen(l), lr = strlen(r);
if (ll > lr) return -1;
if (ll < lr) return 1;
return strcasecmp(l, r);
}
int main()
{
const char *strings[] = {
"Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);
return 0;
}
| using System;
using System.Collections.Generic;
namespace RosettaCode {
class SortCustomComparator {
public void CustomSort() {
String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
List<String> list = new List<string>(items);
DisplayList("Unsorted", list);
list.Sort(CustomCompare);
DisplayList("Descending Length", list);
list.Sort();
DisplayList("Ascending order", list);
}
public int CustomCompare(String x, String y) {
int result = -x.Length.CompareTo(y.Length);
if (result == 0) {
result = x.ToLower().CompareTo(y.ToLower());
}
return result;
}
public void DisplayList(String header, List<String> theList) {
Console.WriteLine(header);
Console.WriteLine("".PadLeft(header.Length, '*'));
foreach (String str in theList) {
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
|
Port the provided C code into C# while preserving the original functionality. | #include <stdlib.h>
#include <string.h>
#include <strings.h>
int mycmp(const void *s1, const void *s2)
{
const char *l = *(const char **)s1, *r = *(const char **)s2;
size_t ll = strlen(l), lr = strlen(r);
if (ll > lr) return -1;
if (ll < lr) return 1;
return strcasecmp(l, r);
}
int main()
{
const char *strings[] = {
"Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp);
return 0;
}
| using System;
using System.Collections.Generic;
namespace RosettaCode {
class SortCustomComparator {
public void CustomSort() {
String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
List<String> list = new List<string>(items);
DisplayList("Unsorted", list);
list.Sort(CustomCompare);
DisplayList("Descending Length", list);
list.Sort();
DisplayList("Ascending order", list);
}
public int CustomCompare(String x, String y) {
int result = -x.Length.CompareTo(y.Length);
if (result == 0) {
result = x.ToLower().CompareTo(y.ToLower());
}
return result;
}
public void DisplayList(String header, List<String> theList) {
Console.WriteLine(header);
Console.WriteLine("".PadLeft(header.Length, '*'));
foreach (String str in theList) {
Console.WriteLine(str);
}
Console.WriteLine();
}
}
}
|
Keep all operations the same but rewrite the snippet in C#. | #include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;
GtkLabel *label;
void change_dir(GtkLayout *o, gpointer d)
{
direction = -direction;
}
gchar *rotateby(const gchar *t, gint q, gint l)
{
gint i, cl = l, j;
gchar *r = malloc(l+1);
for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
r[j] = t[i];
r[l] = 0;
return r;
}
gboolean scroll_it(gpointer data)
{
if ( direction > 0 )
cx = (cx + 1) % slen;
else
cx = (cx + slen - 1 ) % slen;
gchar *scrolled = rotateby(hello, cx, slen);
gtk_label_set_text(label, scrolled);
free(scrolled);
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *win;
GtkButton *button;
PangoFontDescription *pd;
gtk_init(&argc, &argv);
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);
label = (GtkLabel *)gtk_label_new(hello);
pd = pango_font_description_new();
pango_font_description_set_family(pd, "monospace");
gtk_widget_modify_font(GTK_WIDGET(label), pd);
button = (GtkButton *)gtk_button_new();
gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);
slen = strlen(hello);
g_timeout_add(125, scroll_it, NULL);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
}
| using System;
using System.Drawing;
using System.Windows.Forms;
namespace BasicAnimation
{
class BasicAnimationForm : Form
{
bool isReverseDirection;
Label textLabel;
Timer timer;
internal BasicAnimationForm()
{
this.Size = new Size(150, 75);
this.Text = "Basic Animation";
textLabel = new Label();
textLabel.Text = "Hello World! ";
textLabel.Location = new Point(3,3);
textLabel.AutoSize = true;
textLabel.Click += new EventHandler(textLabel_OnClick);
this.Controls.Add(textLabel);
timer = new Timer();
timer.Interval = 500;
timer.Tick += new EventHandler(timer_OnTick);
timer.Enabled = true;
isReverseDirection = false;
}
private void timer_OnTick(object sender, EventArgs e)
{
string oldText = textLabel.Text, newText;
if(isReverseDirection)
newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
else
newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
textLabel.Text = newText;
}
private void textLabel_OnClick(object sender, EventArgs e)
{
isReverseDirection = !isReverseDirection;
}
}
class Program
{
static void Main()
{
Application.Run(new BasicAnimationForm());
}
}
}
|
Convert the following code from C to C#, ensuring the logic remains intact. | #include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;
GtkLabel *label;
void change_dir(GtkLayout *o, gpointer d)
{
direction = -direction;
}
gchar *rotateby(const gchar *t, gint q, gint l)
{
gint i, cl = l, j;
gchar *r = malloc(l+1);
for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
r[j] = t[i];
r[l] = 0;
return r;
}
gboolean scroll_it(gpointer data)
{
if ( direction > 0 )
cx = (cx + 1) % slen;
else
cx = (cx + slen - 1 ) % slen;
gchar *scrolled = rotateby(hello, cx, slen);
gtk_label_set_text(label, scrolled);
free(scrolled);
return TRUE;
}
int main(int argc, char **argv)
{
GtkWidget *win;
GtkButton *button;
PangoFontDescription *pd;
gtk_init(&argc, &argv);
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);
label = (GtkLabel *)gtk_label_new(hello);
pd = pango_font_description_new();
pango_font_description_set_family(pd, "monospace");
gtk_widget_modify_font(GTK_WIDGET(label), pd);
button = (GtkButton *)gtk_button_new();
gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);
slen = strlen(hello);
g_timeout_add(125, scroll_it, NULL);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
}
| using System;
using System.Drawing;
using System.Windows.Forms;
namespace BasicAnimation
{
class BasicAnimationForm : Form
{
bool isReverseDirection;
Label textLabel;
Timer timer;
internal BasicAnimationForm()
{
this.Size = new Size(150, 75);
this.Text = "Basic Animation";
textLabel = new Label();
textLabel.Text = "Hello World! ";
textLabel.Location = new Point(3,3);
textLabel.AutoSize = true;
textLabel.Click += new EventHandler(textLabel_OnClick);
this.Controls.Add(textLabel);
timer = new Timer();
timer.Interval = 500;
timer.Tick += new EventHandler(timer_OnTick);
timer.Enabled = true;
isReverseDirection = false;
}
private void timer_OnTick(object sender, EventArgs e)
{
string oldText = textLabel.Text, newText;
if(isReverseDirection)
newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
else
newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
textLabel.Text = newText;
}
private void textLabel_OnClick(object sender, EventArgs e)
{
isReverseDirection = !isReverseDirection;
}
}
class Program
{
static void Main()
{
Application.Run(new BasicAnimationForm());
}
}
}
|
Convert this C snippet to C# and keep its semantics consistent. | #include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)
#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));
static void swap(unsigned *a, unsigned *b) {
unsigned tmp = *a;
*a = *b;
*b = tmp;
}
static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
{
if (!bit || to < from + 1) return;
unsigned *ll = from, *rr = to - 1;
for (;;) {
while (ll < rr && !(*ll & bit)) ll++;
while (ll < rr && (*rr & bit)) rr--;
if (ll >= rr) break;
swap(ll, rr);
}
if (!(bit & *ll) && ll < to) ll++;
bit >>= 1;
rad_sort_u(from, ll, bit);
rad_sort_u(ll, to, bit);
}
static void radix_sort(int *a, const size_t len)
{
size_t i;
unsigned *x = (unsigned*) a;
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
rad_sort_u(x, x + len, INT_MIN);
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
}
int main(void)
{
srand(time(NULL));
int x[16];
for (size_t i = 0; i < ARR_LEN(x); i++)
x[i] = RAND_RNG(-128,127)
radix_sort(x, ARR_LEN(x));
for (size_t i = 0; i < ARR_LEN(x); i++)
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
}
| using System;
namespace RadixSort
{
class Program
{
static void Sort(int[] old)
{
int i, j;
int[] tmp = new int[old.Length];
for (int shift = 31; shift > -1; --shift)
{
j = 0;
for (i = 0; i < old.Length; ++i)
{
bool move = (old[i] << shift) >= 0;
if (shift == 0 ? !move : move)
old[i-j] = old[i];
else
tmp[j++] = old[i];
}
Array.Copy(tmp, 0, old, old.Length-j, j);
}
}
static void Main(string[] args)
{
int[] old = new int[] { 2, 5, 1, -3, 4 };
Console.WriteLine(string.Join(", ", old));
Sort(old);
Console.WriteLine(string.Join(", ", old));
Console.Read();
}
}
}
|
Rewrite the snippet below in C# so it works the same as the original C code. | #include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)
#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));
static void swap(unsigned *a, unsigned *b) {
unsigned tmp = *a;
*a = *b;
*b = tmp;
}
static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
{
if (!bit || to < from + 1) return;
unsigned *ll = from, *rr = to - 1;
for (;;) {
while (ll < rr && !(*ll & bit)) ll++;
while (ll < rr && (*rr & bit)) rr--;
if (ll >= rr) break;
swap(ll, rr);
}
if (!(bit & *ll) && ll < to) ll++;
bit >>= 1;
rad_sort_u(from, ll, bit);
rad_sort_u(ll, to, bit);
}
static void radix_sort(int *a, const size_t len)
{
size_t i;
unsigned *x = (unsigned*) a;
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
rad_sort_u(x, x + len, INT_MIN);
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
}
int main(void)
{
srand(time(NULL));
int x[16];
for (size_t i = 0; i < ARR_LEN(x); i++)
x[i] = RAND_RNG(-128,127)
radix_sort(x, ARR_LEN(x));
for (size_t i = 0; i < ARR_LEN(x); i++)
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
}
| using System;
namespace RadixSort
{
class Program
{
static void Sort(int[] old)
{
int i, j;
int[] tmp = new int[old.Length];
for (int shift = 31; shift > -1; --shift)
{
j = 0;
for (i = 0; i < old.Length; ++i)
{
bool move = (old[i] << shift) >= 0;
if (shift == 0 ? !move : move)
old[i-j] = old[i];
else
tmp[j++] = old[i];
}
Array.Copy(tmp, 0, old, old.Length-j, j);
}
}
static void Main(string[] args)
{
int[] old = new int[] { 2, 5, 1, -3, 4 };
Console.WriteLine(string.Join(", ", old));
Sort(old);
Console.WriteLine(string.Join(", ", old));
Console.Read();
}
}
}
|
Convert the following code from C to C#, ensuring the logic remains intact. | for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Ensure the translated C# code behaves exactly like the original C snippet. | for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
| using System.Linq;
static class Program
{
static void Main()
{
var ts =
from a in Enumerable.Range(1, 20)
from b in Enumerable.Range(a, 21 - a)
from c in Enumerable.Range(b, 21 - b)
where a * a + b * b == c * c
select new { a, b, c };
foreach (var t in ts)
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.