Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Transform the following Python implementation into C++, maintaining the same output and logic. | def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
| #include <iostream>
#include <map>
class van_eck_generator {
public:
int next() {
int result = last_term;
auto iter = last_pos.find(last_term);
int next_term = (iter != last_pos.end()) ? index - iter->second : 0;
last_pos[last_term] = index;
last_term = next_term;
++index;
return result;
}
private:
int index = 0;
int last_term = 0;
std::map<int, int> last_pos;
};
int main() {
van_eck_generator gen;
int i = 0;
std::cout << "First 10 terms of the Van Eck sequence:\n";
for (; i < 10; ++i)
std::cout << gen.next() << ' ';
for (; i < 990; ++i)
gen.next();
std::cout << "\nTerms 991 to 1000 of the sequence:\n";
for (; i < 1000; ++i)
std::cout << gen.next() << ' ';
std::cout << '\n';
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | from ftplib import FTP
ftp = FTP('kernel.org')
ftp.login()
ftp.cwd('/pub/linux/kernel')
ftp.set_pasv(True)
print ftp.retrlines('LIST')
print ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()
|
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <sys/stat.h>
#include <ftplib.h>
#include <ftp++.hpp>
int stat(const char *pathname, struct stat *buf);
char *strerror(int errnum);
char *basename(char *path);
namespace stl
{
using std::cout;
using std::cerr;
using std::string;
using std::ifstream;
using std::remove;
};
using namespace stl;
using Mode = ftp::Connection::Mode;
Mode PASV = Mode::PASSIVE;
Mode PORT = Mode::PORT;
using TransferMode = ftp::Connection::TransferMode;
TransferMode BINARY = TransferMode::BINARY;
TransferMode TEXT = TransferMode::TEXT;
struct session
{
const string server;
const string port;
const string user;
const string pass;
Mode mode;
TransferMode txmode;
string dir;
};
ftp::Connection connect_ftp( const session& sess);
size_t get_ftp( ftp::Connection& conn, string const& path);
string readFile( const string& filename);
string login_ftp(ftp::Connection& conn, const session& sess);
string dir_listing( ftp::Connection& conn, const string& path);
string readFile( const string& filename)
{
struct stat stat_buf;
string contents;
errno = 0;
if (stat(filename.c_str() , &stat_buf) != -1)
{
size_t len = stat_buf.st_size;
string bytes(len+1, '\0');
ifstream ifs(filename);
ifs.read(&bytes[0], len);
if (! ifs.fail() ) contents.swap(bytes);
ifs.close();
}
else
{
cerr << "stat error: " << strerror(errno);
}
return contents;
}
ftp::Connection connect_ftp( const session& sess)
try
{
string constr = sess.server + ":" + sess.port;
cerr << "connecting to " << constr << " ...\n";
ftp::Connection conn{ constr.c_str() };
cerr << "connected to " << constr << "\n";
conn.setConnectionMode(sess.mode);
return conn;
}
catch (ftp::ConnectException e)
{
cerr << "FTP error: could not connect to server" << "\n";
}
string login_ftp(ftp::Connection& conn, const session& sess)
{
conn.login(sess.user.c_str() , sess.pass.c_str() );
return conn.getLastResponse();
}
string dir_listing( ftp::Connection& conn, const string& path)
try
{
const char* dirdata = "/dev/shm/dirdata";
conn.getList(dirdata, path.c_str() );
string dir_string = readFile(dirdata);
cerr << conn.getLastResponse() << "\n";
errno = 0;
if ( remove(dirdata) != 0 )
{
cerr << "error: " << strerror(errno) << "\n";
}
return dir_string;
}
catch (...) {
cerr << "error: getting dir contents: \n"
<< strerror(errno) << "\n";
}
size_t get_ftp( ftp::Connection& conn, const string& r_path)
{
size_t received = 0;
const char* path = r_path.c_str();
unsigned remotefile_size = conn.size(path , BINARY);
const char* localfile = basename(path);
conn.get(localfile, path, BINARY);
cerr << conn.getLastResponse() << "\n";
struct stat stat_buf;
errno = 0;
if (stat(localfile, &stat_buf) != -1)
received = stat_buf.st_size;
else
cerr << strerror(errno);
return received;
}
const session sonic
{
"mirrors.sonic.net",
"21" ,
"anonymous",
"xxxx@nohost.org",
PASV,
BINARY,
"/pub/OpenBSD"
};
int main(int argc, char* argv[], char * env[] )
{
const session remote = sonic;
try
{
ftp::Connection conn = connect_ftp(remote);
cerr << login_ftp(conn, remote);
cout << "System type: " << conn.getSystemType() << "\n";
cerr << conn.getLastResponse() << "\n";
conn.cd(remote.dir.c_str());
cerr << conn.getLastResponse() << "\n";
string pwdstr = conn.getDirectory();
cout << "PWD: " << pwdstr << "\n";
cerr << conn.getLastResponse() << "\n";
string dirlist = dir_listing(conn, pwdstr.c_str() );
cout << dirlist << "\n";
string filename = "ftplist";
auto pos = dirlist.find(filename);
auto notfound = string::npos;
if (pos != notfound)
{
size_t received = get_ftp(conn, filename.c_str() );
if (received == 0)
cerr << "got 0 bytes\n";
else
cerr << "got " << filename
<< " (" << received << " bytes)\n";
}
else
{
cerr << "file " << filename
<< "not found on server. \n";
}
}
catch (ftp::ConnectException e)
{
cerr << "FTP error: could not connect to server" << "\n";
}
catch (ftp::Exception e)
{
cerr << "FTP error: " << e << "\n";
}
catch (...)
{
cerr << "error: " << strerror(errno) << "\n";
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | from ftplib import FTP
ftp = FTP('kernel.org')
ftp.login()
ftp.cwd('/pub/linux/kernel')
ftp.set_pasv(True)
print ftp.retrlines('LIST')
print ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()
|
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <sys/stat.h>
#include <ftplib.h>
#include <ftp++.hpp>
int stat(const char *pathname, struct stat *buf);
char *strerror(int errnum);
char *basename(char *path);
namespace stl
{
using std::cout;
using std::cerr;
using std::string;
using std::ifstream;
using std::remove;
};
using namespace stl;
using Mode = ftp::Connection::Mode;
Mode PASV = Mode::PASSIVE;
Mode PORT = Mode::PORT;
using TransferMode = ftp::Connection::TransferMode;
TransferMode BINARY = TransferMode::BINARY;
TransferMode TEXT = TransferMode::TEXT;
struct session
{
const string server;
const string port;
const string user;
const string pass;
Mode mode;
TransferMode txmode;
string dir;
};
ftp::Connection connect_ftp( const session& sess);
size_t get_ftp( ftp::Connection& conn, string const& path);
string readFile( const string& filename);
string login_ftp(ftp::Connection& conn, const session& sess);
string dir_listing( ftp::Connection& conn, const string& path);
string readFile( const string& filename)
{
struct stat stat_buf;
string contents;
errno = 0;
if (stat(filename.c_str() , &stat_buf) != -1)
{
size_t len = stat_buf.st_size;
string bytes(len+1, '\0');
ifstream ifs(filename);
ifs.read(&bytes[0], len);
if (! ifs.fail() ) contents.swap(bytes);
ifs.close();
}
else
{
cerr << "stat error: " << strerror(errno);
}
return contents;
}
ftp::Connection connect_ftp( const session& sess)
try
{
string constr = sess.server + ":" + sess.port;
cerr << "connecting to " << constr << " ...\n";
ftp::Connection conn{ constr.c_str() };
cerr << "connected to " << constr << "\n";
conn.setConnectionMode(sess.mode);
return conn;
}
catch (ftp::ConnectException e)
{
cerr << "FTP error: could not connect to server" << "\n";
}
string login_ftp(ftp::Connection& conn, const session& sess)
{
conn.login(sess.user.c_str() , sess.pass.c_str() );
return conn.getLastResponse();
}
string dir_listing( ftp::Connection& conn, const string& path)
try
{
const char* dirdata = "/dev/shm/dirdata";
conn.getList(dirdata, path.c_str() );
string dir_string = readFile(dirdata);
cerr << conn.getLastResponse() << "\n";
errno = 0;
if ( remove(dirdata) != 0 )
{
cerr << "error: " << strerror(errno) << "\n";
}
return dir_string;
}
catch (...) {
cerr << "error: getting dir contents: \n"
<< strerror(errno) << "\n";
}
size_t get_ftp( ftp::Connection& conn, const string& r_path)
{
size_t received = 0;
const char* path = r_path.c_str();
unsigned remotefile_size = conn.size(path , BINARY);
const char* localfile = basename(path);
conn.get(localfile, path, BINARY);
cerr << conn.getLastResponse() << "\n";
struct stat stat_buf;
errno = 0;
if (stat(localfile, &stat_buf) != -1)
received = stat_buf.st_size;
else
cerr << strerror(errno);
return received;
}
const session sonic
{
"mirrors.sonic.net",
"21" ,
"anonymous",
"xxxx@nohost.org",
PASV,
BINARY,
"/pub/OpenBSD"
};
int main(int argc, char* argv[], char * env[] )
{
const session remote = sonic;
try
{
ftp::Connection conn = connect_ftp(remote);
cerr << login_ftp(conn, remote);
cout << "System type: " << conn.getSystemType() << "\n";
cerr << conn.getLastResponse() << "\n";
conn.cd(remote.dir.c_str());
cerr << conn.getLastResponse() << "\n";
string pwdstr = conn.getDirectory();
cout << "PWD: " << pwdstr << "\n";
cerr << conn.getLastResponse() << "\n";
string dirlist = dir_listing(conn, pwdstr.c_str() );
cout << dirlist << "\n";
string filename = "ftplist";
auto pos = dirlist.find(filename);
auto notfound = string::npos;
if (pos != notfound)
{
size_t received = get_ftp(conn, filename.c_str() );
if (received == 0)
cerr << "got 0 bytes\n";
else
cerr << "got " << filename
<< " (" << received << " bytes)\n";
}
else
{
cerr << "file " << filename
<< "not found on server. \n";
}
}
catch (ftp::ConnectException e)
{
cerr << "FTP error: could not connect to server" << "\n";
}
catch (ftp::Exception e)
{
cerr << "FTP error: " << e << "\n";
}
catch (...)
{
cerr << "error: " << strerror(errno) << "\n";
}
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Python version. |
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("New digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
if __name__ == '__main__': main()
| #include <random>
#include <iostream>
#include <stack>
#include <set>
#include <string>
#include <functional>
using namespace std;
class RPNParse
{
public:
stack<double> stk;
multiset<int> digits;
void op(function<double(double,double)> f)
{
if(stk.size() < 2)
throw "Improperly written expression";
int b = stk.top(); stk.pop();
int a = stk.top(); stk.pop();
stk.push(f(a, b));
}
void parse(char c)
{
if(c >= '0' && c <= '9')
{
stk.push(c - '0');
digits.insert(c - '0');
}
else if(c == '+')
op([](double a, double b) {return a+b;});
else if(c == '-')
op([](double a, double b) {return a-b;});
else if(c == '*')
op([](double a, double b) {return a*b;});
else if(c == '/')
op([](double a, double b) {return a/b;});
}
void parse(string s)
{
for(int i = 0; i < s.size(); ++i)
parse(s[i]);
}
double getResult()
{
if(stk.size() != 1)
throw "Improperly written expression";
return stk.top();
}
};
int main()
{
random_device seed;
mt19937 engine(seed());
uniform_int_distribution<> distribution(1, 9);
auto rnd = bind(distribution, engine);
multiset<int> digits;
cout << "Make 24 with the digits: ";
for(int i = 0; i < 4; ++i)
{
int n = rnd();
cout << " " << n;
digits.insert(n);
}
cout << endl;
RPNParse parser;
try
{
string input;
getline(cin, input);
parser.parse(input);
if(digits != parser.digits)
cout << "Error: Not using the given digits" << endl;
else
{
double r = parser.getResult();
cout << "Result: " << r << endl;
if(r > 23.999 && r < 24.001)
cout << "Good job!" << endl;
else
cout << "Try again." << endl;
}
}
catch(char* e)
{
cout << "Error: " << e << endl;
}
return 0;
}
|
Generate a C++ translation of this Python snippet without changing its computational steps. |
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("New digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
if __name__ == '__main__': main()
| #include <random>
#include <iostream>
#include <stack>
#include <set>
#include <string>
#include <functional>
using namespace std;
class RPNParse
{
public:
stack<double> stk;
multiset<int> digits;
void op(function<double(double,double)> f)
{
if(stk.size() < 2)
throw "Improperly written expression";
int b = stk.top(); stk.pop();
int a = stk.top(); stk.pop();
stk.push(f(a, b));
}
void parse(char c)
{
if(c >= '0' && c <= '9')
{
stk.push(c - '0');
digits.insert(c - '0');
}
else if(c == '+')
op([](double a, double b) {return a+b;});
else if(c == '-')
op([](double a, double b) {return a-b;});
else if(c == '*')
op([](double a, double b) {return a*b;});
else if(c == '/')
op([](double a, double b) {return a/b;});
}
void parse(string s)
{
for(int i = 0; i < s.size(); ++i)
parse(s[i]);
}
double getResult()
{
if(stk.size() != 1)
throw "Improperly written expression";
return stk.top();
}
};
int main()
{
random_device seed;
mt19937 engine(seed());
uniform_int_distribution<> distribution(1, 9);
auto rnd = bind(distribution, engine);
multiset<int> digits;
cout << "Make 24 with the digits: ";
for(int i = 0; i < 4; ++i)
{
int n = rnd();
cout << " " << n;
digits.insert(n);
}
cout << endl;
RPNParse parser;
try
{
string input;
getline(cin, input);
parser.parse(input);
if(digits != parser.digits)
cout << "Error: Not using the given digits" << endl;
else
{
double r = parser.getResult();
cout << "Result: " << r << endl;
if(r > 23.999 && r < 24.001)
cout << "Good job!" << endl;
else
cout << "Try again." << endl;
}
}
catch(char* e)
{
cout << "Error: " << e << endl;
}
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | for i in range(1, 11):
if i % 5 == 0:
print(i)
continue
print(i, end=', ')
| for(int i = 1;i <= 10; i++){
cout << i;
if(i % 5 == 0){
cout << endl;
continue;
}
cout << ", ";
}
|
Translate this program into C++ but keep the logic exactly as in Python. |
from livewires import *
horiz=640; vert=480
begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black)
NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"]
stepik=horiz/len(NameColors)
for index,each in enumerate(NameColors):
ExcStrng="set_colour(Colour."+each+")"
exec ExcStrng
box(index*stepik,0,(index+1)*stepik,vert,filled=1)
while keys_pressed() != ['x']:
pass
end_graphics()
| #ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class QPaintEvent ;
class MyWidget : public QWidget {
public :
MyWidget( ) ;
protected :
void paintEvent( QPaintEvent * ) ;
private :
int width ;
int height ;
const int colornumber ;
} ;
#endif
|
Change the programming language of this snippet from Python to C++ without modifying what it does. |
from livewires import *
horiz=640; vert=480
begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black)
NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"]
stepik=horiz/len(NameColors)
for index,each in enumerate(NameColors):
ExcStrng="set_colour(Colour."+each+")"
exec ExcStrng
box(index*stepik,0,(index+1)*stepik,vert,filled=1)
while keys_pressed() != ['x']:
pass
end_graphics()
| #ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class QPaintEvent ;
class MyWidget : public QWidget {
public :
MyWidget( ) ;
protected :
void paintEvent( QPaintEvent * ) ;
private :
int width ;
int height ;
const int colornumber ;
} ;
#endif
|
Preserve the algorithm and functionality while converting the code from Python to C++. | from pprint import pprint
def matrixMul(A, B):
TB = zip(*B)
return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]
def pivotize(m):
n = len(m)
ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]
for j in xrange(n):
row = max(xrange(j, n), key=lambda i: abs(m[i][j]))
if j != row:
ID[j], ID[row] = ID[row], ID[j]
return ID
def lu(A):
n = len(A)
L = [[0.0] * n for i in xrange(n)]
U = [[0.0] * n for i in xrange(n)]
P = pivotize(A)
A2 = matrixMul(P, A)
for j in xrange(n):
L[j][j] = 1.0
for i in xrange(j+1):
s1 = sum(U[k][j] * L[i][k] for k in xrange(i))
U[i][j] = A2[i][j] - s1
for i in xrange(j, n):
s2 = sum(U[k][j] * L[i][k] for k in xrange(j))
L[i][j] = (A2[i][j] - s2) / U[j][j]
return (L, U, P)
a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]
for part in lu(a):
pprint(part, width=19)
print
print
b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]]
for part in lu(b):
pprint(part)
print
| #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numeric>
#include <sstream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::wostream& out, const matrix<scalar_type>& a) {
const wchar_t* box_top_left = L"\x23a1";
const wchar_t* box_top_right = L"\x23a4";
const wchar_t* box_left = L"\x23a2";
const wchar_t* box_right = L"\x23a5";
const wchar_t* box_bottom_left = L"\x23a3";
const wchar_t* box_bottom_right = L"\x23a6";
const int precision = 5;
size_t rows = a.rows(), columns = a.columns();
std::vector<size_t> width(columns);
for (size_t column = 0; column < columns; ++column) {
size_t max_width = 0;
for (size_t row = 0; row < rows; ++row) {
std::ostringstream str;
str << std::fixed << std::setprecision(precision) << a(row, column);
max_width = std::max(max_width, str.str().length());
}
width[column] = max_width;
}
out << std::fixed << std::setprecision(precision);
for (size_t row = 0; row < rows; ++row) {
const bool top(row == 0), bottom(row + 1 == rows);
out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << L' ';
out << std::setw(width[column]) << a(row, column);
}
out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));
out << L'\n';
}
}
template <typename scalar_type>
auto lu_decompose(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
std::vector<size_t> perm(n);
std::iota(perm.begin(), perm.end(), 0);
matrix<scalar_type> lower(n, n);
matrix<scalar_type> upper(n, n);
matrix<scalar_type> input1(input);
for (size_t j = 0; j < n; ++j) {
size_t max_index = j;
scalar_type max_value = 0;
for (size_t i = j; i < n; ++i) {
scalar_type value = std::abs(input1(perm[i], j));
if (value > max_value) {
max_index = i;
max_value = value;
}
}
if (max_value <= std::numeric_limits<scalar_type>::epsilon())
throw std::runtime_error("matrix is singular");
if (j != max_index)
std::swap(perm[j], perm[max_index]);
size_t jj = perm[j];
for (size_t i = j + 1; i < n; ++i) {
size_t ii = perm[i];
input1(ii, j) /= input1(jj, j);
for (size_t k = j + 1; k < n; ++k)
input1(ii, k) -= input1(ii, j) * input1(jj, k);
}
}
for (size_t j = 0; j < n; ++j) {
lower(j, j) = 1;
for (size_t i = j + 1; i < n; ++i)
lower(i, j) = input1(perm[i], j);
for (size_t i = 0; i <= j; ++i)
upper(i, j) = input1(perm[i], j);
}
matrix<scalar_type> pivot(n, n);
for (size_t i = 0; i < n; ++i)
pivot(i, perm[i]) = 1;
return std::make_tuple(lower, upper, pivot);
}
template <typename scalar_type>
void show_lu_decomposition(const matrix<scalar_type>& input) {
try {
std::wcout << L"A\n";
print(std::wcout, input);
auto result(lu_decompose(input));
std::wcout << L"\nL\n";
print(std::wcout, std::get<0>(result));
std::wcout << L"\nU\n";
print(std::wcout, std::get<1>(result));
std::wcout << L"\nP\n";
print(std::wcout, std::get<2>(result));
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
}
}
int main() {
std::wcout.imbue(std::locale(""));
std::wcout << L"Example 1:\n";
matrix<double> matrix1(3, 3,
{{1, 3, 5},
{2, 4, 7},
{1, 1, 0}});
show_lu_decomposition(matrix1);
std::wcout << '\n';
std::wcout << L"Example 2:\n";
matrix<double> matrix2(4, 4,
{{11, 9, 24, 2},
{1, 5, 2, 6},
{3, 17, 18, 1},
{2, 5, 7, 1}});
show_lu_decomposition(matrix2);
std::wcout << '\n';
std::wcout << L"Example 3:\n";
matrix<double> matrix3(3, 3,
{{-5, -6, -3},
{-1, 0, -2},
{-3, -4, -7}});
show_lu_decomposition(matrix3);
std::wcout << '\n';
std::wcout << L"Example 4:\n";
matrix<double> matrix4(3, 3,
{{1, 2, 3},
{4, 5, 6},
{7, 8, 9}});
show_lu_decomposition(matrix4);
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Python. | def genfizzbuzz(factorwords, numbers):
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
lines = []
for num in numbers:
words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
lines.append(words if words else str(num))
return '\n'.join(lines)
if __name__ == '__main__':
print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
| #include <algorithm>
#include <iostream>
#include <vector>
#include <string>
class pair {
public:
pair( int s, std::string z ) { p = std::make_pair( s, z ); }
bool operator < ( const pair& o ) const { return i() < o.i(); }
int i() const { return p.first; }
std::string s() const { return p.second; }
private:
std::pair<int, std::string> p;
};
void gFizzBuzz( int c, std::vector<pair>& v ) {
bool output;
for( int x = 1; x <= c; x++ ) {
output = false;
for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {
if( !( x % ( *i ).i() ) ) {
std::cout << ( *i ).s();
output = true;
}
}
if( !output ) std::cout << x;
std::cout << "\n";
}
}
int main( int argc, char* argv[] ) {
std::vector<pair> v;
v.push_back( pair( 7, "Baxx" ) );
v.push_back( pair( 3, "Fizz" ) );
v.push_back( pair( 5, "Buzz" ) );
std::sort( v.begin(), v.end() );
gFizzBuzz( 20, v );
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Python. | with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
| #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ;
std::getline( std::cin , input ) ;
int linenumber = std::stoi( input ) ;
int lines_read = 0 ;
std::string line ;
if ( infile.is_open( ) ) {
while ( infile ) {
getline( infile , line ) ;
lines_read++ ;
if ( lines_read == linenumber ) {
std::cout << line << std::endl ;
break ;
}
}
infile.close( ) ;
if ( lines_read < linenumber )
std::cout << "No " << linenumber << " lines in " << file << " !\n" ;
return 0 ;
}
else {
std::cerr << "Could not find file " << file << " !\n" ;
return 1 ;
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
| #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ;
std::getline( std::cin , input ) ;
int linenumber = std::stoi( input ) ;
int lines_read = 0 ;
std::string line ;
if ( infile.is_open( ) ) {
while ( infile ) {
getline( infile , line ) ;
lines_read++ ;
if ( lines_read == linenumber ) {
std::cout << line << std::endl ;
break ;
}
}
infile.close( ) ;
if ( lines_read < linenumber )
std::cout << "No " << linenumber << " lines in " << file << " !\n" ;
return 0 ;
}
else {
std::cerr << "Could not find file " << file << " !\n" ;
return 1 ;
}
}
|
Write the same algorithm in C++ as shown in this Python implementation. | def isExt(fileName, extensions):
return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
| #include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
const size_t n1 = str.length();
const size_t n2 = suffix.length();
if (n1 < n2)
return false;
return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),
[](char c1, char c2) {
return std::tolower(static_cast<unsigned char>(c1))
== std::tolower(static_cast<unsigned char>(c2));
});
}
bool filenameHasExtension(const std::string& filename,
const std::vector<std::string>& extensions) {
return std::any_of(extensions.begin(), extensions.end(),
[&filename](const std::string& extension) {
return endsWithIgnoreCase(filename, "." + extension);
});
}
void test(const std::string& filename,
const std::vector<std::string>& extensions) {
std::cout << std::setw(20) << std::left << filename
<< ": " << std::boolalpha
<< filenameHasExtension(filename, extensions) << '\n';
}
int main() {
const std::vector<std::string> extensions{"zip", "rar", "7z",
"gz", "archive", "A##", "tar.bz2"};
test("MyData.a##", extensions);
test("MyData.tar.Gz", extensions);
test("MyData.gzip", extensions);
test("MyData.7z.backup", extensions);
test("MyData...", extensions);
test("MyData", extensions);
test("MyData_v1.0.tar.bz2", extensions);
test("MyData_v1.0.bz2", extensions);
return 0;
}
|
Write the same algorithm in C++ as shown in this Python implementation. | def isExt(fileName, extensions):
return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
| #include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
const size_t n1 = str.length();
const size_t n2 = suffix.length();
if (n1 < n2)
return false;
return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),
[](char c1, char c2) {
return std::tolower(static_cast<unsigned char>(c1))
== std::tolower(static_cast<unsigned char>(c2));
});
}
bool filenameHasExtension(const std::string& filename,
const std::vector<std::string>& extensions) {
return std::any_of(extensions.begin(), extensions.end(),
[&filename](const std::string& extension) {
return endsWithIgnoreCase(filename, "." + extension);
});
}
void test(const std::string& filename,
const std::vector<std::string>& extensions) {
std::cout << std::setw(20) << std::left << filename
<< ": " << std::boolalpha
<< filenameHasExtension(filename, extensions) << '\n';
}
int main() {
const std::vector<std::string> extensions{"zip", "rar", "7z",
"gz", "archive", "A##", "tar.bz2"};
test("MyData.a##", extensions);
test("MyData.tar.Gz", extensions);
test("MyData.gzip", extensions);
test("MyData.7z.backup", extensions);
test("MyData...", extensions);
test("MyData", extensions);
test("MyData_v1.0.tar.bz2", extensions);
test("MyData_v1.0.bz2", extensions);
return 0;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. |
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from itertools import izip_longest as zip_longest
else:
from itertools import zip_longest
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def ask4():
'get four random digits >0 from the player'
digits = ''
while len(digits) != 4 or not all(d in '123456789' for d in digits):
digits = input('Enter the digits to solve for: ')
digits = ''.join(digits.strip().split())
return list(digits)
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def solve(digits):
digilen = len(digits)
exprlen = 2 * digilen - 1
digiperm = sorted(set(permutations(digits)))
opcomb = list(product('+-*/', repeat=digilen-1))
brackets = ( [()] + [(x,y)
for x in range(0, exprlen, 2)
for y in range(x+4, exprlen+2, 2)
if (x,y) != (0,exprlen+1)]
+ [(0, 3+1, 4+2, 7+3)] )
for d in digiperm:
for ops in opcomb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insertpoint, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insertpoint, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [ (term if not term.startswith('F(') else term[2])
for term in exp ]
ans = ' '.join(exp).rstrip()
print ("Solution found:",ans)
return ans
print ("No solution found for:", ' '.join(digits))
return '!'
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer == '?':
solve(digits)
answer = '!'
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if answer == '!!':
digits = ask4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
if '/' in answer:
answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)
for char in answer )
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
main()
| #include <iostream>
#include <ratio>
#include <array>
#include <algorithm>
#include <random>
typedef short int Digit;
constexpr Digit nDigits{4};
constexpr Digit maximumDigit{9};
constexpr short int gameGoal{24};
typedef std::array<Digit, nDigits> digitSet;
digitSet d;
void printTrivialOperation(std::string operation) {
bool printOperation(false);
for(const Digit& number : d) {
if(printOperation)
std::cout << operation;
else
printOperation = true;
std::cout << number;
}
std::cout << std::endl;
}
void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") {
std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;
}
int main() {
std::mt19937_64 randomGenerator;
std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};
for(int trial{10}; trial; --trial) {
for(Digit& digit : d) {
digit = digitDistro(randomGenerator);
std::cout << digit << " ";
}
std::cout << std::endl;
std::sort(d.begin(), d.end());
if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)
printTrivialOperation(" + ");
if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)
printTrivialOperation(" * ");
do {
if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - ");
if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + ");
if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + ");
if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )");
if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + ");
if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )");
if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )");
if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - ");
if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )");
if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )");
if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - ");
if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - ");
if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + ");
if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )");
if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )");
if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + ");
if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / ");
if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / ");
if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )");
if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - ");
if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / ");
if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / ");
if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )");
if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / ");
if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )");
if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )");
if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", "");
} while(std::next_permutation(d.begin(), d.end()));
}
return 0;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. |
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from itertools import izip_longest as zip_longest
else:
from itertools import zip_longest
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def ask4():
'get four random digits >0 from the player'
digits = ''
while len(digits) != 4 or not all(d in '123456789' for d in digits):
digits = input('Enter the digits to solve for: ')
digits = ''.join(digits.strip().split())
return list(digits)
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def solve(digits):
digilen = len(digits)
exprlen = 2 * digilen - 1
digiperm = sorted(set(permutations(digits)))
opcomb = list(product('+-*/', repeat=digilen-1))
brackets = ( [()] + [(x,y)
for x in range(0, exprlen, 2)
for y in range(x+4, exprlen+2, 2)
if (x,y) != (0,exprlen+1)]
+ [(0, 3+1, 4+2, 7+3)] )
for d in digiperm:
for ops in opcomb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insertpoint, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insertpoint, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [ (term if not term.startswith('F(') else term[2])
for term in exp ]
ans = ' '.join(exp).rstrip()
print ("Solution found:",ans)
return ans
print ("No solution found for:", ' '.join(digits))
return '!'
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer == '?':
solve(digits)
answer = '!'
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if answer == '!!':
digits = ask4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
if '/' in answer:
answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)
for char in answer )
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
main()
| #include <iostream>
#include <ratio>
#include <array>
#include <algorithm>
#include <random>
typedef short int Digit;
constexpr Digit nDigits{4};
constexpr Digit maximumDigit{9};
constexpr short int gameGoal{24};
typedef std::array<Digit, nDigits> digitSet;
digitSet d;
void printTrivialOperation(std::string operation) {
bool printOperation(false);
for(const Digit& number : d) {
if(printOperation)
std::cout << operation;
else
printOperation = true;
std::cout << number;
}
std::cout << std::endl;
}
void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") {
std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;
}
int main() {
std::mt19937_64 randomGenerator;
std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};
for(int trial{10}; trial; --trial) {
for(Digit& digit : d) {
digit = digitDistro(randomGenerator);
std::cout << digit << " ";
}
std::cout << std::endl;
std::sort(d.begin(), d.end());
if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)
printTrivialOperation(" + ");
if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)
printTrivialOperation(" * ");
do {
if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - ");
if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + ");
if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + ");
if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )");
if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + ");
if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )");
if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )");
if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - ");
if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )");
if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )");
if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - ");
if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - ");
if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + ");
if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )");
if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )");
if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + ");
if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / ");
if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / ");
if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )");
if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - ");
if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / ");
if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / ");
if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )");
if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / ");
if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )");
if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )");
if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", "");
} while(std::next_permutation(d.begin(), d.end()));
}
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Python. |
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Ensure the translated C++ code behaves exactly like the original Python snippet. | def tobits(n, _group=8, _sep='_', _pad=False):
'Express n as binary bits with separator'
bits = '{0:b}'.format(n)[::-1]
if _pad:
bits = '{0:0{1}b}'.format(n,
((_group+len(bits)-1)//_group)*_group)[::-1]
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
answer = '0'*(len(_sep)-1) + answer
else:
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
return answer
def tovlq(n):
return tobits(n, _group=7, _sep='1_', _pad=True)
def toint(vlq):
return int(''.join(vlq.split('_1')), 2)
def vlqsend(vlq):
for i, byte in enumerate(vlq.split('_')[::-1]):
print('Sent byte {0:3}: {1:
| #include <iomanip>
#include <iostream>
#include <vector>
std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[ ";
if (it != end) {
os << std::setfill('0') << std::setw(2) << (uint32_t)*it;
it = std::next(it);
}
while (it != end) {
os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;
it = std::next(it);
}
return os << " ]";
}
std::vector<uint8_t> to_seq(uint64_t x) {
int i;
for (i = 9; i > 0; i--) {
if (x & 127ULL << i * 7) {
break;
}
}
std::vector<uint8_t> out;
for (int j = 0; j <= i; j++) {
out.push_back(((x >> ((i - j) * 7)) & 127) | 128);
}
out[i] ^= 128;
return out;
}
uint64_t from_seq(const std::vector<uint8_t> &seq) {
uint64_t r = 0;
for (auto b : seq) {
r = (r << 7) | (b & 127);
}
return r;
}
int main() {
std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };
for (auto x : src) {
auto s = to_seq(x);
std::cout << std::hex;
std::cout << "seq from " << x << ' ' << s << " back: " << from_seq(s) << '\n';
std::cout << std::dec;
}
return 0;
}
|
Convert the following code from Python to C++, ensuring the logic remains intact. | import pyaudio
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = chunk)
data = stream.read(chunk)
print [ord(i) for i in data]
| #include <iostream>
#include <string>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
using namespace std;
class recorder
{
public:
void start()
{
paused = rec = false; action = "IDLE";
while( true )
{
cout << endl << "==" << action << "==" << endl << endl;
cout << "1) Record" << endl << "2) Play" << endl << "3) Pause" << endl << "4) Stop" << endl << "5) Quit" << endl;
char c; cin >> c;
if( c > '0' && c < '6' )
{
switch( c )
{
case '1': record(); break;
case '2': play(); break;
case '3': pause(); break;
case '4': stop(); break;
case '5': stop(); return;
}
}
}
}
private:
void record()
{
if( mciExecute( "open new type waveaudio alias my_sound") )
{
mciExecute( "record my_sound" );
action = "RECORDING"; rec = true;
}
}
void play()
{
if( paused )
mciExecute( "play my_sound" );
else
if( mciExecute( "open tmp.wav alias my_sound" ) )
mciExecute( "play my_sound" );
action = "PLAYING";
paused = false;
}
void pause()
{
if( rec ) return;
mciExecute( "pause my_sound" );
paused = true; action = "PAUSED";
}
void stop()
{
if( rec )
{
mciExecute( "stop my_sound" );
mciExecute( "save my_sound tmp.wav" );
mciExecute( "close my_sound" );
action = "IDLE"; rec = false;
}
else
{
mciExecute( "stop my_sound" );
mciExecute( "close my_sound" );
action = "IDLE";
}
}
bool mciExecute( string cmd )
{
if( mciSendString( cmd.c_str(), NULL, 0, NULL ) )
{
cout << "Can't do this: " << cmd << endl;
return false;
}
return true;
}
bool paused, rec;
string action;
};
int main( int argc, char* argv[] )
{
recorder r; r.start();
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original Python snippet. |
import argh
import hashlib
import sys
@argh.arg('filename', nargs='?', default=None)
def main(filename, block_size=1024*1024):
if filename:
fin = open(filename, 'rb')
else:
fin = sys.stdin
stack = []
block = fin.read(block_size)
while block:
node = (0, hashlib.sha256(block).digest())
stack.append(node)
while len(stack) >= 2 and stack[-2][0] == stack[-1][0]:
a = stack[-2]
b = stack[-1]
l = a[0]
stack[-2:] = [(l+1, hashlib.sha256(a[1] + b[1]).digest())]
block = fin.read(block_size)
while len(stack) > 1:
a = stack[-2]
b = stack[-1]
al = a[0]
bl = b[0]
stack[-2:] = [(max(al, bl)+1, hashlib.sha256(a[1] + b[1]).digest())]
print(stack[0][1].hex())
argh.dispatch_command(main)
| #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
#include <openssl/sha.h>
class sha256_exception : public std::exception {
public:
const char* what() const noexcept override {
return "SHA-256 error";
}
};
class sha256 {
public:
sha256() { reset(); }
sha256(const sha256&) = delete;
sha256& operator=(const sha256&) = delete;
void reset() {
if (SHA256_Init(&context_) == 0)
throw sha256_exception();
}
void update(const void* data, size_t length) {
if (SHA256_Update(&context_, data, length) == 0)
throw sha256_exception();
}
std::vector<unsigned char> digest() {
std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);
if (SHA256_Final(digest.data(), &context_) == 0)
throw sha256_exception();
return digest;
}
private:
SHA256_CTX context_;
};
std::string digest_to_string(const std::vector<unsigned char>& digest) {
std::ostringstream out;
out << std::hex << std::setfill('0');
for (size_t i = 0; i < digest.size(); ++i)
out << std::setw(2) << static_cast<int>(digest[i]);
return out.str();
}
std::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {
std::vector<std::vector<unsigned char>> hashes;
std::vector<char> buffer(block_size);
sha256 md;
while (in) {
in.read(buffer.data(), block_size);
size_t bytes = in.gcount();
if (bytes == 0)
break;
md.reset();
md.update(buffer.data(), bytes);
hashes.push_back(md.digest());
}
if (hashes.empty())
return {};
size_t length = hashes.size();
while (length > 1) {
size_t j = 0;
for (size_t i = 0; i < length; i += 2, ++j) {
auto& digest1 = hashes[i];
auto& digest_out = hashes[j];
if (i + 1 < length) {
auto& digest2 = hashes[i + 1];
md.reset();
md.update(digest1.data(), digest1.size());
md.update(digest2.data(), digest2.size());
digest_out = md.digest();
} else {
digest_out = digest1;
}
}
length = j;
}
return hashes[0];
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " filename\n";
return EXIT_FAILURE;
}
std::ifstream in(argv[1], std::ios::binary);
if (!in) {
std::cerr << "Cannot open file " << argv[1] << ".\n";
return EXIT_FAILURE;
}
try {
std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\n';
} catch (const std::exception& ex) {
std::cerr << ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Ensure the translated C++ code behaves exactly like the original Python snippet. | s = "alphaBETA"
print s.upper()
print s.lower()
print s.swapcase()
print "fOo bAR".capitalize()
print "fOo bAR".title()
import string
print string.capwords("fOo bAR")
| #include <algorithm>
#include <string>
#include <cctype>
void str_toupper(std::string &str) {
std::transform(str.begin(),
str.end(),
str.begin(),
(int(*)(int)) std::toupper);
}
void str_tolower(std::string &str) {
std::transform(str.begin(),
str.end(),
str.begin(),
(int(*)(int)) std::tolower);
}
|
Convert this Python block to C++, preserving its control flow and logic. | from javax.swing import JOptionPane
def to_int(n, default=0):
try:
return int(n)
except ValueError:
return default
number = to_int(JOptionPane.showInputDialog ("Enter an Integer"))
println(number)
a_string = JOptionPane.showInputDialog ("Enter a String")
println(a_string)
| #ifndef TASK_H
#define TASK_H
#include <QWidget>
class QLabel ;
class QLineEdit ;
class QVBoxLayout ;
class QHBoxLayout ;
class EntryWidget : public QWidget {
Q_OBJECT
public :
EntryWidget( QWidget *parent = 0 ) ;
private :
QHBoxLayout *upperpart , *lowerpart ;
QVBoxLayout *entryLayout ;
QLineEdit *stringinput ;
QLineEdit *numberinput ;
QLabel *stringlabel ;
QLabel *numberlabel ;
} ;
#endif
|
Maintain the same structure and functionality when rewriting this code in C++. | t = { 'x': 20, 'y': 30, 'a': 60 }
def setup():
size(450, 400)
background(0, 0, 200)
stroke(-1)
sc(7, 400, -60)
def sc(o, l, a, s = t, X = 'x', Y = 'y', A = 'a', HALF = .5):
if o:
o -= 1
l *= HALF
sc(o, l, -a)[A] += a
sc(o, l, a)[A] += a
sc(o, l, -a)
else:
x, y = s[X], s[Y]
s[X] += cos(radians(s[A])) * l
s[Y] += sin(radians(s[A])) * l
line(x, y, s[X], s[Y])
return s
| #include <fstream>
#include <iostream>
#include <vector>
constexpr double sqrt3_2 = 0.86602540378444;
struct point {
double x;
double y;
};
std::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {
size_t size = points.size();
std::vector<point> output(3*(size - 1) + 1);
double x0, y0, x1, y1;
size_t j = 0;
for (size_t i = 0; i + 1 < size; ++i, j += 3) {
x0 = points[i].x;
y0 = points[i].y;
x1 = points[i + 1].x;
y1 = points[i + 1].y;
double dx = x1 - x0;
output[j] = {x0, y0};
if (y0 == y1) {
double d = dx * sqrt3_2/2;
if (d < 0) d = -d;
output[j + 1] = {x0 + dx/4, y0 - d};
output[j + 2] = {x1 - dx/4, y0 - d};
} else if (y1 < y0) {
output[j + 1] = {x1, y0};
output[j + 2] = {x1 + dx/2, (y0 + y1)/2};
} else {
output[j + 1] = {x0 - dx/2, (y0 + y1)/2};
output[j + 2] = {x0, y1};
}
}
output[j] = {x1, y1};
return output;
}
void write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
const double margin = 20.0;
const double side = size - 2.0 * margin;
const double x = margin;
const double y = 0.5 * size + 0.5 * sqrt3_2 * side;
std::vector<point> points{{x, y}, {x + side, y}};
for (int i = 0; i < iterations; ++i)
points = sierpinski_arrowhead_next(points);
for (size_t i = 0, n = points.size(); i < n; ++i)
out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n';
out << "'/>\n</svg>\n";
}
int main() {
std::ofstream out("sierpinski_arrowhead.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
write_sierpinski_arrowhead(out, 600, 8);
return EXIT_SUCCESS;
}
|
Write a version of this Python function in C++ with identical behavior. | import fileinput
import sys
nodata = 0;
nodata_max=-1;
nodata_maxline=[];
tot_file = 0
num_file = 0
infiles = sys.argv[1:]
for line in fileinput.input():
tot_line=0;
num_line=0;
field = line.split()
date = field[0]
data = [float(f) for f in field[1::2]]
flags = [int(f) for f in field[2::2]]
for datum, flag in zip(data, flags):
if flag<1:
nodata += 1
else:
if nodata_max==nodata and nodata>0:
nodata_maxline.append(date)
if nodata_max<nodata and nodata>0:
nodata_max=nodata
nodata_maxline=[date]
nodata=0;
tot_line += datum
num_line += 1
tot_file += tot_line
num_file += num_line
print "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f" % (
date,
len(data) -num_line,
num_line, tot_line,
tot_line/num_line if (num_line>0) else 0)
print ""
print "File(s) = %s" % (", ".join(infiles),)
print "Total = %10.3f" % (tot_file,)
print "Readings = %6i" % (num_file,)
print "Average = %10.3f" % (tot_file / num_file,)
print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % (
nodata_max, ", ".join(nodata_maxline))
| #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
using std::cout;
using std::endl;
const int NumFlags = 24;
int main()
{
std::fstream file("readings.txt");
int badCount = 0;
std::string badDate;
int badCountMax = 0;
while(true)
{
std::string line;
getline(file, line);
if(!file.good())
break;
std::vector<std::string> tokens;
boost::algorithm::split(tokens, line, boost::is_space());
if(tokens.size() != NumFlags * 2 + 1)
{
cout << "Bad input file." << endl;
return 0;
}
double total = 0.0;
int accepted = 0;
for(size_t i = 1; i < tokens.size(); i += 2)
{
double val = boost::lexical_cast<double>(tokens[i]);
int flag = boost::lexical_cast<int>(tokens[i+1]);
if(flag > 0)
{
total += val;
++accepted;
badCount = 0;
}
else
{
++badCount;
if(badCount > badCountMax)
{
badCountMax = badCount;
badDate = tokens[0];
}
}
}
cout << tokens[0];
cout << " Reject: " << std::setw(2) << (NumFlags - accepted);
cout << " Accept: " << std::setw(2) << accepted;
cout << " Average: " << std::setprecision(5) << total / accepted << endl;
}
cout << endl;
cout << "Maximum number of consecutive bad readings is " << badCountMax << endl;
cout << "Ends on date " << badDate << endl;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | >>> import hashlib
>>>
>>> tests = (
(b"", 'd41d8cd98f00b204e9800998ecf8427e'),
(b"a", '0cc175b9c0f1b6a831c399e269772661'),
(b"abc", '900150983cd24fb0d6963f7d28e17f72'),
(b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'),
(b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'),
(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'),
(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden
>>>
| #include <string>
#include <iostream>
#include "Poco/MD5Engine.h"
#include "Poco/DigestStream.h"
using Poco::DigestEngine ;
using Poco::MD5Engine ;
using Poco::DigestOutputStream ;
int main( ) {
std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ;
MD5Engine md5 ;
DigestOutputStream outstr( md5 ) ;
outstr << myphrase ;
outstr.flush( ) ;
const DigestEngine::Digest& digest = md5.digest( ) ;
std::cout << myphrase << " as a MD5 digest :\n" << DigestEngine::digestToHex( digest )
<< " !" << std::endl ;
return 0 ;
}
|
Generate an equivalent C++ version of this Python code. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pdsum(s[-1])
if new in s:
if s[0] == new:
if slen == 1:
return 'perfect', s
elif slen == 2:
return 'amicable', s
else:
return 'sociable of length %i' % slen, s
elif s[-1] == new:
return 'aspiring', s
else:
return 'cyclic back to %i' % new, s
elif new == 0:
return 'terminating', s + [0]
else:
s.append(new)
slen += 1
else:
return 'non-terminating', s
if __name__ == '__main__':
for n in range(1, 11):
print('%s: %r' % aliquot(n))
print()
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
print('%s: %r' % aliquot(n))
| #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
integer divisor_sum(integer n) {
integer total = 1, power = 2;
for (; n % 2 == 0; power *= 2, n /= 2)
total += power;
for (integer p = 3; p * p <= n; p += 2) {
integer sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (n > 1)
total *= n + 1;
return total;
}
void classify_aliquot_sequence(integer n) {
constexpr int limit = 16;
integer terms[limit];
terms[0] = n;
std::string classification("non-terminating");
int length = 1;
for (int i = 1; i < limit; ++i) {
++length;
terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];
if (terms[i] == n) {
classification =
(i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable"));
break;
}
int j = 1;
for (; j < i; ++j) {
if (terms[i] == terms[i - j])
break;
}
if (j < i) {
classification = (j == 1 ? "aspiring" : "cyclic");
break;
}
if (terms[i] == 0) {
classification = "terminating";
break;
}
}
std::cout << n << ": " << classification << ", sequence: " << terms[0];
for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)
std::cout << ' ' << terms[i];
std::cout << '\n';
}
int main() {
for (integer i = 1; i <= 10; ++i)
classify_aliquot_sequence(i);
for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,
1064, 1488})
classify_aliquot_sequence(i);
classify_aliquot_sequence(15355717786080);
classify_aliquot_sequence(153557177860800);
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Python. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pdsum(s[-1])
if new in s:
if s[0] == new:
if slen == 1:
return 'perfect', s
elif slen == 2:
return 'amicable', s
else:
return 'sociable of length %i' % slen, s
elif s[-1] == new:
return 'aspiring', s
else:
return 'cyclic back to %i' % new, s
elif new == 0:
return 'terminating', s + [0]
else:
s.append(new)
slen += 1
else:
return 'non-terminating', s
if __name__ == '__main__':
for n in range(1, 11):
print('%s: %r' % aliquot(n))
print()
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
print('%s: %r' % aliquot(n))
| #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
integer divisor_sum(integer n) {
integer total = 1, power = 2;
for (; n % 2 == 0; power *= 2, n /= 2)
total += power;
for (integer p = 3; p * p <= n; p += 2) {
integer sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (n > 1)
total *= n + 1;
return total;
}
void classify_aliquot_sequence(integer n) {
constexpr int limit = 16;
integer terms[limit];
terms[0] = n;
std::string classification("non-terminating");
int length = 1;
for (int i = 1; i < limit; ++i) {
++length;
terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];
if (terms[i] == n) {
classification =
(i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable"));
break;
}
int j = 1;
for (; j < i; ++j) {
if (terms[i] == terms[i - j])
break;
}
if (j < i) {
classification = (j == 1 ? "aspiring" : "cyclic");
break;
}
if (terms[i] == 0) {
classification = "terminating";
break;
}
}
std::cout << n << ": " << classification << ", sequence: " << terms[0];
for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)
std::cout << ' ' << terms[i];
std::cout << '\n';
}
int main() {
for (integer i = 1; i <= 10; ++i)
classify_aliquot_sequence(i);
for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,
1064, 1488})
classify_aliquot_sequence(i);
classify_aliquot_sequence(15355717786080);
classify_aliquot_sequence(153557177860800);
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Python. | import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3]
tdelta = datetime.timedelta(hours=12)
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]
mt()
| #include <string>
#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>
#include <sstream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <locale>
int main( ) {
std::string datestring ("March 7 2009 7:30pm EST" ) ;
std::vector<std::string> elements ;
boost::split( elements , datestring , boost::is_any_of( " " ) ) ;
std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " +
elements[ 2 ] ;
std::string timepart = elements[ 3 ] ;
std::string timezone = elements[ 4 ] ;
const char meridians[ ] = { 'a' , 'p' } ;
std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;
std::string twelve_hour ( timepart.substr( found , 1 ) ) ;
timepart = timepart.substr( 0 , found ) ;
elements.clear( ) ;
boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ;
long hour = std::atol( (elements.begin( ))->c_str( ) ) ;
if ( twelve_hour == "p" )
hour += 12 ;
long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ;
boost::local_time::tz_database tz_db ;
tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ;
boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ;
boost::gregorian::date_input_facet *f =
new boost::gregorian::date_input_facet( "%B %d %Y" ) ;
std::stringstream ss ;
ss << datepart ;
ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;
boost::gregorian::date d ;
ss >> d ;
boost::posix_time::time_duration td ( hour , minute , 0 ) ;
boost::local_time::local_date_time lt ( d , td , dyc ,
boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;
std::cout << "local time: " << lt << '\n' ;
ss.str( "" ) ;
ss << lt ;
boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;
boost::local_time::local_date_time ltlater = lt + td2 ;
boost::gregorian::date_facet *f2 =
new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ;
std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;
std::cout << "12 hours after " << ss.str( ) << " it is " << ltlater << " !\n" ;
boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ;
std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ;
std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ;
return 0 ;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Python version. | import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3]
tdelta = datetime.timedelta(hours=12)
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]
mt()
| #include <string>
#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>
#include <sstream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <locale>
int main( ) {
std::string datestring ("March 7 2009 7:30pm EST" ) ;
std::vector<std::string> elements ;
boost::split( elements , datestring , boost::is_any_of( " " ) ) ;
std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " +
elements[ 2 ] ;
std::string timepart = elements[ 3 ] ;
std::string timezone = elements[ 4 ] ;
const char meridians[ ] = { 'a' , 'p' } ;
std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;
std::string twelve_hour ( timepart.substr( found , 1 ) ) ;
timepart = timepart.substr( 0 , found ) ;
elements.clear( ) ;
boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ;
long hour = std::atol( (elements.begin( ))->c_str( ) ) ;
if ( twelve_hour == "p" )
hour += 12 ;
long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ;
boost::local_time::tz_database tz_db ;
tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ;
boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ;
boost::gregorian::date_input_facet *f =
new boost::gregorian::date_input_facet( "%B %d %Y" ) ;
std::stringstream ss ;
ss << datepart ;
ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;
boost::gregorian::date d ;
ss >> d ;
boost::posix_time::time_duration td ( hour , minute , 0 ) ;
boost::local_time::local_date_time lt ( d , td , dyc ,
boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;
std::cout << "local time: " << lt << '\n' ;
ss.str( "" ) ;
ss << lt ;
boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;
boost::local_time::local_date_time ltlater = lt + td2 ;
boost::gregorian::date_facet *f2 =
new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ;
std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;
std::cout << "12 hours after " << ss.str( ) << " it is " << ltlater << " !\n" ;
boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ;
std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ;
std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ;
return 0 ;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Python version. | from time import sleep
from threading import Timer
def sleepsort(values):
sleepsort.result = []
def add1(x):
sleepsort.result.append(x)
mx = values[0]
for v in values:
if mx < v: mx = v
Timer(v, add1, [v]).start()
sleep(mx+1)
return sleepsort.result
if __name__ == '__main__':
x = [3,2,4,7,3,6,9,1]
if sleepsort(x) == sorted(x):
print('sleep sort worked for:',x)
else:
print('sleep sort FAILED for:',x)
| #include <chrono>
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char* argv[]) {
std::vector<std::thread> threads;
for (int i = 1; i < argc; ++i) {
threads.emplace_back([i, &argv]() {
int arg = std::stoi(argv[i]);
std::this_thread::sleep_for(std::chrono::seconds(arg));
std::cout << argv[i] << std::endl;
});
}
for (auto& thread : threads) {
thread.join();
}
}
|
Translate the given Python code snippet into C++ without altering its behavior. | from random import randint
def do_scan(mat):
for row in mat:
for item in row:
print item,
if item == 20:
print
return
print
print
mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)
| #include<cstdlib>
#include<ctime>
#include<iostream>
using namespace std;
int main()
{
int arr[10][10];
srand(time(NULL));
for(auto& row: arr)
for(auto& col: row)
col = rand() % 20 + 1;
([&](){
for(auto& row : arr)
for(auto& col: row)
{
cout << col << endl;
if(col == 20)return;
}
})();
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Python. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| #include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>
using namespace std;
auto CountTriplets(unsigned long long maxPerimeter)
{
unsigned long long totalCount = 0;
unsigned long long primitveCount = 0;
auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
for(unsigned long long m = 2; m < max_M; ++m)
{
for(unsigned long long n = 1 + m % 2; n < m; n+=2)
{
if(gcd(m,n) != 1)
{
continue;
}
auto a = m * m - n * n;
auto b = 2 * m * n;
auto c = m * m + n * n;
auto perimeter = a + b + c;
if(perimeter <= maxPerimeter)
{
primitveCount++;
totalCount+= maxPerimeter / perimeter;
}
}
}
return tuple(totalCount, primitveCount);
}
int main()
{
vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
1000'000, 10'000'000, 100'000'000, 1000'000'000,
10'000'000'000};
for(auto maxPerimeter : inputs)
{
auto [total, primitive] = CountTriplets(maxPerimeter);
cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
}
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| #include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>
using namespace std;
auto CountTriplets(unsigned long long maxPerimeter)
{
unsigned long long totalCount = 0;
unsigned long long primitveCount = 0;
auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
for(unsigned long long m = 2; m < max_M; ++m)
{
for(unsigned long long n = 1 + m % 2; n < m; n+=2)
{
if(gcd(m,n) != 1)
{
continue;
}
auto a = m * m - n * n;
auto b = 2 * m * n;
auto c = m * m + n * n;
auto perimeter = a + b + c;
if(perimeter <= maxPerimeter)
{
primitveCount++;
totalCount+= maxPerimeter / perimeter;
}
}
}
return tuple(totalCount, primitveCount);
}
int main()
{
vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
1000'000, 10'000'000, 100'000'000, 1000'000'000,
10'000'000'000};
for(auto maxPerimeter : inputs)
{
auto [total, primitive] = CountTriplets(maxPerimeter);
cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
}
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
| #include <set>
#include <iostream>
using namespace std;
int main() {
typedef set<int> TySet;
int data[] = {1, 2, 3, 2, 3, 4};
TySet unique_set(data, data + 6);
cout << "Set items:" << endl;
for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)
cout << *iter << " ";
cout << endl;
}
|
Write the same algorithm in C++ as shown in this Python implementation. | def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
| #include <iostream>
#include <sstream>
#include <string>
std::string lookandsay(const std::string& s)
{
std::ostringstream r;
for (std::size_t i = 0; i != s.length();) {
auto new_i = s.find_first_not_of(s[i], i + 1);
if (new_i == std::string::npos)
new_i = s.length();
r << new_i - i << s[i];
i = new_i;
}
return r.str();
}
int main()
{
std::string laf = "1";
std::cout << laf << '\n';
for (int i = 0; i < 10; ++i) {
laf = lookandsay(laf);
std::cout << laf << '\n';
}
}
|
Produce a functionally identical C++ code for the snippet given in Python. | from math import gcd
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return φ(n) == n - 1
for n in range(1, 26):
print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}")
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f"Primes up to {n}: {count}")
| #include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
continue;
for (int j = i; j <= max; j += i)
totient_[j] -= totient_[j] / i;
}
}
int totient(int n) const {
assert (n >= 1 && n < totient_.size());
return totient_[n];
}
bool is_prime(int n) const {
return totient(n) == n - 1;
}
private:
std::vector<int> totient_;
};
int count_primes(const totient_calculator& tc, int min, int max) {
int count = 0;
for (int i = min; i <= max; ++i) {
if (tc.is_prime(i))
++count;
}
return count;
}
int main() {
const int max = 10000000;
totient_calculator tc(max);
std::cout << " n totient prime?\n";
for (int i = 1; i <= 25; ++i) {
std::cout << std::setw(2) << i
<< std::setw(9) << tc.totient(i)
<< std::setw(8) << (tc.is_prime(i) ? "yes" : "no") << '\n';
}
for (int n = 100; n <= max; n *= 10) {
std::cout << "Count of primes up to " << n << ": "
<< count_primes(tc, 1, n) << '\n';
}
return 0;
}
|
Convert the following code from Python to C++, ensuring the logic remains intact. | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
| template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;
template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>
{
typedef ThenType type;
};
template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>
{
typedef ElseType type;
};
ifthenelse<INT_MAX == 32767,
long int,
int>
::type myvar;
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | from fractions import Fraction
def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
'77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
'13 / 11, 15 / 14, 15 / 2, 55 / 1'):
flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]
n = Fraction(n)
while True:
yield n.numerator
for f in flist:
if (n * f).denominator == 1:
break
else:
break
n *= f
if __name__ == '__main__':
n, m = 2, 15
print('First %i members of fractran(%i):\n ' % (m, n) +
', '.join(str(f) for f,i in zip(fractran(n), range(m))))
| #include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <cmath>
using namespace std;
class fractran
{
public:
void run( std::string p, int s, int l )
{
start = s; limit = l;
istringstream iss( p ); vector<string> tmp;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );
string item; vector< pair<float, float> > v;
pair<float, float> a;
for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )
{
string::size_type pos = ( *i ).find( '/', 0 );
if( pos != std::string::npos )
{
a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );
v.push_back( a );
}
}
exec( &v );
}
private:
void exec( vector< pair<float, float> >* v )
{
int cnt = 0;
while( cnt < limit )
{
cout << cnt << " : " << start << "\n";
cnt++;
vector< pair<float, float> >::iterator it = v->begin();
bool found = false; float r;
while( it != v->end() )
{
r = start * ( ( *it ).first / ( *it ).second );
if( r == floor( r ) )
{
found = true;
break;
}
++it;
}
if( found ) start = ( int )r;
else break;
}
}
int start, limit;
};
int main( int argc, char* argv[] )
{
fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 );
cin.get();
return 0;
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | from fractions import Fraction
def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
'77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
'13 / 11, 15 / 14, 15 / 2, 55 / 1'):
flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]
n = Fraction(n)
while True:
yield n.numerator
for f in flist:
if (n * f).denominator == 1:
break
else:
break
n *= f
if __name__ == '__main__':
n, m = 2, 15
print('First %i members of fractran(%i):\n ' % (m, n) +
', '.join(str(f) for f,i in zip(fractran(n), range(m))))
| #include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <cmath>
using namespace std;
class fractran
{
public:
void run( std::string p, int s, int l )
{
start = s; limit = l;
istringstream iss( p ); vector<string> tmp;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );
string item; vector< pair<float, float> > v;
pair<float, float> a;
for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )
{
string::size_type pos = ( *i ).find( '/', 0 );
if( pos != std::string::npos )
{
a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );
v.push_back( a );
}
}
exec( &v );
}
private:
void exec( vector< pair<float, float> >* v )
{
int cnt = 0;
while( cnt < limit )
{
cout << cnt << " : " << start << "\n";
cnt++;
vector< pair<float, float> >::iterator it = v->begin();
bool found = false; float r;
while( it != v->end() )
{
r = start * ( ( *it ).first / ( *it ).second );
if( r == floor( r ) )
{
found = true;
break;
}
++it;
}
if( found ) start = ( int )r;
else break;
}
}
int start, limit;
};
int main( int argc, char* argv[] )
{
fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 );
cin.get();
return 0;
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
if j is None:
j = len(L) - 1
if L[j] < L[i]:
L[i], L[j] = L[j], L[i]
if j - i > 1:
t = (j - i + 1) // 3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
| #include <iostream>
#include <time.h>
using namespace std;
class stooge
{
public:
void sort( int* arr, int start, int end )
{
if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );
int n = end - start; if( n > 2 )
{
n /= 3; sort( arr, start, end - n );
sort( arr, start + n, end ); sort( arr, start, end - n );
}
}
};
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80;
cout << "before:\n";
for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20; cout << a[x] << " "; }
s.sort( a, 0, m ); cout << "\n\nafter:\n";
for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n";
return system( "pause" );
}
|
Generate an equivalent C++ version of this Python code. |
import sys, os
import random
import time
def print_there(x, y, text):
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush()
class Ball():
def __init__(self):
self.x = 0
self.y = 0
def update(self):
self.x += random.randint(0,1)
self.y += 1
def fall(self):
self.y +=1
class Board():
def __init__(self, width, well_depth, N):
self.balls = []
self.fallen = [0] * (width + 1)
self.width = width
self.well_depth = well_depth
self.N = N
self.shift = 4
def update(self):
for ball in self.balls:
if ball.y < self.width:
ball.update()
elif ball.y < self.width + self.well_depth - self.fallen[ball.x]:
ball.fall()
elif ball.y == self.width + self.well_depth - self.fallen[ball.x]:
self.fallen[ball.x] += 1
else:
pass
def balls_on_board(self):
return len(self.balls) - sum(self.fallen)
def add_ball(self):
if(len(self.balls) <= self.N):
self.balls.append(Ball())
def print_board(self):
for y in range(self.width + 1):
for x in range(y):
print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, "
def print_ball(self, ball):
if ball.y <= self.width:
x = self.width - ball.y + 2*ball.x + self.shift
else:
x = 2*ball.x + self.shift
y = ball.y + 1
print_there(y, x, "*")
def print_all(self):
print(chr(27) + "[2J")
self.print_board();
for ball in self.balls:
self.print_ball(ball)
def main():
board = Board(width = 15, well_depth = 5, N = 10)
board.add_ball()
while(board.balls_on_board() > 0):
board.print_all()
time.sleep(0.25)
board.update()
board.print_all()
time.sleep(0.25)
board.update()
board.add_ball()
if __name__=="__main__":
main()
| #include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void *pBits;
int width, height, wid;
DWORD clr;
};
class point {
public:
int x; float y;
void set( int a, float b ) { x = a; y = b; }
};
typedef struct {
point position, offset;
bool alive, start;
}ball;
class galton {
public :
galton() {
bmp.create( BMP_WID, BMP_HEI );
initialize();
}
void setHWND( HWND hwnd ) { _hwnd = hwnd; }
void simulate() {
draw(); update(); Sleep( 1 );
}
private:
void draw() {
bmp.clear();
bmp.setPenColor( RGB( 0, 255, 0 ) );
bmp.setBrushColor( RGB( 0, 255, 0 ) );
int xx, yy;
for( int y = 3; y < 14; y++ ) {
yy = 10 * y;
for( int x = 0; x < 41; x++ ) {
xx = 10 * x;
if( pins[y][x] )
Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );
}
}
bmp.setPenColor( RGB( 255, 0, 0 ) );
bmp.setBrushColor( RGB( 255, 0, 0 ) );
ball* b;
for( int x = 0; x < MAX_BALLS; x++ ) {
b = &balls[x];
if( b->alive )
Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ),
static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );
}
for( int x = 0; x < 70; x++ ) {
if( cols[x] > 0 ) {
xx = 10 * x;
Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );
}
}
HDC dc = GetDC( _hwnd );
BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );
ReleaseDC( _hwnd, dc );
}
void update() {
ball* b;
for( int x = 0; x < MAX_BALLS; x++ ) {
b = &balls[x];
if( b->alive ) {
b->position.x += b->offset.x; b->position.y += b->offset.y;
if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {
b->start = true;
balls[x + 1].alive = true;
}
int c = ( int )b->position.x, d = ( int )b->position.y + 6;
if( d > 10 || d < 41 ) {
if( pins[d / 10][c / 10] ) {
if( rand() % 30 < 15 ) b->position.x -= 10;
else b->position.x += 10;
}
}
if( b->position.y > 160 ) {
b->alive = false;
cols[c / 10] += 1;
}
}
}
}
void initialize() {
for( int x = 0; x < MAX_BALLS; x++ ) {
balls[x].position.set( 200, -10 );
balls[x].offset.set( 0, 0.5f );
balls[x].alive = balls[x].start = false;
}
balls[0].alive = true;
for( int x = 0; x < 70; x++ )
cols[x] = 0;
for( int y = 0; y < 70; y++ )
for( int x = 0; x < 41; x++ )
pins[x][y] = false;
int p;
for( int y = 0; y < 11; y++ ) {
p = ( 41 / 2 ) - y;
for( int z = 0; z < y + 1; z++ ) {
pins[3 + y][p] = true;
p += 2;
}
}
}
myBitmap bmp;
HWND _hwnd;
bool pins[70][40];
ball balls[MAX_BALLS];
int cols[70];
};
class wnd {
public:
int wnd::Run( HINSTANCE hInst ) {
_hInst = hInst;
_hwnd = InitAll();
_gtn.setHWND( _hwnd );
ShowWindow( _hwnd, SW_SHOW );
UpdateWindow( _hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT ) {
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {
TranslateMessage( &msg );
DispatchMessage( &msg );
} else _gtn.simulate();
}
return UnregisterClass( "_GALTON_", _hInst );
}
private:
static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
switch( msg ) {
case WM_DESTROY: PostQuitMessage( 0 ); break;
default:
return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );
}
return 0;
}
HWND InitAll() {
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ( WNDPROC )WndProc;
wcex.hInstance = _hInst;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_GALTON_";
RegisterClassEx( &wcex );
RECT rc;
SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );
AdjustWindowRect( &rc, WS_CAPTION, FALSE );
return CreateWindow( "_GALTON_", ".: Galton Box -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );
}
HINSTANCE _hInst;
HWND _hwnd;
galton _gtn;
};
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {
srand( GetTickCount() );
wnd myWnd;
return myWnd.Run( hInstance );
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. |
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':
n = R-L
if n < 2:
return 0
swaps = 0
m = n//2
for i in range(m):
if A[R-(i+1)] < A[L+i]:
(A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
swaps += 1
if (n & 1) and (A[L+m] < A[L+m-1]):
(A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)
swaps += 1
return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)
def circle_sort(L:list)->'sort A in place, returning the number of swaps':
swaps = 0
s = 1
while s:
s = circle_sort_backend(L, 0, len(L))
swaps += s
return swaps
if __name__ == '__main__':
from random import shuffle
for i in range(309):
L = list(range(i))
M = L[:]
shuffle(L)
N = L[:]
circle_sort(L)
if L != M:
print(len(L))
print(N)
print(L)
| #include <iostream>
int circlesort(int* arr, int lo, int hi, int swaps) {
if(lo == hi) {
return swaps;
}
int high = hi;
int low = lo;
int mid = (high - low) / 2;
while(lo < hi) {
if(arr[lo] > arr[hi]) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
swaps++;
}
lo++;
hi--;
}
if(lo == hi) {
if(arr[lo] > arr[hi+1]) {
int temp = arr[lo];
arr[lo] = arr[hi+1];
arr[hi+1] = temp;
swaps++;
}
}
swaps = circlesort(arr, low, low+mid, swaps);
swaps = circlesort(arr, low+mid+1, high, swaps);
return swaps;
}
void circlesortDriver(int* arr, int n) {
do {
for(int i = 0; i < n; i++) {
std::cout << arr[i] << ' ';
}
std::cout << std::endl;
} while(circlesort(arr, 0, n-1, 0));
}
int main() {
int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };
circlesortDriver(arr, sizeof(arr)/sizeof(int));
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Python. | import os
from PIL import Image
def imgsave(path, arr):
w, h = len(arr), len(arr[0])
img = Image.new('1', (w, h))
for x in range(w):
for y in range(h):
img.putpixel((x, y), arr[x][y])
img.save(path)
def get_shape(mat):
return len(mat), len(mat[0])
def kron(matrix1, matrix2):
final_list = []
count = len(matrix2)
for elem1 in matrix1:
for i in range(count):
sub_list = []
for num1 in elem1:
for num2 in matrix2[i]:
sub_list.append(num1 * num2)
final_list.append(sub_list)
return final_list
def kronpow(mat):
matrix = mat
while True:
yield matrix
matrix = kron(mat, matrix)
def fractal(name, mat, order=6):
path = os.path.join('fractals', name)
os.makedirs(path, exist_ok=True)
fgen = kronpow(mat)
print(name)
for i in range(order):
p = os.path.join(path, f'{i}.jpg')
print('Calculating n =', i, end='\t', flush=True)
mat = next(fgen)
imgsave(p, mat)
x, y = get_shape(mat)
print('Saved as', x, 'x', y, 'image', p)
test1 = [
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
]
test2 = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
test3 = [
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
]
fractal('test1', test1)
fractal('test2', test2)
fractal('test3', test3)
| #include <cassert>
#include <vector>
#include <QImage>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
matrix<scalar_type> kronecker_product(const matrix<scalar_type>& a,
const matrix<scalar_type>& b) {
size_t arows = a.rows();
size_t acolumns = a.columns();
size_t brows = b.rows();
size_t bcolumns = b.columns();
matrix<scalar_type> c(arows * brows, acolumns * bcolumns);
for (size_t i = 0; i < arows; ++i)
for (size_t j = 0; j < acolumns; ++j)
for (size_t k = 0; k < brows; ++k)
for (size_t l = 0; l < bcolumns; ++l)
c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l);
return c;
}
bool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) {
matrix<unsigned char> result = m;
for (int i = 0; i < order; ++i)
result = kronecker_product(result, m);
size_t height = result.rows();
size_t width = result.columns();
size_t bytesPerLine = 4 * ((width + 3)/4);
std::vector<uchar> imageData(bytesPerLine * height);
for (size_t i = 0; i < height; ++i)
for (size_t j = 0; j < width; ++j)
imageData[i * bytesPerLine + j] = result(i, j);
QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8);
QVector<QRgb> colours(2);
colours[0] = qRgb(0, 0, 0);
colours[1] = qRgb(255, 255, 255);
image.setColorTable(colours);
return image.save(fileName);
}
int main() {
matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}});
matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}});
matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}});
kronecker_fractal("vicsek.png", matrix1, 5);
kronecker_fractal("sierpinski_carpet.png", matrix2, 5);
kronecker_fractal("sierpinski_triangle.png", matrix3, 8);
return 0;
}
|
Write the same code in C++ as shown below in Python. | def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
if len(line.split()) != 1: continue
boolval = False
bits = line.split(None, 1)
if len(bits) == 1:
k = bits[0]
v = boolval
else:
k, v = bits
ret[k.lower()] = v
return ret
if __name__ == '__main__':
import sys
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v
| #include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/case_conv.hpp>
using namespace std;
using namespace boost;
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
static const char_separator<char> sep(" ","#;,");
struct configs{
string fullname;
string favoritefruit;
bool needspelling;
bool seedsremoved;
vector<string> otherfamily;
} conf;
void parseLine(const string &line, configs &conf)
{
if (line[0] == '#' || line.empty())
return;
Tokenizer tokenizer(line, sep);
vector<string> tokens;
for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)
tokens.push_back(*iter);
if (tokens[0] == ";"){
algorithm::to_lower(tokens[1]);
if (tokens[1] == "needspeeling")
conf.needspelling = false;
if (tokens[1] == "seedsremoved")
conf.seedsremoved = false;
}
algorithm::to_lower(tokens[0]);
if (tokens[0] == "needspeeling")
conf.needspelling = true;
if (tokens[0] == "seedsremoved")
conf.seedsremoved = true;
if (tokens[0] == "fullname"){
for (unsigned int i=1; i<tokens.size(); i++)
conf.fullname += tokens[i] + " ";
conf.fullname.erase(conf.fullname.size() -1, 1);
}
if (tokens[0] == "favouritefruit")
for (unsigned int i=1; i<tokens.size(); i++)
conf.favoritefruit += tokens[i];
if (tokens[0] == "otherfamily"){
unsigned int i=1;
string tmp;
while (i<=tokens.size()){
if ( i == tokens.size() || tokens[i] ==","){
tmp.erase(tmp.size()-1, 1);
conf.otherfamily.push_back(tmp);
tmp = "";
i++;
}
else{
tmp += tokens[i];
tmp += " ";
i++;
}
}
}
}
int _tmain(int argc, TCHAR* argv[])
{
if (argc != 2)
{
wstring tmp = argv[0];
wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl;
return -1;
}
ifstream file (argv[1]);
if (file.is_open())
while(file.good())
{
char line[255];
file.getline(line, 255);
string linestring(line);
parseLine(linestring, conf);
}
else
{
cout << "Unable to open the file" << endl;
return -2;
}
cout << "Fullname= " << conf.fullname << endl;
cout << "Favorite Fruit= " << conf.favoritefruit << endl;
cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl;
cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl;
string otherFamily;
for (unsigned int i = 0; i < conf.otherfamily.size(); i++)
otherFamily += conf.otherfamily[i] + ", ";
otherFamily.erase(otherFamily.size()-2, 2);
cout << "Other Family= " << otherFamily << endl;
return 0;
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
| #include <algorithm>
#include <string>
#include <cctype>
struct icompare_char {
bool operator()(char c1, char c2) {
return std::toupper(c1) < std::toupper(c2);
}
};
struct compare {
bool operator()(std::string const& s1, std::string const& s2) {
if (s1.length() > s2.length())
return true;
if (s1.length() < s2.length())
return false;
return std::lexicographical_compare(s1.begin(), s1.end(),
s2.begin(), s2.end(),
icompare_char());
}
};
int main() {
std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};
std::sort(strings, strings+8, compare());
return 0;
}
|
Generate an equivalent C++ version of this Python code. | import random
def is_Prime(n):
if n!=int(n):
return False
n=int(n)
if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
return False
if n==2 or n==3 or n==5 or n==7:
return True
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(8):
a = random.randrange(2, n)
if trial_composite(a):
return False
return True
def isPrime(n: int) -> bool:
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def rotations(n: int)-> set((int,)):
a = str(n)
return set(int(a[i:] + a[:i]) for i in range(len(a)))
def isCircular(n: int) -> bool:
return all(isPrime(int(o)) for o in rotations(n))
from itertools import product
def main():
result = [2, 3, 5, 7]
first = '137'
latter = '1379'
for i in range(1, 6):
s = set(int(''.join(a)) for a in product(first, *((latter,) * i)))
while s:
a = s.pop()
b = rotations(a)
if isCircular(a):
result.append(min(b))
s -= b
result.sort()
return result
assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main()
repunit = lambda n: int('1' * n)
def repmain(n: int) -> list:
result = []
i = 2
while len(result) < n:
if is_Prime(repunit(i)):
result.append(i)
i += 1
return result
assert [2, 19, 23, 317, 1031] == repmain(5)
| #include <cstdint>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
typedef mpz_class integer;
bool is_prime(const integer& n, int reps = 50) {
return mpz_probab_prime_p(n.get_mpz_t(), reps);
}
std::string to_string(const integer& n) {
std::ostringstream out;
out << n;
return out.str();
}
bool is_circular_prime(const integer& p) {
if (!is_prime(p))
return false;
std::string str(to_string(p));
for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {
std::rotate(str.begin(), str.begin() + 1, str.end());
integer p2(str, 10);
if (p2 < p || !is_prime(p2))
return false;
}
return true;
}
integer next_repunit(const integer& n) {
integer p = 1;
while (p < n)
p = 10 * p + 1;
return p;
}
integer repunit(int digits) {
std::string str(digits, '1');
integer p(str);
return p;
}
void test_repunit(int digits) {
if (is_prime(repunit(digits), 10))
std::cout << "R(" << digits << ") is probably prime\n";
else
std::cout << "R(" << digits << ") is not prime\n";
}
int main() {
integer p = 2;
std::cout << "First 19 circular primes:\n";
for (int count = 0; count < 19; ++p) {
if (is_circular_prime(p)) {
if (count > 0)
std::cout << ", ";
std::cout << p;
++count;
}
}
std::cout << '\n';
std::cout << "Next 4 circular primes:\n";
p = next_repunit(p);
std::string str(to_string(p));
int digits = str.size();
for (int count = 0; count < 4; ) {
if (is_prime(p, 15)) {
if (count > 0)
std::cout << ", ";
std::cout << "R(" << digits << ")";
++count;
}
p = repunit(++digits);
}
std::cout << '\n';
test_repunit(5003);
test_repunit(9887);
test_repunit(15073);
test_repunit(25031);
test_repunit(35317);
test_repunit(49081);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Python to C++. | import random
def is_Prime(n):
if n!=int(n):
return False
n=int(n)
if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
return False
if n==2 or n==3 or n==5 or n==7:
return True
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(8):
a = random.randrange(2, n)
if trial_composite(a):
return False
return True
def isPrime(n: int) -> bool:
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def rotations(n: int)-> set((int,)):
a = str(n)
return set(int(a[i:] + a[:i]) for i in range(len(a)))
def isCircular(n: int) -> bool:
return all(isPrime(int(o)) for o in rotations(n))
from itertools import product
def main():
result = [2, 3, 5, 7]
first = '137'
latter = '1379'
for i in range(1, 6):
s = set(int(''.join(a)) for a in product(first, *((latter,) * i)))
while s:
a = s.pop()
b = rotations(a)
if isCircular(a):
result.append(min(b))
s -= b
result.sort()
return result
assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main()
repunit = lambda n: int('1' * n)
def repmain(n: int) -> list:
result = []
i = 2
while len(result) < n:
if is_Prime(repunit(i)):
result.append(i)
i += 1
return result
assert [2, 19, 23, 317, 1031] == repmain(5)
| #include <cstdint>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
typedef mpz_class integer;
bool is_prime(const integer& n, int reps = 50) {
return mpz_probab_prime_p(n.get_mpz_t(), reps);
}
std::string to_string(const integer& n) {
std::ostringstream out;
out << n;
return out.str();
}
bool is_circular_prime(const integer& p) {
if (!is_prime(p))
return false;
std::string str(to_string(p));
for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {
std::rotate(str.begin(), str.begin() + 1, str.end());
integer p2(str, 10);
if (p2 < p || !is_prime(p2))
return false;
}
return true;
}
integer next_repunit(const integer& n) {
integer p = 1;
while (p < n)
p = 10 * p + 1;
return p;
}
integer repunit(int digits) {
std::string str(digits, '1');
integer p(str);
return p;
}
void test_repunit(int digits) {
if (is_prime(repunit(digits), 10))
std::cout << "R(" << digits << ") is probably prime\n";
else
std::cout << "R(" << digits << ") is not prime\n";
}
int main() {
integer p = 2;
std::cout << "First 19 circular primes:\n";
for (int count = 0; count < 19; ++p) {
if (is_circular_prime(p)) {
if (count > 0)
std::cout << ", ";
std::cout << p;
++count;
}
}
std::cout << '\n';
std::cout << "Next 4 circular primes:\n";
p = next_repunit(p);
std::string str(to_string(p));
int digits = str.size();
for (int count = 0; count < 4; ) {
if (is_prime(p, 15)) {
if (count > 0)
std::cout << ", ";
std::cout << "R(" << digits << ")";
++count;
}
p = repunit(++digits);
}
std::cout << '\n';
test_repunit(5003);
test_repunit(9887);
test_repunit(15073);
test_repunit(25031);
test_repunit(35317);
test_repunit(49081);
return 0;
}
|
Generate an equivalent C++ version of this Python code. | txt = "Hello, world! "
left = True
def draw():
global txt
background(128)
text(txt, 10, height / 2)
if frameCount % 10 == 0:
if (left):
txt = rotate(txt, 1)
else:
txt = rotate(txt, -1)
println(txt)
def mouseReleased():
global left
left = not left
def rotate(text, startIdx):
rotated = text[startIdx:] + text[:startIdx]
return rotated
| #include "animationwidget.h"
#include <QLabel>
#include <QTimer>
#include <QVBoxLayout>
#include <algorithm>
AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {
setWindowTitle(tr("Animation"));
QFont font("Courier", 24);
QLabel* label = new QLabel("Hello World! ");
label->setFont(font);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(label);
QTimer* timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, [label,this]() {
QString text = label->text();
std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());
label->setText(text);
});
timer->start(200);
}
void AnimationWidget::mousePressEvent(QMouseEvent*) {
right_ = !right_;
}
|
Maintain the same structure and functionality when rewriting this code in C++. |
from math import log
def getDigit(num, base, digit_num):
return (num // base ** digit_num) % base
def makeBlanks(size):
return [ [] for i in range(size) ]
def split(a_list, base, digit_num):
buckets = makeBlanks(base)
for num in a_list:
buckets[getDigit(num, base, digit_num)].append(num)
return buckets
def merge(a_list):
new_list = []
for sublist in a_list:
new_list.extend(sublist)
return new_list
def maxAbs(a_list):
return max(abs(num) for num in a_list)
def split_by_sign(a_list):
buckets = [[], []]
for num in a_list:
if num < 0:
buckets[0].append(num)
else:
buckets[1].append(num)
return buckets
def radixSort(a_list, base):
passes = int(round(log(maxAbs(a_list), base)) + 1)
new_list = list(a_list)
for digit_num in range(passes):
new_list = merge(split(new_list, base, digit_num))
return merge(split_by_sign(new_list))
| #include <algorithm>
#include <iostream>
#include <iterator>
class radix_test
{
const int bit;
public:
radix_test(int offset) : bit(offset) {}
bool operator()(int value) const
{
if (bit == 31)
return value < 0;
else
return !(value & (1 << bit));
}
};
void lsd_radix_sort(int *first, int *last)
{
for (int lsb = 0; lsb < 32; ++lsb)
{
std::stable_partition(first, last, radix_test(lsb));
}
}
void msd_radix_sort(int *first, int *last, int msb = 31)
{
if (first != last && msb >= 0)
{
int *mid = std::partition(first, last, radix_test(msb));
msb--;
msd_radix_sort(first, mid, msb);
msd_radix_sort(mid, last, msb);
}
}
int main()
{
int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };
lsd_radix_sort(data, data + 8);
std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, " "));
return 0;
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
| #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>
void list_comprehension( std::vector<int> & , int ) ;
int main( ) {
std::vector<int> triangles ;
list_comprehension( triangles , 20 ) ;
std::copy( triangles.begin( ) , triangles.end( ) ,
std::ostream_iterator<int>( std::cout , " " ) ) ;
std::cout << std::endl ;
return 0 ;
}
void list_comprehension( std::vector<int> & numbers , int upper_border ) {
for ( int a = 1 ; a < upper_border ; a++ ) {
for ( int b = a + 1 ; b < upper_border ; b++ ) {
double c = pow( a * a + b * b , 0.5 ) ;
if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
if ( c == floor( c ) ) {
numbers.push_back( a ) ;
numbers.push_back( b ) ;
numbers.push_back( static_cast<int>( c ) ) ;
}
}
}
}
}
|
Port the provided Python code into C++ while preserving the original functionality. | def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
| #include <algorithm>
#include <iterator>
#include <iostream>
template<typename ForwardIterator> void selection_sort(ForwardIterator begin,
ForwardIterator end) {
for(auto i = begin; i != end; ++i) {
std::iter_swap(i, std::min_element(i, end));
}
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
selection_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
|
Keep all operations the same but rewrite the snippet in C++. | def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
| #include <algorithm>
#include <iterator>
#include <iostream>
template<typename ForwardIterator> void selection_sort(ForwardIterator begin,
ForwardIterator end) {
for(auto i = begin; i != end; ++i) {
std::iter_swap(i, std::min_element(i, end));
}
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
selection_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
|
Change the following Python code into C++ without altering its purpose. | def jacobi(a, n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
if n % 2 == 0:
raise ValueError("'n' must be odd.")
a %= n
result = 1
while a != 0:
while a % 2 == 0:
a /= 2
n_mod_8 = n % 8
if n_mod_8 in (3, 5):
result = -result
a, n = n, a
if a % 4 == 3 and n % 4 == 3:
result = -result
a %= n
if n == 1:
return result
else:
return 0
| #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int jacobi(int n, int k) {
assert(k > 0 && k % 2 == 1);
n %= k;
int t = 1;
while (n != 0) {
while (n % 2 == 0) {
n /= 2;
int r = k % 8;
if (r == 3 || r == 5)
t = -t;
}
std::swap(n, k);
if (n % 4 == 3 && k % 4 == 3)
t = -t;
n %= k;
}
return k == 1 ? t : 0;
}
void print_table(std::ostream& out, int kmax, int nmax) {
out << "n\\k|";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << k;
out << "\n----";
for (int k = 0; k <= kmax; ++k)
out << "---";
out << '\n';
for (int n = 1; n <= nmax; n += 2) {
out << std::setw(2) << n << " |";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << jacobi(k, n);
out << '\n';
}
}
int main() {
print_table(std::cout, 20, 21);
return 0;
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | def jacobi(a, n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
if n % 2 == 0:
raise ValueError("'n' must be odd.")
a %= n
result = 1
while a != 0:
while a % 2 == 0:
a /= 2
n_mod_8 = n % 8
if n_mod_8 in (3, 5):
result = -result
a, n = n, a
if a % 4 == 3 and n % 4 == 3:
result = -result
a %= n
if n == 1:
return result
else:
return 0
| #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int jacobi(int n, int k) {
assert(k > 0 && k % 2 == 1);
n %= k;
int t = 1;
while (n != 0) {
while (n % 2 == 0) {
n /= 2;
int r = k % 8;
if (r == 3 || r == 5)
t = -t;
}
std::swap(n, k);
if (n % 4 == 3 && k % 4 == 3)
t = -t;
n %= k;
}
return k == 1 ? t : 0;
}
void print_table(std::ostream& out, int kmax, int nmax) {
out << "n\\k|";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << k;
out << "\n----";
for (int k = 0; k <= kmax; ++k)
out << "---";
out << '\n';
for (int n = 1; n <= nmax; n += 2) {
out << std::setw(2) << n << " |";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << jacobi(k, n);
out << '\n';
}
}
int main() {
print_table(std::cout, 20, 21);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | from random import seed, random
from time import time
from operator import itemgetter
from collections import namedtuple
from math import sqrt
from copy import deepcopy
def sqd(p1, p2):
return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))
class KdNode(object):
__slots__ = ("dom_elt", "split", "left", "right")
def __init__(self, dom_elt, split, left, right):
self.dom_elt = dom_elt
self.split = split
self.left = left
self.right = right
class Orthotope(object):
__slots__ = ("min", "max")
def __init__(self, mi, ma):
self.min, self.max = mi, ma
class KdTree(object):
__slots__ = ("n", "bounds")
def __init__(self, pts, bounds):
def nk2(split, exset):
if not exset:
return None
exset.sort(key=itemgetter(split))
m = len(exset) // 2
d = exset[m]
while m + 1 < len(exset) and exset[m + 1][split] == d[split]:
m += 1
d = exset[m]
s2 = (split + 1) % len(d)
return KdNode(d, split, nk2(s2, exset[:m]),
nk2(s2, exset[m + 1:]))
self.n = nk2(0, pts)
self.bounds = bounds
T3 = namedtuple("T3", "nearest dist_sqd nodes_visited")
def find_nearest(k, t, p):
def nn(kd, target, hr, max_dist_sqd):
if kd is None:
return T3([0.0] * k, float("inf"), 0)
nodes_visited = 1
s = kd.split
pivot = kd.dom_elt
left_hr = deepcopy(hr)
right_hr = deepcopy(hr)
left_hr.max[s] = pivot[s]
right_hr.min[s] = pivot[s]
if target[s] <= pivot[s]:
nearer_kd, nearer_hr = kd.left, left_hr
further_kd, further_hr = kd.right, right_hr
else:
nearer_kd, nearer_hr = kd.right, right_hr
further_kd, further_hr = kd.left, left_hr
n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)
nearest = n1.nearest
dist_sqd = n1.dist_sqd
nodes_visited += n1.nodes_visited
if dist_sqd < max_dist_sqd:
max_dist_sqd = dist_sqd
d = (pivot[s] - target[s]) ** 2
if d > max_dist_sqd:
return T3(nearest, dist_sqd, nodes_visited)
d = sqd(pivot, target)
if d < dist_sqd:
nearest = pivot
dist_sqd = d
max_dist_sqd = dist_sqd
n2 = nn(further_kd, target, further_hr, max_dist_sqd)
nodes_visited += n2.nodes_visited
if n2.dist_sqd < dist_sqd:
nearest = n2.nearest
dist_sqd = n2.dist_sqd
return T3(nearest, dist_sqd, nodes_visited)
return nn(t.n, p, t.bounds, float("inf"))
def show_nearest(k, heading, kd, p):
print(heading + ":")
print("Point: ", p)
n = find_nearest(k, kd, p)
print("Nearest neighbor:", n.nearest)
print("Distance: ", sqrt(n.dist_sqd))
print("Nodes visited: ", n.nodes_visited, "\n")
def random_point(k):
return [random() for _ in range(k)]
def random_points(k, n):
return [random_point(k) for _ in range(n)]
if __name__ == "__main__":
seed(1)
P = lambda *coords: list(coords)
kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],
Orthotope(P(0, 0), P(10, 10)))
show_nearest(2, "Wikipedia example data", kd1, P(9, 2))
N = 400000
t0 = time()
kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))
t1 = time()
text = lambda *parts: "".join(map(str, parts))
show_nearest(2, text("k-d tree with ", N,
" random 3D points (generation time: ",
t1-t0, "s)"),
kd2, random_point(3))
| #include <algorithm>
#include <array>
#include <cmath>
#include <iostream>
#include <random>
#include <vector>
template<typename coordinate_type, size_t dimensions>
class point {
public:
point(std::array<coordinate_type, dimensions> c) : coords_(c) {}
point(std::initializer_list<coordinate_type> list) {
size_t n = std::min(dimensions, list.size());
std::copy_n(list.begin(), n, coords_.begin());
}
coordinate_type get(size_t index) const {
return coords_[index];
}
double distance(const point& pt) const {
double dist = 0;
for (size_t i = 0; i < dimensions; ++i) {
double d = get(i) - pt.get(i);
dist += d * d;
}
return dist;
}
private:
std::array<coordinate_type, dimensions> coords_;
};
template<typename coordinate_type, size_t dimensions>
std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {
out << '(';
for (size_t i = 0; i < dimensions; ++i) {
if (i > 0)
out << ", ";
out << pt.get(i);
}
out << ')';
return out;
}
template<typename coordinate_type, size_t dimensions>
class kdtree {
public:
typedef point<coordinate_type, dimensions> point_type;
private:
struct node {
node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}
coordinate_type get(size_t index) const {
return point_.get(index);
}
double distance(const point_type& pt) const {
return point_.distance(pt);
}
point_type point_;
node* left_;
node* right_;
};
node* root_ = nullptr;
node* best_ = nullptr;
double best_dist_ = 0;
size_t visited_ = 0;
std::vector<node> nodes_;
struct node_cmp {
node_cmp(size_t index) : index_(index) {}
bool operator()(const node& n1, const node& n2) const {
return n1.point_.get(index_) < n2.point_.get(index_);
}
size_t index_;
};
node* make_tree(size_t begin, size_t end, size_t index) {
if (end <= begin)
return nullptr;
size_t n = begin + (end - begin)/2;
auto i = nodes_.begin();
std::nth_element(i + begin, i + n, i + end, node_cmp(index));
index = (index + 1) % dimensions;
nodes_[n].left_ = make_tree(begin, n, index);
nodes_[n].right_ = make_tree(n + 1, end, index);
return &nodes_[n];
}
void nearest(node* root, const point_type& point, size_t index) {
if (root == nullptr)
return;
++visited_;
double d = root->distance(point);
if (best_ == nullptr || d < best_dist_) {
best_dist_ = d;
best_ = root;
}
if (best_dist_ == 0)
return;
double dx = root->get(index) - point.get(index);
index = (index + 1) % dimensions;
nearest(dx > 0 ? root->left_ : root->right_, point, index);
if (dx * dx >= best_dist_)
return;
nearest(dx > 0 ? root->right_ : root->left_, point, index);
}
public:
kdtree(const kdtree&) = delete;
kdtree& operator=(const kdtree&) = delete;
template<typename iterator>
kdtree(iterator begin, iterator end) : nodes_(begin, end) {
root_ = make_tree(0, nodes_.size(), 0);
}
template<typename func>
kdtree(func&& f, size_t n) {
nodes_.reserve(n);
for (size_t i = 0; i < n; ++i)
nodes_.push_back(f());
root_ = make_tree(0, nodes_.size(), 0);
}
bool empty() const { return nodes_.empty(); }
size_t visited() const { return visited_; }
double distance() const { return std::sqrt(best_dist_); }
const point_type& nearest(const point_type& pt) {
if (root_ == nullptr)
throw std::logic_error("tree is empty");
best_ = nullptr;
visited_ = 0;
best_dist_ = 0;
nearest(root_, pt, 0);
return best_->point_;
}
};
void test_wikipedia() {
typedef point<int, 2> point2d;
typedef kdtree<int, 2> tree2d;
point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };
tree2d tree(std::begin(points), std::end(points));
point2d n = tree.nearest({ 9, 2 });
std::cout << "Wikipedia example data:\n";
std::cout << "nearest point: " << n << '\n';
std::cout << "distance: " << tree.distance() << '\n';
std::cout << "nodes visited: " << tree.visited() << '\n';
}
typedef point<double, 3> point3d;
typedef kdtree<double, 3> tree3d;
struct random_point_generator {
random_point_generator(double min, double max)
: engine_(std::random_device()()), distribution_(min, max) {}
point3d operator()() {
double x = distribution_(engine_);
double y = distribution_(engine_);
double z = distribution_(engine_);
return point3d({x, y, z});
}
std::mt19937 engine_;
std::uniform_real_distribution<double> distribution_;
};
void test_random(size_t count) {
random_point_generator rpg(0, 1);
tree3d tree(rpg, count);
point3d pt(rpg());
point3d n = tree.nearest(pt);
std::cout << "Random data (" << count << " points):\n";
std::cout << "point: " << pt << '\n';
std::cout << "nearest point: " << n << '\n';
std::cout << "distance: " << tree.distance() << '\n';
std::cout << "nodes visited: " << tree.visited() << '\n';
}
int main() {
try {
test_wikipedia();
std::cout << '\n';
test_random(1000);
std::cout << '\n';
test_random(1000000);
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
return 0;
}
|
Generate an equivalent C++ version of this Python code. | from random import seed, random
from time import time
from operator import itemgetter
from collections import namedtuple
from math import sqrt
from copy import deepcopy
def sqd(p1, p2):
return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))
class KdNode(object):
__slots__ = ("dom_elt", "split", "left", "right")
def __init__(self, dom_elt, split, left, right):
self.dom_elt = dom_elt
self.split = split
self.left = left
self.right = right
class Orthotope(object):
__slots__ = ("min", "max")
def __init__(self, mi, ma):
self.min, self.max = mi, ma
class KdTree(object):
__slots__ = ("n", "bounds")
def __init__(self, pts, bounds):
def nk2(split, exset):
if not exset:
return None
exset.sort(key=itemgetter(split))
m = len(exset) // 2
d = exset[m]
while m + 1 < len(exset) and exset[m + 1][split] == d[split]:
m += 1
d = exset[m]
s2 = (split + 1) % len(d)
return KdNode(d, split, nk2(s2, exset[:m]),
nk2(s2, exset[m + 1:]))
self.n = nk2(0, pts)
self.bounds = bounds
T3 = namedtuple("T3", "nearest dist_sqd nodes_visited")
def find_nearest(k, t, p):
def nn(kd, target, hr, max_dist_sqd):
if kd is None:
return T3([0.0] * k, float("inf"), 0)
nodes_visited = 1
s = kd.split
pivot = kd.dom_elt
left_hr = deepcopy(hr)
right_hr = deepcopy(hr)
left_hr.max[s] = pivot[s]
right_hr.min[s] = pivot[s]
if target[s] <= pivot[s]:
nearer_kd, nearer_hr = kd.left, left_hr
further_kd, further_hr = kd.right, right_hr
else:
nearer_kd, nearer_hr = kd.right, right_hr
further_kd, further_hr = kd.left, left_hr
n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)
nearest = n1.nearest
dist_sqd = n1.dist_sqd
nodes_visited += n1.nodes_visited
if dist_sqd < max_dist_sqd:
max_dist_sqd = dist_sqd
d = (pivot[s] - target[s]) ** 2
if d > max_dist_sqd:
return T3(nearest, dist_sqd, nodes_visited)
d = sqd(pivot, target)
if d < dist_sqd:
nearest = pivot
dist_sqd = d
max_dist_sqd = dist_sqd
n2 = nn(further_kd, target, further_hr, max_dist_sqd)
nodes_visited += n2.nodes_visited
if n2.dist_sqd < dist_sqd:
nearest = n2.nearest
dist_sqd = n2.dist_sqd
return T3(nearest, dist_sqd, nodes_visited)
return nn(t.n, p, t.bounds, float("inf"))
def show_nearest(k, heading, kd, p):
print(heading + ":")
print("Point: ", p)
n = find_nearest(k, kd, p)
print("Nearest neighbor:", n.nearest)
print("Distance: ", sqrt(n.dist_sqd))
print("Nodes visited: ", n.nodes_visited, "\n")
def random_point(k):
return [random() for _ in range(k)]
def random_points(k, n):
return [random_point(k) for _ in range(n)]
if __name__ == "__main__":
seed(1)
P = lambda *coords: list(coords)
kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],
Orthotope(P(0, 0), P(10, 10)))
show_nearest(2, "Wikipedia example data", kd1, P(9, 2))
N = 400000
t0 = time()
kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))
t1 = time()
text = lambda *parts: "".join(map(str, parts))
show_nearest(2, text("k-d tree with ", N,
" random 3D points (generation time: ",
t1-t0, "s)"),
kd2, random_point(3))
| #include <algorithm>
#include <array>
#include <cmath>
#include <iostream>
#include <random>
#include <vector>
template<typename coordinate_type, size_t dimensions>
class point {
public:
point(std::array<coordinate_type, dimensions> c) : coords_(c) {}
point(std::initializer_list<coordinate_type> list) {
size_t n = std::min(dimensions, list.size());
std::copy_n(list.begin(), n, coords_.begin());
}
coordinate_type get(size_t index) const {
return coords_[index];
}
double distance(const point& pt) const {
double dist = 0;
for (size_t i = 0; i < dimensions; ++i) {
double d = get(i) - pt.get(i);
dist += d * d;
}
return dist;
}
private:
std::array<coordinate_type, dimensions> coords_;
};
template<typename coordinate_type, size_t dimensions>
std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) {
out << '(';
for (size_t i = 0; i < dimensions; ++i) {
if (i > 0)
out << ", ";
out << pt.get(i);
}
out << ')';
return out;
}
template<typename coordinate_type, size_t dimensions>
class kdtree {
public:
typedef point<coordinate_type, dimensions> point_type;
private:
struct node {
node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {}
coordinate_type get(size_t index) const {
return point_.get(index);
}
double distance(const point_type& pt) const {
return point_.distance(pt);
}
point_type point_;
node* left_;
node* right_;
};
node* root_ = nullptr;
node* best_ = nullptr;
double best_dist_ = 0;
size_t visited_ = 0;
std::vector<node> nodes_;
struct node_cmp {
node_cmp(size_t index) : index_(index) {}
bool operator()(const node& n1, const node& n2) const {
return n1.point_.get(index_) < n2.point_.get(index_);
}
size_t index_;
};
node* make_tree(size_t begin, size_t end, size_t index) {
if (end <= begin)
return nullptr;
size_t n = begin + (end - begin)/2;
auto i = nodes_.begin();
std::nth_element(i + begin, i + n, i + end, node_cmp(index));
index = (index + 1) % dimensions;
nodes_[n].left_ = make_tree(begin, n, index);
nodes_[n].right_ = make_tree(n + 1, end, index);
return &nodes_[n];
}
void nearest(node* root, const point_type& point, size_t index) {
if (root == nullptr)
return;
++visited_;
double d = root->distance(point);
if (best_ == nullptr || d < best_dist_) {
best_dist_ = d;
best_ = root;
}
if (best_dist_ == 0)
return;
double dx = root->get(index) - point.get(index);
index = (index + 1) % dimensions;
nearest(dx > 0 ? root->left_ : root->right_, point, index);
if (dx * dx >= best_dist_)
return;
nearest(dx > 0 ? root->right_ : root->left_, point, index);
}
public:
kdtree(const kdtree&) = delete;
kdtree& operator=(const kdtree&) = delete;
template<typename iterator>
kdtree(iterator begin, iterator end) : nodes_(begin, end) {
root_ = make_tree(0, nodes_.size(), 0);
}
template<typename func>
kdtree(func&& f, size_t n) {
nodes_.reserve(n);
for (size_t i = 0; i < n; ++i)
nodes_.push_back(f());
root_ = make_tree(0, nodes_.size(), 0);
}
bool empty() const { return nodes_.empty(); }
size_t visited() const { return visited_; }
double distance() const { return std::sqrt(best_dist_); }
const point_type& nearest(const point_type& pt) {
if (root_ == nullptr)
throw std::logic_error("tree is empty");
best_ = nullptr;
visited_ = 0;
best_dist_ = 0;
nearest(root_, pt, 0);
return best_->point_;
}
};
void test_wikipedia() {
typedef point<int, 2> point2d;
typedef kdtree<int, 2> tree2d;
point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } };
tree2d tree(std::begin(points), std::end(points));
point2d n = tree.nearest({ 9, 2 });
std::cout << "Wikipedia example data:\n";
std::cout << "nearest point: " << n << '\n';
std::cout << "distance: " << tree.distance() << '\n';
std::cout << "nodes visited: " << tree.visited() << '\n';
}
typedef point<double, 3> point3d;
typedef kdtree<double, 3> tree3d;
struct random_point_generator {
random_point_generator(double min, double max)
: engine_(std::random_device()()), distribution_(min, max) {}
point3d operator()() {
double x = distribution_(engine_);
double y = distribution_(engine_);
double z = distribution_(engine_);
return point3d({x, y, z});
}
std::mt19937 engine_;
std::uniform_real_distribution<double> distribution_;
};
void test_random(size_t count) {
random_point_generator rpg(0, 1);
tree3d tree(rpg, count);
point3d pt(rpg());
point3d n = tree.nearest(pt);
std::cout << "Random data (" << count << " points):\n";
std::cout << "point: " << pt << '\n';
std::cout << "nearest point: " << n << '\n';
std::cout << "distance: " << tree.distance() << '\n';
std::cout << "nodes visited: " << tree.visited() << '\n';
}
int main() {
try {
test_wikipedia();
std::cout << '\n';
test_random(1000);
std::cout << '\n';
test_random(1000000);
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
return 0;
}
|
Translate the given Python code snippet into C++ without altering its behavior. | def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers]
squares2a = map(square, numbers)
squares2b = map(lambda x: x*x, numbers)
squares3 = [n * n for n in numbers]
isquares1 = (n * n for n in numbers)
import itertools
isquares2 = itertools.imap(square, numbers)
| #include <iostream>
#include <algorithm>
void print_square(int i) {
std::cout << i*i << " ";
}
int main() {
int ary[]={1,2,3,4,5};
std::for_each(ary,ary+5,print_square);
return 0;
}
|
Change the programming language of this snippet from Python to C++ without modifying what it does. | >>> class Borg(object):
__state = {}
def __init__(self):
self.__dict__ = self.__state
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>>
| #include <stdexcept>
template <typename Self>
class singleton
{
protected:
static Self*
sentry;
public:
static Self&
instance()
{
return *sentry;
}
singleton()
{
if(sentry)
throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!");
sentry = (Self*)this;
}
virtual ~singleton()
{
if(sentry == this)
sentry = 0;
}
};
template <typename Self>
Self*
singleton<Self>::sentry = 0;
#include <iostream>
#include <string>
using namespace
std;
class controller : public singleton<controller>
{
public:
controller(string const& name)
: name(name)
{
trace("begin");
}
~controller()
{
trace("end");
}
void
work()
{
trace("doing stuff");
}
void
trace(string const& message)
{
cout << name << ": " << message << endl;
}
string
name;
};
int
main()
{
controller*
first = new controller("first");
controller::instance().work();
delete first;
controller
second("second");
controller::instance().work();
try
{
controller
goner("goner");
controller::instance().work();
}
catch(exception const& error)
{
cout << error.what() << endl;
}
controller::instance().work();
controller
goner("goner");
controller::instance().work();
}
|
Write the same algorithm in C++ as shown in this Python implementation. | >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> from math import fsum
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
| #include <iostream>
#include <tuple>
union conv {
int i;
float f;
};
float nextUp(float d) {
if (isnan(d) || d == -INFINITY || d == INFINITY) return d;
if (d == 0.0) return FLT_EPSILON;
conv c;
c.f = d;
c.i++;
return c.f;
}
float nextDown(float d) {
if (isnan(d) || d == -INFINITY || d == INFINITY) return d;
if (d == 0.0) return -FLT_EPSILON;
conv c;
c.f = d;
c.i--;
return c.f;
}
auto safeAdd(float a, float b) {
return std::make_tuple(nextDown(a + b), nextUp(a + b));
}
int main() {
float a = 1.20f;
float b = 0.03f;
auto result = safeAdd(a, b);
printf("(%f + %f) is in the range (%0.16f, %0.16f)\n", a, b, std::get<0>(result), std::get<1>(result));
return 0;
}
|
Convert the following code from Python to C++, ensuring the logic remains intact. | >>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named Benjamin , Samba , and Bernie
>>>
| #include <iostream>
#include <string>
using namespace std;
int main() {
string dog = "Benjamin", Dog = "Samba", DOG = "Bernie";
cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl;
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | for i in xrange(10, -1, -1):
print i
| for(int i = 10; i >= 0; --i)
std::cout << i << "\n";
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | with open(filename, 'w') as f:
f.write(data)
| #include <fstream>
using namespace std;
int main()
{
ofstream file("new.txt");
file << "this is a string";
file.close();
return 0;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. | for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
| for(int i = 0; i < 5; ++i) {
for(int j = 0; j < i; ++j)
std::cout.put('*');
std::cout.put('\n');
}
|
Ensure the translated C++ code behaves exactly like the original Python snippet. | from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))
def is_gapful(x):
return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)
if __name__ == '__main__':
start = 100
for mx, last in [(20, 20), (100, 15), (1_000, 10)]:
print(f"\nLast {last} of the first {mx} binned-by-last digit "
f"gapful numbers >= {start}")
bin = {i: [] for i in range(1, 10)}
gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))
while any(len(val) < mx for val in bin.values()):
g = next(gen)
val = bin[g % 10]
if len(val) < mx:
val.append(g)
b = {k:v[-last:] for k, v in bin.items()}
txt = pformat(b, width=220)
print('', re.sub(r"[{},\[\]]", '', txt))
| #include <iostream>
#include <cstdint>
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
class palindrome_generator {
public:
palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),
digit_(digit), even_(false) {}
integer next_palindrome() {
++next_;
if (next_ == power_ * (digit_ + 1)) {
if (even_)
power_ *= 10;
next_ = digit_ * power_;
even_ = !even_;
}
return next_ * (even_ ? 10 * power_ : power_)
+ reverse(even_ ? next_ : next_/10);
}
private:
integer power_;
integer next_;
int digit_;
bool even_;
};
bool gapful(integer n) {
integer m = n;
while (m >= 10)
m /= 10;
return n % (n % 10 + 10 * m) == 0;
}
template<size_t len>
void print(integer (&array)[9][len]) {
for (int digit = 1; digit < 10; ++digit) {
std::cout << digit << ":";
for (int i = 0; i < len; ++i)
std::cout << ' ' << array[digit - 1][i];
std::cout << '\n';
}
}
int main() {
const int n1 = 20, n2 = 15, n3 = 10;
const int m1 = 100, m2 = 1000;
integer pg1[9][n1];
integer pg2[9][n2];
integer pg3[9][n3];
for (int digit = 1; digit < 10; ++digit) {
palindrome_generator pgen(digit);
for (int i = 0; i < m2; ) {
integer n = pgen.next_palindrome();
if (!gapful(n))
continue;
if (i < n1)
pg1[digit - 1][i] = n;
else if (i < m1 && i >= m1 - n2)
pg2[digit - 1][i - (m1 - n2)] = n;
else if (i >= m2 - n3)
pg3[digit - 1][i - (m2 - n3)] = n;
++i;
}
}
std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n";
print(pg1);
std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n";
print(pg2);
std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n";
print(pg3);
return 0;
}
|
Change the programming language of this snippet from Python to C++ without modifying what it does. | from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))
def is_gapful(x):
return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)
if __name__ == '__main__':
start = 100
for mx, last in [(20, 20), (100, 15), (1_000, 10)]:
print(f"\nLast {last} of the first {mx} binned-by-last digit "
f"gapful numbers >= {start}")
bin = {i: [] for i in range(1, 10)}
gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))
while any(len(val) < mx for val in bin.values()):
g = next(gen)
val = bin[g % 10]
if len(val) < mx:
val.append(g)
b = {k:v[-last:] for k, v in bin.items()}
txt = pformat(b, width=220)
print('', re.sub(r"[{},\[\]]", '', txt))
| #include <iostream>
#include <cstdint>
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
class palindrome_generator {
public:
palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),
digit_(digit), even_(false) {}
integer next_palindrome() {
++next_;
if (next_ == power_ * (digit_ + 1)) {
if (even_)
power_ *= 10;
next_ = digit_ * power_;
even_ = !even_;
}
return next_ * (even_ ? 10 * power_ : power_)
+ reverse(even_ ? next_ : next_/10);
}
private:
integer power_;
integer next_;
int digit_;
bool even_;
};
bool gapful(integer n) {
integer m = n;
while (m >= 10)
m /= 10;
return n % (n % 10 + 10 * m) == 0;
}
template<size_t len>
void print(integer (&array)[9][len]) {
for (int digit = 1; digit < 10; ++digit) {
std::cout << digit << ":";
for (int i = 0; i < len; ++i)
std::cout << ' ' << array[digit - 1][i];
std::cout << '\n';
}
}
int main() {
const int n1 = 20, n2 = 15, n3 = 10;
const int m1 = 100, m2 = 1000;
integer pg1[9][n1];
integer pg2[9][n2];
integer pg3[9][n3];
for (int digit = 1; digit < 10; ++digit) {
palindrome_generator pgen(digit);
for (int i = 0; i < m2; ) {
integer n = pgen.next_palindrome();
if (!gapful(n))
continue;
if (i < n1)
pg1[digit - 1][i] = n;
else if (i < m1 && i >= m1 - n2)
pg2[digit - 1][i - (m1 - n2)] = n;
else if (i >= m2 - n3)
pg3[digit - 1][i - (m2 - n3)] = n;
++i;
}
}
std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n";
print(pg1);
std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n";
print(pg2);
std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n";
print(pg3);
return 0;
}
|
Write the same algorithm in C++ as shown in this Python implementation. | from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))
def is_gapful(x):
return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)
if __name__ == '__main__':
start = 100
for mx, last in [(20, 20), (100, 15), (1_000, 10)]:
print(f"\nLast {last} of the first {mx} binned-by-last digit "
f"gapful numbers >= {start}")
bin = {i: [] for i in range(1, 10)}
gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))
while any(len(val) < mx for val in bin.values()):
g = next(gen)
val = bin[g % 10]
if len(val) < mx:
val.append(g)
b = {k:v[-last:] for k, v in bin.items()}
txt = pformat(b, width=220)
print('', re.sub(r"[{},\[\]]", '', txt))
| #include <iostream>
#include <cstdint>
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
class palindrome_generator {
public:
palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),
digit_(digit), even_(false) {}
integer next_palindrome() {
++next_;
if (next_ == power_ * (digit_ + 1)) {
if (even_)
power_ *= 10;
next_ = digit_ * power_;
even_ = !even_;
}
return next_ * (even_ ? 10 * power_ : power_)
+ reverse(even_ ? next_ : next_/10);
}
private:
integer power_;
integer next_;
int digit_;
bool even_;
};
bool gapful(integer n) {
integer m = n;
while (m >= 10)
m /= 10;
return n % (n % 10 + 10 * m) == 0;
}
template<size_t len>
void print(integer (&array)[9][len]) {
for (int digit = 1; digit < 10; ++digit) {
std::cout << digit << ":";
for (int i = 0; i < len; ++i)
std::cout << ' ' << array[digit - 1][i];
std::cout << '\n';
}
}
int main() {
const int n1 = 20, n2 = 15, n3 = 10;
const int m1 = 100, m2 = 1000;
integer pg1[9][n1];
integer pg2[9][n2];
integer pg3[9][n3];
for (int digit = 1; digit < 10; ++digit) {
palindrome_generator pgen(digit);
for (int i = 0; i < m2; ) {
integer n = pgen.next_palindrome();
if (!gapful(n))
continue;
if (i < n1)
pg1[digit - 1][i] = n;
else if (i < m1 && i >= m1 - n2)
pg2[digit - 1][i - (m1 - n2)] = n;
else if (i >= m2 - n3)
pg3[digit - 1][i - (m2 - n3)] = n;
++i;
}
}
std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n";
print(pg1);
std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n";
print(pg2);
std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n";
print(pg3);
return 0;
}
|
Generate a C++ translation of this Python snippet without changing its computational steps. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 612;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class sierpinski {
public:
void draw( int o ) {
colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;
colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;
bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC();
drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );
bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL );
LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );
LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" );
}
private:
void drawTri( HDC dc, float l, float t, float r, float b, int i ) {
float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f;
if( i ) {
drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );
drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );
drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );
}
bmp.setPenColor( colors[i % 6] );
MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL );
LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) );
LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );
LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) );
}
myBitmap bmp;
DWORD colors[6];
};
int main(int argc, char* argv[]) {
sierpinski s; s.draw( 12 );
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Python. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 612;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class sierpinski {
public:
void draw( int o ) {
colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;
colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;
bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC();
drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );
bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL );
LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );
LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" );
}
private:
void drawTri( HDC dc, float l, float t, float r, float b, int i ) {
float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f;
if( i ) {
drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );
drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );
drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );
}
bmp.setPenColor( colors[i % 6] );
MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL );
LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) );
LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );
LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) );
}
myBitmap bmp;
DWORD colors[6];
};
int main(int argc, char* argv[]) {
sierpinski s; s.draw( 12 );
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 612;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class sierpinski {
public:
void draw( int o ) {
colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff;
colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff;
bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC();
drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 );
bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL );
LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 );
LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" );
}
private:
void drawTri( HDC dc, float l, float t, float r, float b, int i ) {
float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f;
if( i ) {
drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 );
drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 );
drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 );
}
bmp.setPenColor( colors[i % 6] );
MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL );
LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) );
LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) );
LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) );
}
myBitmap bmp;
DWORD colors[6];
};
int main(int argc, char* argv[]) {
sierpinski s; s.draw( 12 );
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Python. |
from itertools import accumulate, chain, takewhile
def primeSums():
return (
x for x in enumerate(
accumulate(
chain([(0, 0)], primes()),
lambda a, p: (p, p + a[1])
)
) if isPrime(x[1][1])
)
def main():
for x in takewhile(
lambda t: 1000 > t[1][0],
primeSums()
):
print(f'{x[0]} -> {x[1][1]}')
def isPrime(n):
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
def p(x):
return 0 == n % x or 0 == n % (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
def primes():
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
if __name__ == '__main__':
main()
| #include <iostream>
bool is_prime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
int i = 5;
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
if (n % i == 0) {
return false;
}
i += 4;
}
return true;
}
int main() {
const int start = 1;
const int stop = 1000;
int sum = 0;
int count = 0;
int sc = 0;
for (int p = start; p < stop; p++) {
if (is_prime(p)) {
count++;
sum += p;
if (is_prime(sum)) {
printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum);
sc++;
}
}
}
printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);
return 0;
}
|
Generate an equivalent C++ version of this Python code. |
from itertools import accumulate, chain, takewhile
def primeSums():
return (
x for x in enumerate(
accumulate(
chain([(0, 0)], primes()),
lambda a, p: (p, p + a[1])
)
) if isPrime(x[1][1])
)
def main():
for x in takewhile(
lambda t: 1000 > t[1][0],
primeSums()
):
print(f'{x[0]} -> {x[1][1]}')
def isPrime(n):
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
def p(x):
return 0 == n % x or 0 == n % (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
def primes():
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
if __name__ == '__main__':
main()
| #include <iostream>
bool is_prime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
int i = 5;
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
if (n % i == 0) {
return false;
}
i += 4;
}
return true;
}
int main() {
const int start = 1;
const int stop = 1000;
int sum = 0;
int count = 0;
int sc = 0;
for (int p = start; p < stop; p++) {
if (is_prime(p)) {
count++;
sum += p;
if (is_prime(sum)) {
printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum);
sc++;
}
}
}
printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);
return 0;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. |
from itertools import chain
def main():
print(
sorted(nub(concat([
[5, 1, 3, 8, 9, 4, 8, 7],
[3, 5, 9, 8, 4],
[1, 3, 7, 9]
])))
)
def concat(xs):
return list(chain(*xs))
def nub(xs):
return list(dict.fromkeys(xs))
if __name__ == '__main__':
main()
| #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
template<typename T>
std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {
std::set<T> resultset;
std::vector<T> result;
for (auto& list : ll)
for (auto& item : list)
resultset.insert(item);
for (auto& item : resultset)
result.push_back(item);
std::sort(result.begin(), result.end());
return result;
}
int main() {
std::vector<int> a = {5,1,3,8,9,4,8,7};
std::vector<int> b = {3,5,9,8,4};
std::vector<int> c = {1,3,7,9};
std::vector<std::vector<int>> nums = {a, b, c};
auto csl = common_sorted_list(nums);
for (auto n : csl) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Python to C++. |
from itertools import chain
def main():
print(
sorted(nub(concat([
[5, 1, 3, 8, 9, 4, 8, 7],
[3, 5, 9, 8, 4],
[1, 3, 7, 9]
])))
)
def concat(xs):
return list(chain(*xs))
def nub(xs):
return list(dict.fromkeys(xs))
if __name__ == '__main__':
main()
| #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
template<typename T>
std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {
std::set<T> resultset;
std::vector<T> result;
for (auto& list : ll)
for (auto& item : list)
resultset.insert(item);
for (auto& item : resultset)
result.push_back(item);
std::sort(result.begin(), result.end());
return result;
}
int main() {
std::vector<int> a = {5,1,3,8,9,4,8,7};
std::vector<int> b = {3,5,9,8,4};
std::vector<int> c = {1,3,7,9};
std::vector<std::vector<int>> nums = {a, b, c};
auto csl = common_sorted_list(nums);
for (auto n : csl) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
|
Write a version of this Python function in C++ with identical behavior. |
from itertools import chain
def main():
print(
sorted(nub(concat([
[5, 1, 3, 8, 9, 4, 8, 7],
[3, 5, 9, 8, 4],
[1, 3, 7, 9]
])))
)
def concat(xs):
return list(chain(*xs))
def nub(xs):
return list(dict.fromkeys(xs))
if __name__ == '__main__':
main()
| #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
template<typename T>
std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {
std::set<T> resultset;
std::vector<T> result;
for (auto& list : ll)
for (auto& item : list)
resultset.insert(item);
for (auto& item : resultset)
result.push_back(item);
std::sort(result.begin(), result.end());
return result;
}
int main() {
std::vector<int> a = {5,1,3,8,9,4,8,7};
std::vector<int> b = {3,5,9,8,4};
std::vector<int> c = {1,3,7,9};
std::vector<std::vector<int>> nums = {a, b, c};
auto csl = common_sorted_list(nums);
for (auto n : csl) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | def ncsub(seq, s=0):
if seq:
x = seq[:1]
xs = seq[1:]
p2 = s % 2
p1 = not p2
return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)
else:
return [[]] if s >= 3 else []
|
class N{
uint n,i,g,e,l;
public:
N(uint n): n(n-1),i{},g{},e(1),l(n-1){}
bool hasNext(){
g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i;
if (l==2) {l=--n; e=1; return true;}
if (e<((1<<(l-1))-1)) {++e; return true;}
e=1; --l; return (l>0);
}
uint next() {return g;}
};
|
Translate this program into C++ but keep the logic exactly as in Python. | from functools import wraps
from turtle import *
def memoize(obj):
cache = obj.cache = {}
@wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
@memoize
def fibonacci_word(n):
assert n > 0
if n == 1:
return "1"
if n == 2:
return "0"
return fibonacci_word(n - 1) + fibonacci_word(n - 2)
def draw_fractal(word, step):
for i, c in enumerate(word, 1):
forward(step)
if c == "0":
if i % 2 == 0:
left(90)
else:
right(90)
def main():
n = 25
step = 1
width = 1050
height = 1050
w = fibonacci_word(n)
setup(width=width, height=height)
speed(0)
setheading(90)
left(90)
penup()
forward(500)
right(90)
backward(500)
pendown()
tracer(10000)
hideturtle()
draw_fractal(w, step)
getscreen().getcanvas().postscript(file="fibonacci_word_fractal.eps")
exitonclick()
if __name__ == '__main__':
main()
| #include <windows.h>
#include <string>
using namespace std;
class myBitmap
{
public:
myBitmap() : pen( NULL ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
clear();
return true;
}
void clear()
{
ZeroMemory( pBits, width * height * sizeof( DWORD ) );
}
void setPenColor( DWORD clr )
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, 1, clr );
SelectObject( hdc, pen );
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD* dwpBits;
DWORD wb;
HANDLE file;
GetObject( bmp, sizeof( bitmap ), &bitmap );
dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() { return hdc; }
int getWidth() { return width; }
int getHeight() { return height; }
private:
HBITMAP bmp;
HDC hdc;
HPEN pen;
void *pBits;
int width, height;
};
class fiboFractal
{
public:
fiboFractal( int l )
{
bmp.create( 600, 440 );
bmp.setPenColor( 0x00ff00 );
createWord( l ); createFractal();
bmp.saveBitmap( "path_to_save_bitmap" );
}
private:
void createWord( int l )
{
string a = "1", b = "0", c;
l -= 2;
while( l-- )
{ c = b + a; a = b; b = c; }
fWord = c;
}
void createFractal()
{
int n = 1, px = 10, dir,
py = 420, len = 1,
x = 0, y = -len, goingTo = 0;
HDC dc = bmp.getDC();
MoveToEx( dc, px, py, NULL );
for( string::iterator si = fWord.begin(); si != fWord.end(); si++ )
{
px += x; py += y;
LineTo( dc, px, py );
if( !( *si - 48 ) )
{
if( n & 1 ) dir = 1;
else dir = 0;
switch( goingTo )
{
case 0:
y = 0;
if( dir ){ x = len; goingTo = 1; }
else { x = -len; goingTo = 3; }
break;
case 1:
x = 0;
if( dir ) { y = len; goingTo = 2; }
else { y = -len; goingTo = 0; }
break;
case 2:
y = 0;
if( dir ) { x = -len; goingTo = 3; }
else { x = len; goingTo = 1; }
break;
case 3:
x = 0;
if( dir ) { y = -len; goingTo = 0; }
else { y = len; goingTo = 2; }
}
}
n++;
}
}
string fWord;
myBitmap bmp;
};
int main( int argc, char* argv[] )
{
fiboFractal ff( 23 );
return system( "pause" );
}
|
Write a version of this Python function in C++ with identical behavior. | primes = [2, 3, 5, 7, 11, 13, 17, 19]
def count_twin_primes(limit: int) -> int:
global primes
if limit > primes[-1]:
ram_limit = primes[-1] + 90000000 - len(primes)
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1
while reasonable_limit < limit:
ram_limit = primes[-1] + 90000000 - len(primes)
if ram_limit > primes[-1]:
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit)
else:
reasonable_limit = min(limit, primes[-1] ** 2)
sieve = list({x for prime in primes for x in
range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)})
primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit]
count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y])
return count
def test(limit: int):
count = count_twin_primes(limit)
print(f"Number of twin prime pairs less than {limit} is {count}\n")
test(10)
test(100)
test(1000)
test(10000)
test(100000)
test(1000000)
test(10000000)
test(100000000)
| #include <cstdint>
#include <iostream>
#include <string>
#include <primesieve.hpp>
void print_twin_prime_count(long long limit) {
std::cout << "Number of twin prime pairs less than " << limit
<< " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n';
}
int main(int argc, char** argv) {
std::cout.imbue(std::locale(""));
if (argc > 1) {
for (int i = 1; i < argc; ++i) {
try {
print_twin_prime_count(std::stoll(argv[i]));
} catch (const std::exception& ex) {
std::cerr << "Cannot parse limit from '" << argv[i] << "'\n";
}
}
} else {
uint64_t limit = 10;
for (int power = 1; power < 12; ++power, limit *= 10)
print_twin_prime_count(limit);
}
return 0;
}
|
Translate the given Python code snippet into C++ without altering its behavior. | import random
class IDAStar:
def __init__(self, h, neighbours):
self.h = h
self.neighbours = neighbours
self.FOUND = object()
def solve(self, root, is_goal, max_cost=None):
self.is_goal = is_goal
self.path = [root]
self.is_in_path = {root}
self.path_descrs = []
self.nodes_evaluated = 0
bound = self.h(root)
while True:
t = self._search(0, bound)
if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated
if t is None: return None
bound = t
def _search(self, g, bound):
self.nodes_evaluated += 1
node = self.path[-1]
f = g + self.h(node)
if f > bound: return f
if self.is_goal(node): return self.FOUND
m = None
for cost, n, descr in self.neighbours(node):
if n in self.is_in_path: continue
self.path.append(n)
self.is_in_path.add(n)
self.path_descrs.append(descr)
t = self._search(g + cost, bound)
if t == self.FOUND: return self.FOUND
if m is None or (t is not None and t < m): m = t
self.path.pop()
self.path_descrs.pop()
self.is_in_path.remove(n)
return m
def slide_solved_state(n):
return tuple(i % (n*n) for i in range(1, n*n+1))
def slide_randomize(p, neighbours):
for _ in range(len(p) ** 2):
_, p, _ = random.choice(list(neighbours(p)))
return p
def slide_neighbours(n):
movelist = []
for gap in range(n*n):
x, y = gap % n, gap // n
moves = []
if x > 0: moves.append(-1)
if x < n-1: moves.append(+1)
if y > 0: moves.append(-n)
if y < n-1: moves.append(+n)
movelist.append(moves)
def neighbours(p):
gap = p.index(0)
l = list(p)
for m in movelist[gap]:
l[gap] = l[gap + m]
l[gap + m] = 0
yield (1, tuple(l), (l[gap], m))
l[gap + m] = l[gap]
l[gap] = 0
return neighbours
def slide_print(p):
n = int(round(len(p) ** 0.5))
l = len(str(n*n))
for i in range(0, len(p), n):
print(" ".join("{:>{}}".format(x, l) for x in p[i:i+n]))
def encode_cfg(cfg, n):
r = 0
b = n.bit_length()
for i in range(len(cfg)):
r |= cfg[i] << (b*i)
return r
def gen_wd_table(n):
goal = [[0] * i + [n] + [0] * (n - 1 - i) for i in range(n)]
goal[-1][-1] = n - 1
goal = tuple(sum(goal, []))
table = {}
to_visit = [(goal, 0, n-1)]
while to_visit:
cfg, cost, e = to_visit.pop(0)
enccfg = encode_cfg(cfg, n)
if enccfg in table: continue
table[enccfg] = cost
for d in [-1, 1]:
if 0 <= e + d < n:
for c in range(n):
if cfg[n*(e+d) + c] > 0:
ncfg = list(cfg)
ncfg[n*(e+d) + c] -= 1
ncfg[n*e + c] += 1
to_visit.append((tuple(ncfg), cost + 1, e+d))
return table
def slide_wd(n, goal):
wd = gen_wd_table(n)
goals = {i : goal.index(i) for i in goal}
b = n.bit_length()
def h(p):
ht = 0
vt = 0
d = 0
for i, c in enumerate(p):
if c == 0: continue
g = goals[c]
xi, yi = i % n, i // n
xg, yg = g % n, g // n
ht += 1 << (b*(n*yi+yg))
vt += 1 << (b*(n*xi+xg))
if yg == yi:
for k in range(i + 1, i - i%n + n):
if p[k] and goals[p[k]] // n == yi and goals[p[k]] < g:
d += 2
if xg == xi:
for k in range(i + n, n * n, n):
if p[k] and goals[p[k]] % n == xi and goals[p[k]] < g:
d += 2
d += wd[ht] + wd[vt]
return d
return h
if __name__ == "__main__":
solved_state = slide_solved_state(4)
neighbours = slide_neighbours(4)
is_goal = lambda p: p == solved_state
tests = [
(15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2),
]
slide_solver = IDAStar(slide_wd(4, solved_state), neighbours)
for p in tests:
path, moves, cost, num_eval = slide_solver.solve(p, is_goal, 80)
slide_print(p)
print(", ".join({-1: "Left", 1: "Right", -4: "Up", 4: "Down"}[move[1]] for move in moves))
print(cost, num_eval)
|
class fifteenSolver{
const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2};
int n{},_n{}, N0[100]{},N3[100]{},N4[100]{};
unsigned long N2[100]{};
const bool fY(){
if (N4[n]<_n) return fN();
if (N2[n]==0x123456789abcdef0) {std::cout<<"Solution found in "<<n<<" moves :"; for (int g{1};g<=n;++g) std::cout<<(char)N3[g]; std::cout<<std::endl; return true;};
if (N4[n]==_n) return fN(); else return false;
}
const bool fN(){
if (N3[n]!='u' && N0[n]/4<3){fI(); ++n; if (fY()) return true; --n;}
if (N3[n]!='d' && N0[n]/4>0){fG(); ++n; if (fY()) return true; --n;}
if (N3[n]!='l' && N0[n]%4<3){fE(); ++n; if (fY()) return true; --n;}
if (N3[n]!='r' && N0[n]%4>0){fL(); ++n; if (fY()) return true; --n;}
return false;
}
void fI(){
const int g = (11-N0[n])*4;
const unsigned long a = N2[n]&((unsigned long)15<<g);
N0[n+1]=N0[n]+4; N2[n+1]=N2[n]-a+(a<<16); N3[n+1]='d'; N4[n+1]=N4[n]+(Nr[a>>g]<=N0[n]/4?0:1);
}
void fG(){
const int g = (19-N0[n])*4;
const unsigned long a = N2[n]&((unsigned long)15<<g);
N0[n+1]=N0[n]-4; N2[n+1]=N2[n]-a+(a>>16); N3[n+1]='u'; N4[n+1]=N4[n]+(Nr[a>>g]>=N0[n]/4?0:1);
}
void fE(){
const int g = (14-N0[n])*4;
const unsigned long a = N2[n]&((unsigned long)15<<g);
N0[n+1]=N0[n]+1; N2[n+1]=N2[n]-a+(a<<4); N3[n+1]='r'; N4[n+1]=N4[n]+(Nc[a>>g]<=N0[n]%4?0:1);
}
void fL(){
const int g = (16-N0[n])*4;
const unsigned long a = N2[n]&((unsigned long)15<<g);
N0[n+1]=N0[n]-1; N2[n+1]=N2[n]-a+(a>>4); N3[n+1]='l'; N4[n+1]=N4[n]+(Nc[a>>g]>=N0[n]%4?0:1);
}
public:
fifteenSolver(int n, unsigned long g){N0[0]=n; N2[0]=g;}
void Solve(){for(;not fY();++_n);}
};
|
Produce a functionally identical C++ code for the snippet given in Python. | import cmath
class Complex(complex):
def __repr__(self):
rp = '%7.5f' % self.real if not self.pureImag() else ''
ip = '%7.5fj' % self.imag if not self.pureReal() else ''
conj = '' if (
self.pureImag() or self.pureReal() or self.imag < 0.0
) else '+'
return '0.0' if (
self.pureImag() and self.pureReal()
) else rp + conj + ip
def pureImag(self):
return abs(self.real) < 0.000005
def pureReal(self):
return abs(self.imag) < 0.000005
def croots(n):
if n <= 0:
return None
return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))
for nr in range(2, 11):
print(nr, list(croots(nr)))
| #include <complex>
#include <cmath>
#include <iostream>
double const pi = 4 * std::atan(1);
int main()
{
for (int n = 2; n <= 10; ++n)
{
std::cout << n << ": ";
for (int k = 0; k < n; ++k)
std::cout << std::polar(1, 2*pi*k/n) << " ";
std::cout << std::endl;
}
}
|
Produce a functionally identical C++ code for the snippet given in Python. |
print 2**64*2**64
| #include <iostream>
#include <sstream>
typedef long long bigInt;
using namespace std;
class number
{
public:
number() { s = "0"; neg = false; }
number( bigInt a ) { set( a ); }
number( string a ) { set( a ); }
void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }
void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }
number operator * ( const number& b ) { return this->mul( b ); }
number& operator *= ( const number& b ) { *this = *this * b; return *this; }
number& operator = ( const number& b ) { s = b.s; return *this; }
friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; }
friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }
private:
number mul( const number& b )
{
number a; bool neg = false;
string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );
int xx, ss, rr, t, c, stp = 0;
string::reverse_iterator xi = bs.rbegin(), si, ri;
for( ; xi != bs.rend(); xi++ )
{
c = 0; ri = r.rbegin() + stp;
for( si = s.rbegin(); si != s.rend(); si++ )
{
xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;
ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;
( *ri++ ) = t + 48;
}
if( c > 0 ) ( *ri ) = c + 48;
stp++;
}
trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;
if( t & 1 ) a.s = "-" + r;
else a.s = r;
return a;
}
void trimLeft( string& r )
{
if( r.length() < 2 ) return;
for( string::iterator x = r.begin(); x != ( r.end() - 1 ); )
{
if( ( *x ) != '0' ) return;
x = r.erase( x );
}
}
void clearStr()
{
for( string::iterator x = s.begin(); x != s.end(); )
{
if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );
else x++;
}
}
string s;
bool neg;
};
int main( int argc, char* argv[] )
{
number a, b;
a.set( "18446744073709551616" ); b.set( "18446744073709551616" );
cout << a * b << endl << endl;
cout << "Factor 1 = "; cin >> a;
cout << "Factor 2 = "; cin >> b;
cout << "Product: = " << a * b << endl << endl;
return system( "pause" );
}
|
Convert this Python block to C++, preserving its control flow and logic. | import math
def solvePell(n):
x = int(math.sqrt(n))
y, z, r = x, 1, x << 1
e1, e2 = 1, 0
f1, f2 = 0, 1
while True:
y = r * z - y
z = (n - y * y) // z
r = (x + y) // z
e1, e2 = e2, e1 + e2 * r
f1, f2 = f2, f1 + f2 * r
a, b = f2 * x + e2, f2
if a * a - n * b * b == 1:
return a, b
for n in [61, 109, 181, 277]:
x, y = solvePell(n)
print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))
| #include <iomanip>
#include <iostream>
#include <tuple>
std::tuple<uint64_t, uint64_t> solvePell(int n) {
int x = (int)sqrt(n);
if (x * x == n) {
return std::make_pair(1, 0);
}
int y = x;
int z = 1;
int r = 2 * x;
std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0);
std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1);
uint64_t a = 0;
uint64_t b = 0;
while (true) {
y = r * z - y;
z = (n - y * y) / z;
r = (x + y) / z;
e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e));
f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f));
a = std::get<1>(e) + x * std::get<1>(f);
b = std::get<1>(f);
if (a * a - n * b * b == 1) {
break;
}
}
return std::make_pair(a, b);
}
void test(int n) {
auto r = solvePell(n);
std::cout << "x^2 - " << std::setw(3) << n << " * y^2 = 1 for x = " << std::setw(21) << std::get<0>(r) << " and y = " << std::setw(21) << std::get<1>(r) << '\n';
}
int main() {
test(61);
test(109);
test(181);
test(277);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. |
import random
digits = '123456789'
size = 4
chosen = ''.join(random.sample(digits,size))
print % (size, size)
guesses = 0
while True:
guesses += 1
while True:
guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
if len(guess) == size and \
all(char in digits for char in guess) \
and len(set(guess)) == size:
break
print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size
if guess == chosen:
print '\nCongratulations you guessed correctly in',guesses,'attempts'
break
bulls = cows = 0
for i in range(size):
if guess[i] == chosen[i]:
bulls += 1
elif guess[i] in chosen:
cows += 1
print ' %i Bulls\n %i Cows' % (bulls, cows)
| #include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
bool contains_duplicates(std::string s)
{
std::sort(s.begin(), s.end());
return std::adjacent_find(s.begin(), s.end()) != s.end();
}
void game()
{
typedef std::string::size_type index;
std::string symbols = "0123456789";
unsigned int const selection_length = 4;
std::random_shuffle(symbols.begin(), symbols.end());
std::string selection = symbols.substr(0, selection_length);
std::string guess;
while (std::cout << "Your guess? ", std::getline(std::cin, guess))
{
if (guess.length() != selection_length
|| guess.find_first_not_of(symbols) != std::string::npos
|| contains_duplicates(guess))
{
std::cout << guess << " is not a valid guess!";
continue;
}
unsigned int bulls = 0;
unsigned int cows = 0;
for (index i = 0; i != selection_length; ++i)
{
index pos = selection.find(guess[i]);
if (pos == i)
++bulls;
else if (pos != std::string::npos)
++cows;
}
std::cout << bulls << " bulls, " << cows << " cows.\n";
if (bulls == selection_length)
{
std::cout << "Congratulations! You have won!\n";
return;
}
}
std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n";
std::exit(EXIT_FAILURE);
}
int main()
{
std::cout << "Welcome to bulls and cows!\nDo you want to play? ";
std::string answer;
while (true)
{
while (true)
{
if (!std::getline(std::cin, answer))
{
std::cout << "I can't get an answer. Exiting.\n";
return EXIT_FAILURE;
}
if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y")
break;
if (answer == "no" || answer == "No" || answer == "n" || answer == "N")
{
std::cout << "Ok. Goodbye.\n";
return EXIT_SUCCESS;
}
std::cout << "Please answer yes or no: ";
}
game();
std::cout << "Another game? ";
}
}
|
Write the same algorithm in C++ as shown in this Python implementation. | def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return seq
if __name__ == "__main__":
from random import shuffle
testset = [_ for _ in range(100)]
testcase = testset.copy()
shuffle(testcase)
assert testcase != testset
bubble_sort(testcase)
assert testcase == testset
| #include <algorithm>
#include <iostream>
#include <iterator>
template <typename RandomAccessIterator>
void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {
bool swapped = true;
while (begin != end-- && swapped) {
swapped = false;
for (auto i = begin; i != end; ++i) {
if (*(i + 1) < *i) {
std::iter_swap(i, i + 1);
swapped = true;
}
}
}
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
bubble_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
|
Maintain the same structure and functionality when rewriting this code in C++. | def product_of_divisors(n):
assert(isinstance(n, int) and 0 < n)
ans = i = j = 1
while i*i <= n:
if 0 == n%i:
ans *= i
j = n//i
if j != i:
ans *= j
i += 1
return ans
if __name__ == "__main__":
print([product_of_divisors(n) for n in range(1,51)])
| #include <cmath>
#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;
}
unsigned int divisor_product(unsigned int n) {
return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));
}
int main() {
const unsigned int limit = 50;
std::cout << "Product of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(11) << divisor_product(n);
if (n % 5 == 0)
std::cout << '\n';
}
}
|
Convert this Python block to C++, preserving its control flow and logic. | def product_of_divisors(n):
assert(isinstance(n, int) and 0 < n)
ans = i = j = 1
while i*i <= n:
if 0 == n%i:
ans *= i
j = n//i
if j != i:
ans *= j
i += 1
return ans
if __name__ == "__main__":
print([product_of_divisors(n) for n in range(1,51)])
| #include <cmath>
#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;
}
unsigned int divisor_product(unsigned int n) {
return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0));
}
int main() {
const unsigned int limit = 50;
std::cout << "Product of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(11) << divisor_product(n);
if (n % 5 == 0)
std::cout << '\n';
}
}
|
Produce a functionally identical C++ code for the snippet given in Python. | import shutil
shutil.copyfile('input.txt', 'output.txt')
| #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream input ( "input.txt" );
ofstream output ("output.txt");
if (output.is_open()) {
if (input.is_open()){
while (getline (input,line)) {
output << line << endl;
}
input.close();
}
else {
cout << "input.txt cannot be opened!\n";
}
output.close();
}
else {
cout << "output.txt cannot be written to!\n";
}
return 0;
}
|
Please provide an equivalent version of this Python code in C++. | x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y)
print "Remainder: %d" % (x % y)
print "Quotient: %d with Remainder: %d" % divmod(x, y)
print "Power: %d" % x**y
raw_input( )
| #include <iostream>
int main()
{
int a, b;
std::cin >> a >> b;
std::cout << "a+b = " << a+b << "\n";
std::cout << "a-b = " << a-b << "\n";
std::cout << "a*b = " << a*b << "\n";
std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n";
return 0;
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m))
| #include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
int main()
{
using namespace boost::numeric::ublas;
matrix<double> m(3,3);
for(int i=0; i!=m.size1(); ++i)
for(int j=0; j!=m.size2(); ++j)
m(i,j)=3*i+j;
std::cout << trans(m) << std::endl;
}
|
Generate an equivalent C++ version of this Python code. |
import sys
sys.setrecursionlimit(1025)
def a(in_k, x1, x2, x3, x4, x5):
k = [in_k]
def b():
k[0] -= 1
return a(k[0], b, x1, x2, x3, x4)
return x4() + x5() if k[0] <= 0 else b()
x = lambda i: lambda: i
print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
| #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Python. | >>> def a(answer):
print("
return answer
>>> def b(answer):
print("
return answer
>>> for i in (False, True):
for j in (False, True):
print ("\nCalculating: x = a(i) and b(j)")
x = a(i) and b(j)
print ("Calculating: y = a(i) or b(j)")
y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
| #include <iostream>
bool a(bool in)
{
std::cout << "a" << std::endl;
return in;
}
bool b(bool in)
{
std::cout << "b" << std::endl;
return in;
}
void test(bool i, bool j) {
std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl;
std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl;
}
int main()
{
test(false, false);
test(false, true);
test(true, false);
test(true, true);
return 0;
}
|
Write the same code in C++ as shown below in Python. | import sys
print(sys.getrecursionlimit())
| #include <iostream>
void recurse(unsigned int i)
{
std::cout<<i<<"\n";
recurse(i+1);
}
int main()
{
recurse(0);
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | import sys
print(sys.getrecursionlimit())
| #include <iostream>
void recurse(unsigned int i)
{
std::cout<<i<<"\n";
recurse(i+1);
}
int main()
{
recurse(0);
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | import sys
print(sys.getrecursionlimit())
| #include <iostream>
void recurse(unsigned int i)
{
std::cout<<i<<"\n";
recurse(i+1);
}
int main()
{
recurse(0);
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | class Isprime():
multiples = {2}
primes = [2]
nmax = 2
def __init__(self, nmax):
if nmax > self.nmax:
self.check(nmax)
def check(self, n):
if type(n) == float:
if not n.is_integer(): return False
n = int(n)
multiples = self.multiples
if n <= self.nmax:
return n not in multiples
else:
primes, nmax = self.primes, self.nmax
newmax = max(nmax*2, n)
for p in primes:
multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))
for i in range(nmax+1, newmax+1):
if i not in multiples:
primes.append(i)
multiples.update(range(i*2, newmax+1, i))
self.nmax = newmax
return n not in multiples
__call__ = check
def carmichael(p1):
ans = []
if isprime(p1):
for h3 in range(2, p1):
g = h3 + p1
for d in range(1, g):
if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:
p2 = 1 + ((p1 - 1)* g // d)
if isprime(p2):
p3 = 1 + (p1 * p2 // h3)
if isprime(p3):
if (p2 * p3) % (p1 - 1) == 1:
ans += [tuple(sorted((p1, p2, p3)))]
return ans
isprime = Isprime(2)
ans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))
print(',\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))
| #include <iomanip>
#include <iostream>
int mod(int n, int d) {
return (d + n % d) % d;
}
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
void print_carmichael_numbers(int prime1) {
for (int h3 = 1; h3 < prime1; ++h3) {
for (int d = 1; d < h3 + prime1; ++d) {
if (mod((h3 + prime1) * (prime1 - 1), d) != 0
|| mod(-prime1 * prime1, h3) != mod(d, h3))
continue;
int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;
if (!is_prime(prime2))
continue;
int prime3 = 1 + prime1 * prime2/h3;
if (!is_prime(prime3))
continue;
if (mod(prime2 * prime3, prime1 - 1) != 1)
continue;
unsigned int c = prime1 * prime2 * prime3;
std::cout << std::setw(2) << prime1 << " x "
<< std::setw(4) << prime2 << " x "
<< std::setw(5) << prime3 << " = "
<< std::setw(10) << c << '\n';
}
}
}
int main() {
for (int p = 2; p <= 61; ++p) {
if (is_prime(p))
print_carmichael_numbers(p);
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | black = color(0)
white = color(255)
def setup():
size(320, 240)
def draw():
loadPixels()
for i in range(len(pixels)):
if random(1) < 0.5:
pixels[i] = black
else:
pixels[i] = white
updatePixels()
fill(0, 128)
rect(0, 0, 60, 20)
fill(255)
text(frameRate, 5, 15)
| #include <windows.h>
#include <sstream>
#include <tchar.h>
using namespace std;
const unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0;
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) { clr = c; createPen(); }
void setPenWidth( int w ) { wid = w; createPen(); }
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
void* getBits( void ) const { return pBits; }
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen()
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void* pBits;
int width, height, wid;
DWORD clr;
};
class bmpNoise
{
public:
bmpNoise()
{
QueryPerformanceFrequency( &_frequency );
_bmp.create( BMP_WID, BMP_HEI );
_frameTime = _fps = 0; _start = getTime(); _frames = 0;
}
void mainLoop()
{
float now = getTime();
if( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; }
HDC wdc, dc = _bmp.getDC();
unsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() );
for( int y = 0; y < BMP_HEI; y++ )
{
for( int x = 0; x < BMP_WID; x++ )
{
if( rand() % 10 < 5 ) memset( bits, 255, 3 );
else memset( bits, 0, 3 );
bits++;
}
}
ostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() );
wdc = GetDC( _hwnd );
BitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY );
ReleaseDC( _hwnd, wdc );
_frames++; _frameTime = getTime() - now;
if( _frameTime > 1.0f ) _frameTime = 1.0f;
}
void setHWND( HWND hwnd ) { _hwnd = hwnd; }
private:
float getTime()
{
LARGE_INTEGER liTime; QueryPerformanceCounter( &liTime );
return liTime.QuadPart / ( float )_frequency.QuadPart;
}
myBitmap _bmp;
HWND _hwnd;
float _start, _fps, _frameTime;
unsigned int _frames;
LARGE_INTEGER _frequency;
};
class wnd
{
public:
wnd() { _inst = this; }
int wnd::Run( HINSTANCE hInst )
{
_hInst = hInst; _hwnd = InitAll();
_noise.setHWND( _hwnd );
ShowWindow( _hwnd, SW_SHOW );
UpdateWindow( _hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
{
_noise.mainLoop();
}
}
return UnregisterClass( "_MY_NOISE_", _hInst );
}
private:
static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY: PostQuitMessage( 0 ); break;
default:
return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
HWND InitAll()
{
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ( WNDPROC )WndProc;
wcex.hInstance = _hInst;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_MY_NOISE_";
RegisterClassEx( &wcex );
RECT rc = { 0, 0, BMP_WID, BMP_HEI };
AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );
int w = rc.right - rc.left, h = rc.bottom - rc.top;
return CreateWindow( "_MY_NOISE_", ".: Noise image -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );
}
static wnd* _inst;
HINSTANCE _hInst;
HWND _hwnd;
bmpNoise _noise;
};
wnd* wnd::_inst = 0;
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
srand( GetTickCount() ); wnd myWnd;
return myWnd.Run( hInstance );
}
|
Convert this Python block to C++, preserving its control flow and logic. |
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
| #include <conio.h>
#include <iostream>
using namespace std;
int main()
{
char ch;
_cputs( "Yes or no?" );
do
{
ch = _getch();
ch = toupper( ch );
} while(ch!='Y'&&ch!='N');
if(ch=='N')
{
cout << "You said no" << endl;
}
else
{
cout << "You said yes" << endl;
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. |
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
| #include <conio.h>
#include <iostream>
using namespace std;
int main()
{
char ch;
_cputs( "Yes or no?" );
do
{
ch = _getch();
ch = toupper( ch );
} while(ch!='Y'&&ch!='N');
if(ch=='N')
{
cout << "You said no" << endl;
}
else
{
cout << "You said yes" << endl;
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | def perf1(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
| #include <iostream>
using namespace std ;
int divisor_sum( int number ) {
int sum = 0 ;
for ( int i = 1 ; i < number ; i++ )
if ( number % i == 0 )
sum += i ;
return sum;
}
int main( ) {
cout << "Perfect numbers from 1 to 33550337:\n" ;
for ( int num = 1 ; num < 33550337 ; num++ ) {
if (divisor_sum(num) == num)
cout << num << '\n' ;
}
return 0 ;
}
|
Convert this Python snippet to C++ and keep its semantics consistent. | def perf1(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
| #include <iostream>
using namespace std ;
int divisor_sum( int number ) {
int sum = 0 ;
for ( int i = 1 ; i < number ; i++ )
if ( number % i == 0 )
sum += i ;
return sum;
}
int main( ) {
cout << "Perfect numbers from 1 to 33550337:\n" ;
for ( int num = 1 ; num < 33550337 ; num++ ) {
if (divisor_sum(num) == num)
cout << num << '\n' ;
}
return 0 ;
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | def conjugate_transpose(m):
return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))
def mmul( ma, mb):
return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)
def mi(size):
'Complex Identity matrix'
sz = range(size)
m = [[0 + 0j for i in sz] for j in sz]
for i in range(size):
m[i][i] = 1 + 0j
return tuple(tuple(row) for row in m)
def __allsame(vector):
first, rest = vector[0], vector[1:]
return all(i == first for i in rest)
def __allnearsame(vector, eps=1e-14):
first, rest = vector[0], vector[1:]
return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps
for i in rest)
def isequal(matrices, eps=1e-14):
'Check any number of matrices for equality within eps'
x = [len(m) for m in matrices]
if not __allsame(x): return False
y = [len(m[0]) for m in matrices]
if not __allsame(y): return False
for s in range(x[0]):
for t in range(y[0]):
if not __allnearsame([m[s][t] for m in matrices], eps): return False
return True
def ishermitian(m, ct):
return isequal([m, ct])
def isnormal(m, ct):
return isequal([mmul(m, ct), mmul(ct, m)])
def isunitary(m, ct):
mct, ctm = mmul(m, ct), mmul(ct, m)
mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])
ident = mi(mctx)
return isequal([mct, ctm, ident])
def printm(comment, m):
print(comment)
fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]
width = max(max(len(f) for f in row) for row in fields)
lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)
print('\n'.join(lines))
if __name__ == '__main__':
for matrix in [
((( 3.000+0.000j), (+2.000+1.000j)),
(( 2.000-1.000j), (+1.000+0.000j))),
((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)),
(( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)),
(( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),
((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)),
(( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)),
(( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:
printm('\nMatrix:', matrix)
ct = conjugate_transpose(matrix)
printm('Its conjugate transpose:', ct)
print('Hermitian? %s.' % ishermitian(matrix, ct))
print('Normal? %s.' % isnormal(matrix, ct))
print('Unitary? %s.' % isunitary(matrix, ct))
| #include <cassert>
#include <cmath>
#include <complex>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
template <typename scalar_type> class complex_matrix {
public:
using element_type = std::complex<scalar_type>;
complex_matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
complex_matrix(size_t rows, size_t columns, element_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
complex_matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<element_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const element_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
element_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
friend bool operator==(const complex_matrix& a, const complex_matrix& b) {
return a.rows_ == b.rows_ && a.columns_ == b.columns_ &&
a.elements_ == b.elements_;
}
private:
size_t rows_;
size_t columns_;
std::vector<element_type> elements_;
};
template <typename scalar_type>
complex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a,
const complex_matrix<scalar_type>& b) {
assert(a.columns() == b.rows());
size_t arows = a.rows();
size_t bcolumns = b.columns();
size_t n = a.columns();
complex_matrix<scalar_type> c(arows, bcolumns);
for (size_t i = 0; i < arows; ++i) {
for (size_t j = 0; j < n; ++j) {
for (size_t k = 0; k < bcolumns; ++k)
c(i, k) += a(i, j) * b(j, k);
}
}
return c;
}
template <typename scalar_type>
complex_matrix<scalar_type>
conjugate_transpose(const complex_matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
complex_matrix<scalar_type> b(columns, rows);
for (size_t i = 0; i < columns; i++) {
for (size_t j = 0; j < rows; j++) {
b(i, j) = std::conj(a(j, i));
}
}
return b;
}
template <typename scalar_type>
std::string to_string(const std::complex<scalar_type>& c) {
std::ostringstream out;
const int precision = 6;
out << std::fixed << std::setprecision(precision);
out << std::setw(precision + 3) << c.real();
if (c.imag() > 0)
out << " + " << std::setw(precision + 2) << c.imag() << 'i';
else if (c.imag() == 0)
out << " + " << std::setw(precision + 2) << 0.0 << 'i';
else
out << " - " << std::setw(precision + 2) << -c.imag() << 'i';
return out.str();
}
template <typename scalar_type>
void print(std::ostream& out, const complex_matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << to_string(a(row, column));
}
out << '\n';
}
}
template <typename scalar_type>
bool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
return matrix == conjugate_transpose(matrix);
}
template <typename scalar_type>
bool is_normal_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
auto c = conjugate_transpose(matrix);
return product(c, matrix) == product(matrix, c);
}
bool is_equal(const std::complex<double>& a, double b) {
constexpr double e = 1e-15;
return std::abs(a.imag()) < e && std::abs(a.real() - b) < e;
}
template <typename scalar_type>
bool is_identity_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
size_t rows = matrix.rows();
for (size_t i = 0; i < rows; ++i) {
for (size_t j = 0; j < rows; ++j) {
if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0)))
return false;
}
}
return true;
}
template <typename scalar_type>
bool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) {
if (matrix.rows() != matrix.columns())
return false;
auto c = conjugate_transpose(matrix);
auto p = product(c, matrix);
return is_identity_matrix(p) && p == product(matrix, c);
}
template <typename scalar_type>
void test(const complex_matrix<scalar_type>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Conjugate transpose:\n";
print(std::cout, conjugate_transpose(matrix));
std::cout << std::boolalpha;
std::cout << "Hermitian: " << is_hermitian_matrix(matrix) << '\n';
std::cout << "Normal: " << is_normal_matrix(matrix) << '\n';
std::cout << "Unitary: " << is_unitary_matrix(matrix) << '\n';
}
int main() {
using matrix = complex_matrix<double>;
matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}},
{{2, -1}, {3, 0}, {0, 1}},
{{4, 0}, {0, -1}, {1, 0}}});
double n = std::sqrt(0.5);
matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}},
{{0, -n}, {0, n}, {0, 0}},
{{0, 0}, {0, 0}, {0, 1}}});
matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}},
{{2, -1}, {4, 1}, {0, 0}},
{{7, -5}, {1, -4}, {1, 0}}});
test(matrix1);
std::cout << '\n';
test(matrix2);
std::cout << '\n';
test(matrix3);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.