Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same algorithm in C++ as shown in this Python implementation. | 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;
}
|
Convert this Python snippet to C++ and keep its semantics consistent. |
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2,n)+pow(-1,n))
def jacobsthal_oblong(n):
return jacobsthal(n)*jacobsthal(n+1)
if __name__ == '__main__':
print("First 30 Jacobsthal numbers:")
for j in range(0, 30):
print(jacobsthal(j), end=" ")
print("\n\nFirst 30 Jacobsthal-Lucas numbers: ")
for j in range(0, 30):
print(jacobsthal_lucas(j), end = '\t')
print("\n\nFirst 20 Jacobsthal oblong numbers: ")
for j in range(0, 20):
print(jacobsthal_oblong(j), end=" ")
print("\n\nFirst 10 Jacobsthal primes: ")
for j in range(3, 33):
if isPrime(jacobsthal(j)):
print(jacobsthal(j))
| #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas_number(unsigned int n) {
return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);
}
big_int jacobsthal_oblong_number(unsigned int n) {
return jacobsthal_number(n) * jacobsthal_number(n + 1);
}
int main() {
std::cout << "First 30 Jacobsthal Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_lucas_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n";
for (unsigned int n = 0; n < 20; ++n) {
std::cout << std::setw(11) << jacobsthal_oblong_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal primes:\n";
for (unsigned int n = 0, count = 0; count < 20; ++n) {
auto jn = jacobsthal_number(n);
if (is_probably_prime(jn)) {
++count;
std::cout << jn << '\n';
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to C++. |
from math import floor, pow
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def odd(n):
return n and 1 != 0
def jacobsthal(n):
return floor((pow(2,n)+odd(n))/3)
def jacobsthal_lucas(n):
return int(pow(2,n)+pow(-1,n))
def jacobsthal_oblong(n):
return jacobsthal(n)*jacobsthal(n+1)
if __name__ == '__main__':
print("First 30 Jacobsthal numbers:")
for j in range(0, 30):
print(jacobsthal(j), end=" ")
print("\n\nFirst 30 Jacobsthal-Lucas numbers: ")
for j in range(0, 30):
print(jacobsthal_lucas(j), end = '\t')
print("\n\nFirst 20 Jacobsthal oblong numbers: ")
for j in range(0, 20):
print(jacobsthal_oblong(j), end=" ")
print("\n\nFirst 10 Jacobsthal primes: ")
for j in range(3, 33):
if isPrime(jacobsthal(j)):
print(jacobsthal(j))
| #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas_number(unsigned int n) {
return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);
}
big_int jacobsthal_oblong_number(unsigned int n) {
return jacobsthal_number(n) * jacobsthal_number(n + 1);
}
int main() {
std::cout << "First 30 Jacobsthal Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_lucas_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n";
for (unsigned int n = 0; n < 20; ++n) {
std::cout << std::setw(11) << jacobsthal_oblong_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal primes:\n";
for (unsigned int n = 0, count = 0; count < 20; ++n) {
auto jn = jacobsthal_number(n);
if (is_probably_prime(jn)) {
++count;
std::cout << jn << '\n';
}
}
}
|
Preserve the algorithm and functionality while converting the code from Python to C++. |
from itertools import zip_longest
def beadsort(l):
return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))
print(beadsort([5,3,1,7,4,1,1]))
|
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
void distribute(int dist, vector<int> &List) {
if (dist > List.size() )
List.resize(dist);
for (int i=0; i < dist; i++)
List[i]++;
}
vector<int> beadSort(int *myints, int n) {
vector<int> list, list2, fifth (myints, myints + n);
cout << "#1 Beads falling down: ";
for (int i=0; i < fifth.size(); i++)
distribute (fifth[i], list);
cout << '\n';
cout << "\nBeads on their sides: ";
for (int i=0; i < list.size(); i++)
cout << " " << list[i];
cout << '\n';
cout << "#2 Beads right side up: ";
for (int i=0; i < list.size(); i++)
distribute (list[i], list2);
cout << '\n';
return list2;
}
int main() {
int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};
vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));
cout << "Sorted list/array: ";
for(unsigned int i=0; i<sorted.size(); i++)
cout << sorted[i] << ' ';
}
|
Ensure the translated C++ code behaves exactly like the original Python snippet. |
def _init():
"digit sections for forming numbers"
digi_bits = .strip()
lines = [[d.replace('.', ' ') for d in ln.strip().split()]
for ln in digi_bits.strip().split('\n')
if '
formats = '<2 >2 <2 >2'.split()
digits = [[f"{dig:{f}}" for dig in line]
for f, line in zip(formats, lines)]
return digits
_digits = _init()
def _to_digits(n):
assert 0 <= n < 10_000 and int(n) == n
return [int(digit) for digit in f"{int(n):04}"][::-1]
def num_to_lines(n):
global _digits
d = _to_digits(n)
lines = [
''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])),
''.join((_digits[0][ 0], '┃', _digits[0][ 0])),
''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])),
]
return lines
def cjoin(c1, c2, spaces=' '):
return [spaces.join(by_row) for by_row in zip(c1, c2)]
if __name__ == '__main__':
for pow10 in range(4):
step = 10 ** pow10
print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n')
lines = num_to_lines(step)
for n in range(step*2, step*10, step):
lines = cjoin(lines, num_to_lines(n))
print('\n'.join(lines))
numbers = [0, 5555, 6789, 6666]
print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n')
lines = num_to_lines(numbers[0])
for n in numbers[1:]:
lines = cjoin(lines, num_to_lines(n))
print('\n'.join(lines))
| #include <array>
#include <iostream>
template<typename T, size_t S>
using FixedSquareGrid = std::array<std::array<T, S>, S>;
struct Cistercian {
public:
Cistercian() {
initN();
}
Cistercian(int v) {
initN();
draw(v);
}
Cistercian &operator=(int v) {
initN();
draw(v);
}
friend std::ostream &operator<<(std::ostream &, const Cistercian &);
private:
FixedSquareGrid<char, 15> canvas;
void initN() {
for (auto &row : canvas) {
row.fill(' ');
row[5] = 'x';
}
}
void horizontal(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
void vertical(size_t r1, size_t r2, size_t c) {
for (size_t r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
void diagd(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
void diagu(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
void drawOnes(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawOnes(1);
drawOnes(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawOnes(1);
drawOnes(6);
break;
case 8:
drawOnes(2);
drawOnes(6);
break;
case 9:
drawOnes(1);
drawOnes(8);
break;
default:
break;
}
}
void drawTens(int v) {
switch (v) {
case 1:
horizontal(0, 4, 0);
break;
case 2:
horizontal(0, 4, 4);
break;
case 3:
diagu(0, 4, 4);
break;
case 4:
diagd(0, 4, 0);
break;
case 5:
drawTens(1);
drawTens(4);
break;
case 6:
vertical(0, 4, 0);
break;
case 7:
drawTens(1);
drawTens(6);
break;
case 8:
drawTens(2);
drawTens(6);
break;
case 9:
drawTens(1);
drawTens(8);
break;
default:
break;
}
}
void drawHundreds(int hundreds) {
switch (hundreds) {
case 1:
horizontal(6, 10, 14);
break;
case 2:
horizontal(6, 10, 10);
break;
case 3:
diagu(6, 10, 14);
break;
case 4:
diagd(6, 10, 10);
break;
case 5:
drawHundreds(1);
drawHundreds(4);
break;
case 6:
vertical(10, 14, 10);
break;
case 7:
drawHundreds(1);
drawHundreds(6);
break;
case 8:
drawHundreds(2);
drawHundreds(6);
break;
case 9:
drawHundreds(1);
drawHundreds(8);
break;
default:
break;
}
}
void drawThousands(int thousands) {
switch (thousands) {
case 1:
horizontal(0, 4, 14);
break;
case 2:
horizontal(0, 4, 10);
break;
case 3:
diagd(0, 4, 10);
break;
case 4:
diagu(0, 4, 14);
break;
case 5:
drawThousands(1);
drawThousands(4);
break;
case 6:
vertical(10, 14, 0);
break;
case 7:
drawThousands(1);
drawThousands(6);
break;
case 8:
drawThousands(2);
drawThousands(6);
break;
case 9:
drawThousands(1);
drawThousands(8);
break;
default:
break;
}
}
void draw(int v) {
int thousands = v / 1000;
v %= 1000;
int hundreds = v / 100;
v %= 100;
int tens = v / 10;
int ones = v % 10;
if (thousands > 0) {
drawThousands(thousands);
}
if (hundreds > 0) {
drawHundreds(hundreds);
}
if (tens > 0) {
drawTens(tens);
}
if (ones > 0) {
drawOnes(ones);
}
}
};
std::ostream &operator<<(std::ostream &os, const Cistercian &c) {
for (auto &row : c.canvas) {
for (auto cell : row) {
os << cell;
}
os << '\n';
}
return os;
}
int main() {
for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {
std::cout << number << ":\n";
Cistercian c(number);
std::cout << c << '\n';
}
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Python. |
def _init():
"digit sections for forming numbers"
digi_bits = .strip()
lines = [[d.replace('.', ' ') for d in ln.strip().split()]
for ln in digi_bits.strip().split('\n')
if '
formats = '<2 >2 <2 >2'.split()
digits = [[f"{dig:{f}}" for dig in line]
for f, line in zip(formats, lines)]
return digits
_digits = _init()
def _to_digits(n):
assert 0 <= n < 10_000 and int(n) == n
return [int(digit) for digit in f"{int(n):04}"][::-1]
def num_to_lines(n):
global _digits
d = _to_digits(n)
lines = [
''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])),
''.join((_digits[0][ 0], '┃', _digits[0][ 0])),
''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])),
]
return lines
def cjoin(c1, c2, spaces=' '):
return [spaces.join(by_row) for by_row in zip(c1, c2)]
if __name__ == '__main__':
for pow10 in range(4):
step = 10 ** pow10
print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n')
lines = num_to_lines(step)
for n in range(step*2, step*10, step):
lines = cjoin(lines, num_to_lines(n))
print('\n'.join(lines))
numbers = [0, 5555, 6789, 6666]
print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n')
lines = num_to_lines(numbers[0])
for n in numbers[1:]:
lines = cjoin(lines, num_to_lines(n))
print('\n'.join(lines))
| #include <array>
#include <iostream>
template<typename T, size_t S>
using FixedSquareGrid = std::array<std::array<T, S>, S>;
struct Cistercian {
public:
Cistercian() {
initN();
}
Cistercian(int v) {
initN();
draw(v);
}
Cistercian &operator=(int v) {
initN();
draw(v);
}
friend std::ostream &operator<<(std::ostream &, const Cistercian &);
private:
FixedSquareGrid<char, 15> canvas;
void initN() {
for (auto &row : canvas) {
row.fill(' ');
row[5] = 'x';
}
}
void horizontal(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
void vertical(size_t r1, size_t r2, size_t c) {
for (size_t r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
void diagd(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
void diagu(size_t c1, size_t c2, size_t r) {
for (size_t c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
void drawOnes(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawOnes(1);
drawOnes(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawOnes(1);
drawOnes(6);
break;
case 8:
drawOnes(2);
drawOnes(6);
break;
case 9:
drawOnes(1);
drawOnes(8);
break;
default:
break;
}
}
void drawTens(int v) {
switch (v) {
case 1:
horizontal(0, 4, 0);
break;
case 2:
horizontal(0, 4, 4);
break;
case 3:
diagu(0, 4, 4);
break;
case 4:
diagd(0, 4, 0);
break;
case 5:
drawTens(1);
drawTens(4);
break;
case 6:
vertical(0, 4, 0);
break;
case 7:
drawTens(1);
drawTens(6);
break;
case 8:
drawTens(2);
drawTens(6);
break;
case 9:
drawTens(1);
drawTens(8);
break;
default:
break;
}
}
void drawHundreds(int hundreds) {
switch (hundreds) {
case 1:
horizontal(6, 10, 14);
break;
case 2:
horizontal(6, 10, 10);
break;
case 3:
diagu(6, 10, 14);
break;
case 4:
diagd(6, 10, 10);
break;
case 5:
drawHundreds(1);
drawHundreds(4);
break;
case 6:
vertical(10, 14, 10);
break;
case 7:
drawHundreds(1);
drawHundreds(6);
break;
case 8:
drawHundreds(2);
drawHundreds(6);
break;
case 9:
drawHundreds(1);
drawHundreds(8);
break;
default:
break;
}
}
void drawThousands(int thousands) {
switch (thousands) {
case 1:
horizontal(0, 4, 14);
break;
case 2:
horizontal(0, 4, 10);
break;
case 3:
diagd(0, 4, 10);
break;
case 4:
diagu(0, 4, 14);
break;
case 5:
drawThousands(1);
drawThousands(4);
break;
case 6:
vertical(10, 14, 0);
break;
case 7:
drawThousands(1);
drawThousands(6);
break;
case 8:
drawThousands(2);
drawThousands(6);
break;
case 9:
drawThousands(1);
drawThousands(8);
break;
default:
break;
}
}
void draw(int v) {
int thousands = v / 1000;
v %= 1000;
int hundreds = v / 100;
v %= 100;
int tens = v / 10;
int ones = v % 10;
if (thousands > 0) {
drawThousands(thousands);
}
if (hundreds > 0) {
drawHundreds(hundreds);
}
if (tens > 0) {
drawTens(tens);
}
if (ones > 0) {
drawOnes(ones);
}
}
};
std::ostream &operator<<(std::ostream &os, const Cistercian &c) {
for (auto &row : c.canvas) {
for (auto cell : row) {
os << cell;
}
os << '\n';
}
return os;
}
int main() {
for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) {
std::cout << number << ":\n";
Cistercian c(number);
std::cout << c << '\n';
}
return 0;
}
|
Write the same code in C++ as shown below in Python. | >>> y = str( 5**4**3**2 )
>>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y)))
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
| #include <iostream>
#include <boost/multiprecision/gmp.hpp>
#include <string>
namespace mp = boost::multiprecision;
int main(int argc, char const *argv[])
{
uint64_t tmpres = mp::pow(mp::mpz_int(4)
, mp::pow(mp::mpz_int(3)
, 2).convert_to<uint64_t>()
).convert_to<uint64_t>();
mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);
std::string s = res.str();
std::cout << s.substr(0, 20)
<< "..."
<< s.substr(s.length() - 20, 20) << std::endl;
return 0;
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | import math
shades = ('.',':','!','*','o','e','&','
def normalize(v):
len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
return (v[0]/len, v[1]/len, v[2]/len)
def dot(x,y):
d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return -d if d < 0 else 0
def draw_sphere(r, k, ambient, light):
for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
x = i + 0.5
line = ''
for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
y = j/2 + 0.5
if x*x + y*y <= r*r:
vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
b = dot(light,vec)**k + ambient
intensity = int((1-b)*(len(shades)-1))
line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
else:
line += ' '
print(line)
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)
|
#include <QImage>
#include <QPainter>
int main() {
const QColor black(0, 0, 0);
const QColor white(255, 255, 255);
const int size = 300;
const double diameter = 0.6 * size;
QImage image(size, size, QImage::Format_RGB32);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
QLinearGradient linearGradient(0, 0, 0, size);
linearGradient.setColorAt(0, white);
linearGradient.setColorAt(1, black);
QBrush brush(linearGradient);
painter.fillRect(QRect(0, 0, size, size), brush);
QPointF point1(0.4 * size, 0.4 * size);
QPointF point2(0.45 * size, 0.4 * size);
QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);
radialGradient.setColorAt(0, white);
radialGradient.setColorAt(1, black);
QBrush brush2(radialGradient);
painter.setPen(Qt::NoPen);
painter.setBrush(brush2);
painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));
image.save("sphere.png");
return 0;
}
|
Convert this Python snippet to C++ and keep its semantics consistent. | import math
shades = ('.',':','!','*','o','e','&','
def normalize(v):
len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
return (v[0]/len, v[1]/len, v[2]/len)
def dot(x,y):
d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return -d if d < 0 else 0
def draw_sphere(r, k, ambient, light):
for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
x = i + 0.5
line = ''
for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
y = j/2 + 0.5
if x*x + y*y <= r*r:
vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
b = dot(light,vec)**k + ambient
intensity = int((1-b)*(len(shades)-1))
line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
else:
line += ' '
print(line)
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)
|
#include <QImage>
#include <QPainter>
int main() {
const QColor black(0, 0, 0);
const QColor white(255, 255, 255);
const int size = 300;
const double diameter = 0.6 * size;
QImage image(size, size, QImage::Format_RGB32);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
QLinearGradient linearGradient(0, 0, 0, size);
linearGradient.setColorAt(0, white);
linearGradient.setColorAt(1, black);
QBrush brush(linearGradient);
painter.fillRect(QRect(0, 0, size, size), brush);
QPointF point1(0.4 * size, 0.4 * size);
QPointF point2(0.45 * size, 0.4 * size);
QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);
radialGradient.setColorAt(0, white);
radialGradient.setColorAt(1, black);
QBrush brush2(radialGradient);
painter.setPen(Qt::NoPen);
painter.setBrush(brush2);
painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));
image.save("sphere.png");
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. |
from pprint import pprint as pp
from glob import glob
try: reduce
except: from functools import reduce
try: raw_input
except: raw_input = input
def parsetexts(fileglob='InvertedIndex/T*.txt'):
texts, words = {}, set()
for txtfile in glob(fileglob):
with open(txtfile, 'r') as f:
txt = f.read().split()
words |= set(txt)
texts[txtfile.split('\\')[-1]] = txt
return texts, words
def termsearch(terms):
return reduce(set.intersection,
(invindex[term] for term in terms),
set(texts.keys()))
texts, words = parsetexts()
print('\nTexts')
pp(texts)
print('\nWords')
pp(sorted(words))
invindex = {word:set(txt
for txt, wrds in texts.items() if word in wrds)
for word in words}
print('\nInverted Index')
pp({k:sorted(v) for k,v in invindex.items()})
terms = ["what", "is", "it"]
print('\nTerm Search for: ' + repr(terms))
pp(sorted(termsearch(terms)))
| #include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
const std::string _CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.:-_/";
const size_t MAX_NODES = 41;
class node
{
public:
node() { clear(); }
node( char z ) { clear(); }
~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }
void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }
bool isWord;
std::vector<std::string> files;
node* next[MAX_NODES];
};
class index {
public:
void add( std::string s, std::string fileName ) {
std::transform( s.begin(), s.end(), s.begin(), tolower );
std::string h;
for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
if( *i == 32 ) {
pushFileName( addWord( h ), fileName );
h.clear();
continue;
}
h.append( 1, *i );
}
if( h.length() )
pushFileName( addWord( h ), fileName );
}
void findWord( std::string s ) {
std::vector<std::string> v = find( s );
if( !v.size() ) {
std::cout << s + " was not found!\n";
return;
}
std::cout << s << " found in:\n";
for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {
std::cout << *i << "\n";
}
std::cout << "\n";
}
private:
void pushFileName( node* n, std::string fn ) {
std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );
if( i == n->files.end() ) n->files.push_back( fn );
}
const std::vector<std::string>& find( std::string s ) {
size_t idx;
std::transform( s.begin(), s.end(), s.begin(), tolower );
node* rt = &root;
for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
idx = _CHARS.find( *i );
if( idx < MAX_NODES ) {
if( !rt->next[idx] ) return std::vector<std::string>();
rt = rt->next[idx];
}
}
if( rt->isWord ) return rt->files;
return std::vector<std::string>();
}
node* addWord( std::string s ) {
size_t idx;
node* rt = &root, *n;
for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
idx = _CHARS.find( *i );
if( idx < MAX_NODES ) {
n = rt->next[idx];
if( n ){
rt = n;
continue;
}
n = new node( *i );
rt->next[idx] = n;
rt = n;
}
}
rt->isWord = true;
return rt;
}
node root;
};
int main( int argc, char* argv[] ) {
index t;
std::string s;
std::string files[] = { "file1.txt", "f_text.txt", "text_1b.txt" };
for( int x = 0; x < 3; x++ ) {
std::ifstream f;
f.open( files[x].c_str(), std::ios::in );
if( f.good() ) {
while( !f.eof() ) {
f >> s;
t.add( s, files[x] );
s.clear();
}
f.close();
}
}
while( true ) {
std::cout << "Enter one word to search for, return to exit: ";
std::getline( std::cin, s );
if( !s.length() ) break;
t.findWord( s );
}
return 0;
}
|
Write the same algorithm in C++ as shown in this Python implementation. | >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
| #include <boost/math/common_factor.hpp>
#include <iostream>
int main( ) {
std::cout << "The least common multiple of 12 and 18 is " <<
boost::math::lcm( 12 , 18 ) << " ,\n"
<< "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
return 0 ;
}
|
Write the same code in C++ as shown below in Python. | >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
| #include <boost/math/common_factor.hpp>
#include <iostream>
int main( ) {
std::cout << "The least common multiple of 12 and 18 is " <<
boost::math::lcm( 12 , 18 ) << " ,\n"
<< "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
return 0 ;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | def factors(x):
factors = []
i = 2
s = int(x ** 0.5)
while i < s:
if x % i == 0:
factors.append(i)
x = int(x / i)
s = int(x ** 0.5)
i += 1
factors.append(x)
return factors
print("First 10 Fermat numbers:")
for i in range(10):
fermat = 2 ** 2 ** i + 1
print("F{} = {}".format(chr(i + 0x2080) , fermat))
print("\nFactors of first few Fermat numbers:")
for i in range(10):
fermat = 2 ** 2 ** i + 1
fac = factors(fermat)
if len(fac) == 1:
print("F{} -> IS PRIME".format(chr(i + 0x2080)))
else:
print("F{} -> FACTORS: {}".format(chr(i + 0x2080), fac))
| #include <iostream>
#include <vector>
#include <boost/integer/common_factor.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/miller_rabin.hpp>
typedef boost::multiprecision::cpp_int integer;
integer fermat(unsigned int n) {
unsigned int p = 1;
for (unsigned int i = 0; i < n; ++i)
p *= 2;
return 1 + pow(integer(2), p);
}
inline void g(integer& x, const integer& n) {
x *= x;
x += 1;
x %= n;
}
integer pollard_rho(const integer& n) {
integer x = 2, y = 2, d = 1, z = 1;
int count = 0;
for (;;) {
g(x, n);
g(y, n);
g(y, n);
d = abs(x - y);
z = (z * d) % n;
++count;
if (count == 100) {
d = gcd(z, n);
if (d != 1)
break;
z = 1;
count = 0;
}
}
if (d == n)
return 0;
return d;
}
std::vector<integer> get_prime_factors(integer n) {
std::vector<integer> factors;
for (;;) {
if (miller_rabin_test(n, 25)) {
factors.push_back(n);
break;
}
integer f = pollard_rho(n);
if (f == 0) {
factors.push_back(n);
break;
}
factors.push_back(f);
n /= f;
}
return factors;
}
void print_vector(const std::vector<integer>& factors) {
if (factors.empty())
return;
auto i = factors.begin();
std::cout << *i++;
for (; i != factors.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
int main() {
std::cout << "First 10 Fermat numbers:\n";
for (unsigned int i = 0; i < 10; ++i)
std::cout << "F(" << i << ") = " << fermat(i) << '\n';
std::cout << "\nPrime factors:\n";
for (unsigned int i = 0; i < 9; ++i) {
std::cout << "F(" << i << "): ";
print_vector(get_prime_factors(fermat(i)));
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | from random import randrange
while True:
a = randrange(20)
print(a)
if a == 10:
break
b = randrange(20)
print(b)
| #include <iostream>
#include <ctime>
#include <cstdlib>
int main(){
srand(time(NULL));
while(true){
const int a = rand() % 20;
std::cout << a << std::endl;
if(a == 10)
break;
const int b = rand() % 20;
std::cout << b << std::endl;
}
return 0;
}
|
Change the programming language of this snippet from Python to C++ without modifying what it does. | lp = open("/dev/lp0")
lp.write("Hello World!\n")
lp.close()
| #include <iostream>
#include <fstream>
int main(){
std::ofstream lprFile;
lprFile.open( "/dev/lp0" );
lprFile << "Hello World!\n";
lprFile.close();
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Python version. | lp = open("/dev/lp0")
lp.write("Hello World!\n")
lp.close()
| #include <iostream>
#include <fstream>
int main(){
std::ofstream lprFile;
lprFile.open( "/dev/lp0" );
lprFile << "Hello World!\n";
lprFile.close();
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Python. | def water_collected(tower):
N = len(tower)
highest_left = [0] + [max(tower[:n]) for n in range(1,N)]
highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]
water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)
for n in range(N)]
print("highest_left: ", highest_left)
print("highest_right: ", highest_right)
print("water_level: ", water_level)
print("tower_level: ", tower)
print("total_water: ", sum(water_level))
print("")
return sum(water_level)
towers = [[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
[water_collected(tower) for tower in towers]
| #include <iostream>
#include <vector>
#include <algorithm>
enum { EMPTY, WALL, WATER };
auto fill(const std::vector<int> b) {
auto water = 0;
const auto rows = *std::max_element(std::begin(b), std::end(b));
const auto cols = std::size(b);
std::vector<std::vector<int>> g(rows);
for (auto& r : g) {
for (auto i = 0; i < cols; ++i) {
r.push_back(EMPTY);
}
}
for (auto c = 0; c < cols; ++c) {
for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) {
g[r][c] = WALL;
}
}
for (auto c = 0; c < cols - 1; ++c) {
auto start_row = rows - b[c];
while (start_row < rows) {
if (g[start_row][c] == EMPTY) break;
auto c2 = c + 1;
bool hitWall = false;
while (c2 < cols) {
if (g[start_row][c2] == WALL) {
hitWall = true;
break;
}
++c2;
}
if (hitWall) {
for (auto i = c + 1; i < c2; ++i) {
g[start_row][i] = WATER;
++water;
}
}
++start_row;
}
}
return water;
}
int main() {
std::vector<std::vector<int>> b = {
{ 1, 5, 3, 7, 2 },
{ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 },
{ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 },
{ 5, 5, 5, 5 },
{ 5, 6, 7, 8 },
{ 8, 7, 7, 6 },
{ 6, 7, 10, 7, 6 }
};
for (const auto v : b) {
auto water = fill(v);
std::cout << water << " water drops." << std::endl;
}
std::cin.ignore();
std::cin.get();
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | from sympy import isprime
def descending(xs=range(10)):
for x in xs:
yield x
yield from descending(x*10 + d for d in range(x%10))
for i, p in enumerate(sorted(filter(isprime, descending()))):
print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n')
print()
| #include <iostream>
bool ispr(unsigned int n) {
if ((n & 1) == 0 || n < 2) return n == 2;
for (unsigned int j = 3; j * j <= n; j += 2)
if (n % j == 0) return false; return true; }
int main() {
unsigned int c = 0, nc, pc = 9, i, a, b, l,
ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128];
while (true) {
nc = 0;
for (i = 0; i < pc; i++) {
if (ispr(a = ps[i]))
printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " ");
for (b = a * 10, l = a % 10 + b++; b < l; b++)
nxt[nc++] = b;
}
if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i];
else break;
}
printf("\n%d descending primes found", c);
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | import math
def SquareFree ( _number ) :
max = (int) (math.sqrt ( _number ))
for root in range ( 2, max+1 ):
if 0 == _number % ( root * root ):
return False
return True
def ListSquareFrees( _start, _end ):
count = 0
for i in range ( _start, _end+1 ):
if True == SquareFree( i ):
print ( "{}\t".format(i), end="" )
count += 1
print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count))
ListSquareFrees( 1, 100 )
ListSquareFrees( 1000000000000, 1000000000145 )
| #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
bool square_free(integer n) {
if (n % 4 == 0)
return false;
for (integer p = 3; p * p <= n; p += 2) {
integer count = 0;
for (; n % p == 0; n /= p) {
if (++count > 1)
return false;
}
}
return true;
}
void print_square_free_numbers(integer from, integer to) {
std::cout << "Square-free numbers between " << from
<< " and " << to << ":\n";
std::string line;
for (integer i = from; i <= to; ++i) {
if (square_free(i)) {
if (!line.empty())
line += ' ';
line += std::to_string(i);
if (line.size() >= 80) {
std::cout << line << '\n';
line.clear();
}
}
}
if (!line.empty())
std::cout << line << '\n';
}
void print_square_free_count(integer from, integer to) {
integer count = 0;
for (integer i = from; i <= to; ++i) {
if (square_free(i))
++count;
}
std::cout << "Number of square-free numbers between "
<< from << " and " << to << ": " << count << '\n';
}
int main() {
print_square_free_numbers(1, 145);
print_square_free_numbers(1000000000000LL, 1000000000145LL);
print_square_free_count(1, 100);
print_square_free_count(1, 1000);
print_square_free_count(1, 10000);
print_square_free_count(1, 100000);
print_square_free_count(1, 1000000);
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Python version. |
from __future__ import division
def jaro(s, t):
s_len = len(s)
t_len = len(t)
if s_len == 0 and t_len == 0:
return 1
match_distance = (max(s_len, t_len) // 2) - 1
s_matches = [False] * s_len
t_matches = [False] * t_len
matches = 0
transpositions = 0
for i in range(s_len):
start = max(0, i - match_distance)
end = min(i + match_distance + 1, t_len)
for j in range(start, end):
if t_matches[j]:
continue
if s[i] != t[j]:
continue
s_matches[i] = True
t_matches[j] = True
matches += 1
break
if matches == 0:
return 0
k = 0
for i in range(s_len):
if not s_matches[i]:
continue
while not t_matches[k]:
k += 1
if s[i] != t[k]:
transpositions += 1
k += 1
return ((matches / s_len) +
(matches / t_len) +
((matches - transpositions / 2) / matches)) / 3
def main():
for s, t in [('MARTHA', 'MARHTA'),
('DIXON', 'DICKSONX'),
('JELLYFISH', 'SMELLYFISH')]:
print("jaro(%r, %r) = %.10f" % (s, t, jaro(s, t)))
if __name__ == '__main__':
main()
| #include <algorithm>
#include <iostream>
#include <string>
double jaro(const std::string s1, const std::string s2) {
const uint l1 = s1.length(), l2 = s2.length();
if (l1 == 0)
return l2 == 0 ? 1.0 : 0.0;
const uint match_distance = std::max(l1, l2) / 2 - 1;
bool s1_matches[l1];
bool s2_matches[l2];
std::fill(s1_matches, s1_matches + l1, false);
std::fill(s2_matches, s2_matches + l2, false);
uint matches = 0;
for (uint i = 0; i < l1; i++)
{
const int end = std::min(i + match_distance + 1, l2);
for (int k = std::max(0u, i - match_distance); k < end; k++)
if (!s2_matches[k] && s1[i] == s2[k])
{
s1_matches[i] = true;
s2_matches[k] = true;
matches++;
break;
}
}
if (matches == 0)
return 0.0;
double t = 0.0;
uint k = 0;
for (uint i = 0; i < l1; i++)
if (s1_matches[i])
{
while (!s2_matches[k]) k++;
if (s1[i] != s2[k]) t += 0.5;
k++;
}
const double m = matches;
return (m / l1 + m / l2 + (m - t) / m) / 3.0;
}
int main() {
using namespace std;
cout << jaro("MARTHA", "MARHTA") << endl;
cout << jaro("DIXON", "DICKSONX") << endl;
cout << jaro("JELLYFISH", "SMELLYFISH") << endl;
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Python. |
from collections import Counter
def decompose_sum(s):
return [(a,s-a) for a in range(2,int(s/2+1))]
all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)
product_counts = Counter(c*d for c,d in all_pairs)
unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)
s_pairs = [(a,b) for a,b in all_pairs if
all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]
product_counts = Counter(c*d for c,d in s_pairs)
p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]
sum_counts = Counter(c+d for c,d in p_pairs)
final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]
print(final_pairs)
| #include <algorithm>
#include <iostream>
#include <map>
#include <vector>
std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) {
for (auto &p : v) {
auto sum = p.first + p.second;
auto prod = p.first * p.second;
os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod;
}
return os << '\n';
}
void print_count(const std::vector<std::pair<int, int>> &candidates) {
auto c = candidates.size();
if (c == 0) {
std::cout << "no candidates\n";
} else if (c == 1) {
std::cout << "one candidate\n";
} else {
std::cout << c << " candidates\n";
}
}
auto setup() {
std::vector<std::pair<int, int>> candidates;
for (int x = 2; x <= 98; x++) {
for (int y = x + 1; y <= 98; y++) {
if (x + y <= 100) {
candidates.push_back(std::make_pair(x, y));
}
}
}
return candidates;
}
void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) {
candidates.erase(std::remove_if(
candidates.begin(), candidates.end(),
[sum](const std::pair<int, int> &pair) {
auto s = pair.first + pair.second;
return s == sum;
}
), candidates.end());
}
void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) {
candidates.erase(std::remove_if(
candidates.begin(), candidates.end(),
[prod](const std::pair<int, int> &pair) {
auto p = pair.first * pair.second;
return p == prod;
}
), candidates.end());
}
void statement1(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto prod = pair.first * pair.second;
uniqueMap[prod]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto prod = pair.first * pair.second;
if (uniqueMap[prod] == 1) {
auto sum = pair.first + pair.second;
remove_by_sum(candidates, sum);
loop = true;
break;
}
}
} while (loop);
}
void statement2(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto prod = pair.first * pair.second;
uniqueMap[prod]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto prod = pair.first * pair.second;
if (uniqueMap[prod] > 1) {
remove_by_prod(candidates, prod);
loop = true;
break;
}
}
} while (loop);
}
void statement3(std::vector<std::pair<int, int>> &candidates) {
std::map<int, int> uniqueMap;
std::for_each(
candidates.cbegin(), candidates.cend(),
[&uniqueMap](const std::pair<int, int> &pair) {
auto sum = pair.first + pair.second;
uniqueMap[sum]++;
}
);
bool loop;
do {
loop = false;
for (auto &pair : candidates) {
auto sum = pair.first + pair.second;
if (uniqueMap[sum] > 1) {
remove_by_sum(candidates, sum);
loop = true;
break;
}
}
} while (loop);
}
int main() {
auto candidates = setup();
print_count(candidates);
statement1(candidates);
print_count(candidates);
statement2(candidates);
print_count(candidates);
statement3(candidates);
print_count(candidates);
std::cout << candidates;
return 0;
}
|
Write a version of this Python function in C++ with identical behavior. | from itertools import count, islice
def _basechange_int(num, b):
if num == 0:
return [0]
result = []
while num != 0:
num, d = divmod(num, b)
result.append(d)
return result[::-1]
def fairshare(b=2):
for i in count():
yield sum(_basechange_int(i, b)) % b
if __name__ == '__main__':
for b in (2, 3, 5, 11):
print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
| #include <iostream>
#include <vector>
int turn(int base, int n) {
int sum = 0;
while (n != 0) {
int rem = n % base;
n = n / base;
sum += rem;
}
return sum % base;
}
void fairshare(int base, int count) {
printf("Base %2d:", base);
for (int i = 0; i < count; i++) {
int t = turn(base, i);
printf(" %2d", t);
}
printf("\n");
}
void turnCount(int base, int count) {
std::vector<int> cnt(base, 0);
for (int i = 0; i < count; i++) {
int t = turn(base, i);
cnt[t]++;
}
int minTurn = INT_MAX;
int maxTurn = INT_MIN;
int portion = 0;
for (int i = 0; i < base; i++) {
if (cnt[i] > 0) {
portion++;
}
if (cnt[i] < minTurn) {
minTurn = cnt[i];
}
if (cnt[i] > maxTurn) {
maxTurn = cnt[i];
}
}
printf(" With %d people: ", base);
if (0 == minTurn) {
printf("Only %d have a turn\n", portion);
} else if (minTurn == maxTurn) {
printf("%d\n", minTurn);
} else {
printf("%d or %d\n", minTurn, maxTurn);
}
}
int main() {
fairshare(2, 25);
fairshare(3, 25);
fairshare(5, 25);
fairshare(11, 25);
printf("How many times does each get a turn in 50000 iterations?\n");
turnCount(191, 50000);
turnCount(1377, 50000);
turnCount(49999, 50000);
turnCount(50000, 50000);
turnCount(50001, 50000);
return 0;
}
|
Generate an equivalent C++ version of this Python code. |
import numpy as np
class Revolver:
def __init__(self):
self.cylinder = np.array([False] * 6)
def unload(self):
self.cylinder[:] = False
def load(self):
while self.cylinder[1]:
self.cylinder[:] = np.roll(self.cylinder, 1)
self.cylinder[1] = True
def spin(self):
self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))
def fire(self):
shot = self.cylinder[0]
self.cylinder[:] = np.roll(self.cylinder, 1)
return shot
def LSLSFSF(self):
self.unload()
self.load()
self.spin()
self.load()
self.spin()
if self.fire():
return True
self.spin()
if self.fire():
return True
return False
def LSLSFF(self):
self.unload()
self.load()
self.spin()
self.load()
self.spin()
if self.fire():
return True
if self.fire():
return True
return False
def LLSFSF(self):
self.unload()
self.load()
self.load()
self.spin()
if self.fire():
return True
self.spin()
if self.fire():
return True
return False
def LLSFF(self):
self.unload()
self.load()
self.load()
self.spin()
if self.fire():
return True
if self.fire():
return True
return False
if __name__ == '__main__':
REV = Revolver()
TESTCOUNT = 100000
for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],
['load, spin, load, spin, fire, fire', REV.LSLSFF],
['load, load, spin, fire, spin, fire', REV.LLSFSF],
['load, load, spin, fire, fire', REV.LLSFF]]:
percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT
print("Method", name, "produces", percentage, "per cent deaths.")
| #include <array>
#include <iomanip>
#include <iostream>
#include <random>
#include <sstream>
class Roulette {
private:
std::array<bool, 6> cylinder;
std::mt19937 gen;
std::uniform_int_distribution<> distrib;
int next_int() {
return distrib(gen);
}
void rshift() {
std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end());
}
void unload() {
std::fill(cylinder.begin(), cylinder.end(), false);
}
void load() {
while (cylinder[0]) {
rshift();
}
cylinder[0] = true;
rshift();
}
void spin() {
int lim = next_int();
for (int i = 1; i < lim; i++) {
rshift();
}
}
bool fire() {
auto shot = cylinder[0];
rshift();
return shot;
}
public:
Roulette() {
std::random_device rd;
gen = std::mt19937(rd());
distrib = std::uniform_int_distribution<>(1, 6);
unload();
}
int method(const std::string &s) {
unload();
for (auto c : s) {
switch (c) {
case 'L':
load();
break;
case 'S':
spin();
break;
case 'F':
if (fire()) {
return 1;
}
break;
}
}
return 0;
}
};
std::string mstring(const std::string &s) {
std::stringstream ss;
bool first = true;
auto append = [&ss, &first](const std::string s) {
if (first) {
first = false;
} else {
ss << ", ";
}
ss << s;
};
for (auto c : s) {
switch (c) {
case 'L':
append("load");
break;
case 'S':
append("spin");
break;
case 'F':
append("fire");
break;
}
}
return ss.str();
}
void test(const std::string &src) {
const int tests = 100000;
int sum = 0;
Roulette r;
for (int t = 0; t < tests; t++) {
sum += r.method(src);
}
double pc = 100.0 * sum / tests;
std::cout << std::left << std::setw(40) << mstring(src) << " produces " << pc << "% deaths.\n";
}
int main() {
test("LSLSFSF");
test("LSLSFF");
test("LLSFSF");
test("LLSFF");
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | from collections import namedtuple
from pprint import pprint as pp
OpInfo = namedtuple('OpInfo', 'prec assoc')
L, R = 'Left Right'.split()
ops = {
'^': OpInfo(prec=4, assoc=R),
'*': OpInfo(prec=3, assoc=L),
'/': OpInfo(prec=3, assoc=L),
'+': OpInfo(prec=2, assoc=L),
'-': OpInfo(prec=2, assoc=L),
'(': OpInfo(prec=9, assoc=L),
')': OpInfo(prec=0, assoc=L),
}
NUM, LPAREN, RPAREN = 'NUMBER ( )'.split()
def get_input(inp = None):
'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'
if inp is None:
inp = input('expression: ')
tokens = inp.strip().split()
tokenvals = []
for token in tokens:
if token in ops:
tokenvals.append((token, ops[token]))
else:
tokenvals.append((NUM, token))
return tokenvals
def shunting(tokenvals):
outq, stack = [], []
table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]
for token, val in tokenvals:
note = action = ''
if token is NUM:
action = 'Add number to output'
outq.append(val)
table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
elif token in ops:
t1, (p1, a1) = token, val
v = t1
note = 'Pop ops from stack to output'
while stack:
t2, (p2, a2) = stack[-1]
if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):
if t1 != RPAREN:
if t2 != LPAREN:
stack.pop()
action = '(Pop op)'
outq.append(t2)
else:
break
else:
if t2 != LPAREN:
stack.pop()
action = '(Pop op)'
outq.append(t2)
else:
stack.pop()
action = '(Pop & discard "(")'
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
break
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
v = note = ''
else:
note = ''
break
note = ''
note = ''
if t1 != RPAREN:
stack.append((token, val))
action = 'Push op token to stack'
else:
action = 'Discard ")"'
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
note = 'Drain stack to output'
while stack:
v = ''
t2, (p2, a2) = stack[-1]
action = '(Pop op)'
stack.pop()
outq.append(t2)
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
v = note = ''
return table
if __name__ == '__main__':
infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'
print( 'For infix expression: %r\n' % infix )
rp = shunting(get_input(infix))
maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]
row = rp[0]
print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
for row in rp[1:]:
print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
print('\n The final output RPN is: %r' % rp[-1][2])
| #include <ciso646>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
using std::vector;
using std::string;
#include <exception>
#include <stdexcept>
template <typename...Args> std::runtime_error error( Args...args )
{
return std::runtime_error( (std::ostringstream{} << ... << args).str() );
};
template <typename T> struct stack : public std::vector <T>
{
using base_type = std::vector <T> ;
T push ( const T& x ) { base_type::push_back( x ); return x; }
const T& top () { return base_type::back(); }
T pop () { T x = std::move( top() ); base_type::pop_back(); return x; }
bool empty() { return base_type::empty(); }
};
using Number = double;
using Operator_Name = string;
using Precedence = int;
enum class Associates { none, left_to_right, right_to_left };
struct Operator_Info { Precedence precedence; Associates associativity; };
std::unordered_map <Operator_Name, Operator_Info> Operators =
{
{ "^", { 4, Associates::right_to_left } },
{ "*", { 3, Associates::left_to_right } },
{ "/", { 3, Associates::left_to_right } },
{ "+", { 2, Associates::left_to_right } },
{ "-", { 2, Associates::left_to_right } },
};
Precedence precedence ( const Operator_Name& op ) { return Operators[ op ].precedence; }
Associates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }
using Token = string;
bool is_number ( const Token& t ) { return regex_match( t, std::regex{ R"z((\d+(\.\d*)?|\.\d+)([Ee][\+\-]?\d+)?)z" } ); }
bool is_operator ( const Token& t ) { return Operators.count( t ); }
bool is_open_parenthesis ( const Token& t ) { return t == "("; }
bool is_close_parenthesis( const Token& t ) { return t == ")"; }
bool is_parenthesis ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }
template <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )
{
std::size_t n = 0; for (auto x : xs) outs << (n++ ? " " : "") << x; return outs;
}
#include <iomanip>
struct Progressive_Display
{
string token_name;
string token_type;
Progressive_Display()
{
std::cout << "\n"
" INPUT │ TYPE │ ACTION │ STACK │ OUTPUT\n"
"────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\n";
}
Progressive_Display& operator () ( const Token& token )
{
token_name = token;
token_type = is_operator ( token ) ? "op"
: is_parenthesis( token ) ? "()"
: is_number ( token ) ? "num"
: "";
return *this;
}
Progressive_Display& operator () (
const string & description,
const stack <Token> & stack,
const vector <Token> & output )
{
std::cout << std::right
<< std::setw( 7 ) << token_name << " │ " << std::left
<< std::setw( 4 ) << token_type << " │ "
<< std::setw( 16 ) << description << " │ "
<< std::setw( 12 ) << (std::ostringstream{} << stack).str() << " │ "
<< output << "\n";
return operator () ( "" );
}
};
vector <Token> parse( const vector <Token> & tokens )
{
vector <Token> output;
stack <Token> stack;
Progressive_Display display;
for (auto token : tokens)
if (is_number( token ))
{
output.push_back( token );
display( token )( "num --> output", stack, output );
}
else if (is_operator( token ) or is_parenthesis( token ))
{
display( token );
if (!is_open_parenthesis( token ))
{
while (!stack.empty()
and ( (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))
or (precedence( stack.top() ) > precedence( token ))
or ( (precedence( stack.top() ) == precedence( token ))
and (associativity( token ) == Associates::left_to_right))))
{
output.push_back( stack.pop() );
display( "pop --> output", stack, output );
}
if (is_close_parenthesis( token ))
{
stack.pop();
display( "pop", stack, output );
}
}
if (!is_close_parenthesis( token ))
{
stack.push( token );
display( "push op", stack, output );
}
}
else throw error( "unexpected token: ", token );
display( "END" );
while (!stack.empty())
{
output.push_back( stack.pop() );
display( "pop --> output", stack, output );
}
return output;
}
int main( int argc, char** argv )
try
{
auto tokens = vector <Token> ( argv+1, argv+argc );
auto rpn_expr = parse( tokens );
std::cout
<< "\nInfix = " << tokens
<< "\nRPN = " << rpn_expr
<< "\n";
}
catch (std::exception e)
{
std::cerr << "error: " << e.what() << "\n";
return 1;
}
|
Produce a functionally identical C++ code for the snippet given in Python. | Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3
>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!")
for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1])))
11 numbers: 1 2 3 4 5 6 7 8 9 10 11
11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0
>>>
| #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
int main( ) {
std::vector<double> input( 11 ) , results( 11 ) ;
std::cout << "Please enter 11 numbers!\n" ;
for ( int i = 0 ; i < input.size( ) ; i++ )
std::cin >> input[i];
std::transform( input.begin( ) , input.end( ) , results.begin( ) ,
[ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;
for ( int i = 10 ; i > -1 ; i-- ) {
std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ;
if ( results[ i ] > 400 )
std::cout << "too large!" ;
else
std::cout << results[ i ] << " !" ;
std::cout << std::endl ;
}
return 0 ;
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | >>> def middle_three_digits(i):
s = str(abs(i))
length = len(s)
assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits"
mid = length // 2
return s[mid-1:mid+2]
>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
>>> failing = [1, 2, -1, -10, 2002, -2002, 0]
>>> for x in passing + failing:
try:
answer = middle_three_digits(x)
except AssertionError as error:
answer = error
print("middle_three_digits(%s) returned: %r" % (x, answer))
middle_three_digits(123) returned: '123'
middle_three_digits(12345) returned: '234'
middle_three_digits(1234567) returned: '345'
middle_three_digits(987654321) returned: '654'
middle_three_digits(10001) returned: '000'
middle_three_digits(-10001) returned: '000'
middle_three_digits(-123) returned: '123'
middle_three_digits(-100) returned: '100'
middle_three_digits(100) returned: '100'
middle_three_digits(-12345) returned: '234'
middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)
>>>
| #include <iostream>
std::string middleThreeDigits(int n)
{
auto number = std::to_string(std::abs(n));
auto length = number.size();
if (length < 3) {
return "less than three digits";
} else if (length % 2 == 0) {
return "even number of digits";
} else {
return number.substr(length / 2 - 1, 3);
}
}
int main()
{
auto values {123, 12345, 1234567, 987654321, 10001,
-10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0};
for (auto&& v : values) {
std::cout << "middleThreeDigits(" << v << "): " <<
middleThreeDigits(v) << "\n";
}
}
|
Please provide an equivalent version of this Python code in C++. | def divisors(n):
divs = [1]
for ii in range(2, int(n ** 0.5) + 3):
if n % ii == 0:
divs.append(ii)
divs.append(int(n / ii))
divs.append(n)
return list(set(divs))
def is_prime(n):
return len(divisors(n)) == 2
def primes():
ii = 1
while True:
ii += 1
if is_prime(ii):
yield ii
def prime(n):
generator = primes()
for ii in range(n - 1):
generator.__next__()
return generator.__next__()
def n_divisors(n):
ii = 0
while True:
ii += 1
if len(divisors(ii)) == n:
yield ii
def sequence(max_n=None):
if max_n is not None:
for ii in range(1, max_n + 1):
if is_prime(ii):
yield prime(ii) ** (ii - 1)
else:
generator = n_divisors(ii)
for jj, out in zip(range(ii - 1), generator):
pass
yield generator.__next__()
else:
ii = 1
while True:
ii += 1
if is_prime(ii):
yield prime(ii) ** (ii - 1)
else:
generator = n_divisors(ii)
for jj, out in zip(range(ii - 1), generator):
pass
yield generator.__next__()
if __name__ == '__main__':
for item in sequence(15):
print(item)
| #include <iostream>
#include <vector>
std::vector<int> smallPrimes;
bool is_prime(size_t test) {
if (test < 2) {
return false;
}
if (test % 2 == 0) {
return test == 2;
}
for (size_t d = 3; d * d <= test; d += 2) {
if (test % d == 0) {
return false;
}
}
return true;
}
void init_small_primes(size_t numPrimes) {
smallPrimes.push_back(2);
int count = 0;
for (size_t n = 3; count < numPrimes; n += 2) {
if (is_prime(n)) {
smallPrimes.push_back(n);
count++;
}
}
}
size_t divisor_count(size_t n) {
size_t count = 1;
while (n % 2 == 0) {
n /= 2;
count++;
}
for (size_t d = 3; d * d <= n; d += 2) {
size_t q = n / d;
size_t r = n % d;
size_t dc = 0;
while (r == 0) {
dc += count;
n = q;
q = n / d;
r = n % d;
}
count += dc;
}
if (n != 1) {
count *= 2;
}
return count;
}
uint64_t OEISA073916(size_t n) {
if (is_prime(n)) {
return (uint64_t) pow(smallPrimes[n - 1], n - 1);
}
size_t count = 0;
uint64_t result = 0;
for (size_t i = 1; count < n; i++) {
if (n % 2 == 1) {
size_t root = (size_t) sqrt(i);
if (root * root != i) {
continue;
}
}
if (divisor_count(i) == n) {
count++;
result = i;
}
}
return result;
}
int main() {
const int MAX = 15;
init_small_primes(MAX);
for (size_t n = 1; n <= MAX; n++) {
if (n == 13) {
std::cout << "A073916(" << n << ") = One more bit needed to represent result.\n";
} else {
std::cout << "A073916(" << n << ") = " << OEISA073916(n) << '\n';
}
}
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Python. | def divisors(n):
divs = [1]
for ii in range(2, int(n ** 0.5) + 3):
if n % ii == 0:
divs.append(ii)
divs.append(int(n / ii))
divs.append(n)
return list(set(divs))
def sequence(max_n=None):
n = 0
while True:
n += 1
ii = 0
if max_n is not None:
if n > max_n:
break
while True:
ii += 1
if len(divisors(ii)) == n:
yield ii
break
if __name__ == '__main__':
for item in sequence(15):
print(item)
| #include <iostream>
#define MAX 15
using namespace std;
int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
int main() {
int i, k, n, seq[MAX];
for (i = 0; i < MAX; ++i) seq[i] = 0;
cout << "The first " << MAX << " terms of the sequence are:" << endl;
for (i = 1, n = 0; n < MAX; ++i) {
k = count_divisors(i);
if (k <= MAX && seq[k - 1] == 0) {
seq[k - 1] = i;
++n;
}
}
for (i = 0; i < MAX; ++i) cout << seq[i] << " ";
cout << endl;
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original Python snippet. |
import time
from collections import deque
from operator import itemgetter
from typing import Tuple
Pancakes = Tuple[int, ...]
def flip(pancakes: Pancakes, position: int) -> Pancakes:
return tuple([*reversed(pancakes[:position]), *pancakes[position:]])
def pancake(n: int) -> Tuple[Pancakes, int]:
init_stack = tuple(range(1, n + 1))
stack_flips = {init_stack: 0}
queue = deque([init_stack])
while queue:
stack = queue.popleft()
flips = stack_flips[stack] + 1
for i in range(2, n + 1):
flipped = flip(stack, i)
if flipped not in stack_flips:
stack_flips[flipped] = flips
queue.append(flipped)
return max(stack_flips.items(), key=itemgetter(1))
if __name__ == "__main__":
start = time.time()
for n in range(1, 10):
pancakes, p = pancake(n)
print(f"pancake({n}) = {p:>2}. Example: {list(pancakes)}")
print(f"\nTook {time.time() - start:.3} seconds.")
| #include <iomanip>
#include <iostream>
int pancake(int n) {
int gap = 2, sum = 2, adj = -1;
while (sum < n) {
adj++;
gap = gap * 2 - 1;
sum += gap;
}
return n + adj;
}
int main() {
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 6; j++) {
int n = i * 5 + j;
std::cout << "p(" << std::setw(2) << n << ") = " << std::setw(2) << pancake(n) << " ";
}
std::cout << '\n';
}
return 0;
}
|
Write the same algorithm in C++ as shown in this Python implementation. | import random
board = [[" " for x in range(8)] for y in range(8)]
piece_list = ["R", "N", "B", "Q", "P"]
def place_kings(brd):
while True:
rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)
diff_list = [abs(rank_white - rank_black), abs(file_white - file_black)]
if sum(diff_list) > 2 or set(diff_list) == set([0, 2]):
brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k"
break
def populate_board(brd, wp, bp):
for x in range(2):
if x == 0:
piece_amount = wp
pieces = piece_list
else:
piece_amount = bp
pieces = [s.lower() for s in piece_list]
while piece_amount != 0:
piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)
piece = random.choice(pieces)
if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False:
brd[piece_rank][piece_file] = piece
piece_amount -= 1
def fen_from_board(brd):
fen = ""
for x in brd:
n = 0
for y in x:
if y == " ":
n += 1
else:
if n != 0:
fen += str(n)
fen += y
n = 0
if n != 0:
fen += str(n)
fen += "/" if fen.count("/") < 7 else ""
fen += " w - - 0 1\n"
return fen
def pawn_on_promotion_square(pc, pr):
if pc == "P" and pr == 0:
return True
elif pc == "p" and pr == 7:
return True
return False
def start():
piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)
place_kings(board)
populate_board(board, piece_amount_white, piece_amount_black)
print(fen_from_board(board))
for x in board:
print(x)
start()
| #include <ctime>
#include <iostream>
#include <string>
#include <algorithm>
class chessBoard {
public:
void generateRNDBoard( int brds ) {
int a, b, i; char c;
for( int cc = 0; cc < brds; cc++ ) {
memset( brd, 0, 64 );
std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk";
random_shuffle( pieces.begin(), pieces.end() );
while( pieces.length() ) {
i = rand() % pieces.length(); c = pieces.at( i );
while( true ) {
a = rand() % 8; b = rand() % 8;
if( brd[a][b] == 0 ) {
if( c == 'P' && !b || c == 'p' && b == 7 ||
( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;
break;
}
}
brd[a][b] = c;
pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );
}
print();
}
}
private:
bool search( char c, int a, int b ) {
for( int y = -1; y < 2; y++ ) {
for( int x = -1; x < 2; x++ ) {
if( !x && !y ) continue;
if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {
if( brd[a + x][b + y] == c ) return true;
}
}
}
return false;
}
void print() {
int e = 0;
for( int y = 0; y < 8; y++ ) {
for( int x = 0; x < 8; x++ ) {
if( brd[x][y] == 0 ) e++;
else {
if( e > 0 ) { std::cout << e; e = 0; }
std::cout << brd[x][y];
}
}
if( e > 0 ) { std::cout << e; e = 0; }
if( y < 7 ) std::cout << "/";
}
std::cout << " w - - 0 1\n\n";
for( int y = 0; y < 8; y++ ) {
for( int x = 0; x < 8; x++ ) {
if( brd[x][y] == 0 ) std::cout << ".";
else std::cout << brd[x][y];
}
std::cout << "\n";
}
std::cout << "\n\n";
}
char brd[8][8];
};
int main( int argc, char* argv[] ) {
srand( ( unsigned )time( 0 ) );
chessBoard c;
c.generateRNDBoard( 2 );
return 0;
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | from collections import deque
from itertools import dropwhile, islice, takewhile
from textwrap import wrap
from typing import Iterable, Iterator
Digits = str
def esthetic_nums(base: int) -> Iterator[int]:
queue: deque[tuple[int, int]] = deque()
queue.extendleft((d, d) for d in range(1, base))
while True:
num, lsd = queue.pop()
yield num
new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)
num *= base
queue.extendleft((num + d, d) for d in new_lsds)
def to_digits(num: int, base: int) -> Digits:
digits: list[str] = []
while num:
num, d = divmod(num, base)
digits.append("0123456789abcdef"[d])
return "".join(reversed(digits)) if digits else "0"
def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:
joined = ", ".join(it)
lines = wrap(joined, width=width - indent)
for line in lines:
print(f"{indent*' '}{line}")
print()
def task_2() -> None:
nums: Iterator[int]
for base in range(2, 16 + 1):
start, stop = 4 * base, 6 * base
nums = esthetic_nums(base)
nums = islice(nums, start - 1, stop)
print(
f"Base-{base} esthetic numbers from "
f"index {start} through index {stop} inclusive:\n"
)
pprint_it(to_digits(num, base) for num in nums)
def task_3(lower: int, upper: int, base: int = 10) -> None:
nums: Iterator[int] = esthetic_nums(base)
nums = dropwhile(lambda num: num < lower, nums)
nums = takewhile(lambda num: num <= upper, nums)
print(
f"Base-{base} esthetic numbers with "
f"magnitude between {lower:,} and {upper:,}:\n"
)
pprint_it(to_digits(num, base) for num in nums)
if __name__ == "__main__":
print("======\nTask 2\n======\n")
task_2()
print("======\nTask 3\n======\n")
task_3(1_000, 9_999)
print("======\nTask 4\n======\n")
task_3(100_000_000, 130_000_000)
| #include <functional>
#include <iostream>
#include <sstream>
#include <vector>
std::string to(int n, int b) {
static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::stringstream ss;
while (n > 0) {
auto rem = n % b;
n = n / b;
ss << BASE[rem];
}
auto fwd = ss.str();
return std::string(fwd.rbegin(), fwd.rend());
}
uint64_t uabs(uint64_t a, uint64_t b) {
if (a < b) {
return b - a;
}
return a - b;
}
bool isEsthetic(uint64_t n, uint64_t b) {
if (n == 0) {
return false;
}
auto i = n % b;
n /= b;
while (n > 0) {
auto j = n % b;
if (uabs(i, j) != 1) {
return false;
}
n /= b;
i = j;
}
return true;
}
void listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {
std::vector<uint64_t> esths;
const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {
auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {
if (i >= n && i <= m) {
esths.push_back(i);
}
if (i == 0 || i > m) {
return;
}
auto d = i % 10;
auto i1 = i * 10 + d - 1;
auto i2 = i1 + 2;
if (d == 0) {
dfs_ref(n, m, i2, dfs_ref);
} else if (d == 9) {
dfs_ref(n, m, i1, dfs_ref);
} else {
dfs_ref(n, m, i1, dfs_ref);
dfs_ref(n, m, i2, dfs_ref);
}
};
dfs_impl(n, m, i, dfs_impl);
};
for (int i = 0; i < 10; i++) {
dfs(n2, m2, i);
}
auto le = esths.size();
printf("Base 10: %d esthetic numbers between %llu and %llu:\n", le, n, m);
if (all) {
for (size_t c = 0; c < esths.size(); c++) {
auto esth = esths[c];
printf("%llu ", esth);
if ((c + 1) % perLine == 0) {
printf("\n");
}
}
printf("\n");
} else {
for (int c = 0; c < perLine; c++) {
auto esth = esths[c];
printf("%llu ", esth);
}
printf("\n............\n");
for (size_t i = le - perLine; i < le; i++) {
auto esth = esths[i];
printf("%llu ", esth);
}
printf("\n");
}
printf("\n");
}
int main() {
for (int b = 2; b <= 16; b++) {
printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4 * b, 6 * b);
for (int n = 1, c = 0; c < 6 * b; n++) {
if (isEsthetic(n, b)) {
c++;
if (c >= 4 * b) {
std::cout << to(n, b) << ' ';
}
}
}
printf("\n");
}
printf("\n");
listEsths(1000, 1010, 9999, 9898, 16, true);
listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);
listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);
listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);
listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | >>> from itertools import permutations
>>> def f1(p):
i = 0
while True:
p0 = p[0]
if p0 == 1: break
p[:p0] = p[:p0][::-1]
i += 1
return i
>>> def fannkuch(n):
return max(f1(list(p)) for p in permutations(range(1, n+1)))
>>> for n in range(1, 11): print(n,fannkuch(n))
1 0
2 1
3 2
4 4
5 7
6 10
7 16
8 22
9 30
10 38
>>>
| #include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
int topswops(int n) {
std::vector<int> list(n);
std::iota(std::begin(list), std::end(list), 1);
int max_steps = 0;
do {
auto temp_list = list;
for (int steps = 1; temp_list[0] != 1; ++steps) {
std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);
if (steps > max_steps) max_steps = steps;
}
} while (std::next_permutation(std::begin(list), std::end(list)));
return max_steps;
}
int main() {
for (int i = 1; i <= 10; ++i) {
std::cout << i << ": " << topswops(i) << std::endl;
}
return 0;
}
|
Please provide an equivalent version of this Python code in C++. | from sys import argv
unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254,
"fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254,
"meter": 1.0, "milia": 7467.6, "piad": 0.1778,
"sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445,
"versta": 1066.8}
if __name__ == '__main__':
assert len(argv) == 3, 'ERROR. Need two arguments - number then units'
try:
value = float(argv[1])
except:
print('ERROR. First argument must be a (float) number')
raise
unit = argv[2]
assert unit in unit2mult, ( 'ERROR. Only know the following units: '
+ ' '.join(unit2mult.keys()) )
print("%g %s to:" % (value, unit))
for unt, mlt in sorted(unit2mult.items()):
print(' %10s: %g' % (unt, value * unit2mult[unit] / mlt))
| #include <iostream>
#include <iomanip>
using namespace std;
class ormConverter
{
public:
ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),
MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}
void convert( char c, float l )
{
system( "cls" );
cout << endl << l;
switch( c )
{
case 'A': cout << " Arshin to:"; l *= AR; break;
case 'C': cout << " Centimeter to:"; l *= CE; break;
case 'D': cout << " Diuym to:"; l *= DI; break;
case 'F': cout << " Fut to:"; l *= FU; break;
case 'K': cout << " Kilometer to:"; l *= KI; break;
case 'L': cout << " Liniya to:"; l *= LI; break;
case 'M': cout << " Meter to:"; l *= ME; break;
case 'I': cout << " Milia to:"; l *= MI; break;
case 'P': cout << " Piad to:"; l *= PI; break;
case 'S': cout << " Sazhen to:"; l *= SA; break;
case 'T': cout << " Tochka to:"; l *= TO; break;
case 'V': cout << " Vershok to:"; l *= VE; break;
case 'E': cout << " Versta to:"; l *= VR;
}
float ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,
mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;
cout << left << endl << "=================" << endl
<< setw( 12 ) << "Arshin:" << ar << endl << setw( 12 ) << "Centimeter:" << ce << endl
<< setw( 12 ) << "Diuym:" << di << endl << setw( 12 ) << "Fut:" << fu << endl
<< setw( 12 ) << "Kilometer:" << ki << endl << setw( 12 ) << "Liniya:" << li << endl
<< setw( 12 ) << "Meter:" << me << endl << setw( 12 ) << "Milia:" << mi << endl
<< setw( 12 ) << "Piad:" << pi << endl << setw( 12 ) << "Sazhen:" << sa << endl
<< setw( 12 ) << "Tochka:" << to << endl << setw( 12 ) << "Vershok:" << ve << endl
<< setw( 12 ) << "Versta:" << vr << endl << endl << endl;
}
private:
const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;
};
int _tmain(int argc, _TCHAR* argv[])
{
ormConverter c;
char s; float l;
while( true )
{
cout << "What unit:\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\n";
cin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;
cout << "Length (0 to Quit): "; cin >> l; if( l == 0 ) return 0;
c.convert( s, l ); system( "pause" ); system( "cls" );
}
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original Python snippet. | import subprocess
import time
class Tlogger(object):
def __init__(self):
self.counts = 0
self.tottime = 0.0
self.laststart = 0.0
self.lastreport = time.time()
def logstart(self):
self.laststart = time.time()
def logend(self):
self.counts +=1
self.tottime += (time.time()-self.laststart)
if (time.time()-self.lastreport)>5.0:
self.report()
def report(self):
if ( self.counts > 4*self.tottime):
print "Subtask execution rate: %f times/second"% (self.counts/self.tottime);
else:
print "Average execution time: %f seconds"%(self.tottime/self.counts);
self.lastreport = time.time()
def taskTimer( n, subproc_args ):
logger = Tlogger()
for x in range(n):
logger.logstart()
p = subprocess.Popen(subproc_args)
p.wait()
logger.logend()
logger.report()
import timeit
import sys
def main( ):
s =
timer = timeit.Timer(s)
rzlts = timer.repeat(5, 5000)
for t in rzlts:
print "Time for 5000 executions of statement = ",t
print "
print "Command:",sys.argv[2:]
print ""
for k in range(3):
taskTimer( int(sys.argv[1]), sys.argv[2:])
main()
| #include <iostream>
#include <ctime>
class CRateState
{
protected:
time_t m_lastFlush;
time_t m_period;
size_t m_tickCount;
public:
CRateState(time_t period);
void Tick();
};
CRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),
m_period(period),
m_tickCount(0)
{ }
void CRateState::Tick()
{
m_tickCount++;
time_t now = std::time(NULL);
if((now - m_lastFlush) >= m_period)
{
size_t tps = 0.0;
if(m_tickCount > 0)
tps = m_tickCount / (now - m_lastFlush);
std::cout << tps << " tics per second" << std::endl;
m_tickCount = 0;
m_lastFlush = now;
}
}
void something_we_do()
{
volatile size_t anchor = 0;
for(size_t x = 0; x < 0xffff; ++x)
{
anchor = x;
}
}
int main()
{
time_t start = std::time(NULL);
CRateState rateWatch(5);
for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))
{
something_we_do();
rateWatch.Tick();
}
return 0;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. | def divisors(n):
divs = [1]
for ii in range(2, int(n ** 0.5) + 3):
if n % ii == 0:
divs.append(ii)
divs.append(int(n / ii))
divs.append(n)
return list(set(divs))
def sequence(max_n=None):
previous = 0
n = 0
while True:
n += 1
ii = previous
if max_n is not None:
if n > max_n:
break
while True:
ii += 1
if len(divisors(ii)) == n:
yield ii
previous = ii
break
if __name__ == '__main__':
for item in sequence(15):
print(item)
| #include <iostream>
#define MAX 15
using namespace std;
int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
int main() {
cout << "The first " << MAX << " terms of the sequence are:" << endl;
for (int i = 1, next = 1; next <= MAX; ++i) {
if (next == count_divisors(i)) {
cout << i << " ";
next++;
}
}
cout << endl;
return 0;
}
|
Write a version of this Python function in C++ with identical behavior. | from math import floor
from collections import deque
from typing import Dict, Generator
def padovan_r() -> Generator[int, None, None]:
last = deque([1, 1, 1], 4)
while True:
last.append(last[-2] + last[-3])
yield last.popleft()
_p, _s = 1.324717957244746025960908854, 1.0453567932525329623
def padovan_f(n: int) -> int:
return floor(_p**(n-1) / _s + .5)
def padovan_l(start: str='A',
rules: Dict[str, str]=dict(A='B', B='C', C='AB')
) -> Generator[str, None, None]:
axiom = start
while True:
yield axiom
axiom = ''.join(rules[ch] for ch in axiom)
if __name__ == "__main__":
from itertools import islice
print("The first twenty terms of the sequence.")
print(str([padovan_f(n) for n in range(20)])[1:-1])
r_generator = padovan_r()
if all(next(r_generator) == padovan_f(n) for n in range(64)):
print("\nThe recurrence and floor based algorithms match to n=63 .")
else:
print("\nThe recurrence and floor based algorithms DIFFER!")
print("\nThe first 10 L-system string-lengths and strings")
l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))
print('\n'.join(f" {len(string):3} {repr(string)}"
for string in islice(l_generator, 10)))
r_generator = padovan_r()
l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))
if all(len(next(l_generator)) == padovan_f(n) == next(r_generator)
for n in range(32)):
print("\nThe L-system, recurrence and floor based algorithms match to n=31 .")
else:
print("\nThe L-system, recurrence and floor based algorithms DIFFER!")
| #include <iostream>
#include <map>
#include <cmath>
int pRec(int n) {
static std::map<int,int> memo;
auto it = memo.find(n);
if (it != memo.end()) return it->second;
if (n <= 2) memo[n] = 1;
else memo[n] = pRec(n-2) + pRec(n-3);
return memo[n];
}
int pFloor(int n) {
long const double p = 1.324717957244746025960908854;
long const double s = 1.0453567932525329623;
return std::pow(p, n-1)/s + 0.5;
}
std::string& lSystem(int n) {
static std::map<int,std::string> memo;
auto it = memo.find(n);
if (it != memo.end()) return it->second;
if (n == 0) memo[n] = "A";
else {
memo[n] = "";
for (char ch : memo[n-1]) {
switch(ch) {
case 'A': memo[n].push_back('B'); break;
case 'B': memo[n].push_back('C'); break;
case 'C': memo[n].append("AB"); break;
}
}
}
return memo[n];
}
using pFn = int(*)(int);
void compare(pFn f1, pFn f2, const char* descr, int stop) {
std::cout << "The " << descr << " functions ";
int i;
for (i=0; i<stop; i++) {
int n1 = f1(i);
int n2 = f2(i);
if (n1 != n2) {
std::cout << "do not match at " << i
<< ": " << n1 << " != " << n2 << ".\n";
break;
}
}
if (i == stop) {
std::cout << "match from P_0 to P_" << stop << ".\n";
}
}
int main() {
std::cout << "P_0 .. P_19: ";
for (int i=0; i<20; i++) std::cout << pRec(i) << " ";
std::cout << "\n";
compare(pFloor, pRec, "floor- and recurrence-based", 64);
std::cout << "\nThe first 10 L-system strings are:\n";
for (int i=0; i<10; i++) std::cout << lSystem(i) << "\n";
std::cout << "\n";
compare(pFloor, [](int n){return (int)lSystem(n).length();},
"floor- and L-system-based", 32);
return 0;
}
|
Generate a C++ translation of this Python snippet without changing its computational steps. | def setup():
size(800, 400)
background(255)
stroke(0, 255, 0)
tree(width / 2.3, height, width / 1.8, height, 10)
def tree(x1, y1, x2, y2, depth):
if depth <= 0: return
dx = (x2 - x1)
dy = (y1 - y2)
x3 = (x2 - dy)
y3 = (y2 - dx)
x4 = (x1 - dy)
y4 = (y1 - dx)
x5 = (x4 + 0.5 * (dx - dy))
y5 = (y4 - 0.5 * (dx + dy))
beginShape()
fill(0.0, 255.0 / depth, 0.0)
vertex(x1, y1)
vertex(x2, y2)
vertex(x3, y3)
vertex(x4, y4)
vertex(x1, y1)
endShape()
beginShape()
fill(0.0, 255.0 / depth, 0.0)
vertex(x3, y3)
vertex(x4, y4)
vertex(x5, y5)
vertex(x3, y3)
endShape()
tree(x4, y4, x5, y5, depth - 1)
tree(x5, y5, x3, y3, depth - 1)
| #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;
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 tree {
public:
tree() {
bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();
clr[0] = RGB( 90, 30, 0 ); clr[1] = RGB( 255, 255, 0 );
clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );
clr[4] = RGB( 255, 0, 0 ); clr[5] = RGB( 0, 100, 190 );
}
void draw( int it, POINT a, POINT b ) {
if( !it ) return;
bmp.setPenColor( clr[it % 6] );
POINT df = { b.x - a.x, a.y - b.y }; POINT c = { b.x - df.y, b.y - df.x };
POINT d = { a.x - df.y, a.y - df.x };
POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};
drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );
}
void save( std::string p ) { bmp.saveBitmap( p ); }
private:
void drawSqr( POINT a, POINT b, POINT c, POINT d ) {
HDC dc = bmp.getDC();
MoveToEx( dc, a.x, a.y, NULL );
LineTo( dc, b.x, b.y );
LineTo( dc, c.x, c.y );
LineTo( dc, d.x, d.y );
LineTo( dc, a.x, a.y );
}
myBitmap bmp;
DWORD clr[6];
};
int main( int argc, char* argv[] ) {
POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },
ptB = { ptA.x + LINE_LEN, ptA.y };
tree t; t.draw( 12, ptA, ptB );
t.save( "?:/pt.bmp" );
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd(prev = lambda: None):
a = char_in()
if not a.isalpha():
prev()
char_out(a)
return a != '.'
def clos():
char_out(a)
prev()
return odd(clos)
def even():
while True:
c = char_in()
char_out(c)
if not c.isalpha(): return c != '.'
e = False
while odd() if e else even():
e = not e
| #include <iostream>
#include <cctype>
#include <functional>
using namespace std;
bool odd()
{
function<void ()> prev = []{};
while(true) {
int c = cin.get();
if (!isalpha(c)) {
prev();
cout.put(c);
return c != '.';
}
prev = [=] { cout.put(c); prev(); };
}
}
bool even()
{
while(true) {
int c;
cout.put(c = cin.get());
if (!isalpha(c)) return c != '.';
}
}
int main()
{
bool e = false;
while( e ? odd() : even() ) e = !e;
return 0;
}
|
Generate an equivalent C++ version of this Python code. |
a1 = [0, 1403580, -810728]
m1 = 2**32 - 209
a2 = [527612, 0, -1370589]
m2 = 2**32 - 22853
d = m1 + 1
class MRG32k3a():
def __init__(self, seed_state=123):
self.seed(seed_state)
def seed(self, seed_state):
assert 0 <seed_state < d, f"Out of Range 0 x < {d}"
self.x1 = [seed_state, 0, 0]
self.x2 = [seed_state, 0, 0]
def next_int(self):
"return random int in range 0..d"
x1i = sum(aa * xx for aa, xx in zip(a1, self.x1)) % m1
x2i = sum(aa * xx for aa, xx in zip(a2, self.x2)) % m2
self.x1 = [x1i] + self.x1[:2]
self.x2 = [x2i] + self.x2[:2]
z = (x1i - x2i) % m1
answer = (z + 1)
return answer
def next_float(self):
"return random float between 0 and 1"
return self.next_int() / d
if __name__ == '__main__':
random_gen = MRG32k3a()
random_gen.seed(1234567)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist)
| #include <array>
#include <iostream>
int64_t mod(int64_t x, int64_t y) {
int64_t m = x % y;
if (m < 0) {
if (y < 0) {
return m - y;
} else {
return m + y;
}
}
return m;
}
class RNG {
private:
const std::array<int64_t, 3> a1{ 0, 1403580, -810728 };
const int64_t m1 = (1LL << 32) - 209;
std::array<int64_t, 3> x1;
const std::array<int64_t, 3> a2{ 527612, 0, -1370589 };
const int64_t m2 = (1LL << 32) - 22853;
std::array<int64_t, 3> x2;
const int64_t d = (1LL << 32) - 209 + 1;
public:
void seed(int64_t state) {
x1 = { state, 0, 0 };
x2 = { state, 0, 0 };
}
int64_t next_int() {
int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);
int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);
int64_t z = mod(x1i - x2i, m1);
x1 = { x1i, x1[0], x1[1] };
x2 = { x2i, x2[0], x2[1] };
return z + 1;
}
double next_float() {
return static_cast<double>(next_int()) / d;
}
};
int main() {
RNG rng;
rng.seed(1234567);
std::cout << rng.next_int() << '\n';
std::cout << rng.next_int() << '\n';
std::cout << rng.next_int() << '\n';
std::cout << rng.next_int() << '\n';
std::cout << rng.next_int() << '\n';
std::cout << '\n';
std::array<int, 5> counts{ 0, 0, 0, 0, 0 };
rng.seed(987654321);
for (size_t i = 0; i < 100000; i++) {
auto value = floor(rng.next_float() * 5.0);
counts[value]++;
}
for (size_t i = 0; i < counts.size(); i++) {
std::cout << i << ": " << counts[i] << '\n';
}
return 0;
}
|
Change the programming language of this snippet from Python to C++ without modifying what it does. | def stern_brocot(predicate=lambda series: len(series) < 20):
sb, i = [1, 1], 0
while predicate(sb):
sb += [sum(sb[i:i + 2]), sb[i + 1]]
i += 1
return sb
if __name__ == '__main__':
from fractions import gcd
n_first = 15
print('The first %i values:\n ' % n_first,
stern_brocot(lambda series: len(series) < n_first)[:n_first])
print()
n_max = 10
for n_occur in list(range(1, n_max + 1)) + [100]:
print('1-based index of the first occurrence of %3i in the series:' % n_occur,
stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)
print()
n_gcd = 1000
s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]
assert all(gcd(prev, this) == 1
for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
| #include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
unsigned gcd( unsigned i, unsigned j ) {
return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;
}
void createSequence( std::vector<unsigned>& seq, int c ) {
if( 1500 == seq.size() ) return;
unsigned t = seq.at( c ) + seq.at( c + 1 );
seq.push_back( t );
seq.push_back( seq.at( c + 1 ) );
createSequence( seq, c + 1 );
}
int main( int argc, char* argv[] ) {
std::vector<unsigned> seq( 2, 1 );
createSequence( seq, 0 );
std::cout << "First fifteen members of the sequence:\n ";
for( unsigned x = 0; x < 15; x++ ) {
std::cout << seq[x] << " ";
}
std::cout << "\n\n";
for( unsigned x = 1; x < 11; x++ ) {
std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );
if( i != seq.end() ) {
std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n";
}
}
std::cout << "\n";
std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );
if( i != seq.end() ) {
std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n";
}
std::cout << "\n";
unsigned g;
bool f = false;
for( int x = 0, y = 1; x < 1000; x++, y++ ) {
g = gcd( seq[x], seq[y] );
if( g != 1 ) f = true;
std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", "
<< seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" );
}
std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n";
return 0;
}
|
Write the same code in C++ as shown below in Python. | def stern_brocot(predicate=lambda series: len(series) < 20):
sb, i = [1, 1], 0
while predicate(sb):
sb += [sum(sb[i:i + 2]), sb[i + 1]]
i += 1
return sb
if __name__ == '__main__':
from fractions import gcd
n_first = 15
print('The first %i values:\n ' % n_first,
stern_brocot(lambda series: len(series) < n_first)[:n_first])
print()
n_max = 10
for n_occur in list(range(1, n_max + 1)) + [100]:
print('1-based index of the first occurrence of %3i in the series:' % n_occur,
stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)
print()
n_gcd = 1000
s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]
assert all(gcd(prev, this) == 1
for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
| #include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
unsigned gcd( unsigned i, unsigned j ) {
return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;
}
void createSequence( std::vector<unsigned>& seq, int c ) {
if( 1500 == seq.size() ) return;
unsigned t = seq.at( c ) + seq.at( c + 1 );
seq.push_back( t );
seq.push_back( seq.at( c + 1 ) );
createSequence( seq, c + 1 );
}
int main( int argc, char* argv[] ) {
std::vector<unsigned> seq( 2, 1 );
createSequence( seq, 0 );
std::cout << "First fifteen members of the sequence:\n ";
for( unsigned x = 0; x < 15; x++ ) {
std::cout << seq[x] << " ";
}
std::cout << "\n\n";
for( unsigned x = 1; x < 11; x++ ) {
std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );
if( i != seq.end() ) {
std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n";
}
}
std::cout << "\n";
std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );
if( i != seq.end() ) {
std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n";
}
std::cout << "\n";
unsigned g;
bool f = false;
for( int x = 0, y = 1; x < 1000; x++, y++ ) {
g = gcd( seq[x], seq[y] );
if( g != 1 ) f = true;
std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", "
<< seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" );
}
std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n";
return 0;
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | from collections import namedtuple
import math
class I(namedtuple('Imprecise', 'value, delta')):
'Imprecise type: I(value=0.0, delta=0.0)'
__slots__ = ()
def __new__(_cls, value=0.0, delta=0.0):
'Defaults to 0.0 ± delta'
return super().__new__(_cls, float(value), abs(float(delta)))
def reciprocal(self):
return I(1. / self.value, self.delta / (self.value**2))
def __str__(self):
'Shorter form of Imprecise as string'
return 'I(%g, %g)' % self
def __neg__(self):
return I(-self.value, self.delta)
def __add__(self, other):
if type(other) == I:
return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 )
try:
c = float(other)
except:
return NotImplemented
return I(self.value + c, self.delta)
def __sub__(self, other):
return self + (-other)
def __radd__(self, other):
return I.__add__(self, other)
def __mul__(self, other):
if type(other) == I:
a1,b1 = self
a2,b2 = other
f = a1 * a2
return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 )
try:
c = float(other)
except:
return NotImplemented
return I(self.value * c, self.delta * c)
def __pow__(self, other):
if type(other) == I:
return NotImplemented
try:
c = float(other)
except:
return NotImplemented
f = self.value ** c
return I(f, f * c * (self.delta / self.value))
def __rmul__(self, other):
return I.__mul__(self, other)
def __truediv__(self, other):
if type(other) == I:
return self.__mul__(other.reciprocal())
try:
c = float(other)
except:
return NotImplemented
return I(self.value / c, self.delta / c)
def __rtruediv__(self, other):
return other * self.reciprocal()
__div__, __rdiv__ = __truediv__, __rtruediv__
Imprecise = I
def distance(p1, p2):
x1, y1 = p1
x2, y2 = p2
return ((x1 - x2)**2 + (y1 - y2)**2)**0.5
x1 = I(100, 1.1)
x2 = I(200, 2.2)
y1 = I( 50, 1.2)
y2 = I(100, 2.3)
p1, p2 = (x1, y1), (x2, y2)
print("Distance between points\n p1: %s\n and p2: %s\n = %r" % (
p1, p2, distance(p1, p2)))
| #pragma once
#include <cmath>
#include <string>
#include <sstream>
#include <iomanip>
class Approx {
public:
Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}
operator std::string() const {
std::ostringstream os("");
os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s << std::ends;
return os.str();
}
Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }
Approx operator +(double d) const { return Approx(v + d, s); }
Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }
Approx operator -(double d) const { return Approx(v - d, s); }
Approx operator *(const Approx& a) const {
const double t = v * a.v;
return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));
}
Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }
Approx operator /(const Approx& a) const {
const double t = v / a.v;
return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));
}
Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }
Approx pow(double d) const {
const double t = ::pow(v, d);
return Approx(t, fabs(t * d * s / v));
}
private:
double v, s;
};
|
Please provide an equivalent version of this Python code in C++. | def bags(n,cache={}):
if not n: return [(0, "")]
upto = sum([bags(x) for x in range(n-1, 0, -1)], [])
return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)]
def bagchain(x, n, bb, start=0):
if not n: return [x]
out = []
for i in range(start, len(bb)):
c,s = bb[i]
if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)
return out
def replace_brackets(s):
depth,out = 0,[]
for c in s:
if c == '(':
out.append("([{"[depth%3])
depth += 1
else:
depth -= 1
out.append(")]}"[depth%3])
return "".join(out)
for x in bags(5): print(replace_brackets(x[1]))
| #include <iostream>
#include <vector>
std::vector<long> TREE_LIST;
std::vector<int> OFFSET;
void init() {
for (size_t i = 0; i < 32; i++) {
if (i == 1) {
OFFSET.push_back(1);
} else {
OFFSET.push_back(0);
}
}
}
void append(long t) {
TREE_LIST.push_back(1 | (t << 1));
}
void show(long t, int l) {
while (l-- > 0) {
if (t % 2 == 1) {
std::cout << '(';
} else {
std::cout << ')';
}
t = t >> 1;
}
}
void listTrees(int n) {
for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {
show(TREE_LIST[i], 2 * n);
std::cout << '\n';
}
}
void assemble(int n, long t, int sl, int pos, int rem) {
if (rem == 0) {
append(t);
return;
}
auto pp = pos;
auto ss = sl;
if (sl > rem) {
ss = rem;
pp = OFFSET[ss];
} else if (pp >= OFFSET[ss + 1]) {
ss--;
if (ss == 0) {
return;
}
pp = OFFSET[ss];
}
assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);
assemble(n, t, ss, pp + 1, rem);
}
void makeTrees(int n) {
if (OFFSET[n + 1] != 0) {
return;
}
if (n > 0) {
makeTrees(n - 1);
}
assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);
OFFSET[n + 1] = TREE_LIST.size();
}
void test(int n) {
if (n < 1 || n > 12) {
throw std::runtime_error("Argument must be between 1 and 12");
}
append(0);
makeTrees(n);
std::cout << "Number of " << n << "-trees: " << OFFSET[n + 1] - OFFSET[n] << '\n';
listTrees(n);
}
int main() {
init();
test(5);
return 0;
}
|
Convert this Python block to C++, preserving its control flow and logic. | def bags(n,cache={}):
if not n: return [(0, "")]
upto = sum([bags(x) for x in range(n-1, 0, -1)], [])
return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)]
def bagchain(x, n, bb, start=0):
if not n: return [x]
out = []
for i in range(start, len(bb)):
c,s = bb[i]
if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)
return out
def replace_brackets(s):
depth,out = 0,[]
for c in s:
if c == '(':
out.append("([{"[depth%3])
depth += 1
else:
depth -= 1
out.append(")]}"[depth%3])
return "".join(out)
for x in bags(5): print(replace_brackets(x[1]))
| #include <iostream>
#include <vector>
std::vector<long> TREE_LIST;
std::vector<int> OFFSET;
void init() {
for (size_t i = 0; i < 32; i++) {
if (i == 1) {
OFFSET.push_back(1);
} else {
OFFSET.push_back(0);
}
}
}
void append(long t) {
TREE_LIST.push_back(1 | (t << 1));
}
void show(long t, int l) {
while (l-- > 0) {
if (t % 2 == 1) {
std::cout << '(';
} else {
std::cout << ')';
}
t = t >> 1;
}
}
void listTrees(int n) {
for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {
show(TREE_LIST[i], 2 * n);
std::cout << '\n';
}
}
void assemble(int n, long t, int sl, int pos, int rem) {
if (rem == 0) {
append(t);
return;
}
auto pp = pos;
auto ss = sl;
if (sl > rem) {
ss = rem;
pp = OFFSET[ss];
} else if (pp >= OFFSET[ss + 1]) {
ss--;
if (ss == 0) {
return;
}
pp = OFFSET[ss];
}
assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);
assemble(n, t, ss, pp + 1, rem);
}
void makeTrees(int n) {
if (OFFSET[n + 1] != 0) {
return;
}
if (n > 0) {
makeTrees(n - 1);
}
assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);
OFFSET[n + 1] = TREE_LIST.size();
}
void test(int n) {
if (n < 1 || n > 12) {
throw std::runtime_error("Argument must be between 1 and 12");
}
append(0);
makeTrees(n);
std::cout << "Number of " << n << "-trees: " << OFFSET[n + 1] - OFFSET[n] << '\n';
listTrees(n);
}
int main() {
init();
test(5);
return 0;
}
|
Translate the given Python code snippet into C++ without altering its behavior. |
from itertools import takewhile
from functools import reduce
def longestCommonSuffix(xs):
def allSame(cs):
h = cs[0]
return all(h == c for c in cs[1:])
def firstCharPrepended(s, cs):
return cs[0] + s
return reduce(
firstCharPrepended,
takewhile(
allSame,
zip(*(reversed(x) for x in xs))
),
''
)
def main():
samples = [
[
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
], [
"Sondag", "Maandag", "Dinsdag", "Woensdag",
"Donderdag", "Vrydag", "Saterdag"
]
]
for xs in samples:
print(
longestCommonSuffix(xs)
)
if __name__ == '__main__':
main()
| #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
std::string lcs(const std::vector<std::string>& strs) {
std::vector<std::string::const_reverse_iterator> backs;
std::string s;
if (strs.size() == 0) return "";
if (strs.size() == 1) return strs[0];
for (auto& str : strs) backs.push_back(str.crbegin());
while (backs[0] != strs[0].crend()) {
char ch = *backs[0]++;
for (std::size_t i = 1; i<strs.size(); i++) {
if (backs[i] == strs[i].crend()) goto done;
if (*backs[i] != ch) goto done;
backs[i]++;
}
s.push_back(ch);
}
done:
reverse(s.begin(), s.end());
return s;
}
void test(const std::vector<std::string>& strs) {
std::cout << "[";
for (std::size_t i = 0; i<strs.size(); i++) {
std::cout << '"' << strs[i] << '"';
if (i != strs.size()-1) std::cout << ", ";
}
std::cout << "] -> `" << lcs(strs) << "`\n";
}
int main() {
std::vector<std::string> t1 = {"baabababc", "baabc", "bbabc"};
std::vector<std::string> t2 = {"baabababc", "baabc", "bbazc"};
std::vector<std::string> t3 =
{"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"};
std::vector<std::string> t4 = {"longest", "common", "suffix"};
std::vector<std::string> t5 = {""};
std::vector<std::string> t6 = {};
std::vector<std::string> t7 = {"foo", "foo", "foo", "foo"};
std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};
for (auto t : tests) test(t);
return 0;
}
|
Write a version of this Python function in C++ with identical behavior. | from numpy import array, tril, sum
A = [[1,3,7,8,10],
[2,4,16,14,4],
[3,1,9,18,11],
[12,14,17,18,20],
[7,1,3,9,5]]
print(sum(tril(A, -1)))
| #include <iostream>
#include <vector>
template<typename T>
T sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {
T sum = 0;
for (std::size_t y = 0; y < matrix.size(); y++)
for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)
sum += matrix[y][x];
return sum;
}
int main() {
std::vector<std::vector<int>> matrix = {
{1,3,7,8,10},
{2,4,16,14,4},
{3,1,9,18,11},
{12,14,17,18,20},
{7,1,3,9,5}
};
std::cout << sum_below_diagonal(matrix) << std::endl;
return 0;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | import io
FASTA=
infile = io.StringIO(FASTA)
def fasta_parse(infile):
key = ''
for line in infile:
if line.startswith('>'):
if key:
yield key, val
key, val = line[1:].rstrip().split()[0], ''
elif key:
val += line.rstrip()
if key:
yield key, val
print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
| #include <iostream>
#include <fstream>
int main( int argc, char **argv ){
if( argc <= 1 ){
std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl;
return -1;
}
std::ifstream input(argv[1]);
if(!input.good()){
std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << std::endl;
return -1;
}
std::string line, name, content;
while( std::getline( input, line ).good() ){
if( line.empty() || line[0] == '>' ){
if( !name.empty() ){
std::cout << name << " : " << content << std::endl;
name.clear();
}
if( !line.empty() ){
name = line.substr(1);
}
content.clear();
} else if( !name.empty() ){
if( line.find(' ') != std::string::npos ){
name.clear();
content.clear();
} else {
content += line;
}
}
}
if( !name.empty() ){
std::cout << name << " : " << content << std::endl;
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | from elementary_cellular_automaton import eca, eca_wrap
def rule30bytes(lencells=100):
cells = '1' + '0' * (lencells - 1)
gen = eca(cells, 30)
while True:
yield int(''.join(next(gen)[0] for i in range(8)), 2)
if __name__ == '__main__':
print([b for i,b in zip(range(10), rule30bytes())])
| #include <bitset>
#include <stdio.h>
#define SIZE 80
#define RULE 30
#define RULE_TEST(x) (RULE & 1 << (7 & (x)))
void evolve(std::bitset<SIZE> &s) {
int i;
std::bitset<SIZE> t(0);
t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );
t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] );
for (i = 1; i < SIZE-1; i++)
t[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );
for (i = 0; i < SIZE; i++) s[i] = t[i];
}
void show(std::bitset<SIZE> s) {
int i;
for (i = SIZE; i--; ) printf("%c", s[i] ? '#' : ' ');
printf("|\n");
}
unsigned char byte(std::bitset<SIZE> &s) {
unsigned char b = 0;
int i;
for (i=8; i--; ) {
b |= s[0] << i;
evolve(s);
}
return b;
}
int main() {
int i;
std::bitset<SIZE> state(1);
for (i=10; i--; )
printf("%u%c", byte(state), i ? ' ' : '\n');
return 0;
}
|
Change the following Python code into C++ without altering its purpose. | mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
CONST = 6364136223846793005
class PCG32():
def __init__(self, seed_state=None, seed_sequence=None):
if all(type(x) == int for x in (seed_state, seed_sequence)):
self.seed(seed_state, seed_sequence)
else:
self.state = self.inc = 0
def seed(self, seed_state, seed_sequence):
self.state = 0
self.inc = ((seed_sequence << 1) | 1) & mask64
self.next_int()
self.state = (self.state + seed_state)
self.next_int()
def next_int(self):
"return random 32 bit unsigned int"
old = self.state
self.state = ((old * CONST) + self.inc) & mask64
xorshifted = (((old >> 18) ^ old) >> 27) & mask32
rot = (old >> 59) & mask32
answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))
answer = answer &mask32
return answer
def next_float(self):
"return random float between 0 and 1"
return self.next_int() / (1 << 32)
if __name__ == '__main__':
random_gen = PCG32()
random_gen.seed(42, 54)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321, 1)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist)
| #include <array>
#include <iostream>
class PCG32 {
private:
const uint64_t N = 6364136223846793005;
uint64_t state = 0x853c49e6748fea9b;
uint64_t inc = 0xda3e39cb94b95bdb;
public:
uint32_t nextInt() {
uint64_t old = state;
state = old * N + inc;
uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
uint32_t rot = old >> 59;
return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
}
double nextFloat() {
return ((double)nextInt()) / (1LL << 32);
}
void seed(uint64_t seed_state, uint64_t seed_sequence) {
state = 0;
inc = (seed_sequence << 1) | 1;
nextInt();
state = state + seed_state;
nextInt();
}
};
int main() {
auto r = new PCG32();
r->seed(42, 54);
std::cout << r->nextInt() << '\n';
std::cout << r->nextInt() << '\n';
std::cout << r->nextInt() << '\n';
std::cout << r->nextInt() << '\n';
std::cout << r->nextInt() << '\n';
std::cout << '\n';
std::array<int, 5> counts{ 0, 0, 0, 0, 0 };
r->seed(987654321, 1);
for (size_t i = 0; i < 100000; i++) {
int j = (int)floor(r->nextFloat() * 5.0);
counts[j]++;
}
std::cout << "The counts for 100,000 repetitions are:\n";
for (size_t i = 0; i < counts.size(); i++) {
std::cout << " " << i << " : " << counts[i] << '\n';
}
return 0;
}
|
Write a version of this Python function in C++ with identical behavior. | from turtle import *
import math
speed(0)
hideturtle()
part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)
hide_turtles = True
path_color = "black"
fill_color = "black"
def pentagon(t, s):
t.color(path_color, fill_color)
t.pendown()
t.right(36)
t.begin_fill()
for i in range(5):
t.forward(s)
t.right(72)
t.end_fill()
def sierpinski(i, t, s):
t.setheading(0)
new_size = s * side_ratio
if i > 1:
i -= 1
for j in range(4):
t.right(36)
short = s * side_ratio / part_ratio
dist = [short, s, s, short][j]
spawn = Turtle()
if hide_turtles:spawn.hideturtle()
spawn.penup()
spawn.setposition(t.position())
spawn.setheading(t.heading())
spawn.forward(dist)
sierpinski(i, spawn, new_size)
sierpinski(i, t, new_size)
else:
pentagon(t, s)
del t
def main():
t = Turtle()
t.hideturtle()
t.penup()
screen = t.getscreen()
y = screen.window_height()
t.goto(0, y/2-20)
i = 5
size = 300
size *= part_ratio
sierpinski(i, t, size)
main()
| #include <iomanip>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
constexpr double degrees(double deg) {
const double tau = 2.0 * M_PI;
return deg * tau / 360.0;
}
const double part_ratio = 2.0 * cos(degrees(72));
const double side_ratio = 1.0 / (part_ratio + 2.0);
struct Point {
double x, y;
friend std::ostream& operator<<(std::ostream& os, const Point& p);
};
std::ostream& operator<<(std::ostream& os, const Point& p) {
auto f(std::cout.flags());
os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';
std::cout.flags(f);
return os;
}
struct Turtle {
private:
Point pos;
double theta;
bool tracing;
public:
Turtle() : theta(0.0), tracing(false) {
pos.x = 0.0;
pos.y = 0.0;
}
Turtle(double x, double y) : theta(0.0), tracing(false) {
pos.x = x;
pos.y = y;
}
Point position() {
return pos;
}
void position(const Point& p) {
pos = p;
}
double heading() {
return theta;
}
void heading(double angle) {
theta = angle;
}
void forward(double dist) {
auto dx = dist * cos(theta);
auto dy = dist * sin(theta);
pos.x += dx;
pos.y += dy;
if (tracing) {
std::cout << pos;
}
}
void right(double angle) {
theta -= angle;
}
void begin_fill() {
if (!tracing) {
std::cout << "<polygon points=\"";
tracing = true;
}
}
void end_fill() {
if (tracing) {
std::cout << "\"/>\n";
tracing = false;
}
}
};
void pentagon(Turtle& turtle, double size) {
turtle.right(degrees(36));
turtle.begin_fill();
for (size_t i = 0; i < 5; i++) {
turtle.forward(size);
turtle.right(degrees(72));
}
turtle.end_fill();
}
void sierpinski(int order, Turtle& turtle, double size) {
turtle.heading(0.0);
auto new_size = size * side_ratio;
if (order-- > 1) {
for (size_t j = 0; j < 4; j++) {
turtle.right(degrees(36));
double small = size * side_ratio / part_ratio;
auto distList = { small, size, size, small };
auto dist = *(distList.begin() + j);
Turtle spawn{ turtle.position().x, turtle.position().y };
spawn.heading(turtle.heading());
spawn.forward(dist);
sierpinski(order, spawn, new_size);
}
sierpinski(order, turtle, new_size);
} else {
pentagon(turtle, size);
}
if (order > 0) {
std::cout << '\n';
}
}
int main() {
const int order = 5;
double size = 500;
Turtle turtle{ size / 2.0, size };
std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n";
std::cout << "<!DOCTYPE svg PUBLIC \" -
std::cout << " \"http:
std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n";
std::cout << " version=\"1.1\" xmlns=\"http:
size *= part_ratio;
sierpinski(order, turtle, size);
std::cout << "</svg>";
}
|
Keep all operations the same but rewrite the snippet in C++. | from turtle import *
import math
speed(0)
hideturtle()
part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)
hide_turtles = True
path_color = "black"
fill_color = "black"
def pentagon(t, s):
t.color(path_color, fill_color)
t.pendown()
t.right(36)
t.begin_fill()
for i in range(5):
t.forward(s)
t.right(72)
t.end_fill()
def sierpinski(i, t, s):
t.setheading(0)
new_size = s * side_ratio
if i > 1:
i -= 1
for j in range(4):
t.right(36)
short = s * side_ratio / part_ratio
dist = [short, s, s, short][j]
spawn = Turtle()
if hide_turtles:spawn.hideturtle()
spawn.penup()
spawn.setposition(t.position())
spawn.setheading(t.heading())
spawn.forward(dist)
sierpinski(i, spawn, new_size)
sierpinski(i, t, new_size)
else:
pentagon(t, s)
del t
def main():
t = Turtle()
t.hideturtle()
t.penup()
screen = t.getscreen()
y = screen.window_height()
t.goto(0, y/2-20)
i = 5
size = 300
size *= part_ratio
sierpinski(i, t, size)
main()
| #include <iomanip>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
constexpr double degrees(double deg) {
const double tau = 2.0 * M_PI;
return deg * tau / 360.0;
}
const double part_ratio = 2.0 * cos(degrees(72));
const double side_ratio = 1.0 / (part_ratio + 2.0);
struct Point {
double x, y;
friend std::ostream& operator<<(std::ostream& os, const Point& p);
};
std::ostream& operator<<(std::ostream& os, const Point& p) {
auto f(std::cout.flags());
os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';
std::cout.flags(f);
return os;
}
struct Turtle {
private:
Point pos;
double theta;
bool tracing;
public:
Turtle() : theta(0.0), tracing(false) {
pos.x = 0.0;
pos.y = 0.0;
}
Turtle(double x, double y) : theta(0.0), tracing(false) {
pos.x = x;
pos.y = y;
}
Point position() {
return pos;
}
void position(const Point& p) {
pos = p;
}
double heading() {
return theta;
}
void heading(double angle) {
theta = angle;
}
void forward(double dist) {
auto dx = dist * cos(theta);
auto dy = dist * sin(theta);
pos.x += dx;
pos.y += dy;
if (tracing) {
std::cout << pos;
}
}
void right(double angle) {
theta -= angle;
}
void begin_fill() {
if (!tracing) {
std::cout << "<polygon points=\"";
tracing = true;
}
}
void end_fill() {
if (tracing) {
std::cout << "\"/>\n";
tracing = false;
}
}
};
void pentagon(Turtle& turtle, double size) {
turtle.right(degrees(36));
turtle.begin_fill();
for (size_t i = 0; i < 5; i++) {
turtle.forward(size);
turtle.right(degrees(72));
}
turtle.end_fill();
}
void sierpinski(int order, Turtle& turtle, double size) {
turtle.heading(0.0);
auto new_size = size * side_ratio;
if (order-- > 1) {
for (size_t j = 0; j < 4; j++) {
turtle.right(degrees(36));
double small = size * side_ratio / part_ratio;
auto distList = { small, size, size, small };
auto dist = *(distList.begin() + j);
Turtle spawn{ turtle.position().x, turtle.position().y };
spawn.heading(turtle.heading());
spawn.forward(dist);
sierpinski(order, spawn, new_size);
}
sierpinski(order, turtle, new_size);
} else {
pentagon(turtle, size);
}
if (order > 0) {
std::cout << '\n';
}
}
int main() {
const int order = 5;
double size = 500;
Turtle turtle{ size / 2.0, size };
std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n";
std::cout << "<!DOCTYPE svg PUBLIC \" -
std::cout << " \"http:
std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n";
std::cout << " version=\"1.1\" xmlns=\"http:
size *= part_ratio;
sierpinski(order, turtle, size);
std::cout << "</svg>";
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)//2, 0, -1):
if text.startswith(text[x:]): return x
return 0
matchstr =
for line in matchstr.split():
ln = is_repeated(line)
print('%r has a repetition length of %i i.e. %s'
% (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))
| #include <string>
#include <vector>
#include <boost/regex.hpp>
bool is_repstring( const std::string & teststring , std::string & repunit ) {
std::string regex( "^(.+)\\1+(.*)$" ) ;
boost::regex e ( regex ) ;
boost::smatch what ;
if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {
std::string firstbracket( what[1 ] ) ;
std::string secondbracket( what[ 2 ] ) ;
if ( firstbracket.length( ) >= secondbracket.length( ) &&
firstbracket.find( secondbracket ) != std::string::npos ) {
repunit = firstbracket ;
}
}
return !repunit.empty( ) ;
}
int main( ) {
std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" ,
"1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ;
std::string theRep ;
for ( std::string myString : teststrings ) {
if ( is_repstring( myString , theRep ) ) {
std::cout << myString << " is a rep string! Here is a repeating string:\n" ;
std::cout << theRep << " " ;
}
else {
std::cout << myString << " is no rep string!" ;
}
theRep.clear( ) ;
std::cout << std::endl ;
}
return 0 ;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | 'c' == "c"
'text' == "text"
' " '
" ' "
'\x20' == ' '
u'unicode string'
u'\u05d0'
| auto strA = R"(this is
a newline-separated
raw string)";
|
Generate an equivalent C++ version of this Python code. | from collections import defaultdict, Counter
def getwords(minlength=11, fname='unixdict.txt'):
"Return set of lowercased words of > given number of characters"
with open(fname) as f:
words = f.read().strip().lower().split()
return {w for w in words if len(w) > minlength}
words11 = getwords()
word_minus_1 = defaultdict(list)
minus_1_to_word = defaultdict(list)
for w in words11:
for i in range(len(w)):
minus_1 = w[:i] + w[i+1:]
word_minus_1[minus_1].append((w, i))
if minus_1 in words11:
minus_1_to_word[minus_1].append(w)
cwords = set()
for _, v in word_minus_1.items():
if len(v) >1:
change_indices = Counter(i for wrd, i in v)
change_words = set(wrd for wrd, i in v)
words_changed = None
if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:
words_changed = [wrd for wrd, i in v
if change_indices[i] > 1]
if words_changed:
cwords.add(tuple(sorted(words_changed)))
print(f"{len(minus_1_to_word)} words that are from deleting a char from other words:")
for k, v in sorted(minus_1_to_word.items()):
print(f" {k:12} From {', '.join(v)}")
print(f"\n{len(cwords)} words that are from changing a char from other words:")
for v in sorted(cwords):
print(f" {v[0]:12} From {', '.join(v[1:])}")
| #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
int hamming_distance(const std::string& str1, const std::string& str2) {
size_t len1 = str1.size();
size_t len2 = str2.size();
if (len1 != len2)
return 0;
int count = 0;
for (size_t i = 0; i < len1; ++i) {
if (str1[i] != str2[i])
++count;
if (count == 2)
break;
}
return count;
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
std::vector<std::string> dictionary;
while (getline(in, line)) {
if (line.size() > 11)
dictionary.push_back(line);
}
std::cout << "Changeable words in " << filename << ":\n";
int n = 1;
for (const std::string& word1 : dictionary) {
for (const std::string& word2 : dictionary) {
if (hamming_distance(word1, word2) == 1)
std::cout << std::setw(2) << std::right << n++
<< ": " << std::setw(14) << std::left << word1
<< " -> " << word2 << '\n';
}
}
return EXIT_SUCCESS;
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. |
from __future__ import annotations
from itertools import chain
from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar
T = TypeVar("T")
class MList(List[T]):
@classmethod
def unit(cls, value: Iterable[T]) -> MList[T]:
return cls(value)
def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
return MList(chain.from_iterable(map(func, self)))
def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
return self.bind(func)
if __name__ == "__main__":
print(
MList([1, 99, 4])
.bind(lambda val: MList([val + 1]))
.bind(lambda val: MList([f"${val}.00"]))
)
print(
MList([1, 99, 4])
>> (lambda val: MList([val + 1]))
>> (lambda val: MList([f"${val}.00"]))
)
print(
MList(range(1, 6)).bind(
lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))
)
)
print(
MList(range(1, 26)).bind(
lambda x: MList(range(x + 1, 26)).bind(
lambda y: MList(range(y + 1, 26)).bind(
lambda z: MList([(x, y, z)])
if x * x + y * y == z * z
else MList([])
)
)
)
)
| #include <iostream>
#include <vector>
using namespace std;
template <typename T>
auto operator>>(const vector<T>& monad, auto f)
{
vector<remove_reference_t<decltype(f(monad.front()).front())>> result;
for(auto& item : monad)
{
const auto r = f(item);
result.insert(result.end(), begin(r), end(r));
}
return result;
}
auto Pure(auto t)
{
return vector{t};
}
auto Double(int i)
{
return Pure(2 * i);
}
auto Increment(int i)
{
return Pure(i + 1);
}
auto NiceNumber(int i)
{
return Pure(to_string(i) + " is a nice number\n");
}
auto UpperSequence = [](auto startingVal)
{
const int MaxValue = 500;
vector<decltype(startingVal)> sequence;
while(startingVal <= MaxValue)
sequence.push_back(startingVal++);
return sequence;
};
void PrintVector(const auto& vec)
{
cout << " ";
for(auto value : vec)
{
cout << value << " ";
}
cout << "\n";
}
void PrintTriples(const auto& vec)
{
cout << "Pythagorean triples:\n";
for(auto it = vec.begin(); it != vec.end();)
{
auto x = *it++;
auto y = *it++;
auto z = *it++;
cout << x << ", " << y << ", " << z << "\n";
}
cout << "\n";
}
int main()
{
auto listMonad =
vector<int> {2, 3, 4} >>
Increment >>
Double >>
NiceNumber;
PrintVector(listMonad);
auto pythagoreanTriples = UpperSequence(1) >>
[](int x){return UpperSequence(x) >>
[x](int y){return UpperSequence(y) >>
[x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};
PrintTriples(pythagoreanTriples);
}
|
Maintain the same structure and functionality when rewriting this code in C++. |
from math import prod
def superFactorial(n):
return prod([prod(range(1,i+1)) for i in range(1,n+1)])
def hyperFactorial(n):
return prod([i**i for i in range(1,n+1)])
def alternatingFactorial(n):
return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])
def exponentialFactorial(n):
if n in [0,1]:
return 1
else:
return n**exponentialFactorial(n-1)
def inverseFactorial(n):
i = 1
while True:
if n == prod(range(1,i)):
return i-1
elif n < prod(range(1,i)):
return "undefined"
i+=1
print("Superfactorials for [0,9] :")
print({"sf(" + str(i) + ") " : superFactorial(i) for i in range(0,10)})
print("\nHyperfactorials for [0,9] :")
print({"H(" + str(i) + ") " : hyperFactorial(i) for i in range(0,10)})
print("\nAlternating factorials for [0,9] :")
print({"af(" + str(i) + ") " : alternatingFactorial(i) for i in range(0,10)})
print("\nExponential factorials for [0,4] :")
print({str(i) + "$ " : exponentialFactorial(i) for i in range(0,5)})
print("\nDigits in 5$ : " , len(str(exponentialFactorial(5))))
factorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
print("\nInverse factorials for " , factorialSet)
print({"rf(" + str(i) + ") ":inverseFactorial(i) for i in factorialSet})
print("\nrf(119) : " + inverseFactorial(119))
| #include <cmath>
#include <cstdint>
#include <iostream>
#include <functional>
uint64_t factorial(int n) {
uint64_t result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int inverse_factorial(uint64_t f) {
int p = 1;
int i = 1;
if (f == 1) {
return 0;
}
while (p < f) {
p *= i;
i++;
}
if (p == f) {
return i - 1;
}
return -1;
}
uint64_t super_factorial(int n) {
uint64_t result = 1;
for (int i = 1; i <= n; i++) {
result *= factorial(i);
}
return result;
}
uint64_t hyper_factorial(int n) {
uint64_t result = 1;
for (int i = 1; i <= n; i++) {
result *= (uint64_t)powl(i, i);
}
return result;
}
uint64_t alternating_factorial(int n) {
uint64_t result = 0;
for (int i = 1; i <= n; i++) {
if ((n - i) % 2 == 0) {
result += factorial(i);
} else {
result -= factorial(i);
}
}
return result;
}
uint64_t exponential_factorial(int n) {
uint64_t result = 0;
for (int i = 1; i <= n; i++) {
result = (uint64_t)powl(i, (long double)result);
}
return result;
}
void test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) {
std::cout << "First " << count << ' ' << name << '\n';
for (int i = 0; i < count; i++) {
std::cout << func(i) << ' ';
}
std::cout << '\n';
}
void test_inverse(uint64_t f) {
int n = inverse_factorial(f);
if (n < 0) {
std::cout << "rf(" << f << ") = No Solution\n";
} else {
std::cout << "rf(" << f << ") = " << n << '\n';
}
}
int main() {
test_factorial(9, super_factorial, "super factorials");
std::cout << '\n';
test_factorial(8, hyper_factorial, "hyper factorials");
std::cout << '\n';
test_factorial(10, alternating_factorial, "alternating factorials");
std::cout << '\n';
test_factorial(5, exponential_factorial, "exponential factorials");
std::cout << '\n';
test_inverse(1);
test_inverse(2);
test_inverse(6);
test_inverse(24);
test_inverse(120);
test_inverse(720);
test_inverse(5040);
test_inverse(40320);
test_inverse(362880);
test_inverse(3628800);
test_inverse(119);
return 0;
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | import random
from collections import OrderedDict
numbers = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred',
1000: 'thousand',
10 ** 6: 'million',
10 ** 9: 'billion',
10 ** 12: 'trillion',
10 ** 15: 'quadrillion',
10 ** 18: 'quintillion',
10 ** 21: 'sextillion',
10 ** 24: 'septillion',
10 ** 27: 'octillion',
10 ** 30: 'nonillion',
10 ** 33: 'decillion',
10 ** 36: 'undecillion',
10 ** 39: 'duodecillion',
10 ** 42: 'tredecillion',
10 ** 45: 'quattuordecillion',
10 ** 48: 'quinquadecillion',
10 ** 51: 'sedecillion',
10 ** 54: 'septendecillion',
10 ** 57: 'octodecillion',
10 ** 60: 'novendecillion',
10 ** 63: 'vigintillion',
10 ** 66: 'unvigintillion',
10 ** 69: 'duovigintillion',
10 ** 72: 'tresvigintillion',
10 ** 75: 'quattuorvigintillion',
10 ** 78: 'quinquavigintillion',
10 ** 81: 'sesvigintillion',
10 ** 84: 'septemvigintillion',
10 ** 87: 'octovigintillion',
10 ** 90: 'novemvigintillion',
10 ** 93: 'trigintillion',
10 ** 96: 'untrigintillion',
10 ** 99: 'duotrigintillion',
10 ** 102: 'trestrigintillion',
10 ** 105: 'quattuortrigintillion',
10 ** 108: 'quinquatrigintillion',
10 ** 111: 'sestrigintillion',
10 ** 114: 'septentrigintillion',
10 ** 117: 'octotrigintillion',
10 ** 120: 'noventrigintillion',
10 ** 123: 'quadragintillion',
10 ** 153: 'quinquagintillion',
10 ** 183: 'sexagintillion',
10 ** 213: 'septuagintillion',
10 ** 243: 'octogintillion',
10 ** 273: 'nonagintillion',
10 ** 303: 'centillion',
10 ** 306: 'uncentillion',
10 ** 309: 'duocentillion',
10 ** 312: 'trescentillion',
10 ** 333: 'decicentillion',
10 ** 336: 'undecicentillion',
10 ** 363: 'viginticentillion',
10 ** 366: 'unviginticentillion',
10 ** 393: 'trigintacentillion',
10 ** 423: 'quadragintacentillion',
10 ** 453: 'quinquagintacentillion',
10 ** 483: 'sexagintacentillion',
10 ** 513: 'septuagintacentillion',
10 ** 543: 'octogintacentillion',
10 ** 573: 'nonagintacentillion',
10 ** 603: 'ducentillion',
10 ** 903: 'trecentillion',
10 ** 1203: 'quadringentillion',
10 ** 1503: 'quingentillion',
10 ** 1803: 'sescentillion',
10 ** 2103: 'septingentillion',
10 ** 2403: 'octingentillion',
10 ** 2703: 'nongentillion',
10 ** 3003: 'millinillion'
}
numbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True))
def string_representation(i: int) -> str:
if i == 0:
return 'zero'
words = ['negative'] if i < 0 else []
working_copy = abs(i)
for key, value in numbers.items():
if key <= working_copy:
times = int(working_copy / key)
if key >= 100:
words.append(string_representation(times))
words.append(value)
working_copy -= times * key
if working_copy == 0:
break
return ' '.join(words)
def next_phrase(i: int):
while not i == 4:
str_i = string_representation(i)
len_i = len(str_i)
yield str_i, 'is', string_representation(len_i)
i = len_i
yield string_representation(i), 'is', 'magic'
def magic(i: int) -> str:
phrases = []
for phrase in next_phrase(i):
phrases.append(' '.join(phrase))
return f'{", ".join(phrases)}.'.capitalize()
if __name__ == '__main__':
for j in (random.randint(0, 10 ** 3) for i in range(5)):
print(j, ':\n', magic(j), '\n')
for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)):
print(j, ':\n', magic(j), '\n')
| #include <iostream>
#include <string>
#include <cctype>
#include <cstdint>
typedef std::uint64_t integer;
const char* small[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
const char* tens[] = {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
struct named_number {
const char* name_;
integer number_;
};
const named_number named_numbers[] = {
{ "hundred", 100 },
{ "thousand", 1000 },
{ "million", 1000000 },
{ "billion", 1000000000 },
{ "trillion", 1000000000000 },
{ "quadrillion", 1000000000000000ULL },
{ "quintillion", 1000000000000000000ULL }
};
const named_number& get_named_number(integer n) {
constexpr size_t names_len = std::size(named_numbers);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number_)
return named_numbers[i];
}
return named_numbers[names_len - 1];
}
std::string cardinal(integer n) {
std::string result;
if (n < 20)
result = small[n];
else if (n < 100) {
result = tens[n/10 - 2];
if (n % 10 != 0) {
result += "-";
result += small[n % 10];
}
} else {
const named_number& num = get_named_number(n);
integer p = num.number_;
result = cardinal(n/p);
result += " ";
result += num.name_;
if (n % p != 0) {
result += " ";
result += cardinal(n % p);
}
}
return result;
}
inline char uppercase(char ch) {
return static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
}
std::string magic(integer n) {
std::string result;
for (unsigned int i = 0; ; ++i) {
std::string text(cardinal(n));
if (i == 0)
text[0] = uppercase(text[0]);
result += text;
if (n == 4) {
result += " is magic.";
break;
}
integer len = text.length();
result += " is ";
result += cardinal(len);
result += ", ";
n = len;
}
return result;
}
void test_magic(integer n) {
std::cout << magic(n) << '\n';
}
int main() {
test_magic(5);
test_magic(13);
test_magic(78);
test_magic(797);
test_magic(2739);
test_magic(4000);
test_magic(7893);
test_magic(93497412);
test_magic(2673497412U);
test_magic(10344658531277200972ULL);
return 0;
}
|
Transform the following Python implementation into C++, maintaining the same output and logic. | In [6]: def dec(n):
...: return len(n.rsplit('.')[-1]) if '.' in n else 0
In [7]: dec('12.345')
Out[7]: 3
In [8]: dec('12.3450')
Out[8]: 4
In [9]:
| #include <iomanip>
#include <iostream>
#include <sstream>
int findNumOfDec(double x) {
std::stringstream ss;
ss << std::fixed << std::setprecision(14) << x;
auto s = ss.str();
auto pos = s.find('.');
if (pos == std::string::npos) {
return 0;
}
auto tail = s.find_last_not_of('0');
return tail - pos;
}
void test(double x) {
std::cout << x << " has " << findNumOfDec(x) << " decimals\n";
}
int main() {
test(12.0);
test(12.345);
test(12.345555555555);
test(12.3450);
test(12.34555555555555555555);
test(1.2345e+54);
return 0;
}
|
Translate the given Python code snippet into C++ without altering its behavior. | >>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))
>>>
>>>
>>> class Contact2(Enum):
FIRST_NAME = 1
LAST_NAME = 2
PHONE = 3
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>>
| enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 };
|
Write the same algorithm in C++ as shown in this Python implementation. | from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = None
except ValueError:
parsed = urlparse('//{}'.format(netloc))
ip = ip_address(parsed.hostname)
port = parsed.port
return ip, port
for address in tests:
ip, port = parse_ip_port(address)
hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
print("{:39s} {:>32s} IPv{} port={}".format(
str(ip), hex_ip, ip.version, port ))
| #include <boost/asio/ip/address.hpp>
#include <cstdint>
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
using boost::asio::ip::address;
using boost::asio::ip::address_v4;
using boost::asio::ip::address_v6;
using boost::asio::ip::make_address;
using boost::asio::ip::make_address_v4;
using boost::asio::ip::make_address_v6;
template<typename uint>
bool parse_int(const std::string& str, int base, uint& n) {
try {
size_t pos = 0;
unsigned long u = stoul(str, &pos, base);
if (pos != str.length() || u > std::numeric_limits<uint>::max())
return false;
n = static_cast<uint>(u);
return true;
} catch (const std::exception& ex) {
return false;
}
}
void parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {
size_t pos = input.rfind(':');
if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()
&& parse_int(input.substr(pos + 1), 10, port) && port > 0) {
if (input[0] == '[' && input[pos - 1] == ']') {
addr = make_address_v6(input.substr(1, pos - 2));
return;
} else {
try {
addr = make_address_v4(input.substr(0, pos));
return;
} catch (const std::exception& ex) {
}
}
}
port = 0;
addr = make_address(input);
}
void print_address_and_port(const address& addr, uint16_t port) {
std::cout << std::hex << std::uppercase << std::setfill('0');
if (addr.is_v4()) {
address_v4 addr4 = addr.to_v4();
std::cout << "address family: IPv4\n";
std::cout << "address number: " << std::setw(8) << addr4.to_uint() << '\n';
} else if (addr.is_v6()) {
address_v6 addr6 = addr.to_v6();
address_v6::bytes_type bytes(addr6.to_bytes());
std::cout << "address family: IPv6\n";
std::cout << "address number: ";
for (unsigned char byte : bytes)
std::cout << std::setw(2) << static_cast<unsigned int>(byte);
std::cout << '\n';
}
if (port != 0)
std::cout << "port: " << std::dec << port << '\n';
else
std::cout << "port not specified\n";
}
void test(const std::string& input) {
std::cout << "input: " << input << '\n';
try {
address addr;
uint16_t port = 0;
parse_ip_address_and_port(input, addr, port);
print_address_and_port(addr, port);
} catch (const std::exception& ex) {
std::cout << "parsing failed\n";
}
std::cout << '\n';
}
int main(int argc, char** argv) {
test("127.0.0.1");
test("127.0.0.1:80");
test("::ffff:127.0.0.1");
test("::1");
test("[::1]:80");
test("1::80");
test("2605:2700:0:3::4713:93e3");
test("[2605:2700:0:3::4713:93e3]:80");
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Python to C++. | from collections import defaultdict
import urllib.request
CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}
URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
def getwords(url):
return urllib.request.urlopen(url).read().decode("utf-8").lower().split()
def mapnum2words(words):
number2words = defaultdict(list)
reject = 0
for word in words:
try:
number2words[''.join(CH2NUM[ch] for ch in word)].append(word)
except KeyError:
reject += 1
return dict(number2words), reject
def interactiveconversions():
global inp, ch, num
while True:
inp = input("\nType a number or a word to get the translation and textonyms: ").strip().lower()
if inp:
if all(ch in '23456789' for ch in inp):
if inp in num2words:
print(" Number {0} has the following textonyms in the dictionary: {1}".format(inp, ', '.join(
num2words[inp])))
else:
print(" Number {0} has no textonyms in the dictionary.".format(inp))
elif all(ch in CH2NUM for ch in inp):
num = ''.join(CH2NUM[ch] for ch in inp)
print(" Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}".format(
inp, ('' if inp in wordset else "n't"), num, ', '.join(num2words[num])))
else:
print(" I don't understand %r" % inp)
else:
print("Thank you")
break
if __name__ == '__main__':
words = getwords(URL)
print("Read %i words from %r" % (len(words), URL))
wordset = set(words)
num2words, reject = mapnum2words(words)
morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)
maxwordpernum = max(len(values) for values in num2words.values())
print(.format(len(words) - reject, URL, len(num2words), morethan1word))
print("\nThe numbers mapping to the most words map to %i words each:" % maxwordpernum)
maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)
for num, wrds in maxwpn:
print(" %s maps to: %s" % (num, ', '.join(wrds)))
interactiveconversions()
| #include <fstream>
#include <iostream>
#include <unordered_map>
#include <vector>
struct Textonym_Checker {
private:
int total;
int elements;
int textonyms;
int max_found;
std::vector<std::string> max_strings;
std::unordered_map<std::string, std::vector<std::string>> values;
int get_mapping(std::string &result, const std::string &input)
{
static std::unordered_map<char, char> mapping = {
{'A', '2'}, {'B', '2'}, {'C', '2'},
{'D', '3'}, {'E', '3'}, {'F', '3'},
{'G', '4'}, {'H', '4'}, {'I', '4'},
{'J', '5'}, {'K', '5'}, {'L', '5'},
{'M', '6'}, {'N', '6'}, {'O', '6'},
{'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},
{'T', '8'}, {'U', '8'}, {'V', '8'},
{'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}
};
result = input;
for (char &c : result) {
if (!isalnum(c)) return 0;
if (isalpha(c)) c = mapping[toupper(c)];
}
return 1;
}
public:
Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }
~Textonym_Checker() { }
void add(const std::string &str) {
std::string mapping;
total++;
if (!get_mapping(mapping, str)) return;
const int num_strings = values[mapping].size();
if (num_strings == 1) textonyms++;
elements++;
if (num_strings > max_found) {
max_strings.clear();
max_strings.push_back(mapping);
max_found = num_strings;
}
else if (num_strings == max_found)
max_strings.push_back(mapping);
values[mapping].push_back(str);
}
void results(const std::string &filename) {
std::cout << "Read " << total << " words from " << filename << "\n\n";
std::cout << "There are " << elements << " words in " << filename;
std::cout << " which can be represented by the digit key mapping.\n";
std::cout << "They require " << values.size() <<
" digit combinations to represent them.\n";
std::cout << textonyms << " digit combinations represent Textonyms.\n\n";
std::cout << "The numbers mapping to the most words map to ";
std::cout << max_found + 1 << " words each:\n";
for (auto it1 : max_strings) {
std::cout << '\t' << it1 << " maps to: ";
for (auto it2 : values[it1])
std::cout << it2 << " ";
std::cout << '\n';
}
std::cout << '\n';
}
void match(const std::string &str) {
auto match = values.find(str);
if (match == values.end()) {
std::cout << "Key '" << str << "' not found\n";
}
else {
std::cout << "Key '" << str << "' matches: ";
for (auto it : values[str])
std::cout << it << " ";
std::cout << '\n';
}
}
};
int main()
{
auto filename = "unixdict.txt";
std::ifstream input(filename);
Textonym_Checker tc;
if (input.is_open()) {
std::string line;
while (getline(input, line))
tc.add(line);
}
input.close();
tc.results(filename);
tc.match("001");
tc.match("228");
tc.match("27484247");
tc.match("7244967473642");
}
|
Translate the given Python code snippet into C++ without altering its behavior. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
| #include <list>
#include <algorithm>
#include <iostream>
class point {
public:
point( int a = 0, int b = 0 ) { x = a; y = b; }
bool operator ==( const point& o ) { return o.x == x && o.y == y; }
point operator +( const point& o ) { return point( o.x + x, o.y + y ); }
int x, y;
};
class map {
public:
map() {
char t[8][8] = {
{0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},
{0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}
};
w = h = 8;
for( int r = 0; r < h; r++ )
for( int s = 0; s < w; s++ )
m[s][r] = t[r][s];
}
int operator() ( int x, int y ) { return m[x][y]; }
char m[8][8];
int w, h;
};
class node {
public:
bool operator == (const node& o ) { return pos == o.pos; }
bool operator == (const point& o ) { return pos == o; }
bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }
point pos, parent;
int dist, cost;
};
class aStar {
public:
aStar() {
neighbours[0] = point( -1, -1 ); neighbours[1] = point( 1, -1 );
neighbours[2] = point( -1, 1 ); neighbours[3] = point( 1, 1 );
neighbours[4] = point( 0, -1 ); neighbours[5] = point( -1, 0 );
neighbours[6] = point( 0, 1 ); neighbours[7] = point( 1, 0 );
}
int calcDist( point& p ){
int x = end.x - p.x, y = end.y - p.y;
return( x * x + y * y );
}
bool isValid( point& p ) {
return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );
}
bool existPoint( point& p, int cost ) {
std::list<node>::iterator i;
i = std::find( closed.begin(), closed.end(), p );
if( i != closed.end() ) {
if( ( *i ).cost + ( *i ).dist < cost ) return true;
else { closed.erase( i ); return false; }
}
i = std::find( open.begin(), open.end(), p );
if( i != open.end() ) {
if( ( *i ).cost + ( *i ).dist < cost ) return true;
else { open.erase( i ); return false; }
}
return false;
}
bool fillOpen( node& n ) {
int stepCost, nc, dist;
point neighbour;
for( int x = 0; x < 8; x++ ) {
stepCost = x < 4 ? 1 : 1;
neighbour = n.pos + neighbours[x];
if( neighbour == end ) return true;
if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {
nc = stepCost + n.cost;
dist = calcDist( neighbour );
if( !existPoint( neighbour, nc + dist ) ) {
node m;
m.cost = nc; m.dist = dist;
m.pos = neighbour;
m.parent = n.pos;
open.push_back( m );
}
}
}
return false;
}
bool search( point& s, point& e, map& mp ) {
node n; end = e; start = s; m = mp;
n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );
open.push_back( n );
while( !open.empty() ) {
node n = open.front();
open.pop_front();
closed.push_back( n );
if( fillOpen( n ) ) return true;
}
return false;
}
int path( std::list<point>& path ) {
path.push_front( end );
int cost = 1 + closed.back().cost;
path.push_front( closed.back().pos );
point parent = closed.back().parent;
for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {
if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {
path.push_front( ( *i ).pos );
parent = ( *i ).parent;
}
}
path.push_front( start );
return cost;
}
map m; point end, start;
point neighbours[8];
std::list<node> open;
std::list<node> closed;
};
int main( int argc, char* argv[] ) {
map m;
point s, e( 7, 7 );
aStar as;
if( as.search( s, e, m ) ) {
std::list<point> path;
int c = as.path( path );
for( int y = -1; y < 9; y++ ) {
for( int x = -1; x < 9; x++ ) {
if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )
std::cout << char(0xdb);
else {
if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )
std::cout << "x";
else std::cout << ".";
}
}
std::cout << "\n";
}
std::cout << "\nPath cost " << c << ": ";
for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {
std::cout<< "(" << ( *i ).x << ", " << ( *i ).y << ") ";
}
}
std::cout << "\n\n";
return 0;
}
|
Generate an equivalent C++ version of this Python code. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
| #include <list>
#include <algorithm>
#include <iostream>
class point {
public:
point( int a = 0, int b = 0 ) { x = a; y = b; }
bool operator ==( const point& o ) { return o.x == x && o.y == y; }
point operator +( const point& o ) { return point( o.x + x, o.y + y ); }
int x, y;
};
class map {
public:
map() {
char t[8][8] = {
{0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0},
{0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}
};
w = h = 8;
for( int r = 0; r < h; r++ )
for( int s = 0; s < w; s++ )
m[s][r] = t[r][s];
}
int operator() ( int x, int y ) { return m[x][y]; }
char m[8][8];
int w, h;
};
class node {
public:
bool operator == (const node& o ) { return pos == o.pos; }
bool operator == (const point& o ) { return pos == o; }
bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; }
point pos, parent;
int dist, cost;
};
class aStar {
public:
aStar() {
neighbours[0] = point( -1, -1 ); neighbours[1] = point( 1, -1 );
neighbours[2] = point( -1, 1 ); neighbours[3] = point( 1, 1 );
neighbours[4] = point( 0, -1 ); neighbours[5] = point( -1, 0 );
neighbours[6] = point( 0, 1 ); neighbours[7] = point( 1, 0 );
}
int calcDist( point& p ){
int x = end.x - p.x, y = end.y - p.y;
return( x * x + y * y );
}
bool isValid( point& p ) {
return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h );
}
bool existPoint( point& p, int cost ) {
std::list<node>::iterator i;
i = std::find( closed.begin(), closed.end(), p );
if( i != closed.end() ) {
if( ( *i ).cost + ( *i ).dist < cost ) return true;
else { closed.erase( i ); return false; }
}
i = std::find( open.begin(), open.end(), p );
if( i != open.end() ) {
if( ( *i ).cost + ( *i ).dist < cost ) return true;
else { open.erase( i ); return false; }
}
return false;
}
bool fillOpen( node& n ) {
int stepCost, nc, dist;
point neighbour;
for( int x = 0; x < 8; x++ ) {
stepCost = x < 4 ? 1 : 1;
neighbour = n.pos + neighbours[x];
if( neighbour == end ) return true;
if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) {
nc = stepCost + n.cost;
dist = calcDist( neighbour );
if( !existPoint( neighbour, nc + dist ) ) {
node m;
m.cost = nc; m.dist = dist;
m.pos = neighbour;
m.parent = n.pos;
open.push_back( m );
}
}
}
return false;
}
bool search( point& s, point& e, map& mp ) {
node n; end = e; start = s; m = mp;
n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s );
open.push_back( n );
while( !open.empty() ) {
node n = open.front();
open.pop_front();
closed.push_back( n );
if( fillOpen( n ) ) return true;
}
return false;
}
int path( std::list<point>& path ) {
path.push_front( end );
int cost = 1 + closed.back().cost;
path.push_front( closed.back().pos );
point parent = closed.back().parent;
for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) {
if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) {
path.push_front( ( *i ).pos );
parent = ( *i ).parent;
}
}
path.push_front( start );
return cost;
}
map m; point end, start;
point neighbours[8];
std::list<node> open;
std::list<node> closed;
};
int main( int argc, char* argv[] ) {
map m;
point s, e( 7, 7 );
aStar as;
if( as.search( s, e, m ) ) {
std::list<point> path;
int c = as.path( path );
for( int y = -1; y < 9; y++ ) {
for( int x = -1; x < 9; x++ ) {
if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 )
std::cout << char(0xdb);
else {
if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() )
std::cout << "x";
else std::cout << ".";
}
}
std::cout << "\n";
}
std::cout << "\nPath cost " << c << ": ";
for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) {
std::cout<< "(" << ( *i ).x << ", " << ( *i ).y << ") ";
}
}
std::cout << "\n\n";
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Python. |
from itertools import chain, groupby
from os.path import expanduser
from functools import reduce
def main():
print('\n'.join(
concatMap(circularGroup)(
anagrams(3)(
lines(readFile('~/mitWords.txt'))
)
)
))
def anagrams(n):
def go(ws):
def f(xs):
return [
[snd(x) for x in xs]
] if n <= len(xs) >= len(xs[0][0]) else []
return concatMap(f)(groupBy(fst)(sorted(
[(''.join(sorted(w)), w) for w in ws],
key=fst
)))
return go
def circularGroup(ws):
lex = set(ws)
iLast = len(ws) - 1
(i, blnCircular) = until(
lambda tpl: tpl[1] or (tpl[0] > iLast)
)(
lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))
)(
(0, False)
)
return [' -> '.join(allRotations(ws[i]))] if blnCircular else []
def isCircular(lexicon):
def go(w):
def f(tpl):
(i, _, x) = tpl
return (1 + i, x in lexicon, rotated(x))
iLast = len(w) - 1
return until(
lambda tpl: iLast < tpl[0] or (not tpl[1])
)(f)(
(0, True, rotated(w))
)[1]
return go
def allRotations(w):
return takeIterate(len(w) - 1)(
rotated
)(w)
def concatMap(f):
def go(xs):
return chain.from_iterable(map(f, xs))
return go
def fst(tpl):
return tpl[0]
def groupBy(f):
def go(xs):
return [
list(x[1]) for x in groupby(xs, key=f)
]
return go
def lines(s):
return s.splitlines()
def mapAccumL(f):
def go(a, x):
tpl = f(a[0], x)
return (tpl[0], a[1] + [tpl[1]])
return lambda acc: lambda xs: (
reduce(go, xs, (acc, []))
)
def readFile(fp):
with open(expanduser(fp), 'r', encoding='utf-8') as f:
return f.read()
def rotated(s):
return s[1:] + s[0]
def snd(tpl):
return tpl[1]
def takeIterate(n):
def go(f):
def g(x):
def h(a, i):
v = f(a) if i else x
return (v, v)
return mapAccumL(h)(x)(
range(0, 1 + n)
)[1]
return g
return go
def until(p):
def go(f):
def g(x):
v = x
while not p(v):
v = f(v)
return v
return g
return go
if __name__ == '__main__':
main()
| #include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <vector>
std::set<std::string> load_dictionary(const std::string& filename) {
std::ifstream in(filename);
if (!in)
throw std::runtime_error("Cannot open file " + filename);
std::set<std::string> words;
std::string word;
while (getline(in, word))
words.insert(word);
return words;
}
void find_teacup_words(const std::set<std::string>& words) {
std::vector<std::string> teacup_words;
std::set<std::string> found;
for (auto w = words.begin(); w != words.end(); ++w) {
std::string word = *w;
size_t len = word.size();
if (len < 3 || found.find(word) != found.end())
continue;
teacup_words.clear();
teacup_words.push_back(word);
for (size_t i = 0; i + 1 < len; ++i) {
std::rotate(word.begin(), word.begin() + 1, word.end());
if (word == *w || words.find(word) == words.end())
break;
teacup_words.push_back(word);
}
if (teacup_words.size() == len) {
found.insert(teacup_words.begin(), teacup_words.end());
std::cout << teacup_words[0];
for (size_t i = 1; i < len; ++i)
std::cout << ' ' << teacup_words[i];
std::cout << '\n';
}
}
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " dictionary\n";
return EXIT_FAILURE;
}
try {
find_teacup_words(load_dictionary(argv[1]));
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? |
def digit_sum(n, sum):
sum += 1
while n > 0 and n % 10 == 0:
sum -= 9
n /= 10
return sum
previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1
print("Gap index Gap Niven index Niven number")
niven = 1
while gap_index <= 22:
sum = digit_sum(niven, sum)
if niven % sum == 0:
if niven > previous + gap:
gap = niven - previous;
print('{0:9d} {1:4d} {2:13d} {3:11d}'.format(gap_index, gap, niven_index, previous))
gap_index += 1
previous = niven
niven_index += 1
niven += 1
| #include <cstdint>
#include <iomanip>
#include <iostream>
uint64_t digit_sum(uint64_t n, uint64_t sum) {
++sum;
while (n > 0 && n % 10 == 0) {
sum -= 9;
n /= 10;
}
return sum;
}
inline bool divisible(uint64_t n, uint64_t d) {
if ((d & 1) == 0 && (n & 1) == 1)
return false;
return n % d == 0;
}
int main() {
std::cout.imbue(std::locale(""));
uint64_t previous = 1, gap = 0, sum = 0;
int niven_index = 0, gap_index = 1;
std::cout << "Gap index Gap Niven index Niven number\n";
for (uint64_t niven = 1; gap_index <= 32; ++niven) {
sum = digit_sum(niven, sum);
if (divisible(niven, sum)) {
if (niven > previous + gap) {
gap = niven - previous;
std::cout << std::setw(9) << gap_index++
<< std::setw(5) << gap
<< std::setw(15) << niven_index
<< std::setw(16) << previous << '\n';
}
previous = niven;
++niven_index;
}
}
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Python version. | import logging, logging.handlers
LOG_FILENAME = "logdemo.log"
FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s"
LOGLEVEL = logging.DEBUG
def print_squares(number):
logger.info("In print_squares")
for i in range(number):
print("square of {0} is {1}".format(i , i*i))
logger.debug(f'square of {i} is {i*i}')
def print_cubes(number):
logger.info("In print_cubes")
for j in range(number):
print("cube of {0} is {1}".format(j, j*j*j))
logger.debug(f'cube of {j} is {j*j*j}')
if __name__ == "__main__":
logger = logging.getLogger("logdemo")
logger.setLevel(LOGLEVEL)
handler = logging.FileHandler(LOG_FILENAME)
handler.setFormatter(logging.Formatter(FORMAT_STRING))
logger.addHandler(handler)
print_squares(10)
print_cubes(10)
logger.info("All done")
| #include <iostream>
#define DEBUG(msg,...) fprintf(stderr, "[DEBUG %s@%d] " msg "\n", __FILE__, __LINE__, __VA_ARGS__)
int main() {
DEBUG("Hello world");
DEBUG("Some %d Things", 42);
return 0;
}
|
Translate the given Python code snippet into C++ without altering its behavior. | import logging, logging.handlers
LOG_FILENAME = "logdemo.log"
FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s"
LOGLEVEL = logging.DEBUG
def print_squares(number):
logger.info("In print_squares")
for i in range(number):
print("square of {0} is {1}".format(i , i*i))
logger.debug(f'square of {i} is {i*i}')
def print_cubes(number):
logger.info("In print_cubes")
for j in range(number):
print("cube of {0} is {1}".format(j, j*j*j))
logger.debug(f'cube of {j} is {j*j*j}')
if __name__ == "__main__":
logger = logging.getLogger("logdemo")
logger.setLevel(LOGLEVEL)
handler = logging.FileHandler(LOG_FILENAME)
handler.setFormatter(logging.Formatter(FORMAT_STRING))
logger.addHandler(handler)
print_squares(10)
print_cubes(10)
logger.info("All done")
| #include <iostream>
#define DEBUG(msg,...) fprintf(stderr, "[DEBUG %s@%d] " msg "\n", __FILE__, __LINE__, __VA_ARGS__)
int main() {
DEBUG("Hello world");
DEBUG("Some %d Things", 42);
return 0;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. | def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
elif hi - low == 1:
yield (low,)
yield (hi,)
else:
yield (low,)
i += 1
def printr(ranges):
print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
for r in ranges ) )
if __name__ == '__main__':
for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
printr(range_extract(lst))
| #include <iostream>
#include <iterator>
#include <cstddef>
template<typename InIter>
void extract_ranges(InIter begin, InIter end, std::ostream& os)
{
if (begin == end)
return;
int current = *begin++;
os << current;
int count = 1;
while (begin != end)
{
int next = *begin++;
if (next == current+1)
++count;
else
{
if (count > 2)
os << '-';
else
os << ',';
if (count > 1)
os << current << ',';
os << next;
count = 1;
}
current = next;
}
if (count > 1)
os << (count > 2? '-' : ',') << current;
}
template<typename T, std::size_t n>
T* end(T (&array)[n])
{
return array+n;
}
int main()
{
int data[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39 };
extract_ranges(data, end(data), std::cout);
std::cout << std::endl;
}
|
Convert the following code from Python to C++, ensuring the logic remains intact. | fun maxpathsum(t):
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
a[r, c] += max(a[r+1, c], a[r=1, c+1])
return a[1, 1]
let test = [
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[07, 36, 79, 16, 37, 68],
[48, 07, 09, 18, 70, 26, 06],
[18, 72, 79, 46, 59, 79, 29, 90],
[20, 76, 87, 11, 32, 07, 07, 49, 18],
[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]
@print maxpathsum test
|
#include <iostream>
int main( int argc, char* argv[] )
{
int triangle[] =
{
55,
94, 48,
95, 30, 96,
77, 71, 26, 67,
97, 13, 76, 38, 45,
7, 36, 79, 16, 37, 68,
48, 7, 9, 18, 70, 26, 6,
18, 72, 79, 46, 59, 79, 29, 90,
20, 76, 87, 11, 32, 7, 7, 49, 18,
27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
};
const int size = sizeof( triangle ) / sizeof( int );
const int tn = static_cast<int>(sqrt(2.0 * size));
assert(tn * (tn + 1) == 2 * size);
for (int n = tn - 1; n > 0; --n)
for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k)
triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);
std::cout << "Maximum total: " << triangle[0] << "\n\n";
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. |
beforeTxt =
smallrc01 =
rc01 =
def intarray(binstring):
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
Return 8-neighbours of point p1 of picture, in order'''
i = image
x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1],
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]
def transitions(neighbours):
n = neighbours + neighbours[0:1]
return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))
def zhangSuen(image):
changing1 = changing2 = [(-1, -1)]
while changing1 or changing2:
changing1 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P4 * P6 * P8 == 0 and
P2 * P4 * P6 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing1.append((x,y))
for x, y in changing1: image[y][x] = 0
changing2 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P2 * P6 * P8 == 0 and
P2 * P4 * P8 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing2.append((x,y))
for x, y in changing2: image[y][x] = 0
return image
if __name__ == '__main__':
for picture in (beforeTxt, smallrc01, rc01):
image = intarray(picture)
print('\nFrom:\n%s' % toTxt(image))
after = zhangSuen(image)
print('\nTo thinned:\n%s' % toTxt(after))
| #include <iostream>
#include <string>
#include <sstream>
#include <valarray>
const std::string input {
"................................"
".#########.......########......."
".###...####.....####..####......"
".###....###.....###....###......"
".###...####.....###............."
".#########......###............."
".###.####.......###....###......"
".###..####..###.####..####.###.."
".###...####.###..########..###.."
"................................"
};
const std::string input2 {
".........................................................."
".#################...................#############........"
".##################...............################........"
".###################............##################........"
".########.....#######..........###################........"
"...######.....#######.........#######.......######........"
"...######.....#######........#######......................"
"...#################.........#######......................"
"...################..........#######......................"
"...#################.........#######......................"
"...######.....#######........#######......................"
"...######.....#######........#######......................"
"...######.....#######.........#######.......######........"
".########.....#######..........###################........"
".########.....#######.######....##################.######."
".########.....#######.######......################.######."
".########.....#######.######.........#############.######."
".........................................................."
};
class ZhangSuen;
class Image {
public:
friend class ZhangSuen;
using pixel_t = char;
static const pixel_t BLACK_PIX;
static const pixel_t WHITE_PIX;
Image(unsigned width = 1, unsigned height = 1)
: width_{width}, height_{height}, data_( '\0', width_ * height_)
{}
Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_}
{}
Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)}
{}
~Image() = default;
Image& operator=(const Image& i) {
if (this != &i) {
width_ = i.width_;
height_ = i.height_;
data_ = i.data_;
}
return *this;
}
Image& operator=(Image&& i) {
if (this != &i) {
width_ = i.width_;
height_ = i.height_;
data_ = std::move(i.data_);
}
return *this;
}
size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; }
bool operator()(unsigned x, unsigned y) {
return data_[idx(x, y)];
}
friend std::ostream& operator<<(std::ostream& o, const Image& i) {
o << i.width_ << " x " << i.height_ << std::endl;
size_t px = 0;
for(const auto& e : i.data_) {
o << (e?Image::BLACK_PIX:Image::WHITE_PIX);
if (++px % i.width_ == 0)
o << std::endl;
}
return o << std::endl;
}
friend std::istream& operator>>(std::istream& in, Image& img) {
auto it = std::begin(img.data_);
const auto end = std::end(img.data_);
Image::pixel_t tmp;
while(in && it != end) {
in >> tmp;
if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX)
throw "Bad character found in image";
*it = (tmp == Image::BLACK_PIX)?1:0;
++it;
}
return in;
}
unsigned width() const noexcept { return width_; }
unsigned height() const noexcept { return height_; }
struct Neighbours {
Neighbours(const Image& img, unsigned p1_x, unsigned p1_y)
: img_{img}
, p1_{img.idx(p1_x, p1_y)}
, p2_{p1_ - img.width()}
, p3_{p2_ + 1}
, p4_{p1_ + 1}
, p5_{p4_ + img.width()}
, p6_{p5_ - 1}
, p7_{p6_ - 1}
, p8_{p1_ - 1}
, p9_{p2_ - 1}
{}
const Image& img_;
const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; }
const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; }
const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; }
const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; }
const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; }
const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; }
const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; }
const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; }
const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; }
const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_;
};
Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); }
private:
unsigned height_ { 0 };
unsigned width_ { 0 };
std::valarray<pixel_t> data_;
};
constexpr const Image::pixel_t Image::BLACK_PIX = '#';
constexpr const Image::pixel_t Image::WHITE_PIX = '.';
class ZhangSuen {
public:
unsigned transitions_white_black(const Image::Neighbours& a) const {
unsigned sum = 0;
sum += (a.p9() == 0) && a.p2();
sum += (a.p2() == 0) && a.p3();
sum += (a.p3() == 0) && a.p4();
sum += (a.p8() == 0) && a.p9();
sum += (a.p4() == 0) && a.p5();
sum += (a.p7() == 0) && a.p8();
sum += (a.p6() == 0) && a.p7();
sum += (a.p5() == 0) && a.p6();
return sum;
}
unsigned black_pixels(const Image::Neighbours& a) const {
unsigned sum = 0;
sum += a.p9();
sum += a.p2();
sum += a.p3();
sum += a.p8();
sum += a.p4();
sum += a.p7();
sum += a.p6();
sum += a.p5();
return sum;
}
const Image& operator()(const Image& img) {
tmp_a_ = img;
size_t changed_pixels = 0;
do {
changed_pixels = 0;
tmp_b_ = tmp_a_;
for(size_t y = 1; y < tmp_a_.height() - 1; ++y) {
for(size_t x = 1; x < tmp_a_.width() - 1; ++x) {
if (tmp_a_.data_[tmp_a_.idx(x, y)]) {
auto n = tmp_a_.neighbours(x, y);
auto bp = black_pixels(n);
if (bp >= 2 && bp <= 6) {
auto tr = transitions_white_black(n);
if ( tr == 1
&& (n.p2() * n.p4() * n.p6() == 0)
&& (n.p4() * n.p6() * n.p8() == 0)
) {
tmp_b_.data_[n.p1_] = 0;
++changed_pixels;
}
}
}
}
}
tmp_a_ = tmp_b_;
for(size_t y = 1; y < tmp_b_.height() - 1; ++y) {
for(size_t x = 1; x < tmp_b_.width() - 1; ++x) {
if (tmp_b_.data_[tmp_b_.idx(x, y)]) {
auto n = tmp_b_.neighbours(x, y);
auto bp = black_pixels(n);
if (bp >= 2 && bp <= 6) {
auto tr = transitions_white_black(n);
if ( tr == 1
&& (n.p2() * n.p4() * n.p8() == 0)
&& (n.p2() * n.p6() * n.p8() == 0)
) {
tmp_a_.data_[n.p1_] = 0;
++changed_pixels;
}
}
}
}
}
} while(changed_pixels > 0);
return tmp_a_;
}
private:
Image tmp_a_;
Image tmp_b_;
};
int main(int argc, char const *argv[])
{
using namespace std;
Image img(32, 10);
istringstream iss{input};
iss >> img;
cout << img;
cout << "ZhangSuen" << endl;
ZhangSuen zs;
Image res = std::move(zs(img));
cout << res << endl;
Image img2(58,18);
istringstream iss2{input2};
iss2 >> img2;
cout << img2;
cout << "ZhangSuen with big image" << endl;
Image res2 = std::move(zs(img2));
cout << res2 << endl;
return 0;
}
|
Translate the given Python code snippet into C++ without altering its behavior. | s = [1, 2, 2, 3, 4, 4, 5]
for i in range(len(s)):
curr = s[i]
if i > 0 and curr == prev:
print(i)
prev = curr
| #include <array>
#include <iostream>
int main()
{
constexpr std::array s {1,2,2,3,4,4,5};
if(!s.empty())
{
int previousValue = s[0];
for(size_t i = 1; i < s.size(); ++i)
{
const int currentValue = s[i];
if(i > 0 && previousValue == currentValue)
{
std::cout << i << "\n";
}
previousValue = currentValue;
}
}
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | import itertools
def riseEqFall(num):
height = 0
d1 = num % 10
num //= 10
while num:
d2 = num % 10
height += (d1<d2) - (d1>d2)
d1 = d2
num //= 10
return height == 0
def sequence(start, fn):
num=start-1
while True:
num += 1
while not fn(num): num += 1
yield num
a296712 = sequence(1, riseEqFall)
print("The first 200 numbers are:")
print(*itertools.islice(a296712, 200))
print("The 10,000,000th number is:")
print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
| #include <iomanip>
#include <iostream>
bool equal_rises_and_falls(int n) {
int total = 0;
for (int previous_digit = -1; n > 0; n /= 10) {
int digit = n % 10;
if (previous_digit > digit)
++total;
else if (previous_digit >= 0 && previous_digit < digit)
--total;
previous_digit = digit;
}
return total == 0;
}
int main() {
const int limit1 = 200;
const int limit2 = 10000000;
int n = 0;
std::cout << "The first " << limit1 << " numbers in the sequence are:\n";
for (int count = 0; count < limit2; ) {
if (equal_rises_and_falls(++n)) {
++count;
if (count <= limit1)
std::cout << std::setw(3) << n << (count % 20 == 0 ? '\n' : ' ');
}
}
std::cout << "\nThe " << limit2 << "th number in the sequence is " << n << ".\n";
}
|
Port the provided Python code into C++ while preserving the original functionality. | l = 300
def setup():
size(400, 400)
background(0, 0, 255)
stroke(255)
translate(width / 2.0, height / 2.0)
translate(-l / 2.0, l * sqrt(3) / 6.0)
for i in range(4):
kcurve(0, l)
rotate(radians(120))
translate(-l, 0)
def kcurve(x1, x2):
s = (x2 - x1) / 3.0
if s < 5:
pushMatrix()
translate(x1, 0)
line(0, 0, s, 0)
line(2 * s, 0, 3 * s, 0)
translate(s, 0)
rotate(radians(60))
line(0, 0, s, 0)
translate(s, 0)
rotate(radians(-120))
line(0, 0, s, 0)
popMatrix()
return
pushMatrix()
translate(x1, 0)
kcurve(0, s)
kcurve(2 * s, 3 * s)
translate(s, 0)
rotate(radians(60))
kcurve(0, s)
translate(s, 0)
rotate(radians(-120))
kcurve(0, s)
popMatrix()
|
#include <fstream>
#include <iostream>
#include <vector>
constexpr double sqrt3_2 = 0.86602540378444;
struct point {
double x;
double y;
};
std::vector<point> koch_next(const std::vector<point>& points) {
size_t size = points.size();
std::vector<point> output(4*(size - 1) + 1);
double x0, y0, x1, y1;
size_t j = 0;
for (size_t i = 0; i + 1 < size; ++i) {
x0 = points[i].x;
y0 = points[i].y;
x1 = points[i + 1].x;
y1 = points[i + 1].y;
double dy = y1 - y0;
double dx = x1 - x0;
output[j++] = {x0, y0};
output[j++] = {x0 + dx/3, y0 + dy/3};
output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};
output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};
}
output[j] = {x1, y1};
return output;
}
std::vector<point> koch_points(int size, int iterations) {
double length = size * sqrt3_2 * 0.95;
double x = (size - length)/2;
double y = size/2 - length * sqrt3_2/3;
std::vector<point> points{
{x, y},
{x + length/2, y + length * sqrt3_2},
{x + length, y},
{x, y}
};
for (int i = 0; i < iterations; ++i)
points = koch_next(points);
return points;
}
void koch_curve_svg(std::ostream& out, int size, int iterations) {
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='black'/>\n";
out << "<path stroke-width='1' stroke='white' fill='none' d='";
auto points(koch_points(size, iterations));
for (size_t i = 0, n = points.size(); i < n; ++i)
out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n';
out << "z'/>\n</svg>\n";
}
int main() {
std::ofstream out("koch_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
koch_curve_svg(out, 600, 5);
return EXIT_SUCCESS;
}
|
Please provide an equivalent version of this Python code in C++. | l = 300
def setup():
size(400, 400)
background(0, 0, 255)
stroke(255)
translate(width / 2.0, height / 2.0)
translate(-l / 2.0, l * sqrt(3) / 6.0)
for i in range(4):
kcurve(0, l)
rotate(radians(120))
translate(-l, 0)
def kcurve(x1, x2):
s = (x2 - x1) / 3.0
if s < 5:
pushMatrix()
translate(x1, 0)
line(0, 0, s, 0)
line(2 * s, 0, 3 * s, 0)
translate(s, 0)
rotate(radians(60))
line(0, 0, s, 0)
translate(s, 0)
rotate(radians(-120))
line(0, 0, s, 0)
popMatrix()
return
pushMatrix()
translate(x1, 0)
kcurve(0, s)
kcurve(2 * s, 3 * s)
translate(s, 0)
rotate(radians(60))
kcurve(0, s)
translate(s, 0)
rotate(radians(-120))
kcurve(0, s)
popMatrix()
|
#include <fstream>
#include <iostream>
#include <vector>
constexpr double sqrt3_2 = 0.86602540378444;
struct point {
double x;
double y;
};
std::vector<point> koch_next(const std::vector<point>& points) {
size_t size = points.size();
std::vector<point> output(4*(size - 1) + 1);
double x0, y0, x1, y1;
size_t j = 0;
for (size_t i = 0; i + 1 < size; ++i) {
x0 = points[i].x;
y0 = points[i].y;
x1 = points[i + 1].x;
y1 = points[i + 1].y;
double dy = y1 - y0;
double dx = x1 - x0;
output[j++] = {x0, y0};
output[j++] = {x0 + dx/3, y0 + dy/3};
output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};
output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};
}
output[j] = {x1, y1};
return output;
}
std::vector<point> koch_points(int size, int iterations) {
double length = size * sqrt3_2 * 0.95;
double x = (size - length)/2;
double y = size/2 - length * sqrt3_2/3;
std::vector<point> points{
{x, y},
{x + length/2, y + length * sqrt3_2},
{x + length, y},
{x, y}
};
for (int i = 0; i < iterations; ++i)
points = koch_next(points);
return points;
}
void koch_curve_svg(std::ostream& out, int size, int iterations) {
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='black'/>\n";
out << "<path stroke-width='1' stroke='white' fill='none' d='";
auto points(koch_points(size, iterations));
for (size_t i = 0, n = points.size(); i < n; ++i)
out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n';
out << "z'/>\n</svg>\n";
}
int main() {
std::ofstream out("koch_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
koch_curve_svg(out, 600, 5);
return EXIT_SUCCESS;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. |
import urllib.request
from collections import Counter
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
dictionary = open("unixdict.txt","r")
wordList = dictionary.read().split('\n')
dictionary.close()
filteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]
for word in filteredWords[:-9]:
position = filteredWords.index(word)
newWord = "".join([filteredWords[position+i][i] for i in range(0,9)])
if newWord in filteredWords:
print(newWord)
| #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char** argv) {
const int min_length = 9;
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
std::vector<std::string> words;
while (getline(in, line)) {
if (line.size() >= min_length)
words.push_back(line);
}
std::sort(words.begin(), words.end());
std::string previous_word;
int count = 0;
for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {
std::string word;
word.reserve(min_length);
for (size_t j = 0; j < min_length; ++j)
word += words[i + j][j];
if (previous_word == word)
continue;
auto w = std::lower_bound(words.begin(), words.end(), word);
if (w != words.end() && *w == word)
std::cout << std::setw(2) << ++count << ". " << word << '\n';
previous_word = word;
}
return EXIT_SUCCESS;
}
|
Translate this program into C++ but keep the logic exactly as in Python. | import math
from sys import stdout
LOG_10 = 2.302585092994
def build_oms(s):
if s % 2 == 0:
s += 1
q = [[0 for j in range(s)] for i in range(s)]
p = 1
i = s // 2
j = 0
while p <= (s * s):
q[i][j] = p
ti = i + 1
if ti >= s: ti = 0
tj = j - 1
if tj < 0: tj = s - 1
if q[ti][tj] != 0:
ti = i
tj = j + 1
i = ti
j = tj
p = p + 1
return q, s
def build_sems(s):
if s % 2 == 1:
s += 1
while s % 4 == 0:
s += 2
q = [[0 for j in range(s)] for i in range(s)]
z = s // 2
b = z * z
c = 2 * b
d = 3 * b
o = build_oms(z)
for j in range(0, z):
for i in range(0, z):
a = o[0][i][j]
q[i][j] = a
q[i + z][j + z] = a + b
q[i + z][j] = a + c
q[i][j + z] = a + d
lc = z // 2
rc = lc
for j in range(0, z):
for i in range(0, s):
if i < lc or i > s - rc or (i == lc and j == lc):
if not (i == 0 and j == lc):
t = q[i][j]
q[i][j] = q[i][j + z]
q[i][j + z] = t
return q, s
def format_sqr(s, l):
for i in range(0, l - len(s)):
s = "0" + s
return s + " "
def display(q):
s = q[1]
print(" - {0} x {1}\n".format(s, s))
k = 1 + math.floor(math.log(s * s) / LOG_10)
for j in range(0, s):
for i in range(0, s):
stdout.write(format_sqr("{0}".format(q[0][i][j]), k))
print()
print("Magic sum: {0}\n".format(s * ((s * s) + 1) // 2))
stdout.write("Singly Even Magic Square")
display(build_sems(6))
| #include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
class magicSqr
{
public:
magicSqr() { sqr = 0; }
~magicSqr() { if( sqr ) delete [] sqr; }
void create( int d ) {
if( sqr ) delete [] sqr;
if( d & 1 ) d++;
while( d % 4 == 0 ) { d += 2; }
sz = d;
sqr = new int[sz * sz];
memset( sqr, 0, sz * sz * sizeof( int ) );
fillSqr();
}
void display() {
cout << "Singly Even Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr; cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ ) {
int yy = y * sz;
for( int x = 0; x < sz; x++ ) {
cout << setw( l + 2 ) << sqr[yy + x];
}
cout << "\n";
}
cout << "\n\n";
}
private:
void siamese( int from, int to ) {
int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1;
while( count > 0 ) {
bool done = false;
while ( false == done ) {
if( curCol >= oneSide ) curCol = 0;
if( curRow < 0 ) curRow = oneSide - 1;
done = true;
if( sqr[curCol + sz * curRow] != 0 ) {
curCol -= 1; curRow += 2;
if( curCol < 0 ) curCol = oneSide - 1;
if( curRow >= oneSide ) curRow -= oneSide;
done = false;
}
}
sqr[curCol + sz * curRow] = s;
s++; count--; curCol++; curRow--;
}
}
void fillSqr() {
int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3;
siamese( 0, n );
for( int r = 0; r < n; r++ ) {
int row = r * sz;
for( int c = n; c < sz; c++ ) {
int m = sqr[c - n + row];
sqr[c + row] = m + add1;
sqr[c + row + ns] = m + add3;
sqr[c - n + row + ns] = m + add2;
}
}
int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 );
for( int r = 0; r < n; r++ ) {
int row = r * sz;
for( int c = co; c < sz; c++ ) {
sqr[c + row] -= add3;
sqr[c + row + ns] += add3;
}
}
for( int r = 0; r < n; r++ ) {
int row = r * sz;
for( int c = 0; c < lc; c++ ) {
int cc = c;
if( r == lc ) cc++;
sqr[cc + row] += add2;
sqr[cc + row + ns] -= add2;
}
}
}
int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; }
void inc( int& a ) { if( ++a == sz ) a = 0; }
void dec( int& a ) { if( --a < 0 ) a = sz - 1; }
bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
bool isInside( int s ) { return ( s < sz && s > -1 ); }
int* sqr;
int sz;
};
int main( int argc, char* argv[] ) {
magicSqr s; s.create( 6 );
s.display();
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Python. | >>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
if p.index('B') % 2 != p.index('b') % 2
and ( p.index('r') < p.index('K') < p.index('R')
or p.index('R') < p.index('K') < p.index('r') ) }
>>> len(starts)
960
>>> starts.pop()
'QNBRNKRB'
>>>
| #include <iostream>
#include <string>
#include <time.h>
using namespace std;
namespace
{
void placeRandomly(char* p, char c)
{
int loc = rand() % 8;
if (!p[loc])
p[loc] = c;
else
placeRandomly(p, c);
}
int placeFirst(char* p, char c, int loc = 0)
{
while (p[loc]) ++loc;
p[loc] = c;
return loc;
}
string startPos()
{
char p[8]; memset( p, 0, 8 );
p[2 * (rand() % 4)] = 'B';
p[2 * (rand() % 4) + 1] = 'B';
for (char c : "QNN")
placeRandomly(p, c);
placeFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));
return string(p, 8);
}
}
namespace chess960
{
void generate( int c )
{
for( int x = 0; x < c; x++ )
cout << startPos() << "\n";
}
}
int main( int argc, char* argv[] )
{
srand( time( NULL ) );
chess960::generate( 10 );
cout << "\n\n";
return system( "pause" );
}
|
Please provide an equivalent version of this Python code in C++. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
| int meaning_of_life();
|
Generate a C++ translation of this Python snippet without changing its computational steps. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
| int meaning_of_life();
|
Ensure the translated C++ code behaves exactly like the original Python snippet. | import sys, os
from collections import Counter
def dodir(path):
global h
for name in os.listdir(path):
p = os.path.join(path, name)
if os.path.islink(p):
pass
elif os.path.isfile(p):
h[os.stat(p).st_size] += 1
elif os.path.isdir(p):
dodir(p)
else:
pass
def main(arg):
global h
h = Counter()
for dir in arg:
dodir(dir)
s = n = 0
for k, v in sorted(h.items()):
print("Size %d -> %d file(s)" % (k, v))
n += v
s += k * v
print("Total %d bytes for %d files" % (s, n))
main(sys.argv[1:])
| #include <algorithm>
#include <array>
#include <filesystem>
#include <iomanip>
#include <iostream>
void file_size_distribution(const std::filesystem::path& directory) {
constexpr size_t n = 9;
constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,
100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };
std::array<size_t, n + 1> count = { 0 };
size_t files = 0;
std::uintmax_t total_size = 0;
std::filesystem::recursive_directory_iterator iter(directory);
for (const auto& dir_entry : iter) {
if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {
std::uintmax_t file_size = dir_entry.file_size();
total_size += file_size;
auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);
size_t index = std::distance(sizes.begin(), i);
++count[index];
++files;
}
}
std::cout << "File size distribution for " << directory << ":\n";
for (size_t i = 0; i <= n; ++i) {
if (i == n)
std::cout << "> " << sizes[i - 1];
else
std::cout << std::setw(16) << sizes[i];
std::cout << " bytes: " << count[i] << '\n';
}
std::cout << "Number of files: " << files << '\n';
std::cout << "Total file size: " << total_size << " bytes\n";
}
int main(int argc, char** argv) {
std::cout.imbue(std::locale(""));
try {
const char* directory(argc > 1 ? argv[1] : ".");
std::filesystem::path path(directory);
if (!is_directory(path)) {
std::cerr << directory << " is not a directory.\n";
return EXIT_FAILURE;
}
file_size_distribution(path);
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
| #include <iostream>
#include <set>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main(void)
{
fs::path p(fs::current_path());
std::set<std::string> tree;
for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)
tree.insert(it->path().filename().native());
for (auto entry : tree)
std::cout << entry << '\n';
}
|
Generate an equivalent C++ version of this Python code. | def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
for r in range(n1, order-n1):
r1 = sq[r][:n1]
r2 = sq[order -r - 1][order-n1:]
r1.reverse()
r2.reverse()
sq[r][:n1] = r2
sq[order -r - 1][order-n1:] = r1
return sq
def printsq(s):
n = len(s)
bl = len(str(n**2))+1
for i in range(n):
print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] )
print "\nMagic constant = %d"%sum(s[0])
printsq(MagicSquareDoublyEven(8))
| #include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
class magicSqr
{
public:
magicSqr( int d ) {
while( d % 4 > 0 ) { d++; }
sz = d;
sqr = new int[sz * sz];
fillSqr();
}
~magicSqr() { delete [] sqr; }
void display() const {
cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr; cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ ) {
int yy = y * sz;
for( int x = 0; x < sz; x++ ) {
cout << setw( l + 2 ) << sqr[yy + x];
}
cout << "\n";
}
cout << "\n\n";
}
private:
void fillSqr() {
static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };
int i = 0;
for( int curRow = 0; curRow < sz; curRow++ ) {
for( int curCol = 0; curCol < sz; curCol++ ) {
sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;
i++;
}
}
}
int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }
int* sqr;
int sz;
};
int main( int argc, char* argv[] ) {
magicSqr s( 8 );
s.display();
return 0;
}
|
Write the same code in C++ as shown below in Python. | mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
const = 0x2545F4914F6CDD1D
class Xorshift_star():
def __init__(self, seed=0):
self.state = seed & mask64
def seed(self, num):
self.state = num & mask64
def next_int(self):
"return random int between 0 and 2**32"
x = self.state
x = (x ^ (x >> 12)) & mask64
x = (x ^ (x << 25)) & mask64
x = (x ^ (x >> 27)) & mask64
self.state = x
answer = (((x * const) & mask64) >> 32) & mask32
return answer
def next_float(self):
"return random float between 0 and 1"
return self.next_int() / (1 << 32)
if __name__ == '__main__':
random_gen = Xorshift_star()
random_gen.seed(1234567)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist)
| #include <array>
#include <cstdint>
#include <iostream>
class XorShiftStar {
private:
const uint64_t MAGIC = 0x2545F4914F6CDD1D;
uint64_t state;
public:
void seed(uint64_t num) {
state = num;
}
uint32_t next_int() {
uint64_t x;
uint32_t answer;
x = state;
x = x ^ (x >> 12);
x = x ^ (x << 25);
x = x ^ (x >> 27);
state = x;
answer = ((x * MAGIC) >> 32);
return answer;
}
float next_float() {
return (float)next_int() / (1LL << 32);
}
};
int main() {
auto rng = new XorShiftStar();
rng->seed(1234567);
std::cout << rng->next_int() << '\n';
std::cout << rng->next_int() << '\n';
std::cout << rng->next_int() << '\n';
std::cout << rng->next_int() << '\n';
std::cout << rng->next_int() << '\n';
std::cout << '\n';
std::array<int, 5> counts = { 0, 0, 0, 0, 0 };
rng->seed(987654321);
for (int i = 0; i < 100000; i++) {
int j = (int)floor(rng->next_float() * 5.0);
counts[j]++;
}
for (size_t i = 0; i < counts.size(); i++) {
std::cout << i << ": " << counts[i] << '\n';
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. |
import inflect
def count_letters(word):
count = 0
for letter in word:
if letter != ',' and letter !='-' and letter !=' ':
count += 1
return count
def split_with_spaces(sentence):
sentence_list = []
curr_word = ""
for c in sentence:
if c == " " and curr_word != "":
sentence_list.append(curr_word+" ")
curr_word = ""
else:
curr_word += c
if len(curr_word) > 0:
sentence_list.append(curr_word)
return sentence_list
def my_num_to_words(p, my_number):
number_string_list = p.number_to_words(my_number, wantlist=True, andword='')
number_string = number_string_list[0]
for i in range(1,len(number_string_list)):
number_string += " " + number_string_list[i]
return number_string
def build_sentence(p, max_words):
sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,")
num_words = 13
word_number = 2
while num_words < max_words:
ordinal_string = my_num_to_words(p, p.ordinal(word_number))
word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))
new_string = " "+word_number_string+" in the "+ordinal_string+","
new_list = split_with_spaces(new_string)
sentence_list += new_list
num_words += len(new_list)
word_number += 1
return sentence_list, num_words
def word_and_counts(word_num):
sentence_list, num_words = build_sentence(p, word_num)
word_str = sentence_list[word_num - 1].strip(' ,')
num_letters = len(word_str)
num_characters = 0
for word in sentence_list:
num_characters += len(word)
print('Word {0:8d} is "{1}", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters))
p = inflect.engine()
sentence_list, num_words = build_sentence(p, 201)
print(" ")
print("The lengths of the first 201 words are:")
print(" ")
print('{0:3d}: '.format(1),end='')
total_characters = 0
for word_index in range(201):
word_length = count_letters(sentence_list[word_index])
total_characters += len(sentence_list[word_index])
print('{0:2d}'.format(word_length),end='')
if (word_index+1) % 20 == 0:
print(" ")
print('{0:3d}: '.format(word_index + 2),end='')
else:
print(" ",end='')
print(" ")
print(" ")
print("Length of the sentence so far: "+str(total_characters))
print(" ")
word_and_counts(1000)
word_and_counts(10000)
word_and_counts(100000)
word_and_counts(1000000)
word_and_counts(10000000)
| #include <cctype>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
struct number_names {
const char* cardinal;
const char* ordinal;
};
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
{ "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
{ "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
{ "twelve", "twelfth" }, { "thirteen", "thirteenth" },
{ "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
{ "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
{ "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};
const number_names tens[] = {
{ "twenty", "twentieth" }, { "thirty", "thirtieth" },
{ "forty", "fortieth" }, { "fifty", "fiftieth" },
{ "sixty", "sixtieth" }, { "seventy", "seventieth" },
{ "eighty", "eightieth" }, { "ninety", "ninetieth" }
};
struct named_number {
const char* cardinal;
const char* ordinal;
uint64_t number;
};
const named_number named_numbers[] = {
{ "hundred", "hundredth", 100 },
{ "thousand", "thousandth", 1000 },
{ "million", "millionth", 1000000 },
{ "billion", "biliionth", 1000000000 },
{ "trillion", "trillionth", 1000000000000 },
{ "quadrillion", "quadrillionth", 1000000000000000ULL },
{ "quintillion", "quintillionth", 1000000000000000000ULL }
};
const char* get_name(const number_names& n, bool ordinal) {
return ordinal ? n.ordinal : n.cardinal;
}
const char* get_name(const named_number& n, bool ordinal) {
return ordinal ? n.ordinal : n.cardinal;
}
const named_number& get_named_number(uint64_t n) {
constexpr size_t names_len = std::size(named_numbers);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return named_numbers[i];
}
return named_numbers[names_len - 1];
}
size_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) {
size_t count = 0;
if (n < 20) {
result.push_back(get_name(small[n], ordinal));
count = 1;
}
else if (n < 100) {
if (n % 10 == 0) {
result.push_back(get_name(tens[n/10 - 2], ordinal));
} else {
std::string name(get_name(tens[n/10 - 2], false));
name += "-";
name += get_name(small[n % 10], ordinal);
result.push_back(name);
}
count = 1;
} else {
const named_number& num = get_named_number(n);
uint64_t p = num.number;
count += append_number_name(result, n/p, false);
if (n % p == 0) {
result.push_back(get_name(num, ordinal));
++count;
} else {
result.push_back(get_name(num, false));
++count;
count += append_number_name(result, n % p, ordinal);
}
}
return count;
}
size_t count_letters(const std::string& str) {
size_t letters = 0;
for (size_t i = 0, n = str.size(); i < n; ++i) {
if (isalpha(static_cast<unsigned char>(str[i])))
++letters;
}
return letters;
}
std::vector<std::string> sentence(size_t count) {
static const char* words[] = {
"Four", "is", "the", "number", "of", "letters", "in", "the",
"first", "word", "of", "this", "sentence,"
};
std::vector<std::string> result;
result.reserve(count + 10);
size_t n = std::size(words);
for (size_t i = 0; i < n && i < count; ++i) {
result.push_back(words[i]);
}
for (size_t i = 1; count > n; ++i) {
n += append_number_name(result, count_letters(result[i]), false);
result.push_back("in");
result.push_back("the");
n += 2;
n += append_number_name(result, i + 1, true);
result.back() += ',';
}
return result;
}
size_t sentence_length(const std::vector<std::string>& words) {
size_t n = words.size();
if (n == 0)
return 0;
size_t length = n - 1;
for (size_t i = 0; i < n; ++i)
length += words[i].size();
return length;
}
int main() {
std::cout.imbue(std::locale(""));
size_t n = 201;
auto result = sentence(n);
std::cout << "Number of letters in first " << n << " words in the sequence:\n";
for (size_t i = 0; i < n; ++i) {
if (i != 0)
std::cout << (i % 25 == 0 ? '\n' : ' ');
std::cout << std::setw(2) << count_letters(result[i]);
}
std::cout << '\n';
std::cout << "Sentence length: " << sentence_length(result) << '\n';
for (n = 1000; n <= 10000000; n *= 10) {
result = sentence(n);
const std::string& word = result[n - 1];
std::cout << "The " << n << "th word is '" << word << "' and has "
<< count_letters(word) << " letters. ";
std::cout << "Sentence length: " << sentence_length(result) << '\n';
}
return 0;
}
|
Port the provided Python code into C++ while preserving the original functionality. |
def validate(diagram):
rawlines = diagram.splitlines()
lines = []
for line in rawlines:
if line != '':
lines.append(line)
if len(lines) == 0:
print('diagram has no non-empty lines!')
return None
width = len(lines[0])
cols = (width - 1) // 3
if cols not in [8, 16, 32, 64]:
print('number of columns should be 8, 16, 32 or 64')
return None
if len(lines)%2 == 0:
print('number of non-empty lines should be odd')
return None
if lines[0] != (('+--' * cols)+'+'):
print('incorrect header line')
return None
for i in range(len(lines)):
line=lines[i]
if i == 0:
continue
elif i%2 == 0:
if line != lines[0]:
print('incorrect separator line')
return None
elif len(line) != width:
print('inconsistent line widths')
return None
elif line[0] != '|' or line[width-1] != '|':
print("non-separator lines must begin and end with '|'")
return None
return lines
def decode(lines):
print("Name Bits Start End")
print("======= ==== ===== ===")
startbit = 0
results = []
for line in lines:
infield=False
for c in line:
if not infield and c == '|':
infield = True
spaces = 0
name = ''
elif infield:
if c == ' ':
spaces += 1
elif c != '|':
name += c
else:
bits = (spaces + len(name) + 1) // 3
endbit = startbit + bits - 1
print('{0:7} {1:2d} {2:2d} {3:2d}'.format(name, bits, startbit, endbit))
reslist = [name, bits, startbit, endbit]
results.append(reslist)
spaces = 0
name = ''
startbit += bits
return results
def unpack(results, hex):
print("\nTest string in hex:")
print(hex)
print("\nTest string in binary:")
bin = f'{int(hex, 16):0>{4*len(hex)}b}'
print(bin)
print("\nUnpacked:\n")
print("Name Size Bit pattern")
print("======= ==== ================")
for r in results:
name = r[0]
size = r[1]
startbit = r[2]
endbit = r[3]
bitpattern = bin[startbit:endbit+1]
print('{0:7} {1:2d} {2:16}'.format(name, size, bitpattern))
diagram =
lines = validate(diagram)
if lines == None:
print("No lines returned")
else:
print(" ")
print("Diagram after trimming whitespace and removal of blank lines:")
print(" ")
for line in lines:
print(line)
print(" ")
print("Decoded:")
print(" ")
results = decode(lines)
hex = "78477bbf5496e12e1bf169a4"
unpack(results, hex)
| #include <array>
#include <bitset>
#include <iostream>
using namespace std;
struct FieldDetails {string_view Name; int NumBits;};
template <const char *T> consteval auto ParseDiagram()
{
constexpr string_view rawArt(T);
constexpr auto firstBar = rawArt.find("|");
constexpr auto lastBar = rawArt.find_last_of("|");
constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);
static_assert(firstBar < lastBar, "ASCII Table has no fields");
constexpr auto numFields =
count(rawArt.begin(), rawArt.end(), '|') -
count(rawArt.begin(), rawArt.end(), '\n') / 2;
array<FieldDetails, numFields> fields;
bool isValidDiagram = true;
int startDiagramIndex = 0;
int totalBits = 0;
for(int i = 0; i < numFields; )
{
auto beginningBar = art.find("|", startDiagramIndex);
auto endingBar = art.find("|", beginningBar + 1);
auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);
if(field.find("-") == field.npos)
{
int numBits = (field.size() + 1) / 3;
auto nameStart = field.find_first_not_of(" ");
auto nameEnd = field.find_last_not_of(" ");
if (nameStart > nameEnd || nameStart == string_view::npos)
{
isValidDiagram = false;
field = ""sv;
}
else
{
field = field.substr(nameStart, 1 + nameEnd - nameStart);
}
fields[i++] = FieldDetails {field, numBits};
totalBits += numBits;
}
startDiagramIndex = endingBar;
}
int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;
return make_pair(fields, numRawBytes);
}
template <const char *T> auto Encode(auto inputValues)
{
constexpr auto parsedDiagram = ParseDiagram<T>();
static_assert(parsedDiagram.second > 0, "Invalid ASCII talble");
array<unsigned char, parsedDiagram.second> data;
int startBit = 0;
int i = 0;
for(auto value : inputValues)
{
const auto &field = parsedDiagram.first[i++];
int remainingValueBits = field.NumBits;
while(remainingValueBits > 0)
{
auto [fieldStartByte, fieldStartBit] = div(startBit, 8);
int unusedBits = 8 - fieldStartBit;
int numBitsToEncode = min({unusedBits, 8, field.NumBits});
int divisor = 1 << (remainingValueBits - numBitsToEncode);
unsigned char bitsToEncode = value / divisor;
data[fieldStartByte] <<= numBitsToEncode;
data[fieldStartByte] |= bitsToEncode;
value %= divisor;
startBit += numBitsToEncode;
remainingValueBits -= numBitsToEncode;
}
}
return data;
}
template <const char *T> void Decode(auto data)
{
cout << "Name Bit Pattern\n";
cout << "======= ================\n";
constexpr auto parsedDiagram = ParseDiagram<T>();
static_assert(parsedDiagram.second > 0, "Invalid ASCII talble");
int startBit = 0;
for(const auto& field : parsedDiagram.first)
{
auto [fieldStartByte, fieldStartBit] = div(startBit, 8);
unsigned char firstByte = data[fieldStartByte];
firstByte <<= fieldStartBit;
firstByte >>= fieldStartBit;
int64_t value = firstByte;
auto endBit = startBit + field.NumBits;
auto [fieldEndByte, fieldEndBit] = div(endBit, 8);
fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));
for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)
{
value <<= 8;
value += data[index];
}
value >>= fieldEndBit;
startBit = endBit;
cout << field.Name <<
string_view(" ", (7 - field.Name.size())) << " " <<
string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) << "\n";
}
}
int main(void)
{
static constexpr char art[] = R"(
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)";
auto rawData = Encode<art> (initializer_list<int64_t> {
30791,
0, 15, 0, 1, 1, 1, 3, 15,
21654,
57646,
7153,
27044
});
cout << "Raw encoded data in hex:\n";
for (auto v : rawData) printf("%.2X", v);
cout << "\n\n";
cout << "Decoded raw data:\n";
Decode<art>(rawData);
}
|
Generate a C++ translation of this Python snippet without changing its computational steps. | try:
from itertools import zip_longest as izip_longest
except:
from itertools import izip_longest
def fringe(tree):
for node1 in tree:
if isinstance(node1, tuple):
for node2 in fringe(node1):
yield node2
else:
yield node1
def same_fringe(tree1, tree2):
return all(node1 == node2 for node1, node2 in
izip_longest(fringe(tree1), fringe(tree2)))
if __name__ == '__main__':
a = 1, 2, 3, 4, 5, 6, 7, 8
b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))
c = (((1, 2), 3), 4), 5, 6, 7, 8
x = 1, 2, 3, 4, 5, 6, 7, 8, 9
y = 0, 2, 3, 4, 5, 6, 7, 8
z = 1, 2, (4, 3), 5, 6, 7, 8
assert same_fringe(a, a)
assert same_fringe(a, b)
assert same_fringe(a, c)
assert not same_fringe(a, x)
assert not same_fringe(a, y)
assert not same_fringe(a, z)
| #include <algorithm>
#include <coroutine>
#include <iostream>
#include <memory>
#include <tuple>
#include <variant>
using namespace std;
class BinaryTree
{
using Node = tuple<BinaryTree, int, BinaryTree>;
unique_ptr<Node> m_tree;
public:
BinaryTree() = default;
BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild)
: m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {}
BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){}
BinaryTree(BinaryTree&& leftChild, int value)
: BinaryTree(move(leftChild), value, BinaryTree{}){}
BinaryTree(int value, BinaryTree&& rightChild)
: BinaryTree(BinaryTree{}, value, move(rightChild)){}
explicit operator bool() const
{
return (bool)m_tree;
}
int Value() const
{
return get<1>(*m_tree);
}
const BinaryTree& LeftChild() const
{
return get<0>(*m_tree);
}
const BinaryTree& RightChild() const
{
return get<2>(*m_tree);
}
};
struct TreeWalker {
struct promise_type {
int val;
suspend_never initial_suspend() noexcept {return {};}
suspend_never return_void() noexcept {return {};}
suspend_always final_suspend() noexcept {return {};}
void unhandled_exception() noexcept { }
TreeWalker get_return_object()
{
return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)};
}
suspend_always yield_value(int x) noexcept
{
val=x;
return {};
}
};
coroutine_handle<promise_type> coro;
TreeWalker(coroutine_handle<promise_type> h): coro(h) {}
~TreeWalker()
{
if(coro) coro.destroy();
}
class Iterator
{
const coroutine_handle<promise_type>* m_h = nullptr;
public:
Iterator() = default;
constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){}
Iterator& operator++()
{
m_h->resume();
return *this;
}
Iterator operator++(int)
{
auto old(*this);
m_h->resume();
return old;
}
int operator*() const
{
return m_h->promise().val;
}
bool operator!=(monostate) const noexcept
{
return !m_h->done();
return m_h && !m_h->done();
}
bool operator==(monostate) const noexcept
{
return !operator!=(monostate{});
}
};
constexpr Iterator begin() const noexcept
{
return Iterator(&coro);
}
constexpr monostate end() const noexcept
{
return monostate{};
}
};
namespace std {
template<>
class iterator_traits<TreeWalker::Iterator>
{
public:
using difference_type = std::ptrdiff_t;
using size_type = std::size_t;
using value_type = int;
using pointer = int*;
using reference = int&;
using iterator_category = std::input_iterator_tag;
};
}
TreeWalker WalkFringe(const BinaryTree& tree)
{
if(tree)
{
auto& left = tree.LeftChild();
auto& right = tree.RightChild();
if(!left && !right)
{
co_yield tree.Value();
}
for(auto v : WalkFringe(left))
{
co_yield v;
}
for(auto v : WalkFringe(right))
{
co_yield v;
}
}
co_return;
}
void PrintTree(const BinaryTree& tree)
{
if(tree)
{
cout << "(";
PrintTree(tree.LeftChild());
cout << tree.Value();
PrintTree(tree.RightChild());
cout <<")";
}
}
void Compare(const BinaryTree& tree1, const BinaryTree& tree2)
{
auto walker1 = WalkFringe(tree1);
auto walker2 = WalkFringe(tree2);
bool sameFringe = ranges::equal(walker1.begin(), walker1.end(),
walker2.begin(), walker2.end());
PrintTree(tree1);
cout << (sameFringe ? " has same fringe as " : " has different fringe than ");
PrintTree(tree2);
cout << "\n";
}
int main()
{
BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77,
BinaryTree{77, BinaryTree{9}}});
BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{
BinaryTree{3}, 77, BinaryTree{9}}});
BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}});
Compare(tree1, tree2);
Compare(tree1, tree3);
}
|
Translate this program into C++ but keep the logic exactly as in Python. | from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
"Place m black and white queens, peacefully, on an n-by-n board"
board = set(product(range(n), repeat=2))
placements = {frozenset(c) for c in combinations(board, m)}
for blacks in placements:
black_attacks = reduce(_or,
(queen_attacks_from(pos, n) for pos in blacks),
set())
for whites in {frozenset(c)
for c in combinations(board - black_attacks, m)}:
if not black_attacks & whites:
return blacks, whites
return set(), set()
@lru_cache(maxsize=None)
def queen_attacks_from(pos, n):
x0, y0 = pos
a = set([pos])
a.update((x, y0) for x in range(n))
a.update((x0, y) for y in range(n))
for x1 in range(n):
y1 = y0 -x0 +x1
if 0 <= y1 < n:
a.add((x1, y1))
y1 = y0 +x0 -x1
if 0 <= y1 < n:
a.add((x1, y1))
return a
def pboard(black_white, n):
"Print board"
if black_white is None:
blk, wht = set(), set()
else:
blk, wht = black_white
print(f"
f"on a {n}-by-{n} board:", end='')
for x, y in product(range(n), repeat=2):
if y == 0:
print()
xy = (x, y)
ch = ('?' if xy in blk and xy in wht
else 'B' if xy in blk
else 'W' if xy in wht
else _bbullet if (x + y)%2 else _wbullet)
print('%s' % ch, end='')
print()
if __name__ == '__main__':
n=2
for n in range(2, 7):
print()
for m in count(1):
ans = place(m, n)
if ans[0]:
pboard(ans, n)
else:
print (f"
break
print('\n')
m, n = 5, 7
ans = place(m, n)
pboard(ans, n)
| #include <iostream>
#include <vector>
enum class Piece {
empty,
black,
white
};
typedef std::pair<int, int> position;
bool isAttacking(const position &queen, const position &pos) {
return queen.first == pos.first
|| queen.second == pos.second
|| abs(queen.first - pos.first) == abs(queen.second - pos.second);
}
bool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {
if (m == 0) {
return true;
}
bool placingBlack = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
auto pos = std::make_pair(i, j);
for (auto queen : pBlackQueens) {
if (queen == pos || !placingBlack && isAttacking(queen, pos)) {
goto inner;
}
}
for (auto queen : pWhiteQueens) {
if (queen == pos || placingBlack && isAttacking(queen, pos)) {
goto inner;
}
}
if (placingBlack) {
pBlackQueens.push_back(pos);
placingBlack = false;
} else {
pWhiteQueens.push_back(pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
pBlackQueens.pop_back();
pWhiteQueens.pop_back();
placingBlack = true;
}
inner: {}
}
}
if (!placingBlack) {
pBlackQueens.pop_back();
}
return false;
}
void printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {
std::vector<Piece> board(n * n);
std::fill(board.begin(), board.end(), Piece::empty);
for (auto &queen : blackQueens) {
board[queen.first * n + queen.second] = Piece::black;
}
for (auto &queen : whiteQueens) {
board[queen.first * n + queen.second] = Piece::white;
}
for (size_t i = 0; i < board.size(); ++i) {
if (i != 0 && i % n == 0) {
std::cout << '\n';
}
switch (board[i]) {
case Piece::black:
std::cout << "B ";
break;
case Piece::white:
std::cout << "W ";
break;
case Piece::empty:
default:
int j = i / n;
int k = i - j * n;
if (j % 2 == k % 2) {
std::cout << "x ";
} else {
std::cout << "* ";
}
break;
}
}
std::cout << "\n\n";
}
int main() {
std::vector<position> nms = {
{2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},
{5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},
{6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},
{7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},
};
for (auto nm : nms) {
std::cout << nm.second << " black and " << nm.second << " white queens on a " << nm.first << " x " << nm.first << " board:\n";
std::vector<position> blackQueens, whiteQueens;
if (place(nm.second, nm.first, blackQueens, whiteQueens)) {
printBoard(nm.first, blackQueens, whiteQueens);
} else {
std::cout << "No solution exists.\n\n";
}
}
return 0;
}
|
Please provide an equivalent version of this Python code in C++. | col = 0
for i in range(100000):
if set(str(i)) == set(hex(i)[2:]):
col += 1
print("{:7}".format(i), end='\n'[:col % 10 == 0])
print()
| #include <iostream>
#include <iomanip>
#include <bitset>
const int LIMIT = 100000;
std::bitset<16> digitset(int num, int base) {
std::bitset<16> set;
for (; num; num /= base) set.set(num % base);
return set;
}
int main() {
int c = 0;
for (int i=0; i<LIMIT; i++) {
if (digitset(i,10) == digitset(i,16)) {
std::cout << std::setw(7) << i;
if (++c % 10 == 0) std::cout << std::endl;
}
}
std::cout << std::endl;
return 0;
}
|
Write a version of this Python function in C++ with identical behavior. | def lpd(n):
for i in range(n-1,0,-1):
if n%i==0: return i
return 1
for i in range(1,101):
print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
| #include <cassert>
#include <iomanip>
#include <iostream>
int largest_proper_divisor(int n) {
assert(n > 0);
if ((n & 1) == 0)
return n >> 1;
for (int p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return n / p;
}
return 1;
}
int main() {
for (int n = 1; n < 101; ++n) {
std::cout << std::setw(2) << largest_proper_divisor(n)
<< (n % 10 == 0 ? '\n' : ' ');
}
}
|
Write the same algorithm in C++ as shown in this Python implementation. | from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!'
| #include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
using namespace std;
class MTF
{
public:
string encode( string str )
{
fillSymbolTable();
vector<int> output;
for( string::iterator it = str.begin(); it != str.end(); it++ )
{
for( int i = 0; i < 26; i++ )
{
if( *it == symbolTable[i] )
{
output.push_back( i );
moveToFront( i );
break;
}
}
}
string r;
for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
{
ostringstream ss;
ss << *it;
r += ss.str() + " ";
}
return r;
}
string decode( string str )
{
fillSymbolTable();
istringstream iss( str ); vector<int> output;
copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );
string r;
for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
{
r.append( 1, symbolTable[*it] );
moveToFront( *it );
}
return r;
}
private:
void moveToFront( int i )
{
char t = symbolTable[i];
for( int z = i - 1; z >= 0; z-- )
symbolTable[z + 1] = symbolTable[z];
symbolTable[0] = t;
}
void fillSymbolTable()
{
for( int x = 0; x < 26; x++ )
symbolTable[x] = x + 'a';
}
char symbolTable[26];
};
int main()
{
MTF mtf;
string a, str[] = { "broood", "bananaaa", "hiphophiphop" };
for( int x = 0; x < 3; x++ )
{
a = str[x];
cout << a << " -> encoded = ";
a = mtf.encode( a );
cout << a << "; decoded = " << mtf.decode( a ) << endl;
}
return 0;
}
|
Please provide an equivalent version of this Python code in C++. | def main():
fila = 0
lenCubos = 51
print("Suma de N cubos para n = [0..49]\n")
for n in range(1, lenCubos):
sumCubos = 0
for m in range(1, n):
sumCubos = sumCubos + (m ** 3)
fila += 1
print(f'{sumCubos:7} ', end='')
if fila % 5 == 0:
print(" ")
print(f"\nEncontrados {fila} cubos.")
if __name__ == '__main__': main()
| #include <array>
#include <cstdio>
#include <numeric>
void PrintContainer(const auto& vec)
{
int count = 0;
for(auto value : vec)
{
printf("%7d%c", value, ++count % 10 == 0 ? '\n' : ' ');
}
}
int main()
{
auto cube = [](auto x){return x * x * x;};
std::array<int, 50> a;
std::iota(a.begin(), a.end(), 0);
std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);
PrintContainer(a);
}
|
Change the programming language of this snippet from Python to C++ without modifying what it does. | def main():
fila = 0
lenCubos = 51
print("Suma de N cubos para n = [0..49]\n")
for n in range(1, lenCubos):
sumCubos = 0
for m in range(1, n):
sumCubos = sumCubos + (m ** 3)
fila += 1
print(f'{sumCubos:7} ', end='')
if fila % 5 == 0:
print(" ")
print(f"\nEncontrados {fila} cubos.")
if __name__ == '__main__': main()
| #include <array>
#include <cstdio>
#include <numeric>
void PrintContainer(const auto& vec)
{
int count = 0;
for(auto value : vec)
{
printf("%7d%c", value, ++count % 10 == 0 ? '\n' : ' ');
}
}
int main()
{
auto cube = [](auto x){return x * x * x;};
std::array<int, 50> a;
std::iota(a.begin(), a.end(), 0);
std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);
PrintContainer(a);
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | >>> def isint(f):
return complex(f).imag == 0 and complex(f).real.is_integer()
>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]
[True, True, True, False, False, False]
>>>
...
>>> isint(25.000000)
True
>>> isint(24.999999)
False
>>> isint(25.000100)
False
>>> isint(-2.1e120)
True
>>> isint(-5e-2)
False
>>> isint(float('nan'))
False
>>> isint(float('inf'))
False
>>> isint(5.0+0.0j)
True
>>> isint(5-5j)
False
| #include <complex>
#include <math.h>
#include <iostream>
template<class Type>
struct Precision
{
public:
static Type GetEps()
{
return eps;
}
static void SetEps(Type e)
{
eps = e;
}
private:
static Type eps;
};
template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7);
template<class DigType>
bool IsDoubleEqual(DigType d1, DigType d2)
{
return (fabs(d1 - d2) < Precision<DigType>::GetEps());
}
template<class DigType>
DigType IntegerPart(DigType value)
{
return (value > 0) ? floor(value) : ceil(value);
}
template<class DigType>
DigType FractionPart(DigType value)
{
return fabs(IntegerPart<DigType>(value) - value);
}
template<class Type>
bool IsInteger(const Type& value)
{
return false;
}
#define GEN_CHECK_INTEGER(type) \
template<> \
bool IsInteger<type>(const type& value) \
{ \
return true; \
}
#define GEN_CHECK_CMPL_INTEGER(type) \
template<> \
bool IsInteger<std::complex<type> >(const std::complex<type>& value) \
{ \
type zero = type(); \
return value.imag() == zero; \
}
#define GEN_CHECK_REAL(type) \
template<> \
bool IsInteger<type>(const type& value) \
{ \
type zero = type(); \
return IsDoubleEqual<type>(FractionPart<type>(value), zero); \
}
#define GEN_CHECK_CMPL_REAL(type) \
template<> \
bool IsInteger<std::complex<type> >(const std::complex<type>& value) \
{ \
type zero = type(); \
return IsDoubleEqual<type>(value.imag(), zero); \
}
#define GEN_INTEGER(type) \
GEN_CHECK_INTEGER(type) \
GEN_CHECK_CMPL_INTEGER(type)
#define GEN_REAL(type) \
GEN_CHECK_REAL(type) \
GEN_CHECK_CMPL_REAL(type)
GEN_INTEGER(char)
GEN_INTEGER(unsigned char)
GEN_INTEGER(short)
GEN_INTEGER(unsigned short)
GEN_INTEGER(int)
GEN_INTEGER(unsigned int)
GEN_INTEGER(long)
GEN_INTEGER(unsigned long)
GEN_INTEGER(long long)
GEN_INTEGER(unsigned long long)
GEN_REAL(float)
GEN_REAL(double)
GEN_REAL(long double)
template<class Type>
inline void TestValue(const Type& value)
{
std::cout << "Value: " << value << " of type: " << typeid(Type).name() << " is integer - " << std::boolalpha << IsInteger(value) << std::endl;
}
int main()
{
char c = -100;
unsigned char uc = 200;
short s = c;
unsigned short us = uc;
int i = s;
unsigned int ui = us;
long long ll = i;
unsigned long long ull = ui;
std::complex<unsigned int> ci1(2, 0);
std::complex<int> ci2(2, 4);
std::complex<int> ci3(-2, 4);
std::complex<unsigned short> cs1(2, 0);
std::complex<short> cs2(2, 4);
std::complex<short> cs3(-2, 4);
std::complex<double> cd1(2, 0);
std::complex<float> cf1(2, 4);
std::complex<double> cd2(-2, 4);
float f1 = 1.0;
float f2 = -2.0;
float f3 = -2.4f;
float f4 = 1.23e-5f;
float f5 = 1.23e-10f;
double d1 = f5;
TestValue(c);
TestValue(uc);
TestValue(s);
TestValue(us);
TestValue(i);
TestValue(ui);
TestValue(ll);
TestValue(ull);
TestValue(ci1);
TestValue(ci2);
TestValue(ci3);
TestValue(cs1);
TestValue(cs2);
TestValue(cs3);
TestValue(cd1);
TestValue(cd2);
TestValue(cf1);
TestValue(f1);
TestValue(f2);
TestValue(f3);
TestValue(f4);
TestValue(f5);
std::cout << "Set float precision: 1e-15f\n";
Precision<float>::SetEps(1e-15f);
TestValue(f5);
TestValue(d1);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Python to C++. | def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return S[::-1]
if __name__ == '__main__':
for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
| #include <vector>
#include <list>
#include <algorithm>
#include <iostream>
template <typename T>
struct Node {
T value;
Node* prev_node;
};
template <typename Container>
Container lis(const Container& values) {
using E = typename Container::value_type;
using NodePtr = Node<E>*;
using ConstNodePtr = const NodePtr;
std::vector<NodePtr> pileTops;
std::vector<Node<E>> nodes(values.size());
auto cur_node = std::begin(nodes);
for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)
{
auto node = &*cur_node;
node->value = *cur_value;
auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,
[](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });
if (lb != pileTops.begin())
node->prev_node = *std::prev(lb);
if (lb == pileTops.end())
pileTops.push_back(node);
else
*lb = node;
}
Container result(pileTops.size());
auto r = std::rbegin(result);
for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)
*r = node->value;
return result;
}
template <typename Container>
void show_lis(const Container& values)
{
auto&& result = lis(values);
for (auto& r : result) {
std::cout << r << ' ';
}
std::cout << std::endl;
}
int main()
{
show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });
show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });
}
|
Translate this program into C++ but keep the logic exactly as in Python. | from __future__ import print_function
def lgen(even=False, nmax=1000000):
start = 2 if even else 1
n, lst = 1, list(range(start, nmax + 1, 2))
lenlst = len(lst)
yield lst[0]
while n < lenlst and lst[n] < lenlst:
yield lst[n]
n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]
lenlst = len(lst)
for i in lst[n:]:
yield i
| #include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
const int luckySize = 60000;
std::vector<int> luckyEven(luckySize);
std::vector<int> luckyOdd(luckySize);
void init() {
for (int i = 0; i < luckySize; ++i) {
luckyEven[i] = i * 2 + 2;
luckyOdd[i] = i * 2 + 1;
}
}
void filterLuckyEven() {
for (size_t n = 2; n < luckyEven.size(); ++n) {
int m = luckyEven[n - 1];
int end = (luckyEven.size() / m) * m - 1;
for (int j = end; j >= m - 1; j -= m) {
std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j);
luckyEven.pop_back();
}
}
}
void filterLuckyOdd() {
for (size_t n = 2; n < luckyOdd.size(); ++n) {
int m = luckyOdd[n - 1];
int end = (luckyOdd.size() / m) * m - 1;
for (int j = end; j >= m - 1; j -= m) {
std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j);
luckyOdd.pop_back();
}
}
}
void printBetween(size_t j, size_t k, bool even) {
std::ostream_iterator<int> out_it{ std::cout, ", " };
if (even) {
size_t max = luckyEven.back();
if (j > max || k > max) {
std::cerr << "At least one are is too big\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky even numbers between " << j << " and " << k << " are: ";
std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) {
return j <= n && n <= k;
});
} else {
size_t max = luckyOdd.back();
if (j > max || k > max) {
std::cerr << "At least one are is too big\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky numbers between " << j << " and " << k << " are: ";
std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) {
return j <= n && n <= k;
});
}
std::cout << '\n';
}
void printRange(size_t j, size_t k, bool even) {
std::ostream_iterator<int> out_it{ std::cout, ", " };
if (even) {
if (k >= luckyEven.size()) {
std::cerr << "The argument is too large\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky even numbers " << j << " to " << k << " are: ";
std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it);
} else {
if (k >= luckyOdd.size()) {
std::cerr << "The argument is too large\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky numbers " << j << " to " << k << " are: ";
std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it);
}
}
void printSingle(size_t j, bool even) {
if (even) {
if (j >= luckyEven.size()) {
std::cerr << "The argument is too large\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky even number " << j << "=" << luckyEven[j - 1] << '\n';
} else {
if (j >= luckyOdd.size()) {
std::cerr << "The argument is too large\n";
exit(EXIT_FAILURE);
}
std::cout << "Lucky number " << j << "=" << luckyOdd[j - 1] << '\n';
}
}
void help() {
std::cout << "./lucky j [k] [--lucky|--evenLucky]\n";
std::cout << "\n";
std::cout << " argument(s) | what is displayed\n";
std::cout << "==============================================\n";
std::cout << "-j=m | mth lucky number\n";
std::cout << "-j=m --lucky | mth lucky number\n";
std::cout << "-j=m --evenLucky | mth even lucky number\n";
std::cout << "-j=m -k=n | mth through nth (inclusive) lucky numbers\n";
std::cout << "-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\n";
std::cout << "-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\n";
std::cout << "-j=m -k=-n | all lucky numbers in the range [m, n]\n";
std::cout << "-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\n";
std::cout << "-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\n";
}
int main(int argc, char **argv) {
bool evenLucky = false;
int j = 0;
int k = 0;
if (argc < 2) {
help();
exit(EXIT_FAILURE);
}
bool good = false;
for (int i = 1; i < argc; ++i) {
if ('-' == argv[i][0]) {
if ('-' == argv[i][1]) {
if (0 == strcmp("--lucky", argv[i])) {
evenLucky = false;
} else if (0 == strcmp("--evenLucky", argv[i])) {
evenLucky = true;
} else {
std::cerr << "Unknown long argument: [" << argv[i] << "]\n";
exit(EXIT_FAILURE);
}
} else {
if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {
good = true;
j = atoi(&argv[i][3]);
} else if ('k' == argv[i][1] && '=' == argv[i][2]) {
k = atoi(&argv[i][3]);
} else {
std::cerr << "Unknown short argument: " << argv[i] << '\n';
exit(EXIT_FAILURE);
}
}
} else {
std::cerr << "Unknown argument: " << argv[i] << '\n';
exit(EXIT_FAILURE);
}
}
if (!good) {
help();
exit(EXIT_FAILURE);
}
init();
filterLuckyEven();
filterLuckyOdd();
if (k > 0) {
printRange(j, k, evenLucky);
} else if (k < 0) {
printBetween(j, -k, evenLucky);
} else {
printSingle(j, evenLucky);
}
return 0;
}
|
Change the following Python code into C++ without altering its purpose. | def getitem(s, depth=0):
out = [""]
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c == '\\' and len(s) > 1:
s, c = s[1:], c + s[1]
out, s = [a+c for a in out], s[1:]
return out,s
def getgroup(s, depth):
out, comma = [], False
while s:
g,s = getitem(s, depth)
if not s: break
out += g
if s[0] == '}':
if comma: return out, s[1:]
return ['{' + a + '}' for a in out], s[1:]
if s[0] == ',':
comma,s = True, s[1:]
return None
for s in .split('\n'):
print "\n\t".join([s] + getitem(s)[0]) + "\n"
| #include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
namespace detail {
template <typename ForwardIterator>
class tokenizer
{
ForwardIterator _tbegin, _tend, _end;
public:
tokenizer(ForwardIterator begin, ForwardIterator end)
: _tbegin(begin), _tend(begin), _end(end)
{ }
template <typename Lambda>
bool next(Lambda istoken)
{
if (_tbegin == _end) {
return false;
}
_tbegin = _tend;
for (; _tend != _end && !istoken(*_tend); ++_tend) {
if (*_tend == '\\' && std::next(_tend) != _end) {
++_tend;
}
}
if (_tend == _tbegin) {
_tend++;
}
return _tbegin != _end;
}
ForwardIterator begin() const { return _tbegin; }
ForwardIterator end() const { return _tend; }
bool operator==(char c) { return *_tbegin == c; }
};
template <typename List>
void append_all(List & lista, const List & listb)
{
if (listb.size() == 1) {
for (auto & a : lista) {
a += listb.back();
}
} else {
List tmp;
for (auto & a : lista) {
for (auto & b : listb) {
tmp.push_back(a + b);
}
}
lista = std::move(tmp);
}
}
template <typename String, typename List, typename Tokenizer>
List expand(Tokenizer & token)
{
std::vector<List> alts{ { String() } };
while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {
if (token == '{') {
append_all(alts.back(), expand<String, List>(token));
} else if (token == ',') {
alts.push_back({ String() });
} else if (token == '}') {
if (alts.size() == 1) {
for (auto & a : alts.back()) {
a = '{' + a + '}';
}
return alts.back();
} else {
for (std::size_t i = 1; i < alts.size(); i++) {
alts.front().insert(alts.front().end(),
std::make_move_iterator(std::begin(alts[i])),
std::make_move_iterator(std::end(alts[i])));
}
return std::move(alts.front());
}
} else {
for (auto & a : alts.back()) {
a.append(token.begin(), token.end());
}
}
}
List result{ String{ '{' } };
append_all(result, alts.front());
for (std::size_t i = 1; i < alts.size(); i++) {
for (auto & a : result) {
a += ',';
}
append_all(result, alts[i]);
}
return result;
}
}
template <
typename ForwardIterator,
typename String = std::basic_string<
typename std::iterator_traits<ForwardIterator>::value_type
>,
typename List = std::vector<String>
>
List expand(ForwardIterator begin, ForwardIterator end)
{
detail::tokenizer<ForwardIterator> token(begin, end);
List list{ String() };
while (token.next([](char c) { return c == '{'; })) {
if (token == '{') {
detail::append_all(list, detail::expand<String, List>(token));
} else {
for (auto & a : list) {
a.append(token.begin(), token.end());
}
}
}
return list;
}
template <
typename Range,
typename String = std::basic_string<typename Range::value_type>,
typename List = std::vector<String>
>
List expand(const Range & range)
{
using Iterator = typename Range::const_iterator;
return expand<Iterator, String, List>(std::begin(range), std::end(range));
}
int main()
{
for (std::string string : {
R"(~/{Downloads,Pictures}/*.{jpg,gif,png})",
R"(It{{em,alic}iz,erat}e{d,}, please.)",
R"({,{,gotta have{ ,\, again\, }}more }cowbell!)",
R"({}} some {\\{edge,edgy} }{ cases, here\\\})",
R"(a{b{1,2}c)",
R"(a{1,2}b}c)",
R"(a{1,{2},3}b)",
R"(a{b{1,2}c{}})",
R"(more{ darn{ cowbell,},})",
R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)",
R"({a,{\,b}c)",
R"(a{b,{{c}})",
R"({a{\}b,c}d)",
R"({a,b{{1,2}e}f)",
R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})",
R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)",
}) {
std::cout << string << '\n';
for (auto expansion : expand(string)) {
std::cout << " " << expansion << '\n';
}
std::cout << '\n';
}
return 0;
}
|
Generate a C++ translation of this Python snippet without changing its computational steps. | "Generate a short Superpermutation of n characters A... as a string using various algorithms."
from __future__ import print_function, division
from itertools import permutations
from math import factorial
import string
import datetime
import gc
MAXN = 7
def s_perm0(n):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in permutations(allchars)]
sp, tofind = allperms[0], set(allperms[1:])
while tofind:
for skip in range(1, n):
for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):
trial_perm = (sp + trial_add)[-n:]
if trial_perm in tofind:
sp += trial_add
tofind.discard(trial_perm)
trial_add = None
break
if trial_add is None:
break
assert all(perm in sp for perm in allperms)
return sp
def s_perm1(n):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
nxt = perms.pop()
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def s_perm2(n):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
nxt = perms.pop(0)
if nxt not in sp:
sp += nxt
if perms:
nxt = perms.pop(-1)
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def _s_perm3(n, cmp):
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
lastn = sp[-n:]
nxt = cmp(perms,
key=lambda pm:
sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))
perms.remove(nxt)
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def s_perm3_max(n):
return _s_perm3(n, max)
def s_perm3_min(n):
return _s_perm3(n, min)
longest = [factorial(n) * n for n in range(MAXN + 1)]
weight, runtime = {}, {}
print(__doc__)
for algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:
print('\n
print(algo.__doc__)
weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)
for n in range(1, MAXN + 1):
gc.collect()
gc.disable()
t = datetime.datetime.now()
sp = algo(n)
t = datetime.datetime.now() - t
gc.enable()
runtime[algo.__name__] += t
lensp = len(sp)
wt = (lensp / longest[n]) ** 2
print(' For N=%i: SP length %5i Max: %5i Weight: %5.2f'
% (n, lensp, longest[n], wt))
weight[algo.__name__] *= wt
weight[algo.__name__] **= 1 / n
weight[algo.__name__] = 1 / weight[algo.__name__]
print('%*s Overall Weight: %5.2f in %.1f seconds.'
% (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))
print('\n
print('\n'.join('%12s (%.3f)' % kv for kv in
sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))
print('\n
print('\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in
sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))
| #include <array>
#include <iostream>
#include <vector>
constexpr int MAX = 12;
static std::vector<char> sp;
static std::array<int, MAX> count;
static int pos = 0;
int factSum(int n) {
int s = 0;
int x = 0;
int f = 1;
while (x < n) {
f *= ++x;
s += f;
}
return s;
}
bool r(int n) {
if (n == 0) {
return false;
}
char c = sp[pos - n];
if (--count[n] == 0) {
count[n] = n;
if (!r(n - 1)) {
return false;
}
}
sp[pos++] = c;
return true;
}
void superPerm(int n) {
pos = n;
int len = factSum(n);
if (len > 0) {
sp.resize(len);
}
for (size_t i = 0; i <= n; i++) {
count[i] = i;
}
for (size_t i = 1; i <= n; i++) {
sp[i - 1] = '0' + i;
}
while (r(n)) {}
}
int main() {
for (size_t n = 0; n < MAX; n++) {
superPerm(n);
std::cout << "superPerm(" << n << ") len = " << sp.size() << '\n';
}
return 0;
}
|
Please provide an equivalent version of this Python code in C++. | import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
s.set(int(s.get())+1)
def rand():
if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
s.set(random.randrange(0,5000))
def update(e):
if not e.char.isdigit():
tkMessageBox.showerror('Error', 'Invalid input !')
return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()
| #ifndef INTERACTION_H
#define INTERACTION_H
#include <QWidget>
class QPushButton ;
class QLineEdit ;
class QVBoxLayout ;
class MyWidget : public QWidget {
Q_OBJECT
public :
MyWidget( QWidget *parent = 0 ) ;
private :
QLineEdit *entryField ;
QPushButton *increaseButton ;
QPushButton *randomButton ;
QVBoxLayout *myLayout ;
private slots :
void doIncrement( ) ;
void findRandomNumber( ) ;
} ;
#endif
|
Convert the following code from Python to C++, ensuring the logic remains intact. | from random import randrange
try:
range = xrange
except: pass
def one_of_n(lines):
choice = None
for i, line in enumerate(lines):
if randrange(i+1) == 0:
choice = line
return choice
def one_of_n_test(n=10, trials=1000000):
bins = [0] * n
if n:
for i in range(trials):
bins[one_of_n(range(n))] += 1
return bins
print(one_of_n_test())
| #include <random>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
mt19937 engine;
unsigned int one_of_n(unsigned int n) {
unsigned int choice;
for(unsigned int i = 0; i < n; ++i) {
uniform_int_distribution<unsigned int> distribution(0, i);
if(!distribution(engine))
choice = i;
}
return choice;
}
int main() {
engine = mt19937(random_device()());
unsigned int results[10] = {0};
for(unsigned int i = 0; i < 1000000; ++i)
results[one_of_n(10)]++;
ostream_iterator<unsigned int> out_it(cout, " ");
copy(results, results+10, out_it);
cout << '\n';
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Python version. | from random import randrange
try:
range = xrange
except: pass
def one_of_n(lines):
choice = None
for i, line in enumerate(lines):
if randrange(i+1) == 0:
choice = line
return choice
def one_of_n_test(n=10, trials=1000000):
bins = [0] * n
if n:
for i in range(trials):
bins[one_of_n(range(n))] += 1
return bins
print(one_of_n_test())
| #include <random>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
mt19937 engine;
unsigned int one_of_n(unsigned int n) {
unsigned int choice;
for(unsigned int i = 0; i < n; ++i) {
uniform_int_distribution<unsigned int> distribution(0, i);
if(!distribution(engine))
choice = i;
}
return choice;
}
int main() {
engine = mt19937(random_device()());
unsigned int results[10] = {0};
for(unsigned int i = 0; i < 1000000; ++i)
results[one_of_n(10)]++;
ostream_iterator<unsigned int> out_it(cout, " ");
copy(results, results+10, out_it);
cout << '\n';
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.