Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same algorithm in C++ as shown in this Python implementation. | collection = [0, '1']
x = collection[0]
collection.append(2)
collection.insert(0, '-1')
y = collection[0]
collection.extend([2,'3'])
collection += [2,'3']
collection[2:6]
len(collection)
collection = (0, 1)
collection[:]
collection[-4:-1]
collection[::2]
collection="some string"
x = collection[::-1]
collection[::2] == "some string"[::2]
collection.__getitem__(slice(0,len(collection),2))
collection = {0: "zero", 1: "one"}
collection['zero'] = 2
collection = set([0, '1'])
| int a[5];
a[0] = 1;
int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
#include <string>
std::string strings[4];
|
Keep all operations the same but rewrite the snippet in C++. | for node in lst:
print node.value
| #include <iostream>
#include <forward_list>
int main()
{
std::forward_list<int> list{1, 2, 3, 4, 5};
for (int e : list)
std::cout << e << std::endl;
}
|
Change the following Python code into C++ without altering its purpose. |
import io
ppmfileout = io.StringIO('')
def writeppmp3(self, f):
self.writeppm(f, ppmformat='P3')
def writeppm(self, f, ppmformat='P6'):
assert ppmformat in ['P3', 'P6'], 'Format wrong'
magic = ppmformat + '\n'
comment = '
maxval = max(max(max(bit) for bit in row) for row in self.map)
assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'
if ppmformat == 'P6':
fwrite = lambda s: f.write(bytes(s, 'UTF-8'))
maxval = 255
else:
fwrite = f.write
numsize=len(str(maxval))
fwrite(magic)
fwrite(comment)
fwrite('%i %i\n%i\n' % (self.width, self.height, maxval))
for h in range(self.height-1, -1, -1):
for w in range(self.width):
r, g, b = self.get(w, h)
if ppmformat == 'P3':
fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))
else:
fwrite('%c%c%c' % (r, g, b))
if ppmformat == 'P3':
fwrite('\n')
Bitmap.writeppmp3 = writeppmp3
Bitmap.writeppm = writeppm
bitmap = Bitmap(4, 4, black)
bitmap.fillrect(1, 0, 1, 2, white)
bitmap.set(3, 3, Colour(127, 0, 63))
bitmap.writeppmp3(ppmfileout)
print(ppmfileout.getvalue())
ppmfileout = open('tmp.ppm', 'wb')
bitmap.writeppm(ppmfileout)
ppmfileout.close()
| #include <fstream>
#include <cstdio>
int main() {
constexpr auto dimx = 800u, dimy = 800u;
using namespace std;
ofstream ofs("first.ppm", ios_base::out | ios_base::binary);
ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl;
for (auto j = 0u; j < dimy; ++j)
for (auto i = 0u; i < dimx; ++i)
ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);
ofs.close();
return EXIT_SUCCESS;
}
|
Produce a functionally identical C++ code for the snippet given in Python. | import os
os.remove("output.txt")
os.rmdir("docs")
os.remove("/output.txt")
os.rmdir("/docs")
| #include <cstdio>
#include <direct.h>
int main() {
remove( "input.txt" );
remove( "/input.txt" );
_rmdir( "docs" );
_rmdir( "/docs" );
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | import datetime, calendar
DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]
def ddate(year, month, day):
today = datetime.date(year, month, day)
is_leap_year = calendar.isleap(year)
if is_leap_year and month == 2 and day == 29:
return "St. Tib's Day, YOLD " + (year + 1166)
day_of_year = today.timetuple().tm_yday - 1
if is_leap_year and day_of_year >= 60:
day_of_year -= 1
season, dday = divmod(day_of_year, 73)
return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
| #include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
class myTuple
{
public:
void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }
bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }
string second() { return t.second; }
private:
pair<pair<int, int>, string> t;
};
class discordian
{
public:
discordian() {
myTuple t;
t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t );
t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t );
t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t );
t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t );
t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t );
t.set( 8, 12, "Afflux" ); holyday.push_back( t );
seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" );
seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" );
wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" );
wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" );
}
void convert( int d, int m, int y ) {
if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) {
cout << "\nThis is not a date!";
return;
}
vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) );
int dd = d, day, wday, sea, yr = y + 1166;
for( int x = 1; x < m; x++ )
dd += getMaxDay( x, 1 );
day = dd % 73; if( !day ) day = 73;
wday = dd % 5;
sea = ( dd - 1 ) / 73;
if( d == 29 && m == 2 && isLeap( y ) ) {
cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr;
return;
}
cout << wdays[wday] << " " << seasons[sea] << " " << day;
if( day > 10 && day < 14 ) cout << "th";
else switch( day % 10) {
case 1: cout << "st"; break;
case 2: cout << "nd"; break;
case 3: cout << "rd"; break;
default: cout << "th";
}
cout << ", Year of Our Lady of Discord " << yr;
if( f != holyday.end() ) cout << " - " << ( *f ).second();
}
private:
int getMaxDay( int m, int y ) {
int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m];
}
bool isLeap( int y ) {
bool l = false;
if( !( y % 4 ) ) {
if( y % 100 ) l = true;
else if( !( y % 400 ) ) l = true;
}
return l;
}
vector<myTuple> holyday; vector<string> seasons, wdays;
};
int main( int argc, char* argv[] ) {
string date; discordian disc;
while( true ) {
cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break;
if( date.length() == 10 ) {
istringstream iss( date );
vector<string> vc;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );
disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) );
cout << "\n\n\n";
} else cout << "\nIs this a date?!\n\n";
}
return 0;
}
|
Write a version of this Python function in C++ with identical behavior. |
from random import randrange
from copy import deepcopy
from string import ascii_lowercase
try:
input = raw_input
except:
pass
N = 3
board = [[0]* N for i in range(N)]
def setbits(board, count=1):
for i in range(count):
board[randrange(N)][randrange(N)] ^= 1
def shuffle(board, count=1):
for i in range(count):
if randrange(0, 2):
fliprow(randrange(N))
else:
flipcol(randrange(N))
def pr(board, comment=''):
print(str(comment))
print(' ' + ' '.join(ascii_lowercase[i] for i in range(N)))
print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line])
for j, line in enumerate(board, 1)))
def init(board):
setbits(board, count=randrange(N)+1)
target = deepcopy(board)
while board == target:
shuffle(board, count=2 * N)
prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0],
ascii_lowercase[N-1])
return target, prompt
def fliprow(i):
board[i-1][:] = [x ^ 1 for x in board[i-1] ]
def flipcol(i):
for row in board:
row[i] ^= 1
if __name__ == '__main__':
print(__doc__ % (N, N))
target, prompt = init(board)
pr(target, 'Target configuration is:')
print('')
turns = 0
while board != target:
turns += 1
pr(board, '%i:' % turns)
ans = input(prompt).strip()
if (len(ans) == 1
and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):
flipcol(ascii_lowercase.index(ans))
elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:
fliprow(int(ans))
elif ans == 'T':
pr(target, 'Target configuration is:')
turns -= 1
elif ans == 'X':
break
else:
print(" I don't understand %r... Try again. "
"(X to exit or T to show target)\n" % ans[:9])
turns -= 1
else:
print('\nWell done!\nBye.')
| #include <time.h>
#include <iostream>
#include <string>
typedef unsigned char byte;
using namespace std;
class flip
{
public:
flip() { field = 0; target = 0; }
void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }
private:
void gameLoop()
{
int moves = 0;
while( !solved() )
{
display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r;
for( string::iterator i = r.begin(); i != r.end(); i++ )
{
byte ii = ( *i );
if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }
else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }
}
}
cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl;
}
void display()
{ system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); }
void output( string t, byte* f )
{
cout << t << endl;
cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl;
for( int y = 0; y < hei; y++ )
{
cout << static_cast<char>( y + 'a' ) << " ";
for( int x = 0; x < wid; x++ )
cout << static_cast<char>( f[x + y * wid] + 48 ) << " ";
cout << endl;
}
cout << endl << endl;
}
bool solved()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( target[x + y * wid] != field[x + y * wid] ) return false;
return true;
}
void createTarget()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( frnd() < .5f ) target[x + y * wid] = 1;
else target[x + y * wid] = 0;
memcpy( field, target, wid * hei );
}
void flipCol( int c )
{ for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }
void flipRow( int r )
{ for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }
void calcStartPos()
{
int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;
for( int x = 0; x < flips; x++ )
{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }
}
void createField()
{
if( field ){ delete [] field; delete [] target; }
int t = wid * hei; field = new byte[t]; target = new byte[t];
memset( field, 0, t ); memset( target, 0, t ); createTarget();
while( true ) { calcStartPos(); if( !solved() ) break; }
}
float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }
byte* field, *target; int wid, hei;
};
int main( int argc, char* argv[] )
{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
|
Produce a functionally identical C++ code for the snippet given in Python. |
from random import randrange
from copy import deepcopy
from string import ascii_lowercase
try:
input = raw_input
except:
pass
N = 3
board = [[0]* N for i in range(N)]
def setbits(board, count=1):
for i in range(count):
board[randrange(N)][randrange(N)] ^= 1
def shuffle(board, count=1):
for i in range(count):
if randrange(0, 2):
fliprow(randrange(N))
else:
flipcol(randrange(N))
def pr(board, comment=''):
print(str(comment))
print(' ' + ' '.join(ascii_lowercase[i] for i in range(N)))
print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line])
for j, line in enumerate(board, 1)))
def init(board):
setbits(board, count=randrange(N)+1)
target = deepcopy(board)
while board == target:
shuffle(board, count=2 * N)
prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0],
ascii_lowercase[N-1])
return target, prompt
def fliprow(i):
board[i-1][:] = [x ^ 1 for x in board[i-1] ]
def flipcol(i):
for row in board:
row[i] ^= 1
if __name__ == '__main__':
print(__doc__ % (N, N))
target, prompt = init(board)
pr(target, 'Target configuration is:')
print('')
turns = 0
while board != target:
turns += 1
pr(board, '%i:' % turns)
ans = input(prompt).strip()
if (len(ans) == 1
and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):
flipcol(ascii_lowercase.index(ans))
elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:
fliprow(int(ans))
elif ans == 'T':
pr(target, 'Target configuration is:')
turns -= 1
elif ans == 'X':
break
else:
print(" I don't understand %r... Try again. "
"(X to exit or T to show target)\n" % ans[:9])
turns -= 1
else:
print('\nWell done!\nBye.')
| #include <time.h>
#include <iostream>
#include <string>
typedef unsigned char byte;
using namespace std;
class flip
{
public:
flip() { field = 0; target = 0; }
void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }
private:
void gameLoop()
{
int moves = 0;
while( !solved() )
{
display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r;
for( string::iterator i = r.begin(); i != r.end(); i++ )
{
byte ii = ( *i );
if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }
else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }
}
}
cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl;
}
void display()
{ system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); }
void output( string t, byte* f )
{
cout << t << endl;
cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl;
for( int y = 0; y < hei; y++ )
{
cout << static_cast<char>( y + 'a' ) << " ";
for( int x = 0; x < wid; x++ )
cout << static_cast<char>( f[x + y * wid] + 48 ) << " ";
cout << endl;
}
cout << endl << endl;
}
bool solved()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( target[x + y * wid] != field[x + y * wid] ) return false;
return true;
}
void createTarget()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( frnd() < .5f ) target[x + y * wid] = 1;
else target[x + y * wid] = 0;
memcpy( field, target, wid * hei );
}
void flipCol( int c )
{ for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }
void flipRow( int r )
{ for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }
void calcStartPos()
{
int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;
for( int x = 0; x < flips; x++ )
{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }
}
void createField()
{
if( field ){ delete [] field; delete [] target; }
int t = wid * hei; field = new byte[t]; target = new byte[t];
memset( field, 0, t ); memset( target, 0, t ); createTarget();
while( true ) { calcStartPos(); if( !solved() ) break; }
}
float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }
byte* field, *target; int wid, hei;
};
int main( int argc, char* argv[] )
{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
|
Generate an equivalent C++ version of this Python code. |
from random import randrange
from copy import deepcopy
from string import ascii_lowercase
try:
input = raw_input
except:
pass
N = 3
board = [[0]* N for i in range(N)]
def setbits(board, count=1):
for i in range(count):
board[randrange(N)][randrange(N)] ^= 1
def shuffle(board, count=1):
for i in range(count):
if randrange(0, 2):
fliprow(randrange(N))
else:
flipcol(randrange(N))
def pr(board, comment=''):
print(str(comment))
print(' ' + ' '.join(ascii_lowercase[i] for i in range(N)))
print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line])
for j, line in enumerate(board, 1)))
def init(board):
setbits(board, count=randrange(N)+1)
target = deepcopy(board)
while board == target:
shuffle(board, count=2 * N)
prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0],
ascii_lowercase[N-1])
return target, prompt
def fliprow(i):
board[i-1][:] = [x ^ 1 for x in board[i-1] ]
def flipcol(i):
for row in board:
row[i] ^= 1
if __name__ == '__main__':
print(__doc__ % (N, N))
target, prompt = init(board)
pr(target, 'Target configuration is:')
print('')
turns = 0
while board != target:
turns += 1
pr(board, '%i:' % turns)
ans = input(prompt).strip()
if (len(ans) == 1
and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):
flipcol(ascii_lowercase.index(ans))
elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:
fliprow(int(ans))
elif ans == 'T':
pr(target, 'Target configuration is:')
turns -= 1
elif ans == 'X':
break
else:
print(" I don't understand %r... Try again. "
"(X to exit or T to show target)\n" % ans[:9])
turns -= 1
else:
print('\nWell done!\nBye.')
| #include <time.h>
#include <iostream>
#include <string>
typedef unsigned char byte;
using namespace std;
class flip
{
public:
flip() { field = 0; target = 0; }
void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }
private:
void gameLoop()
{
int moves = 0;
while( !solved() )
{
display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r;
for( string::iterator i = r.begin(); i != r.end(); i++ )
{
byte ii = ( *i );
if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; }
else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; }
}
}
cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl;
}
void display()
{ system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); }
void output( string t, byte* f )
{
cout << t << endl;
cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl;
for( int y = 0; y < hei; y++ )
{
cout << static_cast<char>( y + 'a' ) << " ";
for( int x = 0; x < wid; x++ )
cout << static_cast<char>( f[x + y * wid] + 48 ) << " ";
cout << endl;
}
cout << endl << endl;
}
bool solved()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( target[x + y * wid] != field[x + y * wid] ) return false;
return true;
}
void createTarget()
{
for( int y = 0; y < hei; y++ )
for( int x = 0; x < wid; x++ )
if( frnd() < .5f ) target[x + y * wid] = 1;
else target[x + y * wid] = 0;
memcpy( field, target, wid * hei );
}
void flipCol( int c )
{ for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; }
void flipRow( int r )
{ for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; }
void calcStartPos()
{
int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1;
for( int x = 0; x < flips; x++ )
{ if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); }
}
void createField()
{
if( field ){ delete [] field; delete [] target; }
int t = wid * hei; field = new byte[t]; target = new byte[t];
memset( field, 0, t ); memset( target, 0, t ); createTarget();
while( true ) { calcStartPos(); if( !solved() ) break; }
}
float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); }
byte* field, *target; int wid, hei;
};
int main( int argc, char* argv[] )
{ srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
|
Change the following Python code into C++ without altering its purpose. | from decimal import Decimal
import math
def h(n):
'Simple, reduced precision calculation'
return math.factorial(n) / (2 * math.log(2) ** (n + 1))
def h2(n):
'Extended precision Hickerson function'
return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))
for n in range(18):
x = h2(n)
norm = str(x.normalize())
almostinteger = (' Nearly integer'
if 'E' not in norm and ('.0' in norm or '.9' in norm)
else ' NOT nearly integer!')
print('n:%2i h:%s%s' % (n, norm, almostinteger))
| #include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
typedef boost::multiprecision::cpp_dec_float_50 decfloat;
int main()
{
const decfloat ln_two = boost::math::constants::ln_two<decfloat>();
decfloat numerator = 1, denominator = ln_two;
for(int n = 1; n <= 17; n++) {
decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;
decfloat tenths_dig = floor((h - floor(h)) * 10);
std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h <<
(tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n";
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Python version. | from decimal import Decimal
import math
def h(n):
'Simple, reduced precision calculation'
return math.factorial(n) / (2 * math.log(2) ** (n + 1))
def h2(n):
'Extended precision Hickerson function'
return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1))
for n in range(18):
x = h2(n)
norm = str(x.normalize())
almostinteger = (' Nearly integer'
if 'E' not in norm and ('.0' in norm or '.9' in norm)
else ' NOT nearly integer!')
print('n:%2i h:%s%s' % (n, norm, almostinteger))
| #include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>
typedef boost::multiprecision::cpp_dec_float_50 decfloat;
int main()
{
const decfloat ln_two = boost::math::constants::ln_two<decfloat>();
decfloat numerator = 1, denominator = ln_two;
for(int n = 1; n <= 17; n++) {
decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;
decfloat tenths_dig = floor((h - floor(h)) * 10);
std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h <<
(tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n";
}
}
|
Keep all operations the same but rewrite the snippet in C++. | from __future__ import division
from math import factorial
from random import randrange
MAX_N = 20
TIMES = 1000000
def analytical(n):
return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))
def test(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
if __name__ == '__main__':
print(" n\tavg\texp.\tdiff\n-------------------------------")
for n in range(1, MAX_N+1):
avg = test(n, TIMES)
theory = analytical(n)
diff = (avg / theory - 1) * 100
print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
| #include <random>
#include <random>
#include <vector>
#include <iostream>
#define MAX_N 20
#define TIMES 1000000
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<> dis;
int randint(int n) {
int r, rmax = RAND_MAX / n * n;
dis=std::uniform_int_distribution<int>(0,rmax) ;
r = dis(gen);
return r / (RAND_MAX / n);
}
unsigned long long factorial(size_t n) {
static std::vector<unsigned long long>factorials{1,1,2};
for (;factorials.size() <= n;)
factorials.push_back(((unsigned long long) factorials.back())*factorials.size());
return factorials[n];
}
long double expected(size_t n) {
long double sum = 0;
for (size_t i = 1; i <= n; i++)
sum += factorial(n) / pow(n, i) / factorial(n - i);
return sum;
}
int test(int n, int times) {
int i, count = 0;
for (i = 0; i < times; i++) {
unsigned int x = 1, bits = 0;
while (!(bits & x)) {
count++;
bits |= x;
x = static_cast<unsigned int>(1 << randint(n));
}
}
return count;
}
int main() {
puts(" n\tavg\texp.\tdiff\n-------------------------------");
int n;
for (n = 1; n <= MAX_N; n++) {
int cnt = test(n, TIMES);
long double avg = (double)cnt / TIMES;
long double theory = expected(static_cast<size_t>(n));
long double diff = (avg / theory - 1) * 100;
printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));
}
return 0;
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | from __future__ import division
from math import factorial
from random import randrange
MAX_N = 20
TIMES = 1000000
def analytical(n):
return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))
def test(n, times):
count = 0
for i in range(times):
x, bits = 1, 0
while not (bits & x):
count += 1
bits |= x
x = 1 << randrange(n)
return count / times
if __name__ == '__main__':
print(" n\tavg\texp.\tdiff\n-------------------------------")
for n in range(1, MAX_N+1):
avg = test(n, TIMES)
theory = analytical(n)
diff = (avg / theory - 1) * 100
print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
| #include <random>
#include <random>
#include <vector>
#include <iostream>
#define MAX_N 20
#define TIMES 1000000
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<> dis;
int randint(int n) {
int r, rmax = RAND_MAX / n * n;
dis=std::uniform_int_distribution<int>(0,rmax) ;
r = dis(gen);
return r / (RAND_MAX / n);
}
unsigned long long factorial(size_t n) {
static std::vector<unsigned long long>factorials{1,1,2};
for (;factorials.size() <= n;)
factorials.push_back(((unsigned long long) factorials.back())*factorials.size());
return factorials[n];
}
long double expected(size_t n) {
long double sum = 0;
for (size_t i = 1; i <= n; i++)
sum += factorial(n) / pow(n, i) / factorial(n - i);
return sum;
}
int test(int n, int times) {
int i, count = 0;
for (i = 0; i < times; i++) {
unsigned int x = 1, bits = 0;
while (!(bits & x)) {
count++;
bits |= x;
x = static_cast<unsigned int>(1 << randint(n));
}
}
return count;
}
int main() {
puts(" n\tavg\texp.\tdiff\n-------------------------------");
int n;
for (n = 1; n <= MAX_N; n++) {
int cnt = test(n, TIMES);
long double avg = (double)cnt / TIMES;
long double theory = expected(static_cast<size_t>(n));
long double diff = (avg / theory - 1) * 100;
printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));
}
return 0;
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | >>> original = 'Mary had a %s lamb.'
>>> extra = 'little'
>>> original % extra
'Mary had a little lamb.'
| #include <string>
#include <iostream>
int main( ) {
std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) ,
replacement ( "little" ) ;
std::string newString = original.replace( original.find( "X" ) ,
toBeReplaced.length( ) , replacement ) ;
std::cout << "String after replacement: " << newString << " \n" ;
return 0 ;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | >>> original = 'Mary had a %s lamb.'
>>> extra = 'little'
>>> original % extra
'Mary had a little lamb.'
| #include <string>
#include <iostream>
int main( ) {
std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) ,
replacement ( "little" ) ;
std::string newString = original.replace( original.find( "X" ) ,
toBeReplaced.length( ) , replacement ) ;
std::cout << "String after replacement: " << newString << " \n" ;
return 0 ;
}
|
Change the programming language of this snippet from Python to C++ without modifying what it does. | from functools import total_ordering
from bisect import bisect_left
from heapq import merge
@total_ordering
class Pile(list):
def __lt__(self, other): return self[-1] < other[-1]
def __eq__(self, other): return self[-1] == other[-1]
def patience_sort(n):
piles = []
for x in n:
new_pile = Pile([x])
i = bisect_left(piles, new_pile)
if i != len(piles):
piles[i].append(x)
else:
piles.append(new_pile)
n[:] = merge(*[reversed(pile) for pile in piles])
if __name__ == "__main__":
a = [4, 65, 2, -31, 0, 99, 83, 782, 1]
patience_sort(a)
print a
| #include <iostream>
#include <vector>
#include <stack>
#include <iterator>
#include <algorithm>
#include <cassert>
template <class E>
struct pile_less {
bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {
return pile1.top() < pile2.top();
}
};
template <class E>
struct pile_greater {
bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {
return pile1.top() > pile2.top();
}
};
template <class Iterator>
void patience_sort(Iterator first, Iterator last) {
typedef typename std::iterator_traits<Iterator>::value_type E;
typedef std::stack<E> Pile;
std::vector<Pile> piles;
for (Iterator it = first; it != last; it++) {
E& x = *it;
Pile newPile;
newPile.push(x);
typename std::vector<Pile>::iterator i =
std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>());
if (i != piles.end())
i->push(x);
else
piles.push_back(newPile);
}
std::make_heap(piles.begin(), piles.end(), pile_greater<E>());
for (Iterator it = first; it != last; it++) {
std::pop_heap(piles.begin(), piles.end(), pile_greater<E>());
Pile &smallPile = piles.back();
*it = smallPile.top();
smallPile.pop();
if (smallPile.empty())
piles.pop_back();
else
std::push_heap(piles.begin(), piles.end(), pile_greater<E>());
}
assert(piles.empty());
}
int main() {
int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1};
patience_sort(a, a+sizeof(a)/sizeof(*a));
std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, ", "));
std::cout << std::endl;
return 0;
}
|
Convert the following code from Python to C++, ensuring the logic remains intact. | import random
from collections import Counter
def basecount(dna):
return sorted(Counter(dna).items())
def seq_split(dna, n=50):
return [dna[i: i+n] for i in range(0, len(dna), n)]
def seq_pp(dna, n=50):
for i, part in enumerate(seq_split(dna, n)):
print(f"{i*n:>5}: {part}")
print("\n BASECOUNT:")
tot = 0
for base, count in basecount(dna):
print(f" {base:>3}: {count}")
tot += count
base, count = 'TOT', tot
print(f" {base:>3}= {count}")
def seq_mutate(dna, count=1, kinds="IDSSSS", choice="ATCG" ):
mutation = []
k2txt = dict(I='Insert', D='Delete', S='Substitute')
for _ in range(count):
kind = random.choice(kinds)
index = random.randint(0, len(dna))
if kind == 'I':
dna = dna[:index] + random.choice(choice) + dna[index:]
elif kind == 'D' and dna:
dna = dna[:index] + dna[index+1:]
elif kind == 'S' and dna:
dna = dna[:index] + random.choice(choice) + dna[index+1:]
mutation.append((k2txt[kind], index))
return dna, mutation
if __name__ == '__main__':
length = 250
print("SEQUENCE:")
sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))
seq_pp(sequence)
print("\n\nMUTATIONS:")
mseq, m = seq_mutate(sequence, 10)
for kind, index in m:
print(f" {kind:>10} @{index}")
print()
seq_pp(mseq)
| #include <array>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>
class sequence_generator {
public:
sequence_generator();
std::string generate_sequence(size_t length);
void mutate_sequence(std::string&);
static void print_sequence(std::ostream&, const std::string&);
enum class operation { change, erase, insert };
void set_weight(operation, unsigned int);
private:
char get_random_base() {
return bases_[base_dist_(engine_)];
}
operation get_random_operation();
static const std::array<char, 4> bases_;
std::mt19937 engine_;
std::uniform_int_distribution<size_t> base_dist_;
std::array<unsigned int, 3> operation_weight_;
unsigned int total_weight_;
};
const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };
sequence_generator::sequence_generator() : engine_(std::random_device()()),
base_dist_(0, bases_.size() - 1),
total_weight_(operation_weight_.size()) {
operation_weight_.fill(1);
}
sequence_generator::operation sequence_generator::get_random_operation() {
std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);
unsigned int n = op_dist(engine_), op = 0, weight = 0;
for (; op < operation_weight_.size(); ++op) {
weight += operation_weight_[op];
if (n < weight)
break;
}
return static_cast<operation>(op);
}
void sequence_generator::set_weight(operation op, unsigned int weight) {
total_weight_ -= operation_weight_[static_cast<size_t>(op)];
operation_weight_[static_cast<size_t>(op)] = weight;
total_weight_ += weight;
}
std::string sequence_generator::generate_sequence(size_t length) {
std::string sequence;
sequence.reserve(length);
for (size_t i = 0; i < length; ++i)
sequence += get_random_base();
return sequence;
}
void sequence_generator::mutate_sequence(std::string& sequence) {
std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);
size_t pos = dist(engine_);
char b;
switch (get_random_operation()) {
case operation::change:
b = get_random_base();
std::cout << "Change base at position " << pos << " from "
<< sequence[pos] << " to " << b << '\n';
sequence[pos] = b;
break;
case operation::erase:
std::cout << "Erase base " << sequence[pos] << " at position "
<< pos << '\n';
sequence.erase(pos, 1);
break;
case operation::insert:
b = get_random_base();
std::cout << "Insert base " << b << " at position "
<< pos << '\n';
sequence.insert(pos, 1, b);
break;
}
}
void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {
constexpr size_t base_count = bases_.size();
std::array<size_t, base_count> count = { 0 };
for (size_t i = 0, n = sequence.length(); i < n; ++i) {
if (i % 50 == 0) {
if (i != 0)
out << '\n';
out << std::setw(3) << i << ": ";
}
out << sequence[i];
for (size_t j = 0; j < base_count; ++j) {
if (bases_[j] == sequence[i]) {
++count[j];
break;
}
}
}
out << '\n';
out << "Base counts:\n";
size_t total = 0;
for (size_t j = 0; j < base_count; ++j) {
total += count[j];
out << bases_[j] << ": " << count[j] << ", ";
}
out << "Total: " << total << '\n';
}
int main() {
sequence_generator gen;
gen.set_weight(sequence_generator::operation::change, 2);
std::string sequence = gen.generate_sequence(250);
std::cout << "Initial sequence:\n";
sequence_generator::print_sequence(std::cout, sequence);
constexpr int count = 10;
for (int i = 0; i < count; ++i)
gen.mutate_sequence(sequence);
std::cout << "After " << count << " mutations:\n";
sequence_generator::print_sequence(std::cout, sequence);
return 0;
}
|
Convert this Python snippet to C++ and keep its semantics consistent. | import random
from collections import Counter
def basecount(dna):
return sorted(Counter(dna).items())
def seq_split(dna, n=50):
return [dna[i: i+n] for i in range(0, len(dna), n)]
def seq_pp(dna, n=50):
for i, part in enumerate(seq_split(dna, n)):
print(f"{i*n:>5}: {part}")
print("\n BASECOUNT:")
tot = 0
for base, count in basecount(dna):
print(f" {base:>3}: {count}")
tot += count
base, count = 'TOT', tot
print(f" {base:>3}= {count}")
def seq_mutate(dna, count=1, kinds="IDSSSS", choice="ATCG" ):
mutation = []
k2txt = dict(I='Insert', D='Delete', S='Substitute')
for _ in range(count):
kind = random.choice(kinds)
index = random.randint(0, len(dna))
if kind == 'I':
dna = dna[:index] + random.choice(choice) + dna[index:]
elif kind == 'D' and dna:
dna = dna[:index] + dna[index+1:]
elif kind == 'S' and dna:
dna = dna[:index] + random.choice(choice) + dna[index+1:]
mutation.append((k2txt[kind], index))
return dna, mutation
if __name__ == '__main__':
length = 250
print("SEQUENCE:")
sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))
seq_pp(sequence)
print("\n\nMUTATIONS:")
mseq, m = seq_mutate(sequence, 10)
for kind, index in m:
print(f" {kind:>10} @{index}")
print()
seq_pp(mseq)
| #include <array>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>
class sequence_generator {
public:
sequence_generator();
std::string generate_sequence(size_t length);
void mutate_sequence(std::string&);
static void print_sequence(std::ostream&, const std::string&);
enum class operation { change, erase, insert };
void set_weight(operation, unsigned int);
private:
char get_random_base() {
return bases_[base_dist_(engine_)];
}
operation get_random_operation();
static const std::array<char, 4> bases_;
std::mt19937 engine_;
std::uniform_int_distribution<size_t> base_dist_;
std::array<unsigned int, 3> operation_weight_;
unsigned int total_weight_;
};
const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };
sequence_generator::sequence_generator() : engine_(std::random_device()()),
base_dist_(0, bases_.size() - 1),
total_weight_(operation_weight_.size()) {
operation_weight_.fill(1);
}
sequence_generator::operation sequence_generator::get_random_operation() {
std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);
unsigned int n = op_dist(engine_), op = 0, weight = 0;
for (; op < operation_weight_.size(); ++op) {
weight += operation_weight_[op];
if (n < weight)
break;
}
return static_cast<operation>(op);
}
void sequence_generator::set_weight(operation op, unsigned int weight) {
total_weight_ -= operation_weight_[static_cast<size_t>(op)];
operation_weight_[static_cast<size_t>(op)] = weight;
total_weight_ += weight;
}
std::string sequence_generator::generate_sequence(size_t length) {
std::string sequence;
sequence.reserve(length);
for (size_t i = 0; i < length; ++i)
sequence += get_random_base();
return sequence;
}
void sequence_generator::mutate_sequence(std::string& sequence) {
std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);
size_t pos = dist(engine_);
char b;
switch (get_random_operation()) {
case operation::change:
b = get_random_base();
std::cout << "Change base at position " << pos << " from "
<< sequence[pos] << " to " << b << '\n';
sequence[pos] = b;
break;
case operation::erase:
std::cout << "Erase base " << sequence[pos] << " at position "
<< pos << '\n';
sequence.erase(pos, 1);
break;
case operation::insert:
b = get_random_base();
std::cout << "Insert base " << b << " at position "
<< pos << '\n';
sequence.insert(pos, 1, b);
break;
}
}
void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {
constexpr size_t base_count = bases_.size();
std::array<size_t, base_count> count = { 0 };
for (size_t i = 0, n = sequence.length(); i < n; ++i) {
if (i % 50 == 0) {
if (i != 0)
out << '\n';
out << std::setw(3) << i << ": ";
}
out << sequence[i];
for (size_t j = 0; j < base_count; ++j) {
if (bases_[j] == sequence[i]) {
++count[j];
break;
}
}
}
out << '\n';
out << "Base counts:\n";
size_t total = 0;
for (size_t j = 0; j < base_count; ++j) {
total += count[j];
out << bases_[j] << ": " << count[j] << ", ";
}
out << "Total: " << total << '\n';
}
int main() {
sequence_generator gen;
gen.set_weight(sequence_generator::operation::change, 2);
std::string sequence = gen.generate_sequence(250);
std::cout << "Initial sequence:\n";
sequence_generator::print_sequence(std::cout, sequence);
constexpr int count = 10;
for (int i = 0; i < count; ++i)
gen.mutate_sequence(sequence);
std::cout << "After " << count << " mutations:\n";
sequence_generator::print_sequence(std::cout, sequence);
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original Python snippet. | def tau(n):
assert(isinstance(n, int) and 0 < n)
ans, i, j = 0, 1, 1
while i*i <= n:
if 0 == n%i:
ans += 1
j = n//i
if j != i:
ans += 1
i += 1
return ans
def is_tau_number(n):
assert(isinstance(n, int))
if n <= 0:
return False
return 0 == n%tau(n)
if __name__ == "__main__":
n = 1
ans = []
while len(ans) < 100:
if is_tau_number(n):
ans.append(n)
n += 1
print(ans)
| #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "The first " << limit << " tau numbers are:\n";
unsigned int count = 0;
for (unsigned int n = 1; count < limit; ++n) {
if (n % divisor_count(n) == 0) {
std::cout << std::setw(6) << n;
++count;
if (count % 10 == 0)
std::cout << '\n';
}
}
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | from itertools import permutations
from operator import mul
from math import fsum
from spermutations import spermutations
def prod(lst):
return reduce(mul, lst, 1)
def perm(a):
n = len(a)
r = range(n)
s = permutations(r)
return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)
def det(a):
n = len(a)
r = range(n)
s = spermutations(n)
return fsum(sign * prod(a[i][sigma[i]] for i in r)
for sigma, sign in s)
if __name__ == '__main__':
from pprint import pprint as pp
for a in (
[
[1, 2],
[3, 4]],
[
[1, 2, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 10],
[10, 11, 12, 13]],
[
[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]],
):
print('')
pp(a)
print('Perm: %s Det: %s' % (perm(a), det(a)))
| #include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
using Matrix = std::vector<std::vector<double>>;
Matrix squareMatrix(size_t n) {
Matrix m;
for (size_t i = 0; i < n; i++) {
std::vector<double> inner;
for (size_t j = 0; j < n; j++) {
inner.push_back(nan(""));
}
m.push_back(inner);
}
return m;
}
Matrix minor(const Matrix &a, int x, int y) {
auto length = a.size() - 1;
auto result = squareMatrix(length);
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
if (i < x && j < y) {
result[i][j] = a[i][j];
} else if (i >= x && j < y) {
result[i][j] = a[i + 1][j];
} else if (i < x && j >= y) {
result[i][j] = a[i][j + 1];
} else {
result[i][j] = a[i + 1][j + 1];
}
}
}
return result;
}
double det(const Matrix &a) {
if (a.size() == 1) {
return a[0][0];
}
int sign = 1;
double sum = 0;
for (size_t i = 0; i < a.size(); i++) {
sum += sign * a[0][i] * det(minor(a, 0, i));
sign *= -1;
}
return sum;
}
double perm(const Matrix &a) {
if (a.size() == 1) {
return a[0][0];
}
double sum = 0;
for (size_t i = 0; i < a.size(); i++) {
sum += a[0][i] * perm(minor(a, 0, i));
}
return sum;
}
void test(const Matrix &m) {
auto p = perm(m);
auto d = det(m);
std::cout << m << '\n';
std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n";
}
int main() {
test({ {1, 2}, {3, 4} });
test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });
test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });
return 0;
}
|
Write the same algorithm in C++ as shown in this Python implementation. | from itertools import permutations
from operator import mul
from math import fsum
from spermutations import spermutations
def prod(lst):
return reduce(mul, lst, 1)
def perm(a):
n = len(a)
r = range(n)
s = permutations(r)
return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)
def det(a):
n = len(a)
r = range(n)
s = spermutations(n)
return fsum(sign * prod(a[i][sigma[i]] for i in r)
for sigma, sign in s)
if __name__ == '__main__':
from pprint import pprint as pp
for a in (
[
[1, 2],
[3, 4]],
[
[1, 2, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 10],
[10, 11, 12, 13]],
[
[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]],
):
print('')
pp(a)
print('Perm: %s Det: %s' % (perm(a), det(a)))
| #include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
using Matrix = std::vector<std::vector<double>>;
Matrix squareMatrix(size_t n) {
Matrix m;
for (size_t i = 0; i < n; i++) {
std::vector<double> inner;
for (size_t j = 0; j < n; j++) {
inner.push_back(nan(""));
}
m.push_back(inner);
}
return m;
}
Matrix minor(const Matrix &a, int x, int y) {
auto length = a.size() - 1;
auto result = squareMatrix(length);
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
if (i < x && j < y) {
result[i][j] = a[i][j];
} else if (i >= x && j < y) {
result[i][j] = a[i + 1][j];
} else if (i < x && j >= y) {
result[i][j] = a[i][j + 1];
} else {
result[i][j] = a[i + 1][j + 1];
}
}
}
return result;
}
double det(const Matrix &a) {
if (a.size() == 1) {
return a[0][0];
}
int sign = 1;
double sum = 0;
for (size_t i = 0; i < a.size(); i++) {
sum += sign * a[0][i] * det(minor(a, 0, i));
sign *= -1;
}
return sum;
}
double perm(const Matrix &a) {
if (a.size() == 1) {
return a[0][0];
}
double sum = 0;
for (size_t i = 0; i < a.size(); i++) {
sum += a[0][i] * perm(minor(a, 0, i));
}
return sum;
}
void test(const Matrix &m) {
auto p = perm(m);
auto d = det(m);
std::cout << m << '\n';
std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n";
}
int main() {
test({ {1, 2}, {3, 4} });
test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });
test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} });
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | from itertools import islice
def posd():
"diff between position numbers. 1, 2, 3... interleaved with 3, 5, 7..."
count, odd = 1, 3
while True:
yield count
yield odd
count, odd = count + 1, odd + 2
def pos_gen():
"position numbers. 1 3 2 5 7 4 9 ..."
val = 1
diff = posd()
while True:
yield val
val += next(diff)
def plus_minus():
"yield (list_offset, sign) or zero for Partition calc"
n, sign = 0, [1, 1]
p_gen = pos_gen()
out_on = next(p_gen)
while True:
n += 1
if n == out_on:
next_sign = sign.pop(0)
if not sign:
sign = [-next_sign] * 2
yield -n, next_sign
out_on = next(p_gen)
else:
yield 0
def part(n):
"Partition numbers"
p = [1]
p_m = plus_minus()
mods = []
for _ in range(n):
next_plus_minus = next(p_m)
if next_plus_minus:
mods.append(next_plus_minus)
p.append(sum(p[offset] * sign for offset, sign in mods))
return p[-1]
print("(Intermediaries):")
print(" posd:", list(islice(posd(), 10)))
print(" pos_gen:", list(islice(pos_gen(), 10)))
print(" plus_minus:", list(islice(plus_minus(), 15)))
print("\nPartitions:", [part(x) for x in range(15)])
| #include <chrono>
#include <iostream>
#include <vector>
#include <gmpxx.h>
using big_int = mpz_class;
big_int partitions(int n) {
std::vector<big_int> p(n + 1);
p[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int k = 1;; ++k) {
int j = (k * (3*k - 1))/2;
if (j > i)
break;
if (k & 1)
p[i] += p[i - j];
else
p[i] -= p[i - j];
j = (k * (3*k + 1))/2;
if (j > i)
break;
if (k & 1)
p[i] += p[i - j];
else
p[i] -= p[i - j];
}
}
return p[n];
}
int main() {
auto start = std::chrono::steady_clock::now();
auto result = partitions(6666);
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double, std::milli> ms(end - start);
std::cout << result << '\n';
std::cout << "elapsed time: " << ms.count() << " milliseconds\n";
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? |
from io import StringIO
from collections import namedtuple
from pprint import pprint as pp
import copy
WW = namedtuple('WW', 'world, w, h')
head, tail, conductor, empty = allstates = 'Ht. '
infile = StringIO()
def readfile(f):
world = [row.rstrip('\r\n') for row in f]
height = len(world)
width = max(len(row) for row in world)
nonrow = [ " %*s " % (-width, "") ]
world = nonrow + \
[ " %*s " % (-width, row) for row in world ] + \
nonrow
world = [list(row) for row in world]
return WW(world, width, height)
def newcell(currentworld, x, y):
istate = currentworld[y][x]
assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate
if istate == head:
ostate = tail
elif istate == tail:
ostate = conductor
elif istate == empty:
ostate = empty
else:
n = sum( currentworld[y+dy][x+dx] == head
for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),
(+0,-1), (+0,+1),
(+1,-1), (+1,+0), (+1,+1) ) )
ostate = head if 1 <= n <= 2 else conductor
return ostate
def nextgen(ww):
'compute next generation of wireworld'
world, width, height = ww
newworld = copy.deepcopy(world)
for x in range(1, width+1):
for y in range(1, height+1):
newworld[y][x] = newcell(world, x, y)
return WW(newworld, width, height)
def world2string(ww):
return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )
ww = readfile(infile)
infile.close()
for gen in range(10):
print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' )
print ( world2string(ww) )
ww = nextgen(ww)
| #include <ggi/ggi.h>
#include <set>
#include <map>
#include <utility>
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
enum cell_type { none, wire, head, tail };
class display
{
public:
display(int sizex, int sizey, int pixsizex, int pixsizey,
ggi_color* colors);
~display()
{
ggiClose(visual);
ggiExit();
}
void flush();
bool keypressed() { return ggiKbhit(visual); }
void clear();
void putpixel(int x, int y, cell_type c);
private:
ggi_visual_t visual;
int size_x, size_y;
int pixel_size_x, pixel_size_y;
ggi_pixel pixels[4];
};
display::display(int sizex, int sizey, int pixsizex, int pixsizey,
ggi_color* colors):
pixel_size_x(pixsizex),
pixel_size_y(pixsizey)
{
if (ggiInit() < 0)
{
std::cerr << "couldn't open ggi\n";
exit(1);
}
visual = ggiOpen(NULL);
if (!visual)
{
ggiPanic("couldn't open visual\n");
}
ggi_mode mode;
if (ggiCheckGraphMode(visual, sizex, sizey,
GGI_AUTO, GGI_AUTO, GT_4BIT,
&mode) != 0)
{
if (GT_DEPTH(mode.graphtype) < 2)
ggiPanic("low-color displays are not supported!\n");
}
if (ggiSetMode(visual, &mode) != 0)
{
ggiPanic("couldn't set graph mode\n");
}
ggiAddFlags(visual, GGIFLAG_ASYNC);
size_x = mode.virt.x;
size_y = mode.virt.y;
for (int i = 0; i < 4; ++i)
pixels[i] = ggiMapColor(visual, colors+i);
}
void display::flush()
{
ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));
ggiFlush(visual);
ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual));
}
void display::clear()
{
ggiSetGCForeground(visual, pixels[0]);
ggiDrawBox(visual, 0, 0, size_x, size_y);
}
void display::putpixel(int x, int y, cell_type cell)
{
ggiSetGCForeground(visual, pixels[cell]);
ggiDrawBox(visual,
x*pixel_size_x, y*pixel_size_y,
pixel_size_x, pixel_size_y);
}
class wireworld
{
public:
void set(int posx, int posy, cell_type type);
void draw(display& destination);
void step();
private:
typedef std::pair<int, int> position;
typedef std::set<position> position_set;
typedef position_set::iterator positer;
position_set wires, heads, tails;
};
void wireworld::set(int posx, int posy, cell_type type)
{
position p(posx, posy);
wires.erase(p);
heads.erase(p);
tails.erase(p);
switch(type)
{
case head:
heads.insert(p);
break;
case tail:
tails.insert(p);
break;
case wire:
wires.insert(p);
break;
}
}
void wireworld::draw(display& destination)
{
destination.clear();
for (positer i = heads.begin(); i != heads.end(); ++i)
destination.putpixel(i->first, i->second, head);
for (positer i = tails.begin(); i != tails.end(); ++i)
destination.putpixel(i->first, i->second, tail);
for (positer i = wires.begin(); i != wires.end(); ++i)
destination.putpixel(i->first, i->second, wire);
destination.flush();
}
void wireworld::step()
{
std::map<position, int> new_heads;
for (positer i = heads.begin(); i != heads.end(); ++i)
for (int dx = -1; dx <= 1; ++dx)
for (int dy = -1; dy <= 1; ++dy)
{
position pos(i->first + dx, i->second + dy);
if (wires.count(pos))
new_heads[pos]++;
}
wires.insert(tails.begin(), tails.end());
tails.swap(heads);
heads.clear();
for (std::map<position, int>::iterator i = new_heads.begin();
i != new_heads.end();
++i)
{
if (i->second < 3)
{
wires.erase(i->first);
heads.insert(i->first);
}
}
}
ggi_color colors[4] =
{{ 0x0000, 0x0000, 0x0000 },
{ 0x8000, 0x8000, 0x8000 },
{ 0xffff, 0xffff, 0x0000 },
{ 0xffff, 0x0000, 0x0000 }};
int main(int argc, char* argv[])
{
int display_x = 800;
int display_y = 600;
int pixel_x = 5;
int pixel_y = 5;
if (argc < 2)
{
std::cerr << "No file name given!\n";
return 1;
}
std::ifstream f(argv[1]);
wireworld w;
std::string line;
int line_number = 0;
while (std::getline(f, line))
{
for (int col = 0; col < line.size(); ++col)
{
switch (line[col])
{
case 'h': case 'H':
w.set(col, line_number, head);
break;
case 't': case 'T':
w.set(col, line_number, tail);
break;
case 'w': case 'W': case '.':
w.set(col, line_number, wire);
break;
default:
std::cerr << "unrecognized character: " << line[col] << "\n";
return 1;
case ' ':
;
}
}
++line_number;
}
display d(display_x, display_y, pixel_x, pixel_y, colors);
w.draw(d);
while (!d.keypressed())
{
usleep(100000);
w.step();
w.draw(d);
}
std::cout << std::endl;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. |
from io import StringIO
from collections import namedtuple
from pprint import pprint as pp
import copy
WW = namedtuple('WW', 'world, w, h')
head, tail, conductor, empty = allstates = 'Ht. '
infile = StringIO()
def readfile(f):
world = [row.rstrip('\r\n') for row in f]
height = len(world)
width = max(len(row) for row in world)
nonrow = [ " %*s " % (-width, "") ]
world = nonrow + \
[ " %*s " % (-width, row) for row in world ] + \
nonrow
world = [list(row) for row in world]
return WW(world, width, height)
def newcell(currentworld, x, y):
istate = currentworld[y][x]
assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate
if istate == head:
ostate = tail
elif istate == tail:
ostate = conductor
elif istate == empty:
ostate = empty
else:
n = sum( currentworld[y+dy][x+dx] == head
for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),
(+0,-1), (+0,+1),
(+1,-1), (+1,+0), (+1,+1) ) )
ostate = head if 1 <= n <= 2 else conductor
return ostate
def nextgen(ww):
'compute next generation of wireworld'
world, width, height = ww
newworld = copy.deepcopy(world)
for x in range(1, width+1):
for y in range(1, height+1):
newworld[y][x] = newcell(world, x, y)
return WW(newworld, width, height)
def world2string(ww):
return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )
ww = readfile(infile)
infile.close()
for gen in range(10):
print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' )
print ( world2string(ww) )
ww = nextgen(ww)
| #include <ggi/ggi.h>
#include <set>
#include <map>
#include <utility>
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
enum cell_type { none, wire, head, tail };
class display
{
public:
display(int sizex, int sizey, int pixsizex, int pixsizey,
ggi_color* colors);
~display()
{
ggiClose(visual);
ggiExit();
}
void flush();
bool keypressed() { return ggiKbhit(visual); }
void clear();
void putpixel(int x, int y, cell_type c);
private:
ggi_visual_t visual;
int size_x, size_y;
int pixel_size_x, pixel_size_y;
ggi_pixel pixels[4];
};
display::display(int sizex, int sizey, int pixsizex, int pixsizey,
ggi_color* colors):
pixel_size_x(pixsizex),
pixel_size_y(pixsizey)
{
if (ggiInit() < 0)
{
std::cerr << "couldn't open ggi\n";
exit(1);
}
visual = ggiOpen(NULL);
if (!visual)
{
ggiPanic("couldn't open visual\n");
}
ggi_mode mode;
if (ggiCheckGraphMode(visual, sizex, sizey,
GGI_AUTO, GGI_AUTO, GT_4BIT,
&mode) != 0)
{
if (GT_DEPTH(mode.graphtype) < 2)
ggiPanic("low-color displays are not supported!\n");
}
if (ggiSetMode(visual, &mode) != 0)
{
ggiPanic("couldn't set graph mode\n");
}
ggiAddFlags(visual, GGIFLAG_ASYNC);
size_x = mode.virt.x;
size_y = mode.virt.y;
for (int i = 0; i < 4; ++i)
pixels[i] = ggiMapColor(visual, colors+i);
}
void display::flush()
{
ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));
ggiFlush(visual);
ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual));
}
void display::clear()
{
ggiSetGCForeground(visual, pixels[0]);
ggiDrawBox(visual, 0, 0, size_x, size_y);
}
void display::putpixel(int x, int y, cell_type cell)
{
ggiSetGCForeground(visual, pixels[cell]);
ggiDrawBox(visual,
x*pixel_size_x, y*pixel_size_y,
pixel_size_x, pixel_size_y);
}
class wireworld
{
public:
void set(int posx, int posy, cell_type type);
void draw(display& destination);
void step();
private:
typedef std::pair<int, int> position;
typedef std::set<position> position_set;
typedef position_set::iterator positer;
position_set wires, heads, tails;
};
void wireworld::set(int posx, int posy, cell_type type)
{
position p(posx, posy);
wires.erase(p);
heads.erase(p);
tails.erase(p);
switch(type)
{
case head:
heads.insert(p);
break;
case tail:
tails.insert(p);
break;
case wire:
wires.insert(p);
break;
}
}
void wireworld::draw(display& destination)
{
destination.clear();
for (positer i = heads.begin(); i != heads.end(); ++i)
destination.putpixel(i->first, i->second, head);
for (positer i = tails.begin(); i != tails.end(); ++i)
destination.putpixel(i->first, i->second, tail);
for (positer i = wires.begin(); i != wires.end(); ++i)
destination.putpixel(i->first, i->second, wire);
destination.flush();
}
void wireworld::step()
{
std::map<position, int> new_heads;
for (positer i = heads.begin(); i != heads.end(); ++i)
for (int dx = -1; dx <= 1; ++dx)
for (int dy = -1; dy <= 1; ++dy)
{
position pos(i->first + dx, i->second + dy);
if (wires.count(pos))
new_heads[pos]++;
}
wires.insert(tails.begin(), tails.end());
tails.swap(heads);
heads.clear();
for (std::map<position, int>::iterator i = new_heads.begin();
i != new_heads.end();
++i)
{
if (i->second < 3)
{
wires.erase(i->first);
heads.insert(i->first);
}
}
}
ggi_color colors[4] =
{{ 0x0000, 0x0000, 0x0000 },
{ 0x8000, 0x8000, 0x8000 },
{ 0xffff, 0xffff, 0x0000 },
{ 0xffff, 0x0000, 0x0000 }};
int main(int argc, char* argv[])
{
int display_x = 800;
int display_y = 600;
int pixel_x = 5;
int pixel_y = 5;
if (argc < 2)
{
std::cerr << "No file name given!\n";
return 1;
}
std::ifstream f(argv[1]);
wireworld w;
std::string line;
int line_number = 0;
while (std::getline(f, line))
{
for (int col = 0; col < line.size(); ++col)
{
switch (line[col])
{
case 'h': case 'H':
w.set(col, line_number, head);
break;
case 't': case 'T':
w.set(col, line_number, tail);
break;
case 'w': case 'W': case '.':
w.set(col, line_number, wire);
break;
default:
std::cerr << "unrecognized character: " << line[col] << "\n";
return 1;
case ' ':
;
}
}
++line_number;
}
display d(display_x, display_y, pixel_x, pixel_y, colors);
w.draw(d);
while (!d.keypressed())
{
usleep(100000);
w.step();
w.draw(d);
}
std::cout << std::endl;
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | from collections import namedtuple
from pprint import pprint as pp
import sys
Pt = namedtuple('Pt', 'x, y')
Edge = namedtuple('Edge', 'a, b')
Poly = namedtuple('Poly', 'name, edges')
_eps = 0.00001
_huge = sys.float_info.max
_tiny = sys.float_info.min
def rayintersectseg(p, edge):
a,b = edge
if a.y > b.y:
a,b = b,a
if p.y == a.y or p.y == b.y:
p = Pt(p.x, p.y + _eps)
intersect = False
if (p.y > b.y or p.y < a.y) or (
p.x > max(a.x, b.x)):
return False
if p.x < min(a.x, b.x):
intersect = True
else:
if abs(a.x - b.x) > _tiny:
m_red = (b.y - a.y) / float(b.x - a.x)
else:
m_red = _huge
if abs(a.x - p.x) > _tiny:
m_blue = (p.y - a.y) / float(p.x - a.x)
else:
m_blue = _huge
intersect = m_blue >= m_red
return intersect
def _odd(x): return x%2 == 1
def ispointinside(p, poly):
ln = len(poly)
return _odd(sum(rayintersectseg(p, edge)
for edge in poly.edges ))
def polypp(poly):
print ("\n Polygon(name='%s', edges=(" % poly.name)
print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))')
if __name__ == '__main__':
polys = [
Poly(name='square', edges=(
Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),
Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),
Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),
Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0))
)),
Poly(name='square_hole', edges=(
Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)),
Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)),
Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)),
Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)),
Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)),
Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)),
Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)),
Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5))
)),
Poly(name='strange', edges=(
Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)),
Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)),
Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)),
Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)),
Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)),
Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)),
Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5))
)),
Poly(name='exagon', edges=(
Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)),
Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)),
Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)),
Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)),
Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)),
Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0))
)),
]
testpoints = (Pt(x=5, y=5), Pt(x=5, y=8),
Pt(x=-10, y=5), Pt(x=0, y=5),
Pt(x=10, y=5), Pt(x=8, y=5),
Pt(x=10, y=10))
print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS")
for poly in polys:
polypp(poly)
print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly))
for p in testpoints[:3]))
print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly))
for p in testpoints[3:6]))
print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly))
for p in testpoints[6:]))
| #include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
using namespace std;
const double epsilon = numeric_limits<float>().epsilon();
const numeric_limits<double> DOUBLE;
const double MIN = DOUBLE.min();
const double MAX = DOUBLE.max();
struct Point { const double x, y; };
struct Edge {
const Point a, b;
bool operator()(const Point& p) const
{
if (a.y > b.y) return Edge{ b, a }(p);
if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon });
if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false;
if (p.x < min(a.x, b.x)) return true;
auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX;
auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX;
return blue >= red;
}
};
struct Figure {
const string name;
const initializer_list<Edge> edges;
bool contains(const Point& p) const
{
auto c = 0;
for (auto e : edges) if (e(p)) c++;
return c % 2 != 0;
}
template<unsigned char W = 3>
void check(const initializer_list<Point>& points, ostream& os) const
{
os << "Is point inside figure " << name << '?' << endl;
for (auto p : points)
os << " (" << setw(W) << p.x << ',' << setw(W) << p.y << "): " << boolalpha << contains(p) << endl;
os << endl;
}
};
int main()
{
const initializer_list<Point> points = { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} };
const Figure square = { "Square",
{ {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} }
};
const Figure square_hole = { "Square hole",
{ {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}},
{{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}}
}
};
const Figure strange = { "Strange",
{ {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}},
{{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}}
}
};
const Figure exagon = { "Exagon",
{ {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}},
{{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}}
}
};
for(auto f : {square, square_hole, strange, exagon})
f.check(points, cout);
return EXIT_SUCCESS;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. |
class Point:
b = 7
def __init__(self, x=float('inf'), y=float('inf')):
self.x = x
self.y = y
def copy(self):
return Point(self.x, self.y)
def is_zero(self):
return self.x > 1e20 or self.x < -1e20
def neg(self):
return Point(self.x, -self.y)
def dbl(self):
if self.is_zero():
return self.copy()
try:
L = (3 * self.x * self.x) / (2 * self.y)
except ZeroDivisionError:
return Point()
x = L * L - 2 * self.x
return Point(x, L * (self.x - x) - self.y)
def add(self, q):
if self.x == q.x and self.y == q.y:
return self.dbl()
if self.is_zero():
return q.copy()
if q.is_zero():
return self.copy()
try:
L = (q.y - self.y) / (q.x - self.x)
except ZeroDivisionError:
return Point()
x = L * L - self.x - q.x
return Point(x, L * (self.x - x) - self.y)
def mul(self, n):
p = self.copy()
r = Point()
i = 1
while i <= n:
if i&n:
r = r.add(p)
p = p.dbl()
i <<= 1
return r
def __str__(self):
return "({:.3f}, {:.3f})".format(self.x, self.y)
def show(s, p):
print(s, "Zero" if p.is_zero() else p)
def from_y(y):
n = y * y - Point.b
x = n**(1./3) if n>=0 else -((-n)**(1./3))
return Point(x, y)
a = from_y(1)
b = from_y(2)
show("a =", a)
show("b =", b)
c = a.add(b)
show("c = a + b =", c)
d = c.neg()
show("d = -c =", d)
show("c + d =", c.add(d))
show("a + b + d =", a.add(b.add(d)))
show("a * 12345 =", a.mul(12345))
| #include <cmath>
#include <iostream>
using namespace std;
class EllipticPoint
{
double m_x, m_y;
static constexpr double ZeroThreshold = 1e20;
static constexpr double B = 7;
void Double() noexcept
{
if(IsZero())
{
return;
}
if(m_y == 0)
{
*this = EllipticPoint();
}
else
{
double L = (3 * m_x * m_x) / (2 * m_y);
double newX = L * L - 2 * m_x;
m_y = L * (m_x - newX) - m_y;
m_x = newX;
}
}
public:
friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);
constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}
explicit EllipticPoint(double yCoordinate) noexcept
{
m_y = yCoordinate;
m_x = cbrt(m_y * m_y - B);
}
bool IsZero() const noexcept
{
bool isNotZero = abs(m_y) < ZeroThreshold;
return !isNotZero;
}
EllipticPoint operator-() const noexcept
{
EllipticPoint negPt;
negPt.m_x = m_x;
negPt.m_y = -m_y;
return negPt;
}
EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept
{
if(IsZero())
{
*this = rhs;
}
else if (rhs.IsZero())
{
}
else
{
double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);
if(isfinite(L))
{
double newX = L * L - m_x - rhs.m_x;
m_y = L * (m_x - newX) - m_y;
m_x = newX;
}
else
{
if(signbit(m_y) != signbit(rhs.m_y))
{
*this = EllipticPoint();
}
else
{
Double();
}
}
}
return *this;
}
EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept
{
*this+= -rhs;
return *this;
}
EllipticPoint& operator*=(int rhs) noexcept
{
EllipticPoint r;
EllipticPoint p = *this;
if(rhs < 0)
{
rhs = -rhs;
p = -p;
}
for (int i = 1; i <= rhs; i <<= 1)
{
if (i & rhs) r += p;
p.Double();
}
*this = r;
return *this;
}
};
inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept
{
lhs += rhs;
return lhs;
}
inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept
{
lhs += -rhs;
return lhs;
}
inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept
{
lhs *= rhs;
return lhs;
}
inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept
{
rhs *= lhs;
return rhs;
}
ostream& operator<<(ostream& os, const EllipticPoint& pt)
{
if(pt.IsZero()) cout << "(Zero)\n";
else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n";
return os;
}
int main(void) {
const EllipticPoint a(1), b(2);
cout << "a = " << a;
cout << "b = " << b;
const EllipticPoint c = a + b;
cout << "c = a + b = " << c;
cout << "a + b - c = " << a + b - c;
cout << "a + b - (b + a) = " << a + b - (b + a) << "\n";
cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a;
cout << "a * 12345 = " << a * 12345;
cout << "a * -12345 = " << a * -12345;
cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345;
cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345);
cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n";
const EllipticPoint zero;
EllipticPoint g;
cout << "g = zero = " << g;
cout << "g += a = " << (g+=a);
cout << "g += zero = " << (g+=zero);
cout << "g += b = " << (g+=b);
cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n";
EllipticPoint special(0);
cout << "special = " << special;
cout << "special *= 2 = " << (special*=2);
return 0;
}
|
Write the same algorithm in C++ as shown in this Python implementation. |
class Point:
b = 7
def __init__(self, x=float('inf'), y=float('inf')):
self.x = x
self.y = y
def copy(self):
return Point(self.x, self.y)
def is_zero(self):
return self.x > 1e20 or self.x < -1e20
def neg(self):
return Point(self.x, -self.y)
def dbl(self):
if self.is_zero():
return self.copy()
try:
L = (3 * self.x * self.x) / (2 * self.y)
except ZeroDivisionError:
return Point()
x = L * L - 2 * self.x
return Point(x, L * (self.x - x) - self.y)
def add(self, q):
if self.x == q.x and self.y == q.y:
return self.dbl()
if self.is_zero():
return q.copy()
if q.is_zero():
return self.copy()
try:
L = (q.y - self.y) / (q.x - self.x)
except ZeroDivisionError:
return Point()
x = L * L - self.x - q.x
return Point(x, L * (self.x - x) - self.y)
def mul(self, n):
p = self.copy()
r = Point()
i = 1
while i <= n:
if i&n:
r = r.add(p)
p = p.dbl()
i <<= 1
return r
def __str__(self):
return "({:.3f}, {:.3f})".format(self.x, self.y)
def show(s, p):
print(s, "Zero" if p.is_zero() else p)
def from_y(y):
n = y * y - Point.b
x = n**(1./3) if n>=0 else -((-n)**(1./3))
return Point(x, y)
a = from_y(1)
b = from_y(2)
show("a =", a)
show("b =", b)
c = a.add(b)
show("c = a + b =", c)
d = c.neg()
show("d = -c =", d)
show("c + d =", c.add(d))
show("a + b + d =", a.add(b.add(d)))
show("a * 12345 =", a.mul(12345))
| #include <cmath>
#include <iostream>
using namespace std;
class EllipticPoint
{
double m_x, m_y;
static constexpr double ZeroThreshold = 1e20;
static constexpr double B = 7;
void Double() noexcept
{
if(IsZero())
{
return;
}
if(m_y == 0)
{
*this = EllipticPoint();
}
else
{
double L = (3 * m_x * m_x) / (2 * m_y);
double newX = L * L - 2 * m_x;
m_y = L * (m_x - newX) - m_y;
m_x = newX;
}
}
public:
friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);
constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}
explicit EllipticPoint(double yCoordinate) noexcept
{
m_y = yCoordinate;
m_x = cbrt(m_y * m_y - B);
}
bool IsZero() const noexcept
{
bool isNotZero = abs(m_y) < ZeroThreshold;
return !isNotZero;
}
EllipticPoint operator-() const noexcept
{
EllipticPoint negPt;
negPt.m_x = m_x;
negPt.m_y = -m_y;
return negPt;
}
EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept
{
if(IsZero())
{
*this = rhs;
}
else if (rhs.IsZero())
{
}
else
{
double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);
if(isfinite(L))
{
double newX = L * L - m_x - rhs.m_x;
m_y = L * (m_x - newX) - m_y;
m_x = newX;
}
else
{
if(signbit(m_y) != signbit(rhs.m_y))
{
*this = EllipticPoint();
}
else
{
Double();
}
}
}
return *this;
}
EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept
{
*this+= -rhs;
return *this;
}
EllipticPoint& operator*=(int rhs) noexcept
{
EllipticPoint r;
EllipticPoint p = *this;
if(rhs < 0)
{
rhs = -rhs;
p = -p;
}
for (int i = 1; i <= rhs; i <<= 1)
{
if (i & rhs) r += p;
p.Double();
}
*this = r;
return *this;
}
};
inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept
{
lhs += rhs;
return lhs;
}
inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept
{
lhs += -rhs;
return lhs;
}
inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept
{
lhs *= rhs;
return lhs;
}
inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept
{
rhs *= lhs;
return rhs;
}
ostream& operator<<(ostream& os, const EllipticPoint& pt)
{
if(pt.IsZero()) cout << "(Zero)\n";
else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n";
return os;
}
int main(void) {
const EllipticPoint a(1), b(2);
cout << "a = " << a;
cout << "b = " << b;
const EllipticPoint c = a + b;
cout << "c = a + b = " << c;
cout << "a + b - c = " << a + b - c;
cout << "a + b - (b + a) = " << a + b - (b + a) << "\n";
cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a;
cout << "a * 12345 = " << a * 12345;
cout << "a * -12345 = " << a * -12345;
cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345;
cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345);
cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n";
const EllipticPoint zero;
EllipticPoint g;
cout << "g = zero = " << g;
cout << "g += a = " << (g+=a);
cout << "g += zero = " << (g+=zero);
cout << "g += b = " << (g+=b);
cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n";
EllipticPoint special(0);
cout << "special = " << special;
cout << "special *= 2 = " << (special*=2);
return 0;
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | >>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2
| #include <iostream>
#include <string>
int countSubstring(const std::string& str, const std::string& sub)
{
if (sub.length() == 0) return 0;
int count = 0;
for (size_t offset = str.find(sub); offset != std::string::npos;
offset = str.find(sub, offset + sub.length()))
{
++count;
}
return count;
}
int main()
{
std::cout << countSubstring("the three truths", "th") << '\n';
std::cout << countSubstring("ababababab", "abab") << '\n';
std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n';
return 0;
}
|
Please provide an equivalent version of this Python code in C++. | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| #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; }
|
Preserve the algorithm and functionality while converting the code from Python to C++. | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| #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; }
|
Ensure the translated C++ code behaves exactly like the original Python snippet. | fun compare(a, b):
print("\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}")
if a < b: print("$a is strictly less than $b")
if a <= b: print("$a is less than or equal to $b")
if a > b: print("$a is strictly greater than $b")
if a >= b: print("$a is greater than or equal to $b")
if a == b: print("$a is equal to $b")
if a != b: print("$a is not equal to $b")
if a is b: print("$a has object identity with $b")
if a is not b: print("$a has negated object identity with $b")
compare("YUP", "YUP")
compare('a', 'z')
compare("24", "123")
compare(24, 123)
compare(5.0, 5)
| #include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
template <typename T>
void demo_compare(const T &a, const T &b, const std::string &semantically) {
std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ")
<< "exactly " << semantically << " equal." << std::endl;
std::cout << a << " and " << b << " are " << ((a != b) ? "" : "not ")
<< semantically << "inequal." << std::endl;
std::cout << a << " is " << ((a < b) ? "" : "not ") << semantically
<< " ordered before " << b << '.' << std::endl;
std::cout << a << " is " << ((a > b) ? "" : "not ") << semantically
<< " ordered after " << b << '.' << std::endl;
}
int main(int argc, char *argv[]) {
std::string a((argc > 1) ? argv[1] : "1.2.Foo");
std::string b((argc > 2) ? argv[2] : "1.3.Bar");
demo_compare<std::string>(a, b, "lexically");
std::transform(a.begin(), a.end(), a.begin(), ::tolower);
std::transform(b.begin(), b.end(), b.begin(), ::tolower);
demo_compare<std::string>(a, b, "lexically");
double numA, numB;
std::istringstream(a) >> numA;
std::istringstream(b) >> numB;
demo_compare<double>(numA, numB, "numerically");
return (a == b);
}
|
Generate a C++ translation of this Python snippet without changing its computational steps. | import sys, datetime, shutil
if len(sys.argv) == 1:
try:
with open('notes.txt', 'r') as f:
shutil.copyfileobj(f, sys.stdout)
except IOError:
pass
else:
with open('notes.txt', 'a') as f:
f.write(datetime.datetime.now().isoformat() + '\n')
f.write("\t%s\n" % ' '.join(sys.argv[1:]))
| #include <fstream>
#include <iostream>
#include <ctime>
using namespace std;
#define note_file "NOTES.TXT"
int main(int argc, char **argv)
{
if(argc>1)
{
ofstream Notes(note_file, ios::app);
time_t timer = time(NULL);
if(Notes.is_open())
{
Notes << asctime(localtime(&timer)) << '\t';
for(int i=1;i<argc;i++)
Notes << argv[i] << ' ';
Notes << endl;
Notes.close();
}
}
else
{
ifstream Notes(note_file, ios::in);
string line;
if(Notes.is_open())
{
while(!Notes.eof())
{
getline(Notes, line);
cout << line << endl;
}
Notes.close();
}
}
}
|
Port the provided Python code into C++ while preserving the original functionality. |
import math
def thieleInterpolator(x, y):
ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]
for i in range(len(ρ)-1):
ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])
for i in range(2, len(ρ)):
for j in range(len(ρ)-i):
ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]
ρ0 = ρ[0]
def t(xin):
a = 0
for i in range(len(ρ0)-1, 1, -1):
a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)
return y[0] + (xin-x[0]) / (ρ0[1]+a)
return t
xVal = [i*.05 for i in range(32)]
tSin = [math.sin(x) for x in xVal]
tCos = [math.cos(x) for x in xVal]
tTan = [math.tan(x) for x in xVal]
iSin = thieleInterpolator(tSin, xVal)
iCos = thieleInterpolator(tCos, xVal)
iTan = thieleInterpolator(tTan, xVal)
print('{:16.14f}'.format(6*iSin(.5)))
print('{:16.14f}'.format(3*iCos(.5)))
print('{:16.14f}'.format(4*iTan(1)))
| #include <cmath>
#include <iostream>
#include <iomanip>
#include <string.h>
constexpr unsigned int N = 32u;
double xval[N], t_sin[N], t_cos[N], t_tan[N];
constexpr unsigned int N2 = N * (N - 1u) / 2u;
double r_sin[N2], r_cos[N2], r_tan[N2];
double ρ(double *x, double *y, double *r, int i, int n) {
if (n < 0)
return 0;
if (!n)
return y[i];
unsigned int idx = (N - 1 - n) * (N - n) / 2 + i;
if (r[idx] != r[idx])
r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2);
return r[idx];
}
double thiele(double *x, double *y, double *r, double xin, unsigned int n) {
return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1);
}
inline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); }
inline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); }
inline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); }
int main() {
constexpr double step = .05;
for (auto i = 0u; i < N; i++) {
xval[i] = i * step;
t_sin[i] = sin(xval[i]);
t_cos[i] = cos(xval[i]);
t_tan[i] = t_sin[i] / t_cos[i];
}
for (auto i = 0u; i < N2; i++)
r_sin[i] = r_cos[i] = r_tan[i] = NAN;
std::cout << std::setw(16) << std::setprecision(25)
<< 6 * i_sin(.5) << std::endl
<< 3 * i_cos(.5) << std::endl
<< 4 * i_tan(1.) << std::endl;
return 0;
}
|
Convert this Python snippet to C++ and keep its semantics consistent. | >>> import math
>>> from collections import Counter
>>>
>>> def entropy(s):
... p, lns = Counter(s), float(len(s))
... return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
...
>>>
>>> def fibword(nmax=37):
... fwords = ['1', '0']
... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))
... def pr(n, fwords):
... while len(fwords) < n:
... fwords += [''.join(fwords[-2:][::-1])]
... v = fwords[n-1]
... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))
... for n in range(1, nmax+1): pr(n, fwords)
...
>>> fibword()
N Length Entropy Fibword
1 1 -0 1
2 1 -0 0
3 2 1 01
4 3 0.9182958 010
5 5 0.9709506 01001
6 8 0.954434 01001010
7 13 0.9612366 0100101001001
8 21 0.9587119 <too long>
9 34 0.9596869 <too long>
10 55 0.959316 <too long>
11 89 0.9594579 <too long>
12 144 0.9594038 <too long>
13 233 0.9594244 <too long>
14 377 0.9594165 <too long>
15 610 0.9594196 <too long>
16 987 0.9594184 <too long>
17 1597 0.9594188 <too long>
18 2584 0.9594187 <too long>
19 4181 0.9594187 <too long>
20 6765 0.9594187 <too long>
21 10946 0.9594187 <too long>
22 17711 0.9594187 <too long>
23 28657 0.9594187 <too long>
24 46368 0.9594187 <too long>
25 75025 0.9594187 <too long>
26 121393 0.9594187 <too long>
27 196418 0.9594187 <too long>
28 317811 0.9594187 <too long>
29 514229 0.9594187 <too long>
30 832040 0.9594187 <too long>
31 1346269 0.9594187 <too long>
32 2178309 0.9594187 <too long>
33 3524578 0.9594187 <too long>
34 5702887 0.9594187 <too long>
35 9227465 0.9594187 <too long>
36 14930352 0.9594187 <too long>
37 24157817 0.9594187 <too long>
>>>
| #include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>
double log2( double number ) {
return ( log( number ) / log( 2 ) ) ;
}
double find_entropy( std::string & fiboword ) {
std::map<char , int> frequencies ;
std::for_each( fiboword.begin( ) , fiboword.end( ) ,
[ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ;
int numlen = fiboword.length( ) ;
double infocontent = 0 ;
for ( std::pair<char , int> p : frequencies ) {
double freq = static_cast<double>( p.second ) / numlen ;
infocontent += freq * log2( freq ) ;
}
infocontent *= -1 ;
return infocontent ;
}
void printLine( std::string &fiboword , int n ) {
std::cout << std::setw( 5 ) << std::left << n ;
std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;
std::cout << " " << std::setw( 16 ) << std::setprecision( 13 )
<< std::left << find_entropy( fiboword ) ;
std::cout << "\n" ;
}
int main( ) {
std::cout << std::setw( 5 ) << std::left << "N" ;
std::cout << std::setw( 12 ) << std::right << "length" ;
std::cout << " " << std::setw( 16 ) << std::left << "entropy" ;
std::cout << "\n" ;
std::string firststring ( "1" ) ;
int n = 1 ;
printLine( firststring , n ) ;
std::string secondstring( "0" ) ;
n++ ;
printLine( secondstring , n ) ;
while ( n < 37 ) {
std::string resultstring = firststring + secondstring ;
firststring.assign( secondstring ) ;
secondstring.assign( resultstring ) ;
n++ ;
printLine( resultstring , n ) ;
}
return 0 ;
}
|
Write a version of this Python function in C++ with identical behavior. | >>> import math
>>> from collections import Counter
>>>
>>> def entropy(s):
... p, lns = Counter(s), float(len(s))
... return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
...
>>>
>>> def fibword(nmax=37):
... fwords = ['1', '0']
... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))
... def pr(n, fwords):
... while len(fwords) < n:
... fwords += [''.join(fwords[-2:][::-1])]
... v = fwords[n-1]
... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))
... for n in range(1, nmax+1): pr(n, fwords)
...
>>> fibword()
N Length Entropy Fibword
1 1 -0 1
2 1 -0 0
3 2 1 01
4 3 0.9182958 010
5 5 0.9709506 01001
6 8 0.954434 01001010
7 13 0.9612366 0100101001001
8 21 0.9587119 <too long>
9 34 0.9596869 <too long>
10 55 0.959316 <too long>
11 89 0.9594579 <too long>
12 144 0.9594038 <too long>
13 233 0.9594244 <too long>
14 377 0.9594165 <too long>
15 610 0.9594196 <too long>
16 987 0.9594184 <too long>
17 1597 0.9594188 <too long>
18 2584 0.9594187 <too long>
19 4181 0.9594187 <too long>
20 6765 0.9594187 <too long>
21 10946 0.9594187 <too long>
22 17711 0.9594187 <too long>
23 28657 0.9594187 <too long>
24 46368 0.9594187 <too long>
25 75025 0.9594187 <too long>
26 121393 0.9594187 <too long>
27 196418 0.9594187 <too long>
28 317811 0.9594187 <too long>
29 514229 0.9594187 <too long>
30 832040 0.9594187 <too long>
31 1346269 0.9594187 <too long>
32 2178309 0.9594187 <too long>
33 3524578 0.9594187 <too long>
34 5702887 0.9594187 <too long>
35 9227465 0.9594187 <too long>
36 14930352 0.9594187 <too long>
37 24157817 0.9594187 <too long>
>>>
| #include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>
double log2( double number ) {
return ( log( number ) / log( 2 ) ) ;
}
double find_entropy( std::string & fiboword ) {
std::map<char , int> frequencies ;
std::for_each( fiboword.begin( ) , fiboword.end( ) ,
[ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ;
int numlen = fiboword.length( ) ;
double infocontent = 0 ;
for ( std::pair<char , int> p : frequencies ) {
double freq = static_cast<double>( p.second ) / numlen ;
infocontent += freq * log2( freq ) ;
}
infocontent *= -1 ;
return infocontent ;
}
void printLine( std::string &fiboword , int n ) {
std::cout << std::setw( 5 ) << std::left << n ;
std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;
std::cout << " " << std::setw( 16 ) << std::setprecision( 13 )
<< std::left << find_entropy( fiboword ) ;
std::cout << "\n" ;
}
int main( ) {
std::cout << std::setw( 5 ) << std::left << "N" ;
std::cout << std::setw( 12 ) << std::right << "length" ;
std::cout << " " << std::setw( 16 ) << std::left << "entropy" ;
std::cout << "\n" ;
std::string firststring ( "1" ) ;
int n = 1 ;
printLine( firststring , n ) ;
std::string secondstring( "0" ) ;
n++ ;
printLine( secondstring , n ) ;
while ( n < 37 ) {
std::string resultstring = firststring + secondstring ;
firststring.assign( secondstring ) ;
secondstring.assign( resultstring ) ;
n++ ;
printLine( resultstring , n ) ;
}
return 0 ;
}
|
Change the following Python code into C++ without altering its purpose. | >>> import math
>>> from collections import Counter
>>>
>>> def entropy(s):
... p, lns = Counter(s), float(len(s))
... return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
...
>>>
>>> def fibword(nmax=37):
... fwords = ['1', '0']
... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split()))
... def pr(n, fwords):
... while len(fwords) < n:
... fwords += [''.join(fwords[-2:][::-1])]
... v = fwords[n-1]
... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>'))
... for n in range(1, nmax+1): pr(n, fwords)
...
>>> fibword()
N Length Entropy Fibword
1 1 -0 1
2 1 -0 0
3 2 1 01
4 3 0.9182958 010
5 5 0.9709506 01001
6 8 0.954434 01001010
7 13 0.9612366 0100101001001
8 21 0.9587119 <too long>
9 34 0.9596869 <too long>
10 55 0.959316 <too long>
11 89 0.9594579 <too long>
12 144 0.9594038 <too long>
13 233 0.9594244 <too long>
14 377 0.9594165 <too long>
15 610 0.9594196 <too long>
16 987 0.9594184 <too long>
17 1597 0.9594188 <too long>
18 2584 0.9594187 <too long>
19 4181 0.9594187 <too long>
20 6765 0.9594187 <too long>
21 10946 0.9594187 <too long>
22 17711 0.9594187 <too long>
23 28657 0.9594187 <too long>
24 46368 0.9594187 <too long>
25 75025 0.9594187 <too long>
26 121393 0.9594187 <too long>
27 196418 0.9594187 <too long>
28 317811 0.9594187 <too long>
29 514229 0.9594187 <too long>
30 832040 0.9594187 <too long>
31 1346269 0.9594187 <too long>
32 2178309 0.9594187 <too long>
33 3524578 0.9594187 <too long>
34 5702887 0.9594187 <too long>
35 9227465 0.9594187 <too long>
36 14930352 0.9594187 <too long>
37 24157817 0.9594187 <too long>
>>>
| #include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>
double log2( double number ) {
return ( log( number ) / log( 2 ) ) ;
}
double find_entropy( std::string & fiboword ) {
std::map<char , int> frequencies ;
std::for_each( fiboword.begin( ) , fiboword.end( ) ,
[ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ;
int numlen = fiboword.length( ) ;
double infocontent = 0 ;
for ( std::pair<char , int> p : frequencies ) {
double freq = static_cast<double>( p.second ) / numlen ;
infocontent += freq * log2( freq ) ;
}
infocontent *= -1 ;
return infocontent ;
}
void printLine( std::string &fiboword , int n ) {
std::cout << std::setw( 5 ) << std::left << n ;
std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ;
std::cout << " " << std::setw( 16 ) << std::setprecision( 13 )
<< std::left << find_entropy( fiboword ) ;
std::cout << "\n" ;
}
int main( ) {
std::cout << std::setw( 5 ) << std::left << "N" ;
std::cout << std::setw( 12 ) << std::right << "length" ;
std::cout << " " << std::setw( 16 ) << std::left << "entropy" ;
std::cout << "\n" ;
std::string firststring ( "1" ) ;
int n = 1 ;
printLine( firststring , n ) ;
std::string secondstring( "0" ) ;
n++ ;
printLine( secondstring , n ) ;
while ( n < 37 ) {
std::string resultstring = firststring + secondstring ;
firststring.assign( secondstring ) ;
secondstring.assign( resultstring ) ;
n++ ;
printLine( resultstring , n ) ;
}
return 0 ;
}
|
Change the programming language of this snippet from Python to C++ without modifying what it does. | PI = 3.141592653589793
TWO_PI = 6.283185307179586
def normalize2deg(a):
while a < 0: a += 360
while a >= 360: a -= 360
return a
def normalize2grad(a):
while a < 0: a += 400
while a >= 400: a -= 400
return a
def normalize2mil(a):
while a < 0: a += 6400
while a >= 6400: a -= 6400
return a
def normalize2rad(a):
while a < 0: a += TWO_PI
while a >= TWO_PI: a -= TWO_PI
return a
def deg2grad(a): return a * 10.0 / 9.0
def deg2mil(a): return a * 160.0 / 9.0
def deg2rad(a): return a * PI / 180.0
def grad2deg(a): return a * 9.0 / 10.0
def grad2mil(a): return a * 16.0
def grad2rad(a): return a * PI / 200.0
def mil2deg(a): return a * 9.0 / 160.0
def mil2grad(a): return a / 16.0
def mil2rad(a): return a * PI / 3200.0
def rad2deg(a): return a * 180.0 / PI
def rad2grad(a): return a * 200.0 / PI
def rad2mil(a): return a * 3200.0 / PI
| #include <functional>
#include <iostream>
#include <iomanip>
#include <math.h>
#include <sstream>
#include <vector>
#include <boost/algorithm/string.hpp>
template<typename T>
T normalize(T a, double b) { return std::fmod(a, b); }
inline double d2d(double a) { return normalize<double>(a, 360); }
inline double g2g(double a) { return normalize<double>(a, 400); }
inline double m2m(double a) { return normalize<double>(a, 6400); }
inline double r2r(double a) { return normalize<double>(a, 2*M_PI); }
double d2g(double a) { return g2g(a * 10 / 9); }
double d2m(double a) { return m2m(a * 160 / 9); }
double d2r(double a) { return r2r(a * M_PI / 180); }
double g2d(double a) { return d2d(a * 9 / 10); }
double g2m(double a) { return m2m(a * 16); }
double g2r(double a) { return r2r(a * M_PI / 200); }
double m2d(double a) { return d2d(a * 9 / 160); }
double m2g(double a) { return g2g(a / 16); }
double m2r(double a) { return r2r(a * M_PI / 3200); }
double r2d(double a) { return d2d(a * 180 / M_PI); }
double r2g(double a) { return g2g(a * 200 / M_PI); }
double r2m(double a) { return m2m(a * 3200 / M_PI); }
void print(const std::vector<double> &values, const char *s, std::function<double(double)> f) {
using namespace std;
ostringstream out;
out << " ┌───────────────────┐\n";
out << " │ " << setw(17) << s << " │\n";
out << "┌─────────────────┼───────────────────┤\n";
for (double i : values)
out << "│ " << setw(15) << fixed << i << defaultfloat << " │ " << setw(17) << fixed << f(i) << defaultfloat << " │\n";
out << "└─────────────────┴───────────────────┘\n";
auto str = out.str();
boost::algorithm::replace_all(str, ".000000", " ");
cout << str;
}
int main() {
std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 };
print(values, "normalized (deg)", d2d);
print(values, "normalized (grad)", g2g);
print(values, "normalized (mil)", m2m);
print(values, "normalized (rad)", r2r);
print(values, "deg -> grad ", d2g);
print(values, "deg -> mil ", d2m);
print(values, "deg -> rad ", d2r);
print(values, "grad -> deg ", g2d);
print(values, "grad -> mil ", g2m);
print(values, "grad -> rad ", g2r);
print(values, "mil -> deg ", m2d);
print(values, "mil -> grad ", m2g);
print(values, "mil -> rad ", m2r);
print(values, "rad -> deg ", r2d);
print(values, "rad -> grad ", r2g);
print(values, "rad -> mil ", r2m);
return 0;
}
|
Port the provided Python code into C++ while preserving the original functionality. | >>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
| #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
std::string longestPath( const std::vector<std::string> & , char ) ;
int main( ) {
std::string dirs[ ] = {
"/home/user1/tmp/coverage/test" ,
"/home/user1/tmp/covert/operator" ,
"/home/user1/tmp/coven/members" } ;
std::vector<std::string> myDirs ( dirs , dirs + 3 ) ;
std::cout << "The longest common path of the given directories is "
<< longestPath( myDirs , '/' ) << "!\n" ;
return 0 ;
}
std::string longestPath( const std::vector<std::string> & dirs , char separator ) {
std::vector<std::string>::const_iterator vsi = dirs.begin( ) ;
int maxCharactersCommon = vsi->length( ) ;
std::string compareString = *vsi ;
for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) {
std::pair<std::string::const_iterator , std::string::const_iterator> p =
std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ;
if (( p.first - compareString.begin( ) ) < maxCharactersCommon )
maxCharactersCommon = p.first - compareString.begin( ) ;
}
std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;
return compareString.substr( 0 , found ) ;
}
|
Convert this Python block to C++, preserving its control flow and logic. | from collections import Counter
from pprint import pprint as pp
def distcheck(fn, repeats, delta):
bin = Counter(fn() for i in range(repeats))
target = repeats // len(bin)
deltacount = int(delta / 100. * target)
assert all( abs(target - count) < deltacount
for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % (
target, deltacount, [ (key, target - count)
for key, count in sorted(bin.items()) ]
)
pp(dict(bin))
| #include <map>
#include <iostream>
#include <cmath>
template<typename F>
bool test_distribution(F f, int calls, double delta)
{
typedef std::map<int, int> distmap;
distmap dist;
for (int i = 0; i < calls; ++i)
++dist[f()];
double mean = 1.0/dist.size();
bool good = true;
for (distmap::iterator i = dist.begin(); i != dist.end(); ++i)
{
if (std::abs((1.0 * i->second)/calls - mean) > delta)
{
std::cout << "Relative frequency " << i->second/(1.0*calls)
<< " of result " << i->first
<< " deviates by more than " << delta
<< " from the expected value " << mean << "\n";
good = false;
}
}
return good;
}
|
Write the same code in C++ as shown below in Python. | computed = {}
def sterling2(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if (n > 0 and k == 0) or (n == 0 and k > 0):
return 0
if n == k:
return 1
if k > n:
return 0
result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
computed[key] = result
return result
print("Stirling numbers of the second kind:")
MAX = 12
print("n/k".ljust(10), end="")
for n in range(MAX + 1):
print(str(n).rjust(10), end="")
print()
for n in range(MAX + 1):
print(str(n).ljust(10), end="")
for k in range(n + 1):
print(str(sterling2(n, k)).rjust(10), end="")
print()
print("The maximum value of S2(100, k) = ")
previous = 0
for k in range(1, 100 + 1):
current = sterling2(100, k)
if current > previous:
previous = current
else:
print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1))
break
| #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <gmpxx.h>
using integer = mpz_class;
class stirling2 {
public:
integer get(int n, int k);
private:
std::map<std::pair<int, int>, integer> cache_;
};
integer stirling2::get(int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n)
return 0;
auto p = std::make_pair(n, k);
auto i = cache_.find(p);
if (i != cache_.end())
return i->second;
integer s = k * get(n - 1, k) + get(n - 1, k - 1);
cache_.emplace(p, s);
return s;
}
void print_stirling_numbers(stirling2& s2, int n) {
std::cout << "Stirling numbers of the second kind:\nn/k";
for (int j = 0; j <= n; ++j) {
std::cout << std::setw(j == 0 ? 2 : 8) << j;
}
std::cout << '\n';
for (int i = 0; i <= n; ++i) {
std::cout << std::setw(2) << i << ' ';
for (int j = 0; j <= i; ++j)
std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);
std::cout << '\n';
}
}
int main() {
stirling2 s2;
print_stirling_numbers(s2, 12);
std::cout << "Maximum value of S2(n,k) where n == 100:\n";
integer max = 0;
for (int k = 0; k <= 100; ++k)
max = std::max(max, s2.get(100, k));
std::cout << max << '\n';
return 0;
}
|
Write a version of this Python function in C++ with identical behavior. | computed = {}
def sterling2(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if (n > 0 and k == 0) or (n == 0 and k > 0):
return 0
if n == k:
return 1
if k > n:
return 0
result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
computed[key] = result
return result
print("Stirling numbers of the second kind:")
MAX = 12
print("n/k".ljust(10), end="")
for n in range(MAX + 1):
print(str(n).rjust(10), end="")
print()
for n in range(MAX + 1):
print(str(n).ljust(10), end="")
for k in range(n + 1):
print(str(sterling2(n, k)).rjust(10), end="")
print()
print("The maximum value of S2(100, k) = ")
previous = 0
for k in range(1, 100 + 1):
current = sterling2(100, k)
if current > previous:
previous = current
else:
print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1))
break
| #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <gmpxx.h>
using integer = mpz_class;
class stirling2 {
public:
integer get(int n, int k);
private:
std::map<std::pair<int, int>, integer> cache_;
};
integer stirling2::get(int n, int k) {
if (k == n)
return 1;
if (k == 0 || k > n)
return 0;
auto p = std::make_pair(n, k);
auto i = cache_.find(p);
if (i != cache_.end())
return i->second;
integer s = k * get(n - 1, k) + get(n - 1, k - 1);
cache_.emplace(p, s);
return s;
}
void print_stirling_numbers(stirling2& s2, int n) {
std::cout << "Stirling numbers of the second kind:\nn/k";
for (int j = 0; j <= n; ++j) {
std::cout << std::setw(j == 0 ? 2 : 8) << j;
}
std::cout << '\n';
for (int i = 0; i <= n; ++i) {
std::cout << std::setw(2) << i << ' ';
for (int j = 0; j <= i; ++j)
std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j);
std::cout << '\n';
}
}
int main() {
stirling2 s2;
print_stirling_numbers(s2, 12);
std::cout << "Maximum value of S2(n,k) where n == 100:\n";
integer max = 0;
for (int k = 0; k <= 100; ++k)
max = std::max(max, s2.get(100, k));
std::cout << max << '\n';
return 0;
}
|
Please provide an equivalent version of this Python code in C++. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
| #include <iostream>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto i = v.cbegin();
auto e = v.cend();
os << '[';
if (i != e) {
os << *i;
i = std::next(i);
}
while (i != e) {
os << ", " << *i;
i = std::next(i);
}
return os << ']';
}
int main() {
using namespace std;
vector<int> a{ 0 };
set<int> used{ 0 };
set<int> used1000{ 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.find(next) != used.end()) {
next += 2 * n;
}
bool alreadyUsed = used.find(next) != used.end();
a.push_back(next);
if (!alreadyUsed) {
used.insert(next);
if (0 <= next && next <= 1000) {
used1000.insert(next);
}
}
if (n == 14) {
cout << "The first 15 terms of the Recaman sequence are: " << a << '\n';
}
if (!foundDup && alreadyUsed) {
cout << "The first duplicated term is a[" << n << "] = " << next << '\n';
foundDup = true;
}
if (used1000.size() == 1001) {
cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n";
}
n++;
}
return 0;
}
|
Change the following Python code into C++ without altering its purpose. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
| #include <iostream>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto i = v.cbegin();
auto e = v.cend();
os << '[';
if (i != e) {
os << *i;
i = std::next(i);
}
while (i != e) {
os << ", " << *i;
i = std::next(i);
}
return os << ']';
}
int main() {
using namespace std;
vector<int> a{ 0 };
set<int> used{ 0 };
set<int> used1000{ 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.find(next) != used.end()) {
next += 2 * n;
}
bool alreadyUsed = used.find(next) != used.end();
a.push_back(next);
if (!alreadyUsed) {
used.insert(next);
if (0 <= next && next <= 1000) {
used1000.insert(next);
}
}
if (n == 14) {
cout << "The first 15 terms of the Recaman sequence are: " << a << '\n';
}
if (!foundDup && alreadyUsed) {
cout << "The first duplicated term is a[" << n << "] = " << next << '\n';
foundDup = true;
}
if (used1000.size() == 1001) {
cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n";
}
n++;
}
return 0;
}
|
Please provide an equivalent version of this Python code in C++. | >>> from array import array
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
>>> for typecode, initializer in argslist:
a = array(typecode, initializer)
print a
del a
array('l')
array('c', 'hello world')
array('u', u'hello \u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.1400000000000001])
>>>
| #include <string>
int main()
{
int* p;
p = new int;
delete p;
p = new int(2);
delete p;
std::string* p2;
p2 = new std::string;
delete p2;
p = new int[10];
delete[] p;
p2 = new std::string[10];
delete[] p2;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Python version. |
import random
board = list('123456789')
wins = ((0,1,2), (3,4,5), (6,7,8),
(0,3,6), (1,4,7), (2,5,8),
(0,4,8), (2,4,6))
def printboard():
print('\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))
def score():
for w in wins:
b = board[w[0]]
if b in 'XO' and all (board[i] == b for i in w):
return b, [i+1 for i in w]
return None, None
def finished():
return all (b in 'XO' for b in board)
def space():
return [ b for b in board if b not in 'XO']
def my_turn(xo):
options = space()
choice = random.choice(options)
board[int(choice)-1] = xo
return choice
def your_turn(xo):
options = space()
while True:
choice = input(" Put your %s in any of these positions: %s "
% (xo, ''.join(options))).strip()
if choice in options:
break
print( "Whoops I don't understand the input" )
board[int(choice)-1] = xo
return choice
def me(xo='X'):
printboard()
print('I go at', my_turn(xo))
return score()
assert not s[0], "\n%s wins across %s" % s
def you(xo='O'):
printboard()
print('You went at', your_turn(xo))
return score()
assert not s[0], "\n%s wins across %s" % s
print(__doc__)
while not finished():
s = me('X')
if s[0]:
printboard()
print("\n%s wins across %s" % s)
break
if not finished():
s = you('O')
if s[0]:
printboard()
print("\n%s wins across %s" % s)
break
else:
print('\nA draw')
| #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
enum players { Computer, Human, Draw, None };
const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };
class ttt
{
public:
ttt() { _p = rand() % 2; reset(); }
void play()
{
int res = Draw;
while( true )
{
drawGrid();
while( true )
{
if( _p ) getHumanMove();
else getComputerMove();
drawGrid();
res = checkVictory();
if( res != None ) break;
++_p %= 2;
}
if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!";
else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!";
else cout << "It's a draw!";
cout << endl << endl;
string r;
cout << "Play again( Y / N )? "; cin >> r;
if( r != "Y" && r != "y" ) return;
++_p %= 2;
reset();
}
}
private:
void reset()
{
for( int x = 0; x < 9; x++ )
_field[x] = None;
}
void drawGrid()
{
system( "cls" );
COORD c = { 0, 2 };
SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
cout << " 1 | 2 | 3 " << endl;
cout << "---+---+---" << endl;
cout << " 4 | 5 | 6 " << endl;
cout << "---+---+---" << endl;
cout << " 7 | 8 | 9 " << endl << endl << endl;
int f = 0;
for( int y = 0; y < 5; y += 2 )
for( int x = 1; x < 11; x += 4 )
{
if( _field[f] != None )
{
COORD c = { x, 2 + y };
SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
string o = _field[f] == Computer ? "X" : "O";
cout << o;
}
f++;
}
c.Y = 9;
SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
}
int checkVictory()
{
for( int i = 0; i < 8; i++ )
{
if( _field[iWin[i][0]] != None &&
_field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] )
{
return _field[iWin[i][0]];
}
}
int i = 0;
for( int f = 0; f < 9; f++ )
{
if( _field[f] != None )
i++;
}
if( i == 9 ) return Draw;
return None;
}
void getHumanMove()
{
int m;
cout << "Enter your move ( 1 - 9 ) ";
while( true )
{
m = 0;
do
{ cin >> m; }
while( m < 1 && m > 9 );
if( _field[m - 1] != None )
cout << "Invalid move. Try again!" << endl;
else break;
}
_field[m - 1] = Human;
}
void getComputerMove()
{
int move = 0;
do{ move = rand() % 9; }
while( _field[move] != None );
for( int i = 0; i < 8; i++ )
{
int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2];
if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None )
{
move = try3;
if( _field[try1] == Computer ) break;
}
if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None )
{
move = try2;
if( _field[try1] == Computer ) break;
}
if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None )
{
move = try1;
if( _field[try2] == Computer ) break;
}
}
_field[move] = Computer;
}
int _p;
int _field[9];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
ttt tic;
tic.play();
return 0;
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | i=1
while i:
print(i)
i += 1
| #include <cstdint>
#include <iostream>
#include <limits>
int main()
{
auto i = std::uintmax_t{};
while (i < std::numeric_limits<decltype(i)>::max())
std::cout << ++i << '\n';
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | i=1
while i:
print(i)
i += 1
| #include <cstdint>
#include <iostream>
#include <limits>
int main()
{
auto i = std::uintmax_t{};
while (i < std::numeric_limits<decltype(i)>::max())
std::cout << ++i << '\n';
}
|
Translate this program into C++ but keep the logic exactly as in Python. | i=1
while i:
print(i)
i += 1
| #include <cstdint>
#include <iostream>
#include <limits>
int main()
{
auto i = std::uintmax_t{};
while (i < std::numeric_limits<decltype(i)>::max())
std::cout << ++i << '\n';
}
|
Translate this program into C++ but keep the logic exactly as in Python. | import math
from collections import Counter
def entropy(s):
p, lns = Counter(s), float(len(s))
return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
with open(__file__) as f:
b=f.read()
print(entropy(b))
| #include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
string readFile (string path) {
string contents;
string line;
ifstream inFile(path);
while (getline (inFile, line)) {
contents.append(line);
contents.append("\n");
}
inFile.close();
return contents;
}
double entropy (string X) {
const int MAXCHAR = 127;
int N = X.length();
int count[MAXCHAR];
double count_i;
char ch;
double sum = 0.0;
for (int i = 0; i < MAXCHAR; i++) count[i] = 0;
for (int pos = 0; pos < N; pos++) {
ch = X[pos];
count[(int)ch]++;
}
for (int n_i = 0; n_i < MAXCHAR; n_i++) {
count_i = count[n_i];
if (count_i > 0) sum -= count_i / N * log2(count_i / N);
}
return sum;
}
int main () {
cout<<entropy(readFile("entropy.cpp"));
return 0;
}
|
Generate an equivalent C version of this C# code. | static void bitwise(int a, int b)
{
Console.WriteLine("a and b is {0}", a & b);
Console.WriteLine("a or b is {0}", a | b);
Console.WriteLine("a xor b is {0}", a ^ b);
Console.WriteLine("not a is {0}", ~a);
Console.WriteLine("a lshift b is {0}", a << b);
Console.WriteLine("a arshift b is {0}", a >> b);
uint c = (uint)a;
Console.WriteLine("c rshift b is {0}", c >> b);
}
| void bitwise(int a, int b)
{
printf("a and b: %d\n", a & b);
printf("a or b: %d\n", a | b);
printf("a xor b: %d\n", a ^ b);
printf("not a: %d\n", ~a);
printf("a << n: %d\n", a << b);
printf("a >> n: %d\n", a >> b);
unsigned int c = a;
printf("c >> b: %d\n", c >> b);
return 0;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class DragonCurve : Form
{
private List<int> turns;
private double startingAngle, side;
public DragonCurve(int iter)
{
Size = new Size(800, 600);
StartPosition = FormStartPosition.CenterScreen;
DoubleBuffered = true;
BackColor = Color.White;
startingAngle = -iter * (Math.PI / 4);
side = 400 / Math.Pow(2, iter / 2.0);
turns = getSequence(iter);
}
private List<int> getSequence(int iter)
{
var turnSequence = new List<int>();
for (int i = 0; i < iter; i++)
{
var copy = new List<int>(turnSequence);
copy.Reverse();
turnSequence.Add(1);
foreach (int turn in copy)
{
turnSequence.Add(-turn);
}
}
return turnSequence;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
double angle = startingAngle;
int x1 = 230, y1 = 350;
int x2 = x1 + (int)(Math.Cos(angle) * side);
int y2 = y1 + (int)(Math.Sin(angle) * side);
e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);
x1 = x2;
y1 = y2;
foreach (int turn in turns)
{
angle += turn * (Math.PI / 2);
x2 = x1 + (int)(Math.Cos(angle) * side);
y2 = y1 + (int)(Math.Sin(angle) * side);
e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);
x1 = x2;
y1 = y2;
}
}
[STAThread]
static void Main()
{
Application.Run(new DragonCurve(14));
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
long long tmp = dx - dy; dy = dx + dy; dx = tmp;
scale *= 2; x *= 2; y *= 2;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
double h = 6.0 * clen / scale;
double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;
double c = SAT * VAL;
double X = c * (1 - fabs(fmod(h, 2) - 1));
switch((int)h) {
case 0: p->r += c; p->g += X; return;
case 1: p->r += X; p->g += c; return;
case 2: p->g += c; p->b += X; return;
case 3: p->g += X; p->b += c; return;
case 4: p->r += X; p->b += c; return;
default:
p->r += c; p->b += X;
}
}
void iter_string(const char * str, int d)
{
long tmp;
# define LEFT tmp = -dy; dy = dx; dx = tmp
# define RIGHT tmp = dy; dy = -dx; dx = tmp
while (*str != '\0') {
switch(*(str++)) {
case 'X': if (d) iter_string("X+YF+", d - 1); continue;
case 'Y': if (d) iter_string("-FX-Y", d - 1); continue;
case '+': RIGHT; continue;
case '-': LEFT; continue;
case 'F':
clen ++;
h_rgb(x/scale, y/scale);
x += dx; y += dy;
continue;
}
}
}
void dragon(long leng, int depth)
{
long i, d = leng / 3 + 1;
long h = leng + 3, w = leng + d * 3 / 2 + 2;
rgb *buf = malloc(sizeof(rgb) * w * h);
pix = malloc(sizeof(rgb *) * h);
for (i = 0; i < h; i++)
pix[i] = buf + w * i;
memset(buf, 0, sizeof(rgb) * w * h);
x = y = d; dx = leng; dy = 0; scale = 1; clen = 0;
for (i = 0; i < depth; i++) sc_up();
iter_string("FX", depth);
unsigned char *fpix = malloc(w * h * 3);
double maxv = 0, *dbuf = (double*)buf;
for (i = 3 * w * h - 1; i >= 0; i--)
if (dbuf[i] > maxv) maxv = dbuf[i];
for (i = 3 * h * w - 1; i >= 0; i--)
fpix[i] = 255 * dbuf[i] / maxv;
printf("P6\n%ld %ld\n255\n", w, h);
fflush(stdout);
fwrite(fpix, h * w * 3, 1, stdout);
}
int main(int c, char ** v)
{
int size, depth;
depth = (c > 1) ? atoi(v[1]) : 10;
size = 1 << depth;
fprintf(stderr, "size: %d depth: %d\n", size, depth);
dragon(size, depth * 2);
return 0;
}
|
Port the following code from C# to C with equivalent syntax and logic. | foreach (string readLine in File.ReadLines("FileName"))
DoSomething(readLine);
|
#include <conio.h>
#include <stdio.h>
int main()
{
int n1, n2, n3;
printf( "\n Introduzca el primer n%cmero (entero): ", 163 );
scanf( "%d", &n1 );
printf( "\n Introduzca el segundo n%cmero (entero): ", 163 );
scanf( "%d", &n2 );
printf( "\n Introduzca el tercer n%cmero (entero): ", 163 );
scanf( "%d", &n3 );
if ( n1 >= n2 && n1 >= n3 )
printf( "\n %d es el mayor.", n1 );
else
if ( n2 > n3 )
printf( "\n %d es el mayor.", n2 );
else
printf( "\n %d es el mayor.", n3 );
getch();
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | static void InsertAfter(Link prev, int i)
{
if (prev.next != null)
{
prev.next.prev = new Link() { item = i, prev = prev, next = prev.next };
prev.next = prev.next.prev;
}
else
prev.next = new Link() { item = i, prev = prev };
}
| void insert(link* anchor, link* newlink) {
newlink->next = anchor->next;
newlink->prev = anchor;
(newlink->next)->prev = newlink;
anchor->next = newlink;
}
|
Produce a language-to-language conversion: from C# to C, same semantics. |
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuickSelect
{
internal static class Program
{
#region Static Members
private static void Main()
{
var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
Console.WriteLine( "Loop quick select 10 times." );
for( var i = 0 ; i < 10 ; i++ )
{
Console.Write( inputArray.NthSmallestElement( i ) );
if( i < 9 )
Console.Write( ", " );
}
Console.WriteLine();
Console.WriteLine( "Just sort 10 elements." );
Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );
Console.WriteLine( "Get 4 smallest and sort them." );
Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );
Console.WriteLine( "< Press any key >" );
Console.ReadKey();
}
#endregion
}
internal static class ArrayExtension
{
#region Static Members
public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>
{
if( count < 0 )
throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." );
if( count == 0 )
return new T[0];
if( array.Length <= count )
return array;
return QuickSelectSmallest( array, count - 1 ).Take( count );
}
public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>
{
if( n < 0 || n > array.Length - 1 )
throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) );
if( array.Length == 0 )
throw new ArgumentException( "Array is empty.", "array" );
if( array.Length == 1 )
return array[ 0 ];
return QuickSelectSmallest( array, n )[ n ];
}
private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>
{
var partiallySortedArray = (T[]) input.Clone();
var startIndex = 0;
var endIndex = input.Length - 1;
var pivotIndex = n;
var r = new Random();
while( endIndex > startIndex )
{
pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );
if( pivotIndex == n )
break;
if( pivotIndex > n )
endIndex = pivotIndex - 1;
else
startIndex = pivotIndex + 1;
pivotIndex = r.Next( startIndex, endIndex );
}
return partiallySortedArray;
}
private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>
{
var pivotValue = array[ pivotIndex ];
array.Swap( pivotIndex, endIndex );
for( var i = startIndex ; i < endIndex ; i++ )
{
if( array[ i ].CompareTo( pivotValue ) > 0 )
continue;
array.Swap( i, startIndex );
startIndex++;
}
array.Swap( endIndex, startIndex );
return startIndex;
}
private static void Swap<T>( this T[] array, int index1, int index2 )
{
if( index1 == index2 )
return;
var temp = array[ index1 ];
array[ index1 ] = array[ index2 ];
array[ index2 ] = temp;
}
#endregion
}
}
| #include <stdio.h>
#include <string.h>
int qselect(int *v, int len, int k)
{
# define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }
int i, st, tmp;
for (st = i = 0; i < len - 1; i++) {
if (v[i] > v[len-1]) continue;
SWAP(i, st);
st++;
}
SWAP(len-1, st);
return k == st ?v[st]
:st > k ? qselect(v, st, k)
: qselect(v + st, len - st, k - st);
}
int main(void)
{
# define N (sizeof(x)/sizeof(x[0]))
int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
int y[N];
int i;
for (i = 0; i < 10; i++) {
memcpy(y, x, sizeof(x));
printf("%d: %d\n", i, qselect(y, 10, i));
}
return 0;
}
|
Change the programming language of this snippet from C# to C without modifying what it does. |
using System;
using System.Collections.Generic;
using System.Linq;
namespace QuickSelect
{
internal static class Program
{
#region Static Members
private static void Main()
{
var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
Console.WriteLine( "Loop quick select 10 times." );
for( var i = 0 ; i < 10 ; i++ )
{
Console.Write( inputArray.NthSmallestElement( i ) );
if( i < 9 )
Console.Write( ", " );
}
Console.WriteLine();
Console.WriteLine( "Just sort 10 elements." );
Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );
Console.WriteLine( "Get 4 smallest and sort them." );
Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );
Console.WriteLine( "< Press any key >" );
Console.ReadKey();
}
#endregion
}
internal static class ArrayExtension
{
#region Static Members
public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>
{
if( count < 0 )
throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." );
if( count == 0 )
return new T[0];
if( array.Length <= count )
return array;
return QuickSelectSmallest( array, count - 1 ).Take( count );
}
public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>
{
if( n < 0 || n > array.Length - 1 )
throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) );
if( array.Length == 0 )
throw new ArgumentException( "Array is empty.", "array" );
if( array.Length == 1 )
return array[ 0 ];
return QuickSelectSmallest( array, n )[ n ];
}
private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>
{
var partiallySortedArray = (T[]) input.Clone();
var startIndex = 0;
var endIndex = input.Length - 1;
var pivotIndex = n;
var r = new Random();
while( endIndex > startIndex )
{
pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );
if( pivotIndex == n )
break;
if( pivotIndex > n )
endIndex = pivotIndex - 1;
else
startIndex = pivotIndex + 1;
pivotIndex = r.Next( startIndex, endIndex );
}
return partiallySortedArray;
}
private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>
{
var pivotValue = array[ pivotIndex ];
array.Swap( pivotIndex, endIndex );
for( var i = startIndex ; i < endIndex ; i++ )
{
if( array[ i ].CompareTo( pivotValue ) > 0 )
continue;
array.Swap( i, startIndex );
startIndex++;
}
array.Swap( endIndex, startIndex );
return startIndex;
}
private static void Swap<T>( this T[] array, int index1, int index2 )
{
if( index1 == index2 )
return;
var temp = array[ index1 ];
array[ index1 ] = array[ index2 ];
array[ index2 ] = temp;
}
#endregion
}
}
| #include <stdio.h>
#include <string.h>
int qselect(int *v, int len, int k)
{
# define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; }
int i, st, tmp;
for (st = i = 0; i < len - 1; i++) {
if (v[i] > v[len-1]) continue;
SWAP(i, st);
st++;
}
SWAP(len-1, st);
return k == st ?v[st]
:st > k ? qselect(v, st, k)
: qselect(v + st, len - st, k - st);
}
int main(void)
{
# define N (sizeof(x)/sizeof(x[0]))
int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
int y[N];
int i;
for (i = 0; i < 10; i++) {
memcpy(y, x, sizeof(x));
printf("%d: %d\n", i, qselect(y, 10, i));
}
return 0;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | public static class BaseConverter {
public static long stringToLong(string s, int b) {
if ( b < 2 || b > 36 )
throw new ArgumentException("Base must be between 2 and 36", "b");
checked {
int slen = s.Length;
long result = 0;
bool isNegative = false;
for ( int i = 0; i < slen; i++ ) {
char c = s[i];
int num;
if ( c == '-' ) {
if ( i != 0 )
throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s");
isNegative = true;
continue;
}
if ( c > 0x2F && c < 0x3A )
num = c - 0x30;
else if ( c > 0x40 && c < 0x5B )
num = c - 0x37;
else if ( c > 0x60 && c < 0x7B )
num = c - 0x57;
else
throw new ArgumentException("The string contains an invalid character '" + c + "'", "s");
if ( num >= b )
throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s");
result *= b;
result += num;
}
if ( isNegative )
result = -result;
return result;
}
}
public static string longToString(long n, int b) {
if ( b < 2 || b > 36 )
throw new ArgumentException("Base must be between 2 and 36", "b");
if ( b == 10 )
return n.ToString();
checked {
long longBase = b;
StringBuilder sb = new StringBuilder();
if ( n < 0 ) {
n = -n;
sb.Append('-');
}
long div = 1;
while ( n / div >= b )
div *= b;
while ( true ) {
byte digit = (byte) (n / div);
if ( digit < 10 )
sb.Append((char) (digit + 0x30));
else
sb.Append((char) (digit + 0x57));
if ( div == 1 )
break;
n %= div;
div /= b;
}
return sb.ToString();
}
}
}
| #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
char *to_base(int64_t num, int base)
{
char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz";
char buf[66] = {'\0'};
char *out;
uint64_t n;
int i, len = 0, neg = 0;
if (base > 36) {
fprintf(stderr, "base %d too large\n", base);
return 0;
}
n = ((neg = num < 0)) ? (~num) + 1 : num;
do { buf[len++] = tbl[n % base]; } while(n /= base);
out = malloc(len + neg + 1);
for (i = neg; len > 0; i++) out[i] = buf[--len];
if (neg) out[0] = '-';
return out;
}
long from_base(const char *num_str, int base)
{
char *endptr;
int result = strtol(num_str, &endptr, base);
return result;
}
int main()
{
int64_t x;
x = ~(1LL << 63) + 1;
printf("%lld in base 2: %s\n", x, to_base(x, 2));
x = 383;
printf("%lld in base 16: %s\n", x, to_base(x, 16));
return 0;
}
|
Translate this program into C but keep the logic exactly as in C#. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Port the following code from C# to C with equivalent syntax and logic. |
public class Crc32
{
#region Constants
private const UInt32 s_generator = 0xEDB88320;
#endregion
#region Constructors
public Crc32()
{
m_checksumTable = Enumerable.Range(0, 256).Select(i =>
{
var tableEntry = (uint)i;
for (var j = 0; j < 8; ++j)
{
tableEntry = ((tableEntry & 1) != 0)
? (s_generator ^ (tableEntry >> 1))
: (tableEntry >> 1);
}
return tableEntry;
}).ToArray();
}
#endregion
#region Methods
public UInt32 Get<T>(IEnumerable<T> byteStream)
{
try
{
return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) =>
(m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));
}
catch (FormatException e)
{
throw new CrcException("Could not read the stream out as bytes.", e);
}
catch (InvalidCastException e)
{
throw new CrcException("Could not read the stream out as bytes.", e);
}
catch (OverflowException e)
{
throw new CrcException("Could not read the stream out as bytes.", e);
}
}
#endregion
#region Fields
private readonly UInt32[] m_checksumTable;
#endregion
}
| #include <stdio.h>
#include <string.h>
#include <zlib.h>
int main()
{
const char *s = "The quick brown fox jumps over the lazy dog";
printf("%lX\n", crc32(0, (const void*)s, strlen(s)));
return 0;
}
|
Convert this C# snippet to C and keep its semantics consistent. | public class MyClass
{
public MyClass()
{
}
public void SomeMethod()
{
}
private int _variable;
public int Variable
{
get { return _variable; }
set { _variable = value; }
}
public static void Main()
{
MyClass instance = new MyClass();
instance.SomeMethod();
instance.Variable = 99;
System.Console.WriteLine( "Variable=" + instance.Variable.ToString() );
}
}
| #include <stdlib.h>
typedef struct sMyClass
{
int variable;
} *MyClass;
MyClass MyClass_new()
{
MyClass pthis = malloc(sizeof *pthis);
pthis->variable = 0;
return pthis;
}
void MyClass_delete(MyClass* pthis)
{
if (pthis)
{
free(*pthis);
*pthis = NULL;
}
}
void MyClass_someMethod(MyClass pthis)
{
pthis->variable = 1;
}
MyClass obj = MyClass_new();
MyClass_someMethod(obj);
MyClass_delete(&obj);
|
Maintain the same structure and functionality when rewriting this code in C. | using System;
using System.Collections.Generic;
public class KaprekarNumbers {
public static void Main() {
int count = 0;
foreach ( ulong i in _kaprekarGenerator(999999) ) {
Console.WriteLine(i);
count++;
}
Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count);
}
private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {
ulong next = 1;
yield return next;
for ( next = 2; next <= max; next++ ) {
ulong square = next * next;
for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {
if ( square <= check )
break;
ulong r = square % check;
ulong q = (square - r) / check;
if ( r != 0 && q + r == next ) {
yield return next;
break;
}
}
}
}
}
| #include <stdio.h>
#include <stdint.h>
typedef uint64_t ulong;
int kaprekar(ulong n, int base)
{
ulong nn = n * n, r, tens = 1;
if ((nn - n) % (base - 1)) return 0;
while (tens < n) tens *= base;
if (n == tens) return 1 == n;
while ((r = nn % tens) < n) {
if (nn / tens + r == n) return tens;
tens *= base;
}
return 0;
}
void print_num(ulong n, int base)
{
ulong q, div = base;
while (div < n) div *= base;
while (n && (div /= base)) {
q = n / div;
if (q < 10) putchar(q + '0');
else putchar(q + 'a' - 10);
n -= q * div;
}
}
int main()
{
ulong i, tens;
int cnt = 0;
int base = 10;
printf("base 10:\n");
for (i = 1; i < 1000000; i++)
if (kaprekar(i, base))
printf("%3d: %llu\n", ++cnt, i);
base = 17;
printf("\nbase %d:\n 1: 1\n", base);
for (i = 2, cnt = 1; i < 1000000; i++)
if ((tens = kaprekar(i, base))) {
printf("%3d: %llu", ++cnt, i);
printf(" \t"); print_num(i, base);
printf("\t"); print_num(i * i, base);
printf("\t"); print_num(i * i / tens, base);
printf(" + "); print_num(i * i % tens, base);
printf("\n");
}
return 0;
}
|
Convert this C# snippet to C and keep its semantics consistent. | using System;
using System.Collections.Generic;
public class KaprekarNumbers {
public static void Main() {
int count = 0;
foreach ( ulong i in _kaprekarGenerator(999999) ) {
Console.WriteLine(i);
count++;
}
Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count);
}
private static IEnumerable<ulong> _kaprekarGenerator(ulong max) {
ulong next = 1;
yield return next;
for ( next = 2; next <= max; next++ ) {
ulong square = next * next;
for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) {
if ( square <= check )
break;
ulong r = square % check;
ulong q = (square - r) / check;
if ( r != 0 && q + r == next ) {
yield return next;
break;
}
}
}
}
}
| #include <stdio.h>
#include <stdint.h>
typedef uint64_t ulong;
int kaprekar(ulong n, int base)
{
ulong nn = n * n, r, tens = 1;
if ((nn - n) % (base - 1)) return 0;
while (tens < n) tens *= base;
if (n == tens) return 1 == n;
while ((r = nn % tens) < n) {
if (nn / tens + r == n) return tens;
tens *= base;
}
return 0;
}
void print_num(ulong n, int base)
{
ulong q, div = base;
while (div < n) div *= base;
while (n && (div /= base)) {
q = n / div;
if (q < 10) putchar(q + '0');
else putchar(q + 'a' - 10);
n -= q * div;
}
}
int main()
{
ulong i, tens;
int cnt = 0;
int base = 10;
printf("base 10:\n");
for (i = 1; i < 1000000; i++)
if (kaprekar(i, base))
printf("%3d: %llu\n", ++cnt, i);
base = 17;
printf("\nbase %d:\n 1: 1\n", base);
for (i = 2, cnt = 1; i < 1000000; i++)
if ((tens = kaprekar(i, base))) {
printf("%3d: %llu", ++cnt, i);
printf(" \t"); print_num(i, base);
printf("\t"); print_num(i * i, base);
printf("\t"); print_num(i * i / tens, base);
printf(" + "); print_num(i * i % tens, base);
printf("\n");
}
return 0;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
using System.Linq;
namespace HofstadterFigureFigure
{
class HofstadterFigureFigure
{
readonly List<int> _r = new List<int>() {1};
readonly List<int> _s = new List<int>();
public IEnumerable<int> R()
{
int iR = 0;
while (true)
{
if (iR >= _r.Count)
{
Advance();
}
yield return _r[iR++];
}
}
public IEnumerable<int> S()
{
int iS = 0;
while (true)
{
if (iS >= _s.Count)
{
Advance();
}
yield return _s[iS++];
}
}
private void Advance()
{
int rCount = _r.Count;
int oldR = _r[rCount - 1];
int sVal;
switch (rCount)
{
case 1:
sVal = 2;
break;
case 2:
sVal = 4;
break;
default:
sVal = _s[rCount - 1];
break;
}
_r.Add(_r[rCount - 1] + sVal);
int newR = _r[rCount];
for (int iS = oldR + 1; iS < newR; iS++)
{
_s.Add(iS);
}
}
}
class Program
{
static void Main()
{
var hff = new HofstadterFigureFigure();
var rs = hff.R();
var arr = rs.Take(40).ToList();
foreach(var v in arr.Take(10))
{
Console.WriteLine("{0}", v);
}
var hs = new HashSet<int>(arr);
hs.UnionWith(hff.S().Take(960));
Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!");
}
}
}
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef struct {
size_t len, alloc;
xint *buf;
} xarray;
xarray rs, ss;
void setsize(xarray *a, size_t size)
{
size_t n = a->alloc;
if (!n) n = 1;
while (n < size) n <<= 1;
if (a->alloc < n) {
a->buf = realloc(a->buf, sizeof(xint) * n);
if (!a->buf) abort();
a->alloc = n;
}
}
void push(xarray *a, xint v)
{
while (a->alloc <= a->len)
setsize(a, a->alloc * 2);
a->buf[a->len++] = v;
}
void RS_append(void);
xint R(int n)
{
while (n > rs.len) RS_append();
return rs.buf[n - 1];
}
xint S(int n)
{
while (n > ss.len) RS_append();
return ss.buf[n - 1];
}
void RS_append()
{
int n = rs.len;
xint r = R(n) + S(n);
xint s = S(ss.len);
push(&rs, r);
while (++s < r) push(&ss, s);
push(&ss, r + 1);
}
int main(void)
{
push(&rs, 1);
push(&ss, 2);
int i;
printf("R(1 .. 10):");
for (i = 1; i <= 10; i++)
printf(" %llu", R(i));
char seen[1001] = { 0 };
for (i = 1; i <= 40; i++) seen[ R(i) ] = 1;
for (i = 1; i <= 960; i++) seen[ S(i) ] = 1;
for (i = 1; i <= 1000 && seen[i]; i++);
if (i <= 1000) {
fprintf(stderr, "%d not seen\n", i);
abort();
}
puts("\nfirst 1000 ok");
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the C# version. | using System;
using System.Collections.Generic;
using System.Linq;
namespace HofstadterFigureFigure
{
class HofstadterFigureFigure
{
readonly List<int> _r = new List<int>() {1};
readonly List<int> _s = new List<int>();
public IEnumerable<int> R()
{
int iR = 0;
while (true)
{
if (iR >= _r.Count)
{
Advance();
}
yield return _r[iR++];
}
}
public IEnumerable<int> S()
{
int iS = 0;
while (true)
{
if (iS >= _s.Count)
{
Advance();
}
yield return _s[iS++];
}
}
private void Advance()
{
int rCount = _r.Count;
int oldR = _r[rCount - 1];
int sVal;
switch (rCount)
{
case 1:
sVal = 2;
break;
case 2:
sVal = 4;
break;
default:
sVal = _s[rCount - 1];
break;
}
_r.Add(_r[rCount - 1] + sVal);
int newR = _r[rCount];
for (int iS = oldR + 1; iS < newR; iS++)
{
_s.Add(iS);
}
}
}
class Program
{
static void Main()
{
var hff = new HofstadterFigureFigure();
var rs = hff.R();
var arr = rs.Take(40).ToList();
foreach(var v in arr.Take(10))
{
Console.WriteLine("{0}", v);
}
var hs = new HashSet<int>(arr);
hs.UnionWith(hff.S().Take(960));
Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!");
}
}
}
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef struct {
size_t len, alloc;
xint *buf;
} xarray;
xarray rs, ss;
void setsize(xarray *a, size_t size)
{
size_t n = a->alloc;
if (!n) n = 1;
while (n < size) n <<= 1;
if (a->alloc < n) {
a->buf = realloc(a->buf, sizeof(xint) * n);
if (!a->buf) abort();
a->alloc = n;
}
}
void push(xarray *a, xint v)
{
while (a->alloc <= a->len)
setsize(a, a->alloc * 2);
a->buf[a->len++] = v;
}
void RS_append(void);
xint R(int n)
{
while (n > rs.len) RS_append();
return rs.buf[n - 1];
}
xint S(int n)
{
while (n > ss.len) RS_append();
return ss.buf[n - 1];
}
void RS_append()
{
int n = rs.len;
xint r = R(n) + S(n);
xint s = S(ss.len);
push(&rs, r);
while (++s < r) push(&ss, s);
push(&ss, r + 1);
}
int main(void)
{
push(&rs, 1);
push(&ss, 2);
int i;
printf("R(1 .. 10):");
for (i = 1; i <= 10; i++)
printf(" %llu", R(i));
char seen[1001] = { 0 };
for (i = 1; i <= 40; i++) seen[ R(i) ] = 1;
for (i = 1; i <= 960; i++) seen[ S(i) ] = 1;
for (i = 1; i <= 1000 && seen[i]; i++);
if (i <= 1000) {
fprintf(stderr, "%d not seen\n", i);
abort();
}
puts("\nfirst 1000 ok");
return 0;
}
|
Write a version of this C# function in C with identical behavior. | using System;
using System.Collections.Generic;
using System.Linq;
namespace HofstadterFigureFigure
{
class HofstadterFigureFigure
{
readonly List<int> _r = new List<int>() {1};
readonly List<int> _s = new List<int>();
public IEnumerable<int> R()
{
int iR = 0;
while (true)
{
if (iR >= _r.Count)
{
Advance();
}
yield return _r[iR++];
}
}
public IEnumerable<int> S()
{
int iS = 0;
while (true)
{
if (iS >= _s.Count)
{
Advance();
}
yield return _s[iS++];
}
}
private void Advance()
{
int rCount = _r.Count;
int oldR = _r[rCount - 1];
int sVal;
switch (rCount)
{
case 1:
sVal = 2;
break;
case 2:
sVal = 4;
break;
default:
sVal = _s[rCount - 1];
break;
}
_r.Add(_r[rCount - 1] + sVal);
int newR = _r[rCount];
for (int iS = oldR + 1; iS < newR; iS++)
{
_s.Add(iS);
}
}
}
class Program
{
static void Main()
{
var hff = new HofstadterFigureFigure();
var rs = hff.R();
var arr = rs.Take(40).ToList();
foreach(var v in arr.Take(10))
{
Console.WriteLine("{0}", v);
}
var hs = new HashSet<int>(arr);
hs.UnionWith(hff.S().Take(960));
Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!");
}
}
}
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef struct {
size_t len, alloc;
xint *buf;
} xarray;
xarray rs, ss;
void setsize(xarray *a, size_t size)
{
size_t n = a->alloc;
if (!n) n = 1;
while (n < size) n <<= 1;
if (a->alloc < n) {
a->buf = realloc(a->buf, sizeof(xint) * n);
if (!a->buf) abort();
a->alloc = n;
}
}
void push(xarray *a, xint v)
{
while (a->alloc <= a->len)
setsize(a, a->alloc * 2);
a->buf[a->len++] = v;
}
void RS_append(void);
xint R(int n)
{
while (n > rs.len) RS_append();
return rs.buf[n - 1];
}
xint S(int n)
{
while (n > ss.len) RS_append();
return ss.buf[n - 1];
}
void RS_append()
{
int n = rs.len;
xint r = R(n) + S(n);
xint s = S(ss.len);
push(&rs, r);
while (++s < r) push(&ss, s);
push(&ss, r + 1);
}
int main(void)
{
push(&rs, 1);
push(&ss, 2);
int i;
printf("R(1 .. 10):");
for (i = 1; i <= 10; i++)
printf(" %llu", R(i));
char seen[1001] = { 0 };
for (i = 1; i <= 40; i++) seen[ R(i) ] = 1;
for (i = 1; i <= 960; i++) seen[ S(i) ] = 1;
for (i = 1; i <= 1000 && seen[i]; i++);
if (i <= 1000) {
fprintf(stderr, "%d not seen\n", i);
abort();
}
puts("\nfirst 1000 ok");
return 0;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | static int Fib(int n)
{
if (n < 0) throw new ArgumentException("Must be non negativ", "n");
Func<int, int> fib = null;
fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p;
return fib(n);
}
| #include <stdio.h>
long fib(long x)
{
long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };
if (x < 0) {
printf("Bad argument: fib(%ld)\n", x);
return -1;
}
return fib_i(x);
}
long fib_i(long n)
{
printf("This is not the fib you are looking for\n");
return -1;
}
int main()
{
long x;
for (x = -1; x < 4; x ++)
printf("fib %ld = %ld\n", x, fib(x));
printf("calling fib_i from outside fib:\n");
fib_i(3);
return 0;
}
|
Produce a language-to-language conversion: from C# to C, same semantics. | using System;
using System.IO;
class Program {
static void Main(string[] args) {
File.Create("output.txt");
File.Create(@"\output.txt");
Directory.CreateDirectory("docs");
Directory.CreateDirectory(@"\docs");
}
}
| #include <stdio.h>
int main() {
FILE *fh = fopen("output.txt", "w");
fclose(fh);
return 0;
}
|
Ensure the translated C code behaves exactly like the original C# snippet. | using System;
interface IOperable
{
string Operate();
}
class Inoperable
{
}
class Operable : IOperable
{
public string Operate()
{
return "Delegate implementation.";
}
}
class Delegator : IOperable
{
object Delegate;
public string Operate()
{
var operable = Delegate as IOperable;
return operable != null ? operable.Operate() : "Default implementation.";
}
static void Main()
{
var delegator = new Delegator();
foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })
{
delegator.Delegate = @delegate;
Console.WriteLine(delegator.Operate());
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef const char * (*Responder)( int p1);
typedef struct sDelegate {
Responder operation;
} *Delegate;
Delegate NewDelegate( Responder rspndr )
{
Delegate dl = malloc(sizeof(struct sDelegate));
dl->operation = rspndr;
return dl;
}
const char *DelegateThing(Delegate dl, int p1)
{
return (dl->operation)? (*dl->operation)(p1) : NULL;
}
typedef struct sDelegator {
int param;
char *phrase;
Delegate delegate;
} *Delegator;
const char * defaultResponse( int p1)
{
return "default implementation";
}
static struct sDelegate defaultDel = { &defaultResponse };
Delegator NewDelegator( int p, char *phrase)
{
Delegator d = malloc(sizeof(struct sDelegator));
d->param = p;
d->phrase = phrase;
d->delegate = &defaultDel;
return d;
}
const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)
{
const char *rtn;
if (delroy) {
rtn = DelegateThing(delroy, p1);
if (!rtn) {
rtn = DelegateThing(theDelegator->delegate, p1);
}
}
else
rtn = DelegateThing(theDelegator->delegate, p1);
printf("%s\n", theDelegator->phrase );
return rtn;
}
const char *thing1( int p1)
{
printf("We're in thing1 with value %d\n" , p1);
return "delegate implementation";
}
int main()
{
Delegate del1 = NewDelegate(&thing1);
Delegate del2 = NewDelegate(NULL);
Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby.");
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, NULL));
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, del1));
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, del2));
return 0;
}
|
Change the programming language of this snippet from C# to C without modifying what it does. | using System;
interface IOperable
{
string Operate();
}
class Inoperable
{
}
class Operable : IOperable
{
public string Operate()
{
return "Delegate implementation.";
}
}
class Delegator : IOperable
{
object Delegate;
public string Operate()
{
var operable = Delegate as IOperable;
return operable != null ? operable.Operate() : "Default implementation.";
}
static void Main()
{
var delegator = new Delegator();
foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })
{
delegator.Delegate = @delegate;
Console.WriteLine(delegator.Operate());
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef const char * (*Responder)( int p1);
typedef struct sDelegate {
Responder operation;
} *Delegate;
Delegate NewDelegate( Responder rspndr )
{
Delegate dl = malloc(sizeof(struct sDelegate));
dl->operation = rspndr;
return dl;
}
const char *DelegateThing(Delegate dl, int p1)
{
return (dl->operation)? (*dl->operation)(p1) : NULL;
}
typedef struct sDelegator {
int param;
char *phrase;
Delegate delegate;
} *Delegator;
const char * defaultResponse( int p1)
{
return "default implementation";
}
static struct sDelegate defaultDel = { &defaultResponse };
Delegator NewDelegator( int p, char *phrase)
{
Delegator d = malloc(sizeof(struct sDelegator));
d->param = p;
d->phrase = phrase;
d->delegate = &defaultDel;
return d;
}
const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)
{
const char *rtn;
if (delroy) {
rtn = DelegateThing(delroy, p1);
if (!rtn) {
rtn = DelegateThing(theDelegator->delegate, p1);
}
}
else
rtn = DelegateThing(theDelegator->delegate, p1);
printf("%s\n", theDelegator->phrase );
return rtn;
}
const char *thing1( int p1)
{
printf("We're in thing1 with value %d\n" , p1);
return "delegate implementation";
}
int main()
{
Delegate del1 = NewDelegate(&thing1);
Delegate del2 = NewDelegate(NULL);
Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby.");
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, NULL));
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, del1));
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, del2));
return 0;
}
|
Produce a language-to-language conversion: from C# to C, same semantics. | #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (n > 1)
total *= n + 1;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "Sum of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(4) << divisor_sum(n);
if (n % 10 == 0)
std::cout << '\n';
}
}
| #include <stdio.h>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
unsigned int p;
for (; (n & 1) == 0; power <<= 1, n >>= 1) {
total += power;
}
for (p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0; power *= p, n /= p) {
sum += power;
}
total *= sum;
}
if (n > 1) {
total *= n + 1;
}
return total;
}
int main() {
const unsigned int limit = 100;
unsigned int n;
printf("Sum of divisors for the first %d positive integers:\n", limit);
for (n = 1; n <= limit; ++n) {
printf("%4d", divisor_sum(n));
if (n % 10 == 0) {
printf("\n");
}
}
return 0;
}
|
Write the same code in C as shown below in C#. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BaconCipher {
class Program {
private static Dictionary<char, string> codes = new Dictionary<char, string> {
{'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" },
{'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" },
{'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" },
{'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" },
{'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" },
{'z', "BBAAB" }, {' ', "BBBAA" },
};
private static string Encode(string plainText, string message) {
string pt = plainText.ToLower();
StringBuilder sb = new StringBuilder();
foreach (char c in pt) {
if ('a' <= c && c <= 'z') sb.Append(codes[c]);
else sb.Append(codes[' ']);
}
string et = sb.ToString();
string mg = message.ToLower();
sb.Length = 0;
int count = 0;
foreach (char c in mg) {
if ('a' <= c && c <= 'z') {
if (et[count] == 'A') sb.Append(c);
else sb.Append((char)(c - 32));
count++;
if (count == et.Length) break;
}
else sb.Append(c);
}
return sb.ToString();
}
private static string Decode(string message) {
StringBuilder sb = new StringBuilder();
foreach (char c in message) {
if ('a' <= c && c <= 'z') sb.Append('A');
else if ('A' <= c && c <= 'Z') sb.Append('B');
}
string et = sb.ToString();
sb.Length = 0;
for (int i = 0; i < et.Length; i += 5) {
string quintet = et.Substring(i, 5);
char key = codes.Where(a => a.Value == quintet).First().Key;
sb.Append(key);
}
return sb.ToString();
}
static void Main(string[] args) {
string plainText = "the quick brown fox jumps over the lazy dog";
string message = "bacon's cipher is a method of steganography created by francis bacon. " +
"this task is to implement a program for encryption and decryption of " +
"plaintext using the simple alphabet of the baconian cipher or some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.";
string cipherText = Encode(plainText, message);
Console.WriteLine("Cipher text ->\n{0}", cipherText);
string decodedText = Decode(cipherText);
Console.WriteLine("\nHidden text ->\n{0}", decodedText);
}
}
}
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *codes[] = {
"AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA",
"AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB",
"ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA",
"ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB",
"BABAA", "BABAB", "BABBA", "BABBB", "BBAAA",
"BBAAB", "BBBAA"
};
char *get_code(const char c) {
if (c >= 97 && c <= 122) return codes[c - 97];
return codes[26];
}
char get_char(const char *code) {
int i;
if (!strcmp(codes[26], code)) return ' ';
for (i = 0; i < 26; ++i) {
if (strcmp(codes[i], code) == 0) return 97 + i;
}
printf("\nCode \"%s\" is invalid\n", code);
exit(1);
}
void str_tolower(char s[]) {
int i;
for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
}
char *bacon_encode(char plain_text[], char message[]) {
int i, count;
int plen = strlen(plain_text), mlen = strlen(message);
int elen = 5 * plen;
char c;
char *p, *et, *mt;
et = malloc(elen + 1);
str_tolower(plain_text);
for (i = 0, p = et; i < plen; ++i, p += 5) {
c = plain_text[i];
strncpy(p, get_code(c), 5);
}
*++p = '\0';
str_tolower(message);
mt = calloc(mlen + 1, 1);
for (i = 0, count = 0; i < mlen; ++i) {
c = message[i];
if (c >= 'a' && c <= 'z') {
if (et[count] == 'A')
mt[i] = c;
else
mt[i] = c - 32;
if (++count == elen) break;
}
else mt[i] = c;
}
free(et);
return mt;
}
char *bacon_decode(char cipher_text[]) {
int i, count, clen = strlen(cipher_text);
int plen;
char *p, *ct, *pt;
char c, quintet[6];
ct = calloc(clen + 1, 1);
for (i = 0, count = 0; i < clen; ++i) {
c = cipher_text[i];
if (c >= 'a' && c <= 'z')
ct[count++] = 'A';
else if (c >= 'A' && c <= 'Z')
ct[count++] = 'B';
}
plen = strlen(ct) / 5;
pt = malloc(plen + 1);
for (i = 0, p = ct; i < plen; ++i, p += 5) {
strncpy(quintet, p, 5);
quintet[5] = '\0';
pt[i] = get_char(quintet);
}
pt[plen] = '\0';
free(ct);
return pt;
}
int main() {
char plain_text[] = "the quick brown fox jumps over the lazy dog";
char message[] = "bacon's cipher is a method of steganography created by francis bacon."
"this task is to implement a program for encryption and decryption of "
"plaintext using the simple alphabet of the baconian cipher or some "
"other kind of representation of this alphabet (make anything signify anything). "
"the baconian alphabet may optionally be extended to encode all lower "
"case characters individually and/or adding a few punctuation characters "
"such as the space.";
char *cipher_text, *hidden_text;
cipher_text = bacon_encode(plain_text, message);
printf("Cipher text ->\n\n%s\n", cipher_text);
hidden_text = bacon_decode(cipher_text);
printf("\nHidden text ->\n\n%s\n", hidden_text);
free(cipher_text);
free(hidden_text);
return 0;
}
|
Change the programming language of this snippet from C# to C without modifying what it does. | #include <iostream>
#include <algorithm>
#include <vector>
#include <bitset>
#include <string>
class bacon {
public:
bacon() {
int x = 0;
for( ; x < 9; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 20; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 24; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
}
std::string encode( std::string txt ) {
std::string r;
size_t z;
for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {
z = toupper( *i );
if( z < 'A' || z > 'Z' ) continue;
r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );
}
return r;
}
std::string decode( std::string txt ) {
size_t len = txt.length();
while( len % 5 != 0 ) len--;
if( len != txt.length() ) txt = txt.substr( 0, len );
std::string r;
for( size_t i = 0; i < len; i += 5 ) {
r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );
}
return r;
}
private:
std::vector<std::string> bAlphabet;
};
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *codes[] = {
"AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA",
"AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB",
"ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA",
"ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB",
"BABAA", "BABAB", "BABBA", "BABBB", "BBAAA",
"BBAAB", "BBBAA"
};
char *get_code(const char c) {
if (c >= 97 && c <= 122) return codes[c - 97];
return codes[26];
}
char get_char(const char *code) {
int i;
if (!strcmp(codes[26], code)) return ' ';
for (i = 0; i < 26; ++i) {
if (strcmp(codes[i], code) == 0) return 97 + i;
}
printf("\nCode \"%s\" is invalid\n", code);
exit(1);
}
void str_tolower(char s[]) {
int i;
for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
}
char *bacon_encode(char plain_text[], char message[]) {
int i, count;
int plen = strlen(plain_text), mlen = strlen(message);
int elen = 5 * plen;
char c;
char *p, *et, *mt;
et = malloc(elen + 1);
str_tolower(plain_text);
for (i = 0, p = et; i < plen; ++i, p += 5) {
c = plain_text[i];
strncpy(p, get_code(c), 5);
}
*++p = '\0';
str_tolower(message);
mt = calloc(mlen + 1, 1);
for (i = 0, count = 0; i < mlen; ++i) {
c = message[i];
if (c >= 'a' && c <= 'z') {
if (et[count] == 'A')
mt[i] = c;
else
mt[i] = c - 32;
if (++count == elen) break;
}
else mt[i] = c;
}
free(et);
return mt;
}
char *bacon_decode(char cipher_text[]) {
int i, count, clen = strlen(cipher_text);
int plen;
char *p, *ct, *pt;
char c, quintet[6];
ct = calloc(clen + 1, 1);
for (i = 0, count = 0; i < clen; ++i) {
c = cipher_text[i];
if (c >= 'a' && c <= 'z')
ct[count++] = 'A';
else if (c >= 'A' && c <= 'Z')
ct[count++] = 'B';
}
plen = strlen(ct) / 5;
pt = malloc(plen + 1);
for (i = 0, p = ct; i < plen; ++i, p += 5) {
strncpy(quintet, p, 5);
quintet[5] = '\0';
pt[i] = get_char(quintet);
}
pt[plen] = '\0';
free(ct);
return pt;
}
int main() {
char plain_text[] = "the quick brown fox jumps over the lazy dog";
char message[] = "bacon's cipher is a method of steganography created by francis bacon."
"this task is to implement a program for encryption and decryption of "
"plaintext using the simple alphabet of the baconian cipher or some "
"other kind of representation of this alphabet (make anything signify anything). "
"the baconian alphabet may optionally be extended to encode all lower "
"case characters individually and/or adding a few punctuation characters "
"such as the space.";
char *cipher_text, *hidden_text;
cipher_text = bacon_encode(plain_text, message);
printf("Cipher text ->\n\n%s\n", cipher_text);
hidden_text = bacon_decode(cipher_text);
printf("\nHidden text ->\n\n%s\n", hidden_text);
free(cipher_text);
free(hidden_text);
return 0;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | #include <iostream>
#include <algorithm>
#include <vector>
#include <bitset>
#include <string>
class bacon {
public:
bacon() {
int x = 0;
for( ; x < 9; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 20; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
bAlphabet.push_back( bAlphabet.back() );
for( ; x < 24; x++ )
bAlphabet.push_back( std::bitset<5>( x ).to_string() );
}
std::string encode( std::string txt ) {
std::string r;
size_t z;
for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) {
z = toupper( *i );
if( z < 'A' || z > 'Z' ) continue;
r.append( bAlphabet.at( ( *i & 31 ) - 1 ) );
}
return r;
}
std::string decode( std::string txt ) {
size_t len = txt.length();
while( len % 5 != 0 ) len--;
if( len != txt.length() ) txt = txt.substr( 0, len );
std::string r;
for( size_t i = 0; i < len; i += 5 ) {
r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) );
}
return r;
}
private:
std::vector<std::string> bAlphabet;
};
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *codes[] = {
"AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA",
"AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB",
"ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA",
"ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB",
"BABAA", "BABAB", "BABBA", "BABBB", "BBAAA",
"BBAAB", "BBBAA"
};
char *get_code(const char c) {
if (c >= 97 && c <= 122) return codes[c - 97];
return codes[26];
}
char get_char(const char *code) {
int i;
if (!strcmp(codes[26], code)) return ' ';
for (i = 0; i < 26; ++i) {
if (strcmp(codes[i], code) == 0) return 97 + i;
}
printf("\nCode \"%s\" is invalid\n", code);
exit(1);
}
void str_tolower(char s[]) {
int i;
for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]);
}
char *bacon_encode(char plain_text[], char message[]) {
int i, count;
int plen = strlen(plain_text), mlen = strlen(message);
int elen = 5 * plen;
char c;
char *p, *et, *mt;
et = malloc(elen + 1);
str_tolower(plain_text);
for (i = 0, p = et; i < plen; ++i, p += 5) {
c = plain_text[i];
strncpy(p, get_code(c), 5);
}
*++p = '\0';
str_tolower(message);
mt = calloc(mlen + 1, 1);
for (i = 0, count = 0; i < mlen; ++i) {
c = message[i];
if (c >= 'a' && c <= 'z') {
if (et[count] == 'A')
mt[i] = c;
else
mt[i] = c - 32;
if (++count == elen) break;
}
else mt[i] = c;
}
free(et);
return mt;
}
char *bacon_decode(char cipher_text[]) {
int i, count, clen = strlen(cipher_text);
int plen;
char *p, *ct, *pt;
char c, quintet[6];
ct = calloc(clen + 1, 1);
for (i = 0, count = 0; i < clen; ++i) {
c = cipher_text[i];
if (c >= 'a' && c <= 'z')
ct[count++] = 'A';
else if (c >= 'A' && c <= 'Z')
ct[count++] = 'B';
}
plen = strlen(ct) / 5;
pt = malloc(plen + 1);
for (i = 0, p = ct; i < plen; ++i, p += 5) {
strncpy(quintet, p, 5);
quintet[5] = '\0';
pt[i] = get_char(quintet);
}
pt[plen] = '\0';
free(ct);
return pt;
}
int main() {
char plain_text[] = "the quick brown fox jumps over the lazy dog";
char message[] = "bacon's cipher is a method of steganography created by francis bacon."
"this task is to implement a program for encryption and decryption of "
"plaintext using the simple alphabet of the baconian cipher or some "
"other kind of representation of this alphabet (make anything signify anything). "
"the baconian alphabet may optionally be extended to encode all lower "
"case characters individually and/or adding a few punctuation characters "
"such as the space.";
char *cipher_text, *hidden_text;
cipher_text = bacon_encode(plain_text, message);
printf("Cipher text ->\n\n%s\n", cipher_text);
hidden_text = bacon_decode(cipher_text);
printf("\nHidden text ->\n\n%s\n", hidden_text);
free(cipher_text);
free(hidden_text);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | public int[,] Spiral(int n) {
int[,] result = new int[n, n];
int pos = 0;
int count = n;
int value = -n;
int sum = -1;
do {
value = -1 * value / n;
for (int i = 0; i < count; i++) {
sum += value;
result[sum / n, sum % n] = pos++;
}
value *= n;
count--;
for (int i = 0; i < count; i++) {
sum += value;
result[sum / n, sum % n] = pos++;
}
} while (count > 0);
return result;
}
public void PrintArray(int[,] array) {
int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1;
for (int i = 0; i < array.GetLength(0); i++) {
for (int j = 0; j < array.GetLength(1); j++) {
Console.Write(array[i, j].ToString().PadLeft(n, ' '));
}
Console.WriteLine();
}
}
| #include <stdio.h>
#include <stdlib.h>
#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]
int main(int c, char **v)
{
int i, j, m = 0, n = 0;
if (c >= 2) m = atoi(v[1]);
if (c >= 3) n = atoi(v[2]);
if (m <= 0) m = 5;
if (n <= 0) n = m;
int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);
s[0] = (int*)(s + m);
for (i = 1; i < m; i++) s[i] = s[i - 1] + n;
int dx = 1, dy = 0, val = 0, t;
for (i = j = 0; valid(i, j); i += dy, j += dx ) {
for (; valid(i, j); j += dx, i += dy)
s[i][j] = ++val;
j -= dx; i -= dy;
t = dy; dy = dx; dx = -t;
}
for (t = 2; val /= 10; t++);
for(i = 0; i < m; i++)
for(j = 0; j < n || !putchar('\n'); j++)
printf("%*d", t, s[i][j]);
return 0;
}
|
Port the provided C# code into C while preserving the original functionality. | using System;
namespace FaulhabersTriangle {
internal class Frac {
private long num;
private long denom;
public static readonly Frac ZERO = new Frac(0, 1);
public static readonly Frac ONE = new Frac(1, 1);
public Frac(long n, long d) {
if (d == 0) {
throw new ArgumentException("d must not be zero");
}
long nn = n;
long dd = d;
if (nn == 0) {
dd = 1;
}
else if (dd < 0) {
nn = -nn;
dd = -dd;
}
long g = Math.Abs(Gcd(nn, dd));
if (g > 1) {
nn /= g;
dd /= g;
}
num = nn;
denom = dd;
}
private static long Gcd(long a, long b) {
if (b == 0) {
return a;
}
return Gcd(b, a % b);
}
public static Frac operator -(Frac self) {
return new Frac(-self.num, self.denom);
}
public static Frac operator +(Frac lhs, Frac rhs) {
return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom);
}
public static Frac operator -(Frac lhs, Frac rhs) {
return lhs + -rhs;
}
public static Frac operator *(Frac lhs, Frac rhs) {
return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom);
}
public static bool operator <(Frac lhs, Frac rhs) {
double x = (double)lhs.num / lhs.denom;
double y = (double)rhs.num / rhs.denom;
return x < y;
}
public static bool operator >(Frac lhs, Frac rhs) {
double x = (double)lhs.num / lhs.denom;
double y = (double)rhs.num / rhs.denom;
return x > y;
}
public static bool operator ==(Frac lhs, Frac rhs) {
return lhs.num == rhs.num && lhs.denom == rhs.denom;
}
public static bool operator !=(Frac lhs, Frac rhs) {
return lhs.num != rhs.num || lhs.denom != rhs.denom;
}
public override string ToString() {
if (denom == 1) {
return num.ToString();
}
return string.Format("{0}/{1}", num, denom);
}
public override bool Equals(object obj) {
var frac = obj as Frac;
return frac != null &&
num == frac.num &&
denom == frac.denom;
}
public override int GetHashCode() {
var hashCode = 1317992671;
hashCode = hashCode * -1521134295 + num.GetHashCode();
hashCode = hashCode * -1521134295 + denom.GetHashCode();
return hashCode;
}
}
class Program {
static Frac Bernoulli(int n) {
if (n < 0) {
throw new ArgumentException("n may not be negative or zero");
}
Frac[] a = new Frac[n + 1];
for (int m = 0; m <= n; m++) {
a[m] = new Frac(1, m + 1);
for (int j = m; j >= 1; j--) {
a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1);
}
}
if (n != 1) return a[0];
return -a[0];
}
static int Binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) {
throw new ArgumentException();
}
if (n == 0 || k == 0) return 1;
int num = 1;
for (int i = k + 1; i <= n; i++) {
num = num * i;
}
int denom = 1;
for (int i = 2; i <= n - k; i++) {
denom = denom * i;
}
return num / denom;
}
static Frac[] FaulhaberTriangle(int p) {
Frac[] coeffs = new Frac[p + 1];
for (int i = 0; i < p + 1; i++) {
coeffs[i] = Frac.ZERO;
}
Frac q = new Frac(1, p + 1);
int sign = -1;
for (int j = 0; j <= p; j++) {
sign *= -1;
coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j);
}
return coeffs;
}
static void Main(string[] args) {
for (int i = 0; i < 10; i++) {
Frac[] coeffs = FaulhaberTriangle(i);
foreach (Frac coeff in coeffs) {
Console.Write("{0,5} ", coeff);
}
Console.WriteLine();
}
}
}
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int binomial(int n, int k) {
int num, denom, i;
if (n < 0 || k < 0 || n < k) return -1;
if (n == 0 || k == 0) return 1;
num = 1;
for (i = k + 1; i <= n; ++i) {
num = num * i;
}
denom = 1;
for (i = 2; i <= n - k; ++i) {
denom *= i;
}
return num / denom;
}
int gcd(int a, int b) {
int temp;
while (b != 0) {
temp = a % b;
a = b;
b = temp;
}
return a;
}
typedef struct tFrac {
int num, denom;
} Frac;
Frac makeFrac(int n, int d) {
Frac result;
int g;
if (d == 0) {
result.num = 0;
result.denom = 0;
return result;
}
if (n == 0) {
d = 1;
} else if (d < 0) {
n = -n;
d = -d;
}
g = abs(gcd(n, d));
if (g > 1) {
n = n / g;
d = d / g;
}
result.num = n;
result.denom = d;
return result;
}
Frac negateFrac(Frac f) {
return makeFrac(-f.num, f.denom);
}
Frac subFrac(Frac lhs, Frac rhs) {
return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);
}
Frac multFrac(Frac lhs, Frac rhs) {
return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);
}
bool equalFrac(Frac lhs, Frac rhs) {
return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);
}
bool lessFrac(Frac lhs, Frac rhs) {
return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);
}
void printFrac(Frac f) {
char buffer[7];
int len;
if (f.denom != 1) {
snprintf(buffer, 7, "%d/%d", f.num, f.denom);
} else {
snprintf(buffer, 7, "%d", f.num);
}
len = 7 - strlen(buffer);
while (len-- > 0) {
putc(' ', stdout);
}
printf(buffer);
}
Frac bernoulli(int n) {
Frac a[16];
int j, m;
if (n < 0) {
a[0].num = 0;
a[0].denom = 0;
return a[0];
}
for (m = 0; m <= n; ++m) {
a[m] = makeFrac(1, m + 1);
for (j = m; j >= 1; --j) {
a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));
}
}
if (n != 1) {
return a[0];
}
return negateFrac(a[0]);
}
void faulhaber(int p) {
Frac q, *coeffs;
int j, sign;
coeffs = malloc(sizeof(Frac)*(p + 1));
q = makeFrac(1, p + 1);
sign = -1;
for (j = 0; j <= p; ++j) {
sign = -1 * sign;
coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));
}
for (j = 0; j <= p; ++j) {
printFrac(coeffs[j]);
}
printf("\n");
free(coeffs);
}
int main() {
int i;
for (i = 0; i < 10; ++i) {
faulhaber(i);
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original C# snippet. | using System;
namespace RosettaCode {
class Program {
static void Main(string[] args) {
for (int i = 0; i < args.Length; i++)
Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i]));
}
}
}
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
(void) printf("This program is named %s.\n", argv[0]);
for (i = 1; i < argc; ++i)
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}
|
Rewrite this program in C while keeping its functionality equivalent to the C# version. | using System;
namespace RosettaCode {
class Program {
static void Main(string[] args) {
for (int i = 0; i < args.Length; i++)
Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i]));
}
}
}
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
(void) printf("This program is named %s.\n", argv[0]);
for (i = 1; i < argc; ++i)
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}
|
Ensure the translated C code behaves exactly like the original C# snippet. | using System;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6 };
int[] c = new int[a.Length + b.Length];
a.CopyTo(c, 0);
b.CopyTo(c, a.Length);
foreach(int n in c)
{
Console.WriteLine(n.ToString());
}
}
}
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
(TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));
void *array_concat(const void *a, size_t an,
const void *b, size_t bn, size_t s)
{
char *p = malloc(s * (an + bn));
memcpy(p, a, an*s);
memcpy(p + an*s, b, bn*s);
return p;
}
const int a[] = { 1, 2, 3, 4, 5 };
const int b[] = { 6, 7, 8, 9, 0 };
int main(void)
{
unsigned int i;
int *c = ARRAY_CONCAT(int, a, 5, b, 5);
for(i = 0; i < 10; i++)
printf("%d\n", c[i]);
free(c);
return EXIT_SUCCCESS;
}
|
Change the programming language of this snippet from C# to C without modifying what it does. | using System;
namespace C_Sharp_Console {
class example {
static void Main() {
string word;
int num;
Console.Write("Enter an integer: ");
num = Console.Read();
Console.Write("Enter a String: ");
word = Console.ReadLine();
}
}
}
| #include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[BUFSIZ];
puts("Enter a string: ");
fgets(str, sizeof(str), stdin);
long num;
char buf[BUFSIZ];
do
{
puts("Enter 75000: ");
fgets(buf, sizeof(buf), stdin);
num = strtol(buf, NULL, 10);
} while (num != 75000);
return EXIT_SUCCESS;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
namespace Tests_With_Framework_4
{
class Bag : IEnumerable<Bag.Item>
{
List<Item> items;
const int MaxWeightAllowed = 400;
public Bag()
{
items = new List<Item>();
}
void AddItem(Item i)
{
if ((TotalWeight + i.Weight) <= MaxWeightAllowed)
items.Add(i);
}
public void Calculate(List<Item> items)
{
foreach (Item i in Sorte(items))
{
AddItem(i);
}
}
List<Item> Sorte(List<Item> inputItems)
{
List<Item> choosenItems = new List<Item>();
for (int i = 0; i < inputItems.Count; i++)
{
int j = -1;
if (i == 0)
{
choosenItems.Add(inputItems[i]);
}
if (i > 0)
{
if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))
{
choosenItems.Add(inputItems[i]);
}
}
}
return choosenItems;
}
bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)
{
if (!(lastBound < 0))
{
if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )
{
indxToAdd = lastBound;
}
return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);
}
if (indxToAdd > -1)
{
choosenItems.Insert(indxToAdd, knapsackItems[i]);
return true;
}
return false;
}
#region IEnumerable<Item> Members
IEnumerator<Item> IEnumerable<Item>.GetEnumerator()
{
foreach (Item i in items)
yield return i;
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return items.GetEnumerator();
}
#endregion
public int TotalWeight
{
get
{
var sum = 0;
foreach (Item i in this)
{
sum += i.Weight;
}
return sum;
}
}
public class Item
{
public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return Weight-Value; } }
public override string ToString()
{
return "Name : " + Name + " Wieght : " + Weight + " Value : " + Value + " ResultWV : " + ResultWV;
}
}
}
class Program
{
static void Main(string[] args)
{List<Bag.Item> knapsackItems = new List<Bag.Item>();
knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 });
knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 });
knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 });
knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 });
knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 });
knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 });
knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 });
knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 });
knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 });
knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 });
knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 });
knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 });
knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 });
knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 });
knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 });
knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 });
knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 });
knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 });
knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 });
knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 });
knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 });
knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 });
Bag b = new Bag();
b.Calculate(knapsackItems);
b.All(x => { Console.WriteLine(x); return true; });
Console.WriteLine(b.Sum(x => x.Weight));
Console.ReadKey();
}
}
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int weight;
int value;
} item_t;
item_t items[] = {
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"glucose", 15, 60},
{"tin", 68, 45},
{"banana", 27, 60},
{"apple", 39, 40},
{"cheese", 23, 30},
{"beer", 52, 10},
{"suntan cream", 11, 70},
{"camera", 32, 30},
{"T-shirt", 24, 15},
{"trousers", 48, 10},
{"umbrella", 73, 40},
{"waterproof trousers", 42, 70},
{"waterproof overclothes", 43, 75},
{"note-case", 22, 80},
{"sunglasses", 7, 20},
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10},
};
int *knapsack (item_t *items, int n, int w) {
int i, j, a, b, *mm, **m, *s;
mm = calloc((n + 1) * (w + 1), sizeof (int));
m = malloc((n + 1) * sizeof (int *));
m[0] = mm;
for (i = 1; i <= n; i++) {
m[i] = &mm[i * (w + 1)];
for (j = 0; j <= w; j++) {
if (items[i - 1].weight > j) {
m[i][j] = m[i - 1][j];
}
else {
a = m[i - 1][j];
b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;
m[i][j] = a > b ? a : b;
}
}
}
s = calloc(n, sizeof (int));
for (i = n, j = w; i > 0; i--) {
if (m[i][j] > m[i - 1][j]) {
s[i - 1] = 1;
j -= items[i - 1].weight;
}
}
free(mm);
free(m);
return s;
}
int main () {
int i, n, tw = 0, tv = 0, *s;
n = sizeof (items) / sizeof (item_t);
s = knapsack(items, n, 400);
for (i = 0; i < n; i++) {
if (s[i]) {
printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value);
tw += items[i].weight;
tv += items[i].value;
}
}
printf("%-22s %5d %5d\n", "totals:", tw, tv);
return 0;
}
|
Produce a language-to-language conversion: from C# to C, same semantics. | using System;
using System.Collections.Generic;
namespace Tests_With_Framework_4
{
class Bag : IEnumerable<Bag.Item>
{
List<Item> items;
const int MaxWeightAllowed = 400;
public Bag()
{
items = new List<Item>();
}
void AddItem(Item i)
{
if ((TotalWeight + i.Weight) <= MaxWeightAllowed)
items.Add(i);
}
public void Calculate(List<Item> items)
{
foreach (Item i in Sorte(items))
{
AddItem(i);
}
}
List<Item> Sorte(List<Item> inputItems)
{
List<Item> choosenItems = new List<Item>();
for (int i = 0; i < inputItems.Count; i++)
{
int j = -1;
if (i == 0)
{
choosenItems.Add(inputItems[i]);
}
if (i > 0)
{
if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))
{
choosenItems.Add(inputItems[i]);
}
}
}
return choosenItems;
}
bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)
{
if (!(lastBound < 0))
{
if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )
{
indxToAdd = lastBound;
}
return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);
}
if (indxToAdd > -1)
{
choosenItems.Insert(indxToAdd, knapsackItems[i]);
return true;
}
return false;
}
#region IEnumerable<Item> Members
IEnumerator<Item> IEnumerable<Item>.GetEnumerator()
{
foreach (Item i in items)
yield return i;
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return items.GetEnumerator();
}
#endregion
public int TotalWeight
{
get
{
var sum = 0;
foreach (Item i in this)
{
sum += i.Weight;
}
return sum;
}
}
public class Item
{
public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return Weight-Value; } }
public override string ToString()
{
return "Name : " + Name + " Wieght : " + Weight + " Value : " + Value + " ResultWV : " + ResultWV;
}
}
}
class Program
{
static void Main(string[] args)
{List<Bag.Item> knapsackItems = new List<Bag.Item>();
knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 });
knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 });
knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 });
knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 });
knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 });
knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 });
knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 });
knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 });
knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 });
knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 });
knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 });
knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 });
knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 });
knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 });
knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 });
knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 });
knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 });
knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 });
knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 });
knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 });
knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 });
knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 });
Bag b = new Bag();
b.Calculate(knapsackItems);
b.All(x => { Console.WriteLine(x); return true; });
Console.WriteLine(b.Sum(x => x.Weight));
Console.ReadKey();
}
}
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int weight;
int value;
} item_t;
item_t items[] = {
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"glucose", 15, 60},
{"tin", 68, 45},
{"banana", 27, 60},
{"apple", 39, 40},
{"cheese", 23, 30},
{"beer", 52, 10},
{"suntan cream", 11, 70},
{"camera", 32, 30},
{"T-shirt", 24, 15},
{"trousers", 48, 10},
{"umbrella", 73, 40},
{"waterproof trousers", 42, 70},
{"waterproof overclothes", 43, 75},
{"note-case", 22, 80},
{"sunglasses", 7, 20},
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10},
};
int *knapsack (item_t *items, int n, int w) {
int i, j, a, b, *mm, **m, *s;
mm = calloc((n + 1) * (w + 1), sizeof (int));
m = malloc((n + 1) * sizeof (int *));
m[0] = mm;
for (i = 1; i <= n; i++) {
m[i] = &mm[i * (w + 1)];
for (j = 0; j <= w; j++) {
if (items[i - 1].weight > j) {
m[i][j] = m[i - 1][j];
}
else {
a = m[i - 1][j];
b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;
m[i][j] = a > b ? a : b;
}
}
}
s = calloc(n, sizeof (int));
for (i = n, j = w; i > 0; i--) {
if (m[i][j] > m[i - 1][j]) {
s[i - 1] = 1;
j -= items[i - 1].weight;
}
}
free(mm);
free(m);
return s;
}
int main () {
int i, n, tw = 0, tv = 0, *s;
n = sizeof (items) / sizeof (item_t);
s = knapsack(items, n, 400);
for (i = 0; i < n; i++) {
if (s[i]) {
printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value);
tw += items[i].weight;
tv += items[i].value;
}
}
printf("%-22s %5d %5d\n", "totals:", tw, tv);
return 0;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | using System;
public class Program
{
public static void Main()
{
int[] empty = new int[0];
int[] list1 = { 1, 2 };
int[] list2 = { 3, 4 };
int[] list3 = { 1776, 1789 };
int[] list4 = { 7, 12 };
int[] list5 = { 4, 14, 23 };
int[] list6 = { 0, 1 };
int[] list7 = { 1, 2, 3 };
int[] list8 = { 30 };
int[] list9 = { 500, 100 };
foreach (var sequenceList in new [] {
new [] { list1, list2 },
new [] { list2, list1 },
new [] { list1, empty },
new [] { empty, list1 },
new [] { list3, list4, list5, list6 },
new [] { list7, list8, list9 },
new [] { list7, empty, list9 }
}) {
var cart = sequenceList.CartesianProduct()
.Select(tuple => $"({string.Join(", ", tuple)})");
Console.WriteLine($"{{{string.Join(", ", cart)}}}");
}
}
}
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from acc in accumulator
from item in sequence
select acc.Concat(new [] { item }));
}
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){
int i,j;
if(times==numSets){
printf("(");
for(i=0;i<times;i++){
printf("%d,",currentSet[i]);
}
printf("\b),");
}
else{
for(j=0;j<setLengths[times];j++){
currentSet[times] = sets[times][j];
cartesianProduct(sets,setLengths,currentSet,numSets,times+1);
}
}
}
void printSets(int** sets, int* setLengths, int numSets){
int i,j;
printf("\nNumber of sets : %d",numSets);
for(i=0;i<numSets+1;i++){
printf("\nSet %d : ",i+1);
for(j=0;j<setLengths[i];j++){
printf(" %d ",sets[i][j]);
}
}
}
void processInputString(char* str){
int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;
char *token,*holder,*holderToken;
for(i=0;str[i]!=00;i++)
if(str[i]=='x')
numSets++;
if(numSets==0){
printf("\n%s",str);
return;
}
currentSet = (int*)calloc(sizeof(int),numSets + 1);
setLengths = (int*)calloc(sizeof(int),numSets + 1);
sets = (int**)malloc((numSets + 1)*sizeof(int*));
token = strtok(str,"x");
while(token!=NULL){
holder = (char*)malloc(strlen(token)*sizeof(char));
j = 0;
for(i=0;token[i]!=00;i++){
if(token[i]>='0' && token[i]<='9')
holder[j++] = token[i];
else if(token[i]==',')
holder[j++] = ' ';
}
holder[j] = 00;
setLength = 0;
for(i=0;holder[i]!=00;i++)
if(holder[i]==' ')
setLength++;
if(setLength==0 && strlen(holder)==0){
printf("\n{}");
return;
}
setLengths[counter] = setLength+1;
sets[counter] = (int*)malloc((1+setLength)*sizeof(int));
k = 0;
start = 0;
for(l=0;holder[l]!=00;l++){
if(holder[l+1]==' '||holder[l+1]==00){
holderToken = (char*)malloc((l+1-start)*sizeof(char));
strncpy(holderToken,holder + start,l+1-start);
sets[counter][k++] = atoi(holderToken);
start = l+2;
}
}
counter++;
token = strtok(NULL,"x");
}
printf("\n{");
cartesianProduct(sets,setLengths,currentSet,numSets + 1,0);
printf("\b}");
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]);
else
processInputString(argV[1]);
return 0;
}
|
Ensure the translated C code behaves exactly like the original C# snippet. | using System;
public class Program
{
public static void Main()
{
int[] empty = new int[0];
int[] list1 = { 1, 2 };
int[] list2 = { 3, 4 };
int[] list3 = { 1776, 1789 };
int[] list4 = { 7, 12 };
int[] list5 = { 4, 14, 23 };
int[] list6 = { 0, 1 };
int[] list7 = { 1, 2, 3 };
int[] list8 = { 30 };
int[] list9 = { 500, 100 };
foreach (var sequenceList in new [] {
new [] { list1, list2 },
new [] { list2, list1 },
new [] { list1, empty },
new [] { empty, list1 },
new [] { list3, list4, list5, list6 },
new [] { list7, list8, list9 },
new [] { list7, empty, list9 }
}) {
var cart = sequenceList.CartesianProduct()
.Select(tuple => $"({string.Join(", ", tuple)})");
Console.WriteLine($"{{{string.Join(", ", cart)}}}");
}
}
}
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from acc in accumulator
from item in sequence
select acc.Concat(new [] { item }));
}
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){
int i,j;
if(times==numSets){
printf("(");
for(i=0;i<times;i++){
printf("%d,",currentSet[i]);
}
printf("\b),");
}
else{
for(j=0;j<setLengths[times];j++){
currentSet[times] = sets[times][j];
cartesianProduct(sets,setLengths,currentSet,numSets,times+1);
}
}
}
void printSets(int** sets, int* setLengths, int numSets){
int i,j;
printf("\nNumber of sets : %d",numSets);
for(i=0;i<numSets+1;i++){
printf("\nSet %d : ",i+1);
for(j=0;j<setLengths[i];j++){
printf(" %d ",sets[i][j]);
}
}
}
void processInputString(char* str){
int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;
char *token,*holder,*holderToken;
for(i=0;str[i]!=00;i++)
if(str[i]=='x')
numSets++;
if(numSets==0){
printf("\n%s",str);
return;
}
currentSet = (int*)calloc(sizeof(int),numSets + 1);
setLengths = (int*)calloc(sizeof(int),numSets + 1);
sets = (int**)malloc((numSets + 1)*sizeof(int*));
token = strtok(str,"x");
while(token!=NULL){
holder = (char*)malloc(strlen(token)*sizeof(char));
j = 0;
for(i=0;token[i]!=00;i++){
if(token[i]>='0' && token[i]<='9')
holder[j++] = token[i];
else if(token[i]==',')
holder[j++] = ' ';
}
holder[j] = 00;
setLength = 0;
for(i=0;holder[i]!=00;i++)
if(holder[i]==' ')
setLength++;
if(setLength==0 && strlen(holder)==0){
printf("\n{}");
return;
}
setLengths[counter] = setLength+1;
sets[counter] = (int*)malloc((1+setLength)*sizeof(int));
k = 0;
start = 0;
for(l=0;holder[l]!=00;l++){
if(holder[l+1]==' '||holder[l+1]==00){
holderToken = (char*)malloc((l+1-start)*sizeof(char));
strncpy(holderToken,holder + start,l+1-start);
sets[counter][k++] = atoi(holderToken);
start = l+2;
}
}
counter++;
token = strtok(NULL,"x");
}
printf("\n{");
cartesianProduct(sets,setLengths,currentSet,numSets + 1,0);
printf("\b}");
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]);
else
processInputString(argV[1]);
return 0;
}
|
Write the same algorithm in C as shown in this C# implementation. | using System;
class Program
{
static void Main(string[] args)
{
var cube = new Func<double, double>(x => Math.Pow(x, 3.0));
var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));
var functionTuples = new[]
{
(forward: Math.Sin, backward: Math.Asin),
(forward: Math.Cos, backward: Math.Acos),
(forward: cube, backward: croot)
};
foreach (var ft in functionTuples)
{
Console.WriteLine(ft.backward(ft.forward(0.5)));
}
}
}
| #include <stdlib.h>
#include <stdio.h>
#include <math.h>
typedef double (*Class2Func)(double);
double functionA( double v)
{
return v*v*v;
}
double functionB(double v)
{
return exp(log(v)/3);
}
double Function1( Class2Func f2, double val )
{
return f2(val);
}
Class2Func WhichFunc( int idx)
{
return (idx < 4) ? &functionA : &functionB;
}
Class2Func funcListA[] = {&functionA, &sin, &cos, &tan };
Class2Func funcListB[] = {&functionB, &asin, &acos, &atan };
double InvokeComposed( Class2Func f1, Class2Func f2, double val )
{
return f1(f2(val));
}
typedef struct sComposition {
Class2Func f1;
Class2Func f2;
} *Composition;
Composition Compose( Class2Func f1, Class2Func f2)
{
Composition comp = malloc(sizeof(struct sComposition));
comp->f1 = f1;
comp->f2 = f2;
return comp;
}
double CallComposed( Composition comp, double val )
{
return comp->f1( comp->f2(val) );
}
int main(int argc, char *argv[])
{
int ix;
Composition c;
printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0));
for (ix=0; ix<4; ix++) {
c = Compose(funcListA[ix], funcListB[ix]);
printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9));
}
return 0;
}
|
Generate a C translation of this C# snippet without changing its computational steps. | namespace RosettaCode.ProperDivisors
{
using System;
using System.Collections.Generic;
using System.Linq;
internal static class Program
{
private static IEnumerable<int> ProperDivisors(int number)
{
return
Enumerable.Range(1, number / 2)
.Where(divisor => number % divisor == 0);
}
private static void Main()
{
foreach (var number in Enumerable.Range(1, 10))
{
Console.WriteLine("{0}: {{{1}}}", number,
string.Join(", ", ProperDivisors(number)));
}
var record = Enumerable.Range(1, 20000).Select(number => new
{
Number = number,
Count = ProperDivisors(number).Count()
}).OrderByDescending(currentRecord => currentRecord.Count).First();
Console.WriteLine("{0}: {1}", record.Number, record.Count);
}
}
}
| #include <stdio.h>
#include <stdbool.h>
int proper_divisors(const int n, bool print_flag)
{
int count = 0;
for (int i = 1; i < n; ++i) {
if (n % i == 0) {
count++;
if (print_flag)
printf("%d ", i);
}
}
if (print_flag)
printf("\n");
return count;
}
int main(void)
{
for (int i = 1; i <= 10; ++i) {
printf("%d: ", i);
proper_divisors(i, true);
}
int max = 0;
int max_i = 1;
for (int i = 1; i <= 20000; ++i) {
int v = proper_divisors(i, false);
if (v >= max) {
max = v;
max_i = i;
}
}
printf("%d with %d divisors\n", max_i, max);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | namespace RosettaCode.ProperDivisors
{
using System;
using System.Collections.Generic;
using System.Linq;
internal static class Program
{
private static IEnumerable<int> ProperDivisors(int number)
{
return
Enumerable.Range(1, number / 2)
.Where(divisor => number % divisor == 0);
}
private static void Main()
{
foreach (var number in Enumerable.Range(1, 10))
{
Console.WriteLine("{0}: {{{1}}}", number,
string.Join(", ", ProperDivisors(number)));
}
var record = Enumerable.Range(1, 20000).Select(number => new
{
Number = number,
Count = ProperDivisors(number).Count()
}).OrderByDescending(currentRecord => currentRecord.Count).First();
Console.WriteLine("{0}: {1}", record.Number, record.Count);
}
}
}
| #include <stdio.h>
#include <stdbool.h>
int proper_divisors(const int n, bool print_flag)
{
int count = 0;
for (int i = 1; i < n; ++i) {
if (n % i == 0) {
count++;
if (print_flag)
printf("%d ", i);
}
}
if (print_flag)
printf("\n");
return count;
}
int main(void)
{
for (int i = 1; i <= 10; ++i) {
printf("%d: ", i);
proper_divisors(i, true);
}
int max = 0;
int max_i = 1;
for (int i = 1; i <= 20000; ++i) {
int v = proper_divisors(i, false);
if (v >= max) {
max = v;
max_i = i;
}
}
printf("%d with %d divisors\n", max_i, max);
return 0;
}
|
Translate this program into C but keep the logic exactly as in C#. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
class Program
{
static string CreateXML(Dictionary<string, string> characterRemarks)
{
var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key)));
var xml = new XElement("CharacterRemarks", remarks);
return xml.ToString();
}
static void Main(string[] args)
{
var characterRemarks = new Dictionary<string, string>
{
{ "April", "Bubbly: I'm > Tam and <= Emily" },
{ "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" },
{ "Emily", "Short & shrift" }
};
string xml = CreateXML(characterRemarks);
Console.WriteLine(xml);
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
const char *names[] = {
"April", "Tam O'Shanter", "Emily", NULL
};
const char *remarks[] = {
"Bubbly: I'm > Tam and <= Emily",
"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift", NULL
};
int main()
{
xmlDoc *doc = NULL;
xmlNode *root = NULL, *node;
const char **next;
int a;
doc = xmlNewDoc("1.0");
root = xmlNewNode(NULL, "CharacterRemarks");
xmlDocSetRootElement(doc, root);
for(next = names, a = 0; *next != NULL; next++, a++) {
node = xmlNewNode(NULL, "Character");
(void)xmlNewProp(node, "name", *next);
xmlAddChild(node, xmlNewText(remarks[a]));
xmlAddChild(root, node);
}
xmlElemDump(stdout, doc, root);
xmlFreeDoc(doc);
xmlCleanupParser();
return EXIT_SUCCESS;
}
|
Can you help me rewrite this code in C instead of C#, keeping it the same logically? | using System;
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string str = "I am a string";
if (new Regex("string$").IsMatch(str)) {
Console.WriteLine("Ends with string.");
}
str = new Regex(" a ").Replace(str, " another ");
Console.WriteLine(str);
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>
int main()
{
regex_t preg;
regmatch_t substmatch[1];
const char *tp = "string$";
const char *t1 = "this is a matching string";
const char *t2 = "this is not a matching string!";
const char *ss = "istyfied";
regcomp(&preg, "string$", REG_EXTENDED);
printf("'%s' %smatched with '%s'\n", t1,
(regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp);
printf("'%s' %smatched with '%s'\n", t2,
(regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp);
regfree(&preg);
regcomp(&preg, "a[a-z]+", REG_EXTENDED);
if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )
{
char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +
(strlen(t1) - substmatch[0].rm_eo) + 2);
memcpy(ns, t1, substmatch[0].rm_so+1);
memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));
memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],
strlen(&t1[substmatch[0].rm_eo]));
ns[ substmatch[0].rm_so + strlen(ss) +
strlen(&t1[substmatch[0].rm_eo]) ] = 0;
printf("mod string: '%s'\n", ns);
free(ns);
} else {
printf("the string '%s' is the same: no matching!\n", t1);
}
regfree(&preg);
return 0;
}
|
Port the provided C# code into C while preserving the original functionality. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class RealisticGuess
{
private int max;
private int min;
private int guess;
public void Start()
{
Console.Clear();
string input;
try
{
Console.WriteLine("Please enter the lower boundary");
input = Console.ReadLine();
min = Convert.ToInt32(input);
Console.WriteLine("Please enter the upper boundary");
input = Console.ReadLine();
max = Convert.ToInt32(input);
}
catch (FormatException)
{
Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again.");
Console.ReadKey(true);
Start();
}
Console.WriteLine("Think of a number between {0} and {1}.", min, max);
Thread.Sleep(2500);
Console.WriteLine("Ready?");
Console.WriteLine("Press any key to begin.");
Console.ReadKey(true);
Guess(min, max);
}
public void Guess(int min, int max)
{
int counter = 1;
string userAnswer;
bool correct = false;
Random rand = new Random();
while (correct == false)
{
guess = rand.Next(min, max);
Console.Clear();
Console.WriteLine("{0}", guess);
Console.WriteLine("Is this number correct? {Y/N}");
userAnswer = Console.ReadLine();
if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N")
{
Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'");
Console.WriteLine("Is the number correct? {Y/N}");
userAnswer = Console.ReadLine();
}
if (userAnswer == "y" || userAnswer == "Y")
{
correct = true;
}
if (userAnswer == "n" || userAnswer == "N")
{
counter++;
if (max == min)
{
Console.WriteLine("Error: Range Intersect. Press enter to restart the game.");
Console.ReadKey(true);
Guess(1, 101);
}
Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}");
userAnswer = Console.ReadLine();
if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H")
{
Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'");
Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}");
userAnswer = Console.ReadLine();
}
if (userAnswer == "l" || userAnswer == "L")
{
max = guess;
}
if (userAnswer == "h" || userAnswer == "H")
{
min = guess;
}
}
}
if (correct == true)
{
EndAndLoop(counter);
}
}
public void EndAndLoop(int iterations)
{
string userChoice;
bool loop = false;
Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations);
while (loop == false)
{
Console.WriteLine("Would you like to play again? {Y/N}");
userChoice = Console.ReadLine();
if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n")
{
Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.");
}
if (userChoice == "Y" || userChoice == "y")
{
Start();
}
if (userChoice == "N" || userChoice == "n")
{
Environment.Exit(1);
}
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Title = "Random Number";
RealisticGuess game = new RealisticGuess();
game.Start();
}
}
}
| #include <stdio.h>
int main(){
int bounds[ 2 ] = {1, 100};
char input[ 2 ] = " ";
int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] );
do{
switch( input[ 0 ] ){
case 'H':
bounds[ 1 ] = choice;
break;
case 'L':
bounds[ 0 ] = choice;
break;
case 'Y':
printf( "\nAwwwright\n" );
return 0;
}
choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( "Is the number %d? (Y/H/L) ", choice );
}while( scanf( "%1s", input ) == 1 );
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class RealisticGuess
{
private int max;
private int min;
private int guess;
public void Start()
{
Console.Clear();
string input;
try
{
Console.WriteLine("Please enter the lower boundary");
input = Console.ReadLine();
min = Convert.ToInt32(input);
Console.WriteLine("Please enter the upper boundary");
input = Console.ReadLine();
max = Convert.ToInt32(input);
}
catch (FormatException)
{
Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again.");
Console.ReadKey(true);
Start();
}
Console.WriteLine("Think of a number between {0} and {1}.", min, max);
Thread.Sleep(2500);
Console.WriteLine("Ready?");
Console.WriteLine("Press any key to begin.");
Console.ReadKey(true);
Guess(min, max);
}
public void Guess(int min, int max)
{
int counter = 1;
string userAnswer;
bool correct = false;
Random rand = new Random();
while (correct == false)
{
guess = rand.Next(min, max);
Console.Clear();
Console.WriteLine("{0}", guess);
Console.WriteLine("Is this number correct? {Y/N}");
userAnswer = Console.ReadLine();
if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N")
{
Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'");
Console.WriteLine("Is the number correct? {Y/N}");
userAnswer = Console.ReadLine();
}
if (userAnswer == "y" || userAnswer == "Y")
{
correct = true;
}
if (userAnswer == "n" || userAnswer == "N")
{
counter++;
if (max == min)
{
Console.WriteLine("Error: Range Intersect. Press enter to restart the game.");
Console.ReadKey(true);
Guess(1, 101);
}
Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}");
userAnswer = Console.ReadLine();
if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H")
{
Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'");
Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}");
userAnswer = Console.ReadLine();
}
if (userAnswer == "l" || userAnswer == "L")
{
max = guess;
}
if (userAnswer == "h" || userAnswer == "H")
{
min = guess;
}
}
}
if (correct == true)
{
EndAndLoop(counter);
}
}
public void EndAndLoop(int iterations)
{
string userChoice;
bool loop = false;
Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations);
while (loop == false)
{
Console.WriteLine("Would you like to play again? {Y/N}");
userChoice = Console.ReadLine();
if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n")
{
Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.");
}
if (userChoice == "Y" || userChoice == "y")
{
Start();
}
if (userChoice == "N" || userChoice == "n")
{
Environment.Exit(1);
}
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Title = "Random Number";
RealisticGuess game = new RealisticGuess();
game.Start();
}
}
}
| #include <stdio.h>
int main(){
int bounds[ 2 ] = {1, 100};
char input[ 2 ] = " ";
int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] );
do{
switch( input[ 0 ] ){
case 'H':
bounds[ 1 ] = choice;
break;
case 'L':
bounds[ 0 ] = choice;
break;
case 'Y':
printf( "\nAwwwright\n" );
return 0;
}
choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( "Is the number %d? (Y/H/L) ", choice );
}while( scanf( "%1s", input ) == 1 );
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the C# version. | static class Program
{
static void Main()
{
System.Collections.Hashtable h = new System.Collections.Hashtable();
string[] keys = { "foo", "bar", "val" };
string[] values = { "little", "miss", "muffet" };
System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length.");
for (int i = 0; i < keys.Length; i++)
{
h.Add(keys[i], values[i]);
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define KeyType const char *
#define ValType int
#define HASH_SIZE 4096
unsigned strhashkey( const char * key, int max)
{
unsigned h=0;
unsigned hl, hr;
while(*key) {
h += *key;
hl= 0x5C5 ^ (h&0xfff00000 )>>18;
hr =(h&0x000fffff );
h = hl ^ hr ^ *key++;
}
return h % max;
}
typedef struct sHme {
KeyType key;
ValType value;
struct sHme *link;
} *MapEntry;
typedef struct he {
MapEntry first, last;
} HashElement;
HashElement hash[HASH_SIZE];
typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);
typedef void (*ValCopyF)(ValType *vdest, ValType vsrc);
typedef unsigned (*KeyHashF)( KeyType key, int upperBound );
typedef int (*KeyCmprF)(KeyType key1, KeyType key2);
void HashAddH( KeyType key, ValType value,
KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
(*copyVal)(&m_ent->value, value);
}
else {
MapEntry last;
MapEntry hme = malloc(sizeof(struct sHme));
(*copyKey)(&hme->key, key);
(*copyVal)(&hme->value, value);
hme->link = NULL;
last = hash[hix].last;
if (last) {
last->link = hme;
}
else
hash[hix].first = hme;
hash[hix].last = hme;
}
}
int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
*val = m_ent->value;
}
return (m_ent != NULL);
}
void copyStr(const char**dest, const char *src)
{
*dest = strdup(src);
}
void copyInt( int *dest, int src)
{
*dest = src;
}
int strCompare( const char *key1, const char *key2)
{
return strcmp(key1, key2) == 0;
}
void HashAdd( KeyType key, ValType value )
{
HashAddH( key, value, ©Str, ©Int, &strhashkey, &strCompare);
}
int HashGet(ValType *val, KeyType key)
{
return HashGetH( val, key, &strhashkey, &strCompare);
}
int main()
{
static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" };
static int valuList[] = {1,43,640, 747, 42, 42};
int ix;
for (ix=0; ix<6; ix++) {
HashAdd(keyList[ix], valuList[ix]);
}
return 0;
}
|
Transform the following C# implementation into C, maintaining the same output and logic. | using System;
public class Program
{
static void Main()
{
PrintBins(new [] { 23, 37, 43, 53, 67, 83 },
95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55
);
Console.WriteLine();
PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },
445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,
253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,
622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,
945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759,
898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,
736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,
892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749);
}
static void PrintBins(int[] limits, params int[] data)
{
int[] bins = Bins(limits, data);
Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}");
for (int i = 0; i < limits.Length-1; i++) {
Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}");
}
Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}");
}
static int[] Bins(int[] limits, params int[] data)
{
Array.Sort(limits);
int[] bins = new int[limits.Length + 1];
foreach (int n in data) {
int i = Array.BinarySearch(limits, n);
i = i < 0 ? ~i : i+1;
bins[i]++;
}
return bins;
}
}
| #include <stdio.h>
#include <stdlib.h>
size_t upper_bound(const int* array, size_t n, int value) {
size_t start = 0;
while (n > 0) {
size_t step = n / 2;
size_t index = start + step;
if (value >= array[index]) {
start = index + 1;
n -= step + 1;
} else {
n = step;
}
}
return start;
}
int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {
int* result = calloc(nlimits + 1, sizeof(int));
if (result == NULL)
return NULL;
for (size_t i = 0; i < ndata; ++i)
++result[upper_bound(limits, nlimits, data[i])];
return result;
}
void print_bins(const int* limits, size_t n, const int* bins) {
if (n == 0)
return;
printf(" < %3d: %2d\n", limits[0], bins[0]);
for (size_t i = 1; i < n; ++i)
printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]);
printf(">= %3d : %2d\n", limits[n - 1], bins[n]);
}
int main() {
const int limits1[] = {23, 37, 43, 53, 67, 83};
const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,
5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,
8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,
40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
printf("Example 1:\n");
size_t n = sizeof(limits1) / sizeof(int);
int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits1, n, b);
free(b);
const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};
const int data2[] = {
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
printf("\nExample 2:\n");
n = sizeof(limits2) / sizeof(int);
b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits2, n, b);
free(b);
return EXIT_SUCCESS;
}
|
Rewrite the snippet below in C so it works the same as the original C# code. | using System;
public class Program
{
static void Main()
{
PrintBins(new [] { 23, 37, 43, 53, 67, 83 },
95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55
);
Console.WriteLine();
PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },
445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,
253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,
622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,
945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759,
898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,
736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,
892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749);
}
static void PrintBins(int[] limits, params int[] data)
{
int[] bins = Bins(limits, data);
Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}");
for (int i = 0; i < limits.Length-1; i++) {
Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}");
}
Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}");
}
static int[] Bins(int[] limits, params int[] data)
{
Array.Sort(limits);
int[] bins = new int[limits.Length + 1];
foreach (int n in data) {
int i = Array.BinarySearch(limits, n);
i = i < 0 ? ~i : i+1;
bins[i]++;
}
return bins;
}
}
| #include <stdio.h>
#include <stdlib.h>
size_t upper_bound(const int* array, size_t n, int value) {
size_t start = 0;
while (n > 0) {
size_t step = n / 2;
size_t index = start + step;
if (value >= array[index]) {
start = index + 1;
n -= step + 1;
} else {
n = step;
}
}
return start;
}
int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {
int* result = calloc(nlimits + 1, sizeof(int));
if (result == NULL)
return NULL;
for (size_t i = 0; i < ndata; ++i)
++result[upper_bound(limits, nlimits, data[i])];
return result;
}
void print_bins(const int* limits, size_t n, const int* bins) {
if (n == 0)
return;
printf(" < %3d: %2d\n", limits[0], bins[0]);
for (size_t i = 1; i < n; ++i)
printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]);
printf(">= %3d : %2d\n", limits[n - 1], bins[n]);
}
int main() {
const int limits1[] = {23, 37, 43, 53, 67, 83};
const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,
5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,
8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,
40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
printf("Example 1:\n");
size_t n = sizeof(limits1) / sizeof(int);
int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits1, n, b);
free(b);
const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};
const int data2[] = {
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
printf("\nExample 2:\n");
n = sizeof(limits2) / sizeof(int);
b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits2, n, b);
free(b);
return EXIT_SUCCESS;
}
|
Translate this program into C but keep the logic exactly as in C#. | using System;
public class Program
{
static void Main()
{
PrintBins(new [] { 23, 37, 43, 53, 67, 83 },
95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55
);
Console.WriteLine();
PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },
445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,
253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,
622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,
945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759,
898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,
736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,
892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749);
}
static void PrintBins(int[] limits, params int[] data)
{
int[] bins = Bins(limits, data);
Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}");
for (int i = 0; i < limits.Length-1; i++) {
Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}");
}
Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}");
}
static int[] Bins(int[] limits, params int[] data)
{
Array.Sort(limits);
int[] bins = new int[limits.Length + 1];
foreach (int n in data) {
int i = Array.BinarySearch(limits, n);
i = i < 0 ? ~i : i+1;
bins[i]++;
}
return bins;
}
}
| #include <stdio.h>
#include <stdlib.h>
size_t upper_bound(const int* array, size_t n, int value) {
size_t start = 0;
while (n > 0) {
size_t step = n / 2;
size_t index = start + step;
if (value >= array[index]) {
start = index + 1;
n -= step + 1;
} else {
n = step;
}
}
return start;
}
int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {
int* result = calloc(nlimits + 1, sizeof(int));
if (result == NULL)
return NULL;
for (size_t i = 0; i < ndata; ++i)
++result[upper_bound(limits, nlimits, data[i])];
return result;
}
void print_bins(const int* limits, size_t n, const int* bins) {
if (n == 0)
return;
printf(" < %3d: %2d\n", limits[0], bins[0]);
for (size_t i = 1; i < n; ++i)
printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]);
printf(">= %3d : %2d\n", limits[n - 1], bins[n]);
}
int main() {
const int limits1[] = {23, 37, 43, 53, 67, 83};
const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,
5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,
8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,
40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
printf("Example 1:\n");
size_t n = sizeof(limits1) / sizeof(int);
int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits1, n, b);
free(b);
const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};
const int data2[] = {
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
printf("\nExample 2:\n");
n = sizeof(limits2) / sizeof(int);
b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits2, n, b);
free(b);
return EXIT_SUCCESS;
}
|
Port the following code from C# to C with equivalent syntax and logic. | using System;
using System.Drawing;
using System.Windows.Forms;
class CSharpPendulum
{
Form _form;
Timer _timer;
double _angle = Math.PI / 2,
_angleAccel,
_angleVelocity = 0,
_dt = 0.1;
int _length = 50;
[STAThread]
static void Main()
{
var p = new CSharpPendulum();
}
public CSharpPendulum()
{
_form = new Form() { Text = "Pendulum", Width = 200, Height = 200 };
_timer = new Timer() { Interval = 30 };
_timer.Tick += delegate(object sender, EventArgs e)
{
int anchorX = (_form.Width / 2) - 12,
anchorY = _form.Height / 4,
ballX = anchorX + (int)(Math.Sin(_angle) * _length),
ballY = anchorY + (int)(Math.Cos(_angle) * _length);
_angleAccel = -9.81 / _length * Math.Sin(_angle);
_angleVelocity += _angleAccel * _dt;
_angle += _angleVelocity * _dt;
Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);
Graphics g = Graphics.FromImage(dblBuffer);
Graphics f = Graphics.FromHwnd(_form.Handle);
g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));
g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);
g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);
f.Clear(Color.White);
f.DrawImage(dblBuffer, new Point(0, 0));
};
_timer.Start();
Application.Run(_form);
}
}
| #include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <sys/time.h>
#define length 5
#define g 9.8
double alpha, accl, omega = 0, E;
struct timeval tv;
double elappsed() {
struct timeval now;
gettimeofday(&now, 0);
int ret = (now.tv_sec - tv.tv_sec) * 1000000
+ now.tv_usec - tv.tv_usec;
tv = now;
return ret / 1.e6;
}
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, 1);
}
void render()
{
double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);
resize(640, 320);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2d(320, 0);
glVertex2d(x, y);
glEnd();
glFlush();
double us = elappsed();
alpha += (omega + us * accl / 2) * us;
omega += accl * us;
if (length * g * (1 - cos(alpha)) >= E) {
alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);
omega = 0;
}
accl = -g / length * sin(alpha);
}
void init_gfx(int *c, char **v)
{
glutInit(c, v);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(640, 320);
glutIdleFunc(render);
glutCreateWindow("Pendulum");
}
int main(int c, char **v)
{
alpha = 4 * atan2(1, 1) / 2.1;
E = length * g * (1 - cos(alpha));
accl = -g / length * sin(alpha);
omega = 0;
gettimeofday(&tv, 0);
init_gfx(&c, v);
glutMainLoop();
return 0;
}
|
Generate an equivalent C version of this C# code. | using System;
using System.Drawing;
using System.Windows.Forms;
class CSharpPendulum
{
Form _form;
Timer _timer;
double _angle = Math.PI / 2,
_angleAccel,
_angleVelocity = 0,
_dt = 0.1;
int _length = 50;
[STAThread]
static void Main()
{
var p = new CSharpPendulum();
}
public CSharpPendulum()
{
_form = new Form() { Text = "Pendulum", Width = 200, Height = 200 };
_timer = new Timer() { Interval = 30 };
_timer.Tick += delegate(object sender, EventArgs e)
{
int anchorX = (_form.Width / 2) - 12,
anchorY = _form.Height / 4,
ballX = anchorX + (int)(Math.Sin(_angle) * _length),
ballY = anchorY + (int)(Math.Cos(_angle) * _length);
_angleAccel = -9.81 / _length * Math.Sin(_angle);
_angleVelocity += _angleAccel * _dt;
_angle += _angleVelocity * _dt;
Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);
Graphics g = Graphics.FromImage(dblBuffer);
Graphics f = Graphics.FromHwnd(_form.Handle);
g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));
g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);
g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);
f.Clear(Color.White);
f.DrawImage(dblBuffer, new Point(0, 0));
};
_timer.Start();
Application.Run(_form);
}
}
| #include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <sys/time.h>
#define length 5
#define g 9.8
double alpha, accl, omega = 0, E;
struct timeval tv;
double elappsed() {
struct timeval now;
gettimeofday(&now, 0);
int ret = (now.tv_sec - tv.tv_sec) * 1000000
+ now.tv_usec - tv.tv_usec;
tv = now;
return ret / 1.e6;
}
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, 1);
}
void render()
{
double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);
resize(640, 320);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2d(320, 0);
glVertex2d(x, y);
glEnd();
glFlush();
double us = elappsed();
alpha += (omega + us * accl / 2) * us;
omega += accl * us;
if (length * g * (1 - cos(alpha)) >= E) {
alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);
omega = 0;
}
accl = -g / length * sin(alpha);
}
void init_gfx(int *c, char **v)
{
glutInit(c, v);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(640, 320);
glutIdleFunc(render);
glutCreateWindow("Pendulum");
}
int main(int c, char **v)
{
alpha = 4 * atan2(1, 1) / 2.1;
E = length * g * (1 - cos(alpha));
accl = -g / length * sin(alpha);
omega = 0;
gettimeofday(&tv, 0);
init_gfx(&c, v);
glutMainLoop();
return 0;
}
|
Write the same code in C as shown below in C#. | using System;
using System.Collections.Generic;
using System.Text;
public class HeapSortClass
{
public static void HeapSort<T>(T[] array)
{
HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);
}
public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)
{
HeapSort<T>(array, offset, length, comparer.Compare);
}
public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)
{
for (int i = 0; i < length; i++)
{
int index = i;
T item = array[offset + i];
while (index > 0 &&
comparison(array[offset + (index - 1) / 2], item) < 0)
{
int top = (index - 1) / 2;
array[offset + index] = array[offset + top];
index = top;
}
array[offset + index] = item;
}
for (int i = length - 1; i > 0; i--)
{
T last = array[offset + i];
array[offset + i] = array[offset];
int index = 0;
while (index * 2 + 1 < i)
{
int left = index * 2 + 1, right = left + 1;
if (right < i && comparison(array[offset + left], array[offset + right]) < 0)
{
if (comparison(last, array[offset + right]) > 0) break;
array[offset + index] = array[offset + right];
index = right;
}
else
{
if (comparison(last, array[offset + left]) > 0) break;
array[offset + index] = array[offset + left];
index = left;
}
}
array[offset + index] = last;
}
}
static void Main()
{
byte[] r = {5, 4, 1, 2};
HeapSort(r);
string[] s = { "-", "D", "a", "33" };
HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);
}
}
| #include <stdio.h>
int max (int *a, int n, int i, int j, int k) {
int m = i;
if (j < n && a[j] > a[m]) {
m = j;
}
if (k < n && a[k] > a[m]) {
m = k;
}
return m;
}
void downheap (int *a, int n, int i) {
while (1) {
int j = max(a, n, i, 2 * i + 1, 2 * i + 2);
if (j == i) {
break;
}
int t = a[i];
a[i] = a[j];
a[j] = t;
i = j;
}
}
void heapsort (int *a, int n) {
int i;
for (i = (n - 2) / 2; i >= 0; i--) {
downheap(a, n, i);
}
for (i = 0; i < n; i++) {
int t = a[n - i - 1];
a[n - i - 1] = a[0];
a[0] = t;
downheap(a, n - i - 1, 0);
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
heapsort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
|
Ensure the translated C code behaves exactly like the original C# snippet. | using System;
using System.Linq;
using System.Collections.Generic;
public struct Card
{
public Card(string rank, string suit) : this()
{
Rank = rank;
Suit = suit;
}
public string Rank { get; }
public string Suit { get; }
public override string ToString() => $"{Rank} of {Suit}";
}
public class Deck : IEnumerable<Card>
{
static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
readonly List<Card> cards;
public Deck() {
cards = (from suit in suits
from rank in ranks
select new Card(rank, suit)).ToList();
}
public int Count => cards.Count;
public void Shuffle() {
var random = new Random();
for (int i = 0; i < cards.Count; i++) {
int r = random.Next(i, cards.Count);
var temp = cards[i];
cards[i] = cards[r];
cards[r] = temp;
}
}
public Card Deal() {
int last = cards.Count - 1;
Card card = cards[last];
cards.RemoveAt(last);
return card;
}
public IEnumerator<Card> GetEnumerator() {
for (int i = cards.Count - 1; i >= 0; i--)
yield return cards[i];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
| #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int locale_ok = 0;
wchar_t s_suits[] = L"♠♥♦♣";
const char *s_suits_ascii[] = { "S", "H", "D", "C" };
const char *s_nums[] = { "WHAT",
"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K",
"OVERFLOW"
};
typedef struct { int suit, number, _s; } card_t, *card;
typedef struct { int n; card_t cards[52]; } deck_t, *deck;
void show_card(card c)
{
if (locale_ok)
printf(" %lc%s", s_suits[c->suit], s_nums[c->number]);
else
printf(" %s%s", s_suits_ascii[c->suit], s_nums[c->number]);
}
deck new_deck()
{
int i, j, k;
deck d = malloc(sizeof(deck_t));
d->n = 52;
for (i = k = 0; i < 4; i++)
for (j = 1; j <= 13; j++, k++) {
d->cards[k].suit = i;
d->cards[k].number = j;
}
return d;
}
void show_deck(deck d)
{
int i;
printf("%d cards:", d->n);
for (i = 0; i < d->n; i++)
show_card(d->cards + i);
printf("\n");
}
int cmp_card(const void *a, const void *b)
{
int x = ((card)a)->_s, y = ((card)b)->_s;
return x < y ? -1 : x > y;
}
card deal_card(deck d)
{
if (!d->n) return 0;
return d->cards + --d->n;
}
void shuffle_deck(deck d)
{
int i;
for (i = 0; i < d->n; i++)
d->cards[i]._s = rand();
qsort(d->cards, d->n, sizeof(card_t), cmp_card);
}
int main()
{
int i, j;
deck d = new_deck();
locale_ok = (0 != setlocale(LC_CTYPE, ""));
printf("New deck, "); show_deck(d);
printf("\nShuffle and deal to three players:\n");
shuffle_deck(d);
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++)
show_card(deal_card(d));
printf("\n");
}
printf("Left in deck "); show_deck(d);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original C# code. | int[] numbers = new int[10];
| char foo()
{
char array[5] = {3,6,9,12,15};
return array[2];
}
|
Port the provided C# code into C while preserving the original functionality. | int[] numbers = new int[10];
| char foo()
{
char array[5] = {3,6,9,12,15};
return array[2];
}
|
Can you help me rewrite this code in C instead of C#, keeping it the same logically? | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<string> NextCarpet(List<string> carpet)
{
return carpet.Select(x => x + x + x)
.Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))
.Concat(carpet.Select(x => x + x + x)).ToList();
}
static List<string> SierpinskiCarpet(int n)
{
return Enumerable.Range(1, n).Aggregate(new List<string> { "#" }, (carpet, _) => NextCarpet(carpet));
}
static void Main(string[] args)
{
foreach (string s in SierpinskiCarpet(3))
Console.WriteLine(s);
}
}
| #include <stdio.h>
int main()
{
int i, j, dim, d;
int depth = 3;
for (i = 0, dim = 1; i < depth; i++, dim *= 3);
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
for (d = dim / 3; d; d /= 3)
if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)
break;
printf(d ? " " : "##");
}
printf("\n");
}
return 0;
}
|
Can you help me rewrite this code in C instead of C#, keeping it the same logically? | using System;
using System.Collections.Generic;
namespace RosettaCode.BogoSort
{
public static class BogoSorter
{
public static void Sort<T>(List<T> list) where T:IComparable
{
while (!list.isSorted())
{
list.Shuffle();
}
}
private static bool isSorted<T>(this IList<T> list) where T:IComparable
{
if(list.Count<=1)
return true;
for (int i = 1 ; i < list.Count; i++)
if(list[i].CompareTo(list[i-1])<0) return false;
return true;
}
private static void Shuffle<T>(this IList<T> list)
{
Random rand = new Random();
for (int i = 0; i < list.Count; i++)
{
int swapIndex = rand.Next(list.Count);
T temp = list[swapIndex];
list[swapIndex] = list[i];
list[i] = temp;
}
}
}
class TestProgram
{
static void Main()
{
List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };
BogoSorter.Sort(testList);
foreach (int i in testList) Console.Write(i + " ");
}
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool is_sorted(int *a, int n)
{
while ( --n >= 1 ) {
if ( a[n] < a[n-1] ) return false;
}
return true;
}
void shuffle(int *a, int n)
{
int i, t, r;
for(i=0; i < n; i++) {
t = a[i];
r = rand() % n;
a[i] = a[r];
a[r] = t;
}
}
void bogosort(int *a, int n)
{
while ( !is_sorted(a, n) ) shuffle(a, n);
}
int main()
{
int numbers[] = { 1, 10, 9, 7, 3, 0 };
int i;
bogosort(numbers, 6);
for (i=0; i < 6; i++) printf("%d ", numbers[i]);
printf("\n");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.