Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same code in C as shown below in C++. | #include <conio.h>
#include <iostream>
using namespace std;
int main()
{
char ch;
_cputs( "Yes or no?" );
do
{
ch = _getch();
ch = toupper( ch );
} while(ch!='Y'&&ch!='N');
if(ch=='N')
{
cout << "You said no" << endl;
}
else
{
cout << "You said yes" << endl;
}
return 0;
}
| #include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
void set_mode(int want_key)
{
static struct termios old, new;
if (!want_key) {
tcsetattr(STDIN_FILENO, TCSANOW, &old);
return;
}
tcgetattr(STDIN_FILENO, &old);
new = old;
new.c_lflag &= ~(ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &new);
}
int get_key(int no_timeout)
{
int c = 0;
struct timeval tv;
fd_set fs;
tv.tv_usec = tv.tv_sec = 0;
FD_ZERO(&fs);
FD_SET(STDIN_FILENO, &fs);
select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);
if (FD_ISSET(STDIN_FILENO, &fs)) {
c = getchar();
set_mode(0);
}
return c;
}
int main()
{
int c;
while(1) {
set_mode(1);
while (get_key(0));
printf("Prompt again [Y/N]? ");
fflush(stdout);
c = get_key(1);
if (c == 'Y' || c == 'y') {
printf("\n");
continue;
}
if (c == 'N' || c == 'n') {
printf("\nDone\n");
break;
}
printf("\nYes or no?\n");
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from C++ to C. | #include <iostream>
using namespace std ;
int divisor_sum( int number ) {
int sum = 0 ;
for ( int i = 1 ; i < number ; i++ )
if ( number % i == 0 )
sum += i ;
return sum;
}
int main( ) {
cout << "Perfect numbers from 1 to 33550337:\n" ;
for ( int num = 1 ; num < 33550337 ; num++ ) {
if (divisor_sum(num) == num)
cout << num << '\n' ;
}
return 0 ;
}
| #include "stdio.h"
#include "math.h"
int perfect(int n) {
int max = (int)sqrt((double)n) + 1;
int tot = 1;
int i;
for (i = 2; i < max; i++)
if ( (n % i) == 0 ) {
tot += i;
int q = n / i;
if (q > i)
tot += q;
}
return tot == n;
}
int main() {
int n;
for (n = 2; n < 33550337; n++)
if (perfect(n))
printf("%d\n", n);
return 0;
}
|
Please provide an equivalent version of this C++ code in C. | #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;
}
|
#include<stdlib.h>
#include<stdio.h>
#include<complex.h>
typedef struct
{
int rows, cols;
complex **z;
} matrix;
matrix
transpose (matrix a)
{
int i, j;
matrix b;
b.rows = a.cols;
b.cols = a.rows;
b.z = malloc (b.rows * sizeof (complex *));
for (i = 0; i < b.rows; i++)
{
b.z[i] = malloc (b.cols * sizeof (complex));
for (j = 0; j < b.cols; j++)
{
b.z[i][j] = conj (a.z[j][i]);
}
}
return b;
}
int
isHermitian (matrix a)
{
int i, j;
matrix b = transpose (a);
if (b.rows == a.rows && b.cols == a.cols)
{
for (i = 0; i < b.rows; i++)
{
for (j = 0; j < b.cols; j++)
{
if (b.z[i][j] != a.z[i][j])
return 0;
}
}
}
else
return 0;
return 1;
}
matrix
multiply (matrix a, matrix b)
{
matrix c;
int i, j;
if (a.cols == b.rows)
{
c.rows = a.rows;
c.cols = b.cols;
c.z = malloc (c.rows * (sizeof (complex *)));
for (i = 0; i < c.rows; i++)
{
c.z[i] = malloc (c.cols * sizeof (complex));
c.z[i][j] = 0 + 0 * I;
for (j = 0; j < b.cols; j++)
{
c.z[i][j] += a.z[i][j] * b.z[j][i];
}
}
}
return c;
}
int
isNormal (matrix a)
{
int i, j;
matrix a_ah, ah_a;
if (a.rows != a.cols)
return 0;
a_ah = multiply (a, transpose (a));
ah_a = multiply (transpose (a), a);
for (i = 0; i < a.rows; i++)
{
for (j = 0; j < a.cols; j++)
{
if (a_ah.z[i][j] != ah_a.z[i][j])
return 0;
}
}
return 1;
}
int
isUnitary (matrix a)
{
matrix b;
int i, j;
if (isNormal (a) == 1)
{
b = multiply (a, transpose(a));
for (i = 0; i < b.rows; i++)
{
for (j = 0; j < b.cols; j++)
{
if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))
return 0;
}
}
return 1;
}
return 0;
}
int
main ()
{
complex z = 3 + 4 * I;
matrix a, aT;
int i, j;
printf ("Enter rows and columns :");
scanf ("%d%d", &a.rows, &a.cols);
a.z = malloc (a.rows * sizeof (complex *));
printf ("Randomly Generated Complex Matrix A is : ");
for (i = 0; i < a.rows; i++)
{
printf ("\n");
a.z[i] = malloc (a.cols * sizeof (complex));
for (j = 0; j < a.cols; j++)
{
a.z[i][j] = rand () % 10 + rand () % 10 * I;
printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j]));
}
}
aT = transpose (a);
printf ("\n\nTranspose of Complex Matrix A is : ");
for (i = 0; i < aT.rows; i++)
{
printf ("\n");
aT.z[i] = malloc (aT.cols * sizeof (complex));
for (j = 0; j < aT.cols; j++)
{
aT.z[i][j] = rand () % 10 + rand () % 10 * I;
printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j]));
}
}
printf ("\n\nComplex Matrix A %s hermitian",
isHermitian (a) == 1 ? "is" : "is not");
printf ("\n\nComplex Matrix A %s unitary",
isUnitary (a) == 1 ? "is" : "is not");
printf ("\n\nComplex Matrix A %s normal",
isNormal (a) == 1 ? "is" : "is not");
return 0;
}
|
Write a version of this C++ function in C with identical behavior. | #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;
}
|
#include<stdlib.h>
#include<stdio.h>
#include<complex.h>
typedef struct
{
int rows, cols;
complex **z;
} matrix;
matrix
transpose (matrix a)
{
int i, j;
matrix b;
b.rows = a.cols;
b.cols = a.rows;
b.z = malloc (b.rows * sizeof (complex *));
for (i = 0; i < b.rows; i++)
{
b.z[i] = malloc (b.cols * sizeof (complex));
for (j = 0; j < b.cols; j++)
{
b.z[i][j] = conj (a.z[j][i]);
}
}
return b;
}
int
isHermitian (matrix a)
{
int i, j;
matrix b = transpose (a);
if (b.rows == a.rows && b.cols == a.cols)
{
for (i = 0; i < b.rows; i++)
{
for (j = 0; j < b.cols; j++)
{
if (b.z[i][j] != a.z[i][j])
return 0;
}
}
}
else
return 0;
return 1;
}
matrix
multiply (matrix a, matrix b)
{
matrix c;
int i, j;
if (a.cols == b.rows)
{
c.rows = a.rows;
c.cols = b.cols;
c.z = malloc (c.rows * (sizeof (complex *)));
for (i = 0; i < c.rows; i++)
{
c.z[i] = malloc (c.cols * sizeof (complex));
c.z[i][j] = 0 + 0 * I;
for (j = 0; j < b.cols; j++)
{
c.z[i][j] += a.z[i][j] * b.z[j][i];
}
}
}
return c;
}
int
isNormal (matrix a)
{
int i, j;
matrix a_ah, ah_a;
if (a.rows != a.cols)
return 0;
a_ah = multiply (a, transpose (a));
ah_a = multiply (transpose (a), a);
for (i = 0; i < a.rows; i++)
{
for (j = 0; j < a.cols; j++)
{
if (a_ah.z[i][j] != ah_a.z[i][j])
return 0;
}
}
return 1;
}
int
isUnitary (matrix a)
{
matrix b;
int i, j;
if (isNormal (a) == 1)
{
b = multiply (a, transpose(a));
for (i = 0; i < b.rows; i++)
{
for (j = 0; j < b.cols; j++)
{
if ((i == j && b.z[i][j] != 1) || (i != j && b.z[i][j] != 0))
return 0;
}
}
return 1;
}
return 0;
}
int
main ()
{
complex z = 3 + 4 * I;
matrix a, aT;
int i, j;
printf ("Enter rows and columns :");
scanf ("%d%d", &a.rows, &a.cols);
a.z = malloc (a.rows * sizeof (complex *));
printf ("Randomly Generated Complex Matrix A is : ");
for (i = 0; i < a.rows; i++)
{
printf ("\n");
a.z[i] = malloc (a.cols * sizeof (complex));
for (j = 0; j < a.cols; j++)
{
a.z[i][j] = rand () % 10 + rand () % 10 * I;
printf ("\t%f + %fi", creal (a.z[i][j]), cimag (a.z[i][j]));
}
}
aT = transpose (a);
printf ("\n\nTranspose of Complex Matrix A is : ");
for (i = 0; i < aT.rows; i++)
{
printf ("\n");
aT.z[i] = malloc (aT.cols * sizeof (complex));
for (j = 0; j < aT.cols; j++)
{
aT.z[i][j] = rand () % 10 + rand () % 10 * I;
printf ("\t%f + %fi", creal (aT.z[i][j]), cimag (aT.z[i][j]));
}
}
printf ("\n\nComplex Matrix A %s hermitian",
isHermitian (a) == 1 ? "is" : "is not");
printf ("\n\nComplex Matrix A %s unitary",
isUnitary (a) == 1 ? "is" : "is not");
printf ("\n\nComplex Matrix A %s normal",
isNormal (a) == 1 ? "is" : "is not");
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #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';
}
}
}
| #include <stdio.h>
#include <gmp.h>
void jacobsthal(mpz_t r, unsigned long n) {
mpz_t s;
mpz_init(s);
mpz_set_ui(r, 1);
mpz_mul_2exp(r, r, n);
mpz_set_ui(s, 1);
if (n % 2) mpz_neg(s, s);
mpz_sub(r, r, s);
mpz_div_ui(r, r, 3);
}
void jacobsthal_lucas(mpz_t r, unsigned long n) {
mpz_t a;
mpz_init(a);
mpz_set_ui(r, 1);
mpz_mul_2exp(r, r, n);
mpz_set_ui(a, 1);
if (n % 2) mpz_neg(a, a);
mpz_add(r, r, a);
}
int main() {
int i, count;
mpz_t jac[30], j;
printf("First 30 Jacobsthal numbers:\n");
for (i = 0; i < 30; ++i) {
mpz_init(jac[i]);
jacobsthal(jac[i], i);
gmp_printf("%9Zd ", jac[i]);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 30 Jacobsthal-Lucas numbers:\n");
mpz_init(j);
for (i = 0; i < 30; ++i) {
jacobsthal_lucas(j, i);
gmp_printf("%9Zd ", j);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 20 Jacobsthal oblong numbers:\n");
for (i = 0; i < 20; ++i) {
mpz_mul(j, jac[i], jac[i+1]);
gmp_printf("%11Zd ", j);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 20 Jacobsthal primes:\n");
for (i = 0, count = 0; count < 20; ++i) {
jacobsthal(j, i);
if (mpz_probab_prime_p(j, 15) > 0) {
gmp_printf("%Zd\n", j);
++count;
}
}
return 0;
}
|
Write a version of this C++ function in C with identical behavior. | #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';
}
}
}
| #include <stdio.h>
#include <gmp.h>
void jacobsthal(mpz_t r, unsigned long n) {
mpz_t s;
mpz_init(s);
mpz_set_ui(r, 1);
mpz_mul_2exp(r, r, n);
mpz_set_ui(s, 1);
if (n % 2) mpz_neg(s, s);
mpz_sub(r, r, s);
mpz_div_ui(r, r, 3);
}
void jacobsthal_lucas(mpz_t r, unsigned long n) {
mpz_t a;
mpz_init(a);
mpz_set_ui(r, 1);
mpz_mul_2exp(r, r, n);
mpz_set_ui(a, 1);
if (n % 2) mpz_neg(a, a);
mpz_add(r, r, a);
}
int main() {
int i, count;
mpz_t jac[30], j;
printf("First 30 Jacobsthal numbers:\n");
for (i = 0; i < 30; ++i) {
mpz_init(jac[i]);
jacobsthal(jac[i], i);
gmp_printf("%9Zd ", jac[i]);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 30 Jacobsthal-Lucas numbers:\n");
mpz_init(j);
for (i = 0; i < 30; ++i) {
jacobsthal_lucas(j, i);
gmp_printf("%9Zd ", j);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 20 Jacobsthal oblong numbers:\n");
for (i = 0; i < 20; ++i) {
mpz_mul(j, jac[i], jac[i+1]);
gmp_printf("%11Zd ", j);
if (!((i+1)%5)) printf("\n");
}
printf("\nFirst 20 Jacobsthal primes:\n");
for (i = 0, count = 0; count < 20; ++i) {
jacobsthal(j, i);
if (mpz_probab_prime_p(j, 15) > 0) {
gmp_printf("%Zd\n", j);
++count;
}
}
return 0;
}
|
Produce a functionally identical C code for the snippet given in C++. |
#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] << ' ';
}
| #include <stdio.h>
#include <stdlib.h>
void bead_sort(int *a, int len)
{
int i, j, max, sum;
unsigned char *beads;
# define BEAD(i, j) beads[i * max + j]
for (i = 1, max = a[0]; i < len; i++)
if (a[i] > max) max = a[i];
beads = calloc(1, max * len);
for (i = 0; i < len; i++)
for (j = 0; j < a[i]; j++)
BEAD(i, j) = 1;
for (j = 0; j < max; j++) {
for (sum = i = 0; i < len; i++) {
sum += BEAD(i, j);
BEAD(i, j) = 0;
}
for (i = len - sum; i < len; i++) BEAD(i, j) = 1;
}
for (i = 0; i < len; i++) {
for (j = 0; j < max && BEAD(i, j); j++);
a[i] = j;
}
free(beads);
}
int main()
{
int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20};
int len = sizeof(x)/sizeof(x[0]);
bead_sort(x, len);
for (i = 0; i < len; i++)
printf("%d\n", x[i]);
return 0;
}
|
Port the following code from C++ to C with equivalent syntax and logic. | #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;
}
| #include <stdio.h>
#define GRID_SIZE 15
char canvas[GRID_SIZE][GRID_SIZE];
void initN() {
int i, j;
for (i = 0; i < GRID_SIZE; i++) {
for (j = 0; j < GRID_SIZE; j++) {
canvas[i][j] = ' ';
}
canvas[i][5] = 'x';
}
}
void horizontal(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
void vertical(size_t r1, size_t r2, size_t c) {
size_t r;
for (r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
void diagd(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
void diagu(size_t c1, size_t c2, size_t r) {
size_t c;
for (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);
}
}
void write(FILE *out) {
int i;
for (i = 0; i < GRID_SIZE; i++) {
fprintf(out, "%-.*s", GRID_SIZE, canvas[i]);
putc('\n', out);
}
}
void test(int n) {
printf("%d:\n", n);
initN();
draw(n);
write(stdout);
printf("\n\n");
}
int main() {
test(0);
test(1);
test(20);
test(300);
test(4000);
test(5555);
test(6789);
test(9999);
return 0;
}
|
Port the following code from C++ to C with equivalent syntax and logic. | #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;
}
| #include <stdio.h>
#define GRID_SIZE 15
char canvas[GRID_SIZE][GRID_SIZE];
void initN() {
int i, j;
for (i = 0; i < GRID_SIZE; i++) {
for (j = 0; j < GRID_SIZE; j++) {
canvas[i][j] = ' ';
}
canvas[i][5] = 'x';
}
}
void horizontal(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
void vertical(size_t r1, size_t r2, size_t c) {
size_t r;
for (r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
void diagd(size_t c1, size_t c2, size_t r) {
size_t c;
for (c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
void diagu(size_t c1, size_t c2, size_t r) {
size_t c;
for (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);
}
}
void write(FILE *out) {
int i;
for (i = 0; i < GRID_SIZE; i++) {
fprintf(out, "%-.*s", GRID_SIZE, canvas[i]);
putc('\n', out);
}
}
void test(int n) {
printf("%d:\n", n);
initN();
draw(n);
write(stdout);
printf("\n\n");
}
int main() {
test(0);
test(1);
test(20);
test(300);
test(4000);
test(5555);
test(6789);
test(9999);
return 0;
}
|
Translate the given C++ code snippet into C without altering its behavior. | #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;
}
| #include <gmp.h>
#include <stdio.h>
#include <string.h>
int main()
{
mpz_t a;
mpz_init_set_ui(a, 5);
mpz_pow_ui(a, a, 1 << 18);
int len = mpz_sizeinbase(a, 10);
printf("GMP says size is: %d\n", len);
char *s = mpz_get_str(0, 10, a);
printf("size really is %d\n", len = strlen(s));
printf("Digits: %.20s...%s\n", s, s + len - 20);
return 0;
}
|
Translate the given C++ code snippet into C without altering its behavior. |
#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;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { 30, 30, -50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
void draw_sphere(double R, double k, double ambient)
{
int i, j, intensity;
double b;
double vec[3], x, y;
for (i = floor(-R); i <= ceil(R); i++) {
x = i + .5;
for (j = floor(-2 * R); j <= ceil(2 * R); j++) {
y = j / 2. + .5;
if (x * x + y * y <= R * R) {
vec[0] = x;
vec[1] = y;
vec[2] = sqrt(R * R - x * x - y * y);
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
} else
putchar(' ');
}
putchar('\n');
}
}
int main()
{
normalize(light);
draw_sphere(20, 4, .1);
draw_sphere(10, 2, .4);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. |
#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;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { 30, 30, -50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
void draw_sphere(double R, double k, double ambient)
{
int i, j, intensity;
double b;
double vec[3], x, y;
for (i = floor(-R); i <= ceil(R); i++) {
x = i + .5;
for (j = floor(-2 * R); j <= ceil(2 * R); j++) {
y = j / 2. + .5;
if (x * x + y * y <= R * R) {
vec[0] = x;
vec[1] = y;
vec[2] = sqrt(R * R - x * x - y * y);
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
} else
putchar(' ');
}
putchar('\n');
}
}
int main()
{
normalize(light);
draw_sphere(20, 4, .1);
draw_sphere(10, 2, .4);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #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;
}
| #include <stdio.h>
#include <stdlib.h>
char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./";
int chr_idx[256] = {0};
char idx_chr[256] = {0};
#define FNAME 0
typedef struct trie_t *trie, trie_t;
struct trie_t {
trie next[sizeof(chr_legal)];
int eow;
};
trie trie_new() { return calloc(sizeof(trie_t), 1); }
#define find_word(r, w) trie_trav(r, w, 1)
trie trie_trav(trie root, const char * str, int no_create)
{
int c;
while (root) {
if ((c = str[0]) == '\0') {
if (!root->eow && no_create) return 0;
break;
}
if (! (c = chr_idx[c]) ) {
str++;
continue;
}
if (!root->next[c]) {
if (no_create) return 0;
root->next[c] = trie_new();
}
root = root->next[c];
str++;
}
return root;
}
int trie_all(trie root, char path[], int depth, int (*callback)(char *))
{
int i;
if (root->eow && !callback(path)) return 0;
for (i = 1; i < sizeof(chr_legal); i++) {
if (!root->next[i]) continue;
path[depth] = idx_chr[i];
path[depth + 1] = '\0';
if (!trie_all(root->next[i], path, depth + 1, callback))
return 0;
}
return 1;
}
void add_index(trie root, const char *word, const char *fname)
{
trie x = trie_trav(root, word, 0);
x->eow = 1;
if (!x->next[FNAME])
x->next[FNAME] = trie_new();
x = trie_trav(x->next[FNAME], fname, 0);
x->eow = 1;
}
int print_path(char *path)
{
printf(" %s", path);
return 1;
}
const char *files[] = { "f1.txt", "source/f2.txt", "other_file" };
const char *text[][5] ={{ "it", "is", "what", "it", "is" },
{ "what", "is", "it", 0 },
{ "it", "is", "a", "banana", 0 }};
trie init_tables()
{
int i, j;
trie root = trie_new();
for (i = 0; i < sizeof(chr_legal); i++) {
chr_idx[(int)chr_legal[i]] = i + 1;
idx_chr[i + 1] = chr_legal[i];
}
#define USE_ADVANCED_FILE_HANDLING 0
#if USE_ADVANCED_FILE_HANDLING
void read_file(const char * fname) {
char cmd[1024];
char word[1024];
sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname);
FILE *in = popen(cmd, "r");
while (!feof(in)) {
fscanf(in, "%1000s", word);
add_index(root, word, fname);
}
pclose(in);
};
read_file("f1.txt");
read_file("source/f2.txt");
read_file("other_file");
#else
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++) {
if (!text[i][j]) break;
add_index(root, text[i][j], files[i]);
}
}
#endif
return root;
}
void search_index(trie root, const char *word)
{
char path[1024];
printf("Search for \"%s\": ", word);
trie found = find_word(root, word);
if (!found) printf("not found\n");
else {
trie_all(found->next[FNAME], path, 0, print_path);
printf("\n");
}
}
int main()
{
trie root = init_tables();
search_index(root, "what");
search_index(root, "is");
search_index(root, "banana");
search_index(root, "boo");
return 0;
}
|
Write a version of this C++ function in C with identical behavior. | #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 ;
}
| #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}
|
Preserve the algorithm and functionality while converting the code from C++ to C. | #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 ;
}
| #include <stdio.h>
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf("lcm(35, 21) = %d\n", lcm(21,35));
return 0;
}
|
Produce a functionally identical C code for the snippet given in C++. | #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;
}
| #include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
void mpz_factors(mpz_t n) {
int factors = 0;
mpz_t s, m, p;
mpz_init(s), mpz_init(m), mpz_init(p);
mpz_set_ui(m, 3);
mpz_set(p, n);
mpz_sqrt(s, p);
while (mpz_cmp(m, s) < 0) {
if (mpz_divisible_p(p, m)) {
gmp_printf("%Zd ", m);
mpz_fdiv_q(p, p, m);
mpz_sqrt(s, p);
factors ++;
}
mpz_add_ui(m, m, 2);
}
if (factors == 0) printf("PRIME\n");
else gmp_printf("%Zd\n", p);
}
int main(int argc, char const *argv[]) {
mpz_t fermat;
mpz_init_set_ui(fermat, 3);
printf("F(0) = 3 -> PRIME\n");
for (unsigned i = 1; i < 10; i ++) {
mpz_sub_ui(fermat, fermat, 1);
mpz_mul(fermat, fermat, fermat);
mpz_add_ui(fermat, fermat, 1);
gmp_printf("F(%d) = %Zd -> ", i, fermat);
mpz_factors(fermat);
}
return 0;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #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;
}
| int main(){
time_t t;
int a, b;
srand((unsigned)time(&t));
for(;;){
a = rand() % 20;
printf("%d\n", a);
if(a == 10)
break;
b = rand() % 20;
printf("%d\n", b);
}
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #include <iostream>
#include <fstream>
int main(){
std::ofstream lprFile;
lprFile.open( "/dev/lp0" );
lprFile << "Hello World!\n";
lprFile.close();
return 0;
}
| #include <stdio.h>
int main()
{
FILE *lp;
lp = fopen("/dev/lp0","w");
fprintf(lp,"Hello world!\n");
fclose(lp);
return 0;
}
|
Change the following C++ code into C without altering its purpose. | #include <iostream>
#include <fstream>
int main(){
std::ofstream lprFile;
lprFile.open( "/dev/lp0" );
lprFile << "Hello World!\n";
lprFile.close();
return 0;
}
| #include <stdio.h>
int main()
{
FILE *lp;
lp = fopen("/dev/lp0","w");
fprintf(lp,"Hello world!\n");
fclose(lp);
return 0;
}
|
Write a version of this C++ function in C with identical behavior. | #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;
}
| #include<stdlib.h>
#include<stdio.h>
int getWater(int* arr,int start,int end,int cutoff){
int i, sum = 0;
for(i=start;i<=end;i++)
sum += ((arr[cutoff] > arr[i])?(arr[cutoff] - arr[i]):0);
return sum;
}
int netWater(int* arr,int size){
int i, j, ref1, ref2, marker, markerSet = 0,sum = 0;
if(size<3)
return 0;
for(i=0;i<size-1;i++){
start:if(i!=size-2 && arr[i]>arr[i+1]){
ref1 = i;
for(j=ref1+1;j<size;j++){
if(arr[j]>=arr[ref1]){
ref2 = j;
sum += getWater(arr,ref1+1,ref2-1,ref1);
i = ref2;
goto start;
}
else if(j!=size-1 && arr[j] < arr[j+1] && (markerSet==0||(arr[j+1]>=arr[marker]))){
marker = j+1;
markerSet = 1;
}
}
if(markerSet==1){
sum += getWater(arr,ref1+1,marker-1,marker);
i = marker;
markerSet = 0;
goto start;
}
}
}
return sum;
}
int main(int argC,char* argV[])
{
int *arr,i;
if(argC==1)
printf("Usage : %s <followed by space separated series of integers>");
else{
arr = (int*)malloc((argC-1)*sizeof(int));
for(i=1;i<argC;i++)
arr[i-1] = atoi(argV[i]);
printf("Water collected : %d",netWater(arr,argC-1));
}
return 0;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #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);
}
| #include <stdio.h>
int 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 0; return 1; }
int main() {
unsigned int c = 0, nc, pc = 9, i, a, b, l,
ps[128], nxt[128];
for (a = 0, b = 1; a < pc; a = b++) ps[a] = b;
while (1) {
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);
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #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;
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
#define TRILLION 1000000000000
typedef unsigned char bool;
typedef unsigned long long uint64;
void sieve(uint64 limit, uint64 *primes, uint64 *length) {
uint64 i, count, p, p2;
bool *c = calloc(limit + 1, sizeof(bool));
primes[0] = 2;
count = 1;
p = 3;
for (;;) {
p2 = p * p;
if (p2 > limit) break;
for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;
for (;;) {
p += 2;
if (!c[p]) break;
}
}
for (i = 3; i <= limit; i += 2) {
if (!c[i]) primes[count++] = i;
}
*length = count;
free(c);
}
void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {
uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);
uint64 *primes = malloc((limit + 1) * sizeof(uint64));
bool add;
sieve(limit, primes, &np);
for (i = from; i <= to; ++i) {
add = TRUE;
for (j = 0; j < np; ++j) {
p = primes[j];
p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) {
add = FALSE;
break;
}
}
if (add) results[count++] = i;
}
*len = count;
free(primes);
}
int main() {
uint64 i, *sf, len;
sf = malloc(1000000 * sizeof(uint64));
printf("Square-free integers from 1 to 145:\n");
squareFree(1, 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 20 == 0) {
printf("\n");
}
printf("%4lld", sf[i]);
}
printf("\n\nSquare-free integers from %ld to %ld:\n", TRILLION, TRILLION + 145);
squareFree(TRILLION, TRILLION + 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 5 == 0) {
printf("\n");
}
printf("%14lld", sf[i]);
}
printf("\n\nNumber of square-free integers:\n");
int a[5] = {100, 1000, 10000, 100000, 1000000};
for (i = 0; i < 5; ++i) {
squareFree(1, a[i], sf, &len);
printf(" from %d to %d = %lld\n", 1, a[i], len);
}
free(sf);
return 0;
}
|
Port the following code from C++ to C with equivalent syntax and logic. | #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;
}
| #include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
double jaro(const char *str1, const char *str2) {
int str1_len = strlen(str1);
int str2_len = strlen(str2);
if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0;
int match_distance = (int) max(str1_len, str2_len)/2 - 1;
int *str1_matches = calloc(str1_len, sizeof(int));
int *str2_matches = calloc(str2_len, sizeof(int));
double matches = 0.0;
double transpositions = 0.0;
for (int i = 0; i < str1_len; i++) {
int start = max(0, i - match_distance);
int end = min(i + match_distance + 1, str2_len);
for (int k = start; k < end; k++) {
if (str2_matches[k]) continue;
if (str1[i] != str2[k]) continue;
str1_matches[i] = TRUE;
str2_matches[k] = TRUE;
matches++;
break;
}
}
if (matches == 0) {
free(str1_matches);
free(str2_matches);
return 0.0;
}
int k = 0;
for (int i = 0; i < str1_len; i++) {
if (!str1_matches[i]) continue;
while (!str2_matches[k]) k++;
if (str1[i] != str2[k]) transpositions++;
k++;
}
transpositions /= 2.0;
free(str1_matches);
free(str2_matches);
return ((matches / str1_len) +
(matches / str2_len) +
((matches - transpositions) / matches)) / 3.0;
}
int main() {
printf("%f\n", jaro("MARTHA", "MARHTA"));
printf("%f\n", jaro("DIXON", "DICKSONX"));
printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"));
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #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;
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t {
int x, y;
struct node_t *prev, *next;
} node;
node *new_node(int x, int y) {
node *n = malloc(sizeof(node));
n->x = x;
n->y = y;
n->next = NULL;
n->prev = NULL;
return n;
}
void free_node(node **n) {
if (n == NULL) {
return;
}
(*n)->prev = NULL;
(*n)->next = NULL;
free(*n);
*n = NULL;
}
typedef struct list_t {
node *head;
node *tail;
} list;
list make_list() {
list lst = { NULL, NULL };
return lst;
}
void append_node(list *const lst, int x, int y) {
if (lst == NULL) {
return;
}
node *n = new_node(x, y);
if (lst->head == NULL) {
lst->head = n;
lst->tail = n;
} else {
n->prev = lst->tail;
lst->tail->next = n;
lst->tail = n;
}
}
void remove_node(list *const lst, const node *const n) {
if (lst == NULL || n == NULL) {
return;
}
if (n->prev != NULL) {
n->prev->next = n->next;
if (n->next != NULL) {
n->next->prev = n->prev;
} else {
lst->tail = n->prev;
}
} else {
if (n->next != NULL) {
n->next->prev = NULL;
lst->head = n->next;
}
}
free_node(&n);
}
void free_list(list *const lst) {
node *ptr;
if (lst == NULL) {
return;
}
ptr = lst->head;
while (ptr != NULL) {
node *nxt = ptr->next;
free_node(&ptr);
ptr = nxt;
}
lst->head = NULL;
lst->tail = NULL;
}
void print_list(const list *lst) {
node *it;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
int prod = it->x * it->y;
printf("[%d, %d] S=%d P=%d\n", it->x, it->y, sum, prod);
}
}
void print_count(const list *const lst) {
node *it;
int c = 0;
if (lst == NULL) {
return;
}
for (it = lst->head; it != NULL; it = it->next) {
c++;
}
if (c == 0) {
printf("no candidates\n");
} else if (c == 1) {
printf("one candidate\n");
} else {
printf("%d candidates\n", c);
}
}
void setup(list *const lst) {
int x, y;
if (lst == NULL) {
return;
}
for (x = 2; x <= 98; x++) {
for (y = x + 1; y <= 98; y++) {
if (x + y <= 100) {
append_node(lst, x, y);
}
}
}
}
void remove_by_sum(list *const lst, const int sum) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int s = it->x + it->y;
if (s == sum) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void remove_by_prod(list *const lst, const int prod) {
node *it;
if (lst == NULL) {
return;
}
it = lst->head;
while (it != NULL) {
int p = it->x * it->y;
if (p == prod) {
remove_node(lst, it);
it = lst->head;
} else {
it = it->next;
}
}
}
void statement1(list *const lst) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = lst->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = lst->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] == 1) {
remove_by_sum(lst, it->x + it->y);
it = lst->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement2(list *const candidates) {
short *unique = calloc(100000, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int prod = it->x * it->y;
unique[prod]++;
}
it = candidates->head;
while (it != NULL) {
int prod = it->x * it->y;
nxt = it->next;
if (unique[prod] > 1) {
remove_by_prod(candidates, prod);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
void statement3(list *const candidates) {
short *unique = calloc(100, sizeof(short));
node *it, *nxt;
for (it = candidates->head; it != NULL; it = it->next) {
int sum = it->x + it->y;
unique[sum]++;
}
it = candidates->head;
while (it != NULL) {
int sum = it->x + it->y;
nxt = it->next;
if (unique[sum] > 1) {
remove_by_sum(candidates, sum);
it = candidates->head;
} else {
it = nxt;
}
}
free(unique);
}
int main() {
list candidates = make_list();
setup(&candidates);
print_count(&candidates);
statement1(&candidates);
print_count(&candidates);
statement2(&candidates);
print_count(&candidates);
statement3(&candidates);
print_count(&candidates);
print_list(&candidates);
free_list(&candidates);
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #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;
}
| #include <stdio.h>
#include <stdlib.h>
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) {
int i;
printf("Base %2d:", base);
for (i = 0; i < count; i++) {
int t = turn(base, i);
printf(" %2d", t);
}
printf("\n");
}
void turnCount(int base, int count) {
int *cnt = calloc(base, sizeof(int));
int i, minTurn, maxTurn, portion;
if (NULL == cnt) {
printf("Failed to allocate space to determine the spread of turns.\n");
return;
}
for (i = 0; i < count; i++) {
int t = turn(base, i);
cnt[t]++;
}
minTurn = INT_MAX;
maxTurn = INT_MIN;
portion = 0;
for (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);
}
free(cnt);
}
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;
}
|
Translate this program into C but keep the logic exactly as in C++. | #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;
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static int nextInt(int size) {
return rand() % size;
}
static bool cylinder[6];
static void rshift() {
bool t = cylinder[5];
int i;
for (i = 4; i >= 0; i--) {
cylinder[i + 1] = cylinder[i];
}
cylinder[0] = t;
}
static void unload() {
int i;
for (i = 0; i < 6; i++) {
cylinder[i] = false;
}
}
static void load() {
while (cylinder[0]) {
rshift();
}
cylinder[0] = true;
rshift();
}
static void spin() {
int lim = nextInt(6) + 1;
int i;
for (i = 1; i < lim; i++) {
rshift();
}
}
static bool fire() {
bool shot = cylinder[0];
rshift();
return shot;
}
static int method(const char *s) {
unload();
for (; *s != '\0'; s++) {
switch (*s) {
case 'L':
load();
break;
case 'S':
spin();
break;
case 'F':
if (fire()) {
return 1;
}
break;
}
}
return 0;
}
static void append(char *out, const char *txt) {
if (*out != '\0') {
strcat(out, ", ");
}
strcat(out, txt);
}
static void mstring(const char *s, char *out) {
for (; *s != '\0'; s++) {
switch (*s) {
case 'L':
append(out, "load");
break;
case 'S':
append(out, "spin");
break;
case 'F':
append(out, "fire");
break;
}
}
}
static void test(char *src) {
char buffer[41] = "";
const int tests = 100000;
int sum = 0;
int t;
double pc;
for (t = 0; t < tests; t++) {
sum += method(src);
}
mstring(src, buffer);
pc = 100.0 * sum / tests;
printf("%-40s produces %6.3f%% deaths.\n", buffer, pc);
}
int main() {
srand(time(0));
test("LSLSFSF");
test("LSLSFF");
test("LLSFSF");
test("LLSFF");
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | #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;
}
| #include <sys/types.h>
#include <regex.h>
#include <stdio.h>
typedef struct {
const char *s;
int len, prec, assoc;
} str_tok_t;
typedef struct {
const char * str;
int assoc, prec;
regex_t re;
} pat_t;
enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {"", A_NONE, 0};
pat_t pat_ops[] = {
{"^\\)", A_NONE, -1},
{"^\\*\\*", A_R, 3},
{"^\\^", A_R, 3},
{"^\\*", A_L, 2},
{"^/", A_L, 2},
{"^\\+", A_L, 1},
{"^-", A_L, 1},
{0}
};
pat_t pat_arg[] = {
{"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"},
{"^[a-zA-Z_][a-zA-Z_0-9]*"},
{"^\\(", A_L, -1},
{0}
};
str_tok_t stack[256];
str_tok_t queue[256];
int l_queue, l_stack;
#define qpush(x) queue[l_queue++] = x
#define spush(x) stack[l_stack++] = x
#define spop() stack[--l_stack]
void display(const char *s)
{
int i;
printf("\033[1;1H\033[JText | %s", s);
printf("\nStack| ");
for (i = 0; i < l_stack; i++)
printf("%.*s ", stack[i].len, stack[i].s);
printf("\nQueue| ");
for (i = 0; i < l_queue; i++)
printf("%.*s ", queue[i].len, queue[i].s);
puts("\n\n<press enter>");
getchar();
}
int prec_booster;
#define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;}
int init(void)
{
int i;
pat_t *p;
for (i = 0, p = pat_ops; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
for (i = 0, p = pat_arg; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
return 1;
}
pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)
{
int i;
regmatch_t m;
while (*s == ' ') s++;
*e = s;
if (!*s) return &pat_eos;
for (i = 0; p[i].str; i++) {
if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))
continue;
t->s = s;
*e = s + (t->len = m.rm_eo - m.rm_so);
return p + i;
}
return 0;
}
int parse(const char *s) {
pat_t *p;
str_tok_t *t, tok;
prec_booster = l_queue = l_stack = 0;
display(s);
while (*s) {
p = match(s, pat_arg, &tok, &s);
if (!p || p == &pat_eos) fail("parse arg", s);
if (p->prec == -1) {
prec_booster += 100;
continue;
}
qpush(tok);
display(s);
re_op: p = match(s, pat_ops, &tok, &s);
if (!p) fail("parse op", s);
tok.assoc = p->assoc;
tok.prec = p->prec;
if (p->prec > 0)
tok.prec = p->prec + prec_booster;
else if (p->prec == -1) {
if (prec_booster < 100)
fail("unmatched )", s);
tok.prec = prec_booster;
}
while (l_stack) {
t = stack + l_stack - 1;
if (!(t->prec == tok.prec && t->assoc == A_L)
&& t->prec <= tok.prec)
break;
qpush(spop());
display(s);
}
if (p->prec == -1) {
prec_booster -= 100;
goto re_op;
}
if (!p->prec) {
display(s);
if (prec_booster)
fail("unmatched (", s);
return 1;
}
spush(tok);
display(s);
}
if (p->prec > 0)
fail("unexpected eol", s);
return 1;
}
int main()
{
int i;
const char *tests[] = {
"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",
"123",
"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14",
"(((((((1+2+3**(4 + 5))))))",
"a^(b + c/d * .1e5)!",
"(1**2)**3",
"2 + 2 *",
0
};
if (!init()) return 1;
for (i = 0; tests[i]; i++) {
printf("Testing string `%s' <enter>\n", tests[i]);
getchar();
printf("string `%s': %s\n\n", tests[i],
parse(tests[i]) ? "Ok" : "Error");
}
return 0;
}
|
Generate an equivalent C version of this C++ code. | #include <cassert>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
bool is_prime(unsigned int n) {
assert(n > 0 && n < 64);
return (1ULL << n) & 0x28208a20a08a28ac;
}
template <typename Iterator>
bool prime_triangle_row(Iterator begin, Iterator end) {
if (std::distance(begin, end) == 2)
return is_prime(*begin + *(begin + 1));
for (auto i = begin + 1; i + 1 != end; ++i) {
if (is_prime(*begin + *i)) {
std::iter_swap(i, begin + 1);
if (prime_triangle_row(begin + 1, end))
return true;
std::iter_swap(i, begin + 1);
}
}
return false;
}
template <typename Iterator>
void prime_triangle_count(Iterator begin, Iterator end, int& count) {
if (std::distance(begin, end) == 2) {
if (is_prime(*begin + *(begin + 1)))
++count;
return;
}
for (auto i = begin + 1; i + 1 != end; ++i) {
if (is_prime(*begin + *i)) {
std::iter_swap(i, begin + 1);
prime_triangle_count(begin + 1, end, count);
std::iter_swap(i, begin + 1);
}
}
}
template <typename Iterator>
void print(Iterator begin, Iterator end) {
if (begin == end)
return;
auto i = begin;
std::cout << std::setw(2) << *i++;
for (; i != end; ++i)
std::cout << ' ' << std::setw(2) << *i;
std::cout << '\n';
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
for (unsigned int n = 2; n < 21; ++n) {
std::vector<unsigned int> v(n);
std::iota(v.begin(), v.end(), 1);
if (prime_triangle_row(v.begin(), v.end()))
print(v.begin(), v.end());
}
std::cout << '\n';
for (unsigned int n = 2; n < 21; ++n) {
std::vector<unsigned int> v(n);
std::iota(v.begin(), v.end(), 1);
int count = 0;
prime_triangle_count(v.begin(), v.end(), count);
if (n > 2)
std::cout << ' ';
std::cout << count;
}
std::cout << '\n';
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration(end - start);
std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}
| #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
bool is_prime(unsigned int n) {
assert(n < 64);
static bool isprime[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0,
0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0};
return isprime[n];
}
void swap(unsigned int* a, size_t i, size_t j) {
unsigned int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
bool prime_triangle_row(unsigned int* a, size_t length) {
if (length == 2)
return is_prime(a[0] + a[1]);
for (size_t i = 1; i + 1 < length; i += 2) {
if (is_prime(a[0] + a[i])) {
swap(a, i, 1);
if (prime_triangle_row(a + 1, length - 1))
return true;
swap(a, i, 1);
}
}
return false;
}
int prime_triangle_count(unsigned int* a, size_t length) {
int count = 0;
if (length == 2) {
if (is_prime(a[0] + a[1]))
++count;
} else {
for (size_t i = 1; i + 1 < length; i += 2) {
if (is_prime(a[0] + a[i])) {
swap(a, i, 1);
count += prime_triangle_count(a + 1, length - 1);
swap(a, i, 1);
}
}
}
return count;
}
void print(unsigned int* a, size_t length) {
if (length == 0)
return;
printf("%2u", a[0]);
for (size_t i = 1; i < length; ++i)
printf(" %2u", a[i]);
printf("\n");
}
int main() {
clock_t start = clock();
for (unsigned int n = 2; n < 21; ++n) {
unsigned int a[n];
for (unsigned int i = 0; i < n; ++i)
a[i] = i + 1;
if (prime_triangle_row(a, n))
print(a, n);
}
printf("\n");
for (unsigned int n = 2; n < 21; ++n) {
unsigned int a[n];
for (unsigned int i = 0; i < n; ++i)
a[i] = i + 1;
if (n > 2)
printf(" ");
printf("%d", prime_triangle_count(a, n));
}
printf("\n");
clock_t end = clock();
double duration = (end - start + 0.0) / CLOCKS_PER_SEC;
printf("\nElapsed time: %f seconds\n", duration);
return 0;
}
|
Translate this program into C but keep the logic exactly as in C++. | #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 ;
}
| #include<math.h>
#include<stdio.h>
int
main ()
{
double inputs[11], check = 400, result;
int i;
printf ("\nPlease enter 11 numbers :");
for (i = 0; i < 11; i++)
{
scanf ("%lf", &inputs[i]);
}
printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for (i = 10; i >= 0; i--)
{
result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);
printf ("\nf(%lf) = ");
if (result > check)
{
printf ("Overflow!");
}
else
{
printf ("%lf", result);
}
}
return 0;
}
|
Write the same code in C as shown below in C++. | #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";
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * mid3(int n)
{
static char buf[32];
int l;
sprintf(buf, "%d", n > 0 ? n : -n);
l = strlen(buf);
if (l < 3 || !(l & 1)) return 0;
l = l / 2 - 1;
buf[l + 3] = 0;
return buf + l;
}
int main(void)
{
int x[] = {123, 12345, 1234567, 987654321, 10001, -10001,
-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,
1234567890};
int i;
char *m;
for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {
if (!(m = mid3(x[i])))
m = "error";
printf("%d: %s\n", x[i], m);
}
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #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;
}
| #include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#define LIMIT 15
int smallPrimes[LIMIT];
static void sieve() {
int i = 2, j;
int p = 5;
smallPrimes[0] = 2;
smallPrimes[1] = 3;
while (i < LIMIT) {
for (j = 0; j < i; j++) {
if (smallPrimes[j] * smallPrimes[j] <= p) {
if (p % smallPrimes[j] == 0) {
p += 2;
break;
}
} else {
smallPrimes[i++] = p;
p += 2;
break;
}
}
}
}
static bool is_prime(uint64_t n) {
uint64_t i;
for (i = 0; i < LIMIT; i++) {
if (n % smallPrimes[i] == 0) {
return n == smallPrimes[i];
}
}
i = smallPrimes[LIMIT - 1] + 2;
for (; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
static uint64_t divisor_count(uint64_t n) {
uint64_t count = 1;
uint64_t d;
while (n % 2 == 0) {
n /= 2;
count++;
}
for (d = 3; d * d <= n; d += 2) {
uint64_t q = n / d;
uint64_t r = n % d;
uint64_t dc = 0;
while (r == 0) {
dc += count;
n = q;
q = n / d;
r = n % d;
}
count += dc;
}
if (n != 1) {
return count *= 2;
}
return count;
}
static uint64_t OEISA073916(size_t n) {
uint64_t count = 0;
uint64_t result = 0;
size_t i;
if (is_prime(n)) {
return (uint64_t)pow(smallPrimes[n - 1], n - 1);
}
for (i = 1; count < n; i++) {
if (n % 2 == 1) {
uint64_t root = (uint64_t)sqrt(i);
if (root * root != i) {
continue;
}
}
if (divisor_count(i) == n) {
count++;
result = i;
}
}
return result;
}
int main() {
size_t n;
sieve();
for (n = 1; n <= LIMIT; n++) {
if (n == 13) {
printf("A073916(%lu) = One more bit needed to represent result.\n", n);
} else {
printf("A073916(%lu) = %llu\n", n, OEISA073916(n));
}
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #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;
}
| #include <stdio.h>
#define MAX 15
int count_divisors(int n) {
int i, count = 0;
for (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;
printf("The first %d terms of the sequence are:\n", MAX);
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) printf("%d ", seq[i]);
printf("\n");
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #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;
}
| #include <stdio.h>
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() {
int i, j;
for (i = 0; i < 4; i++) {
for (j = 1; j < 6; j++) {
int n = i * 5 + j;
printf("p(%2d) = %2d ", n, pancake(n));
}
printf("\n");
}
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #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;
}
| #include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
char grid[8][8];
void placeKings() {
int r1, r2, c1, c2;
for (;;) {
r1 = rand() % 8;
c1 = rand() % 8;
r2 = rand() % 8;
c2 = rand() % 8;
if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {
grid[r1][c1] = 'K';
grid[r2][c2] = 'k';
return;
}
}
}
void placePieces(const char *pieces, bool isPawn) {
int n, r, c;
int numToPlace = rand() % strlen(pieces);
for (n = 0; n < numToPlace; ++n) {
do {
r = rand() % 8;
c = rand() % 8;
}
while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));
grid[r][c] = pieces[n];
}
}
void toFen() {
char fen[80], ch;
int r, c, countEmpty = 0, index = 0;
for (r = 0; r < 8; ++r) {
for (c = 0; c < 8; ++c) {
ch = grid[r][c];
printf("%2c ", ch == 0 ? '.' : ch);
if (ch == 0) {
countEmpty++;
}
else {
if (countEmpty > 0) {
fen[index++] = countEmpty + 48;
countEmpty = 0;
}
fen[index++] = ch;
}
}
if (countEmpty > 0) {
fen[index++] = countEmpty + 48;
countEmpty = 0;
}
fen[index++]= '/';
printf("\n");
}
strcpy(fen + index, " w - - 0 1");
printf("%s\n", fen);
}
char *createFen() {
placeKings();
placePieces("PPPPPPPP", TRUE);
placePieces("pppppppp", TRUE);
placePieces("RNBQBNR", FALSE);
placePieces("rnbqbnr", FALSE);
toFen();
}
int main() {
srand(time(NULL));
createFen();
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #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;
}
| #include <stdio.h>
#include <string.h>
#include <locale.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
char as_digit(int d) {
return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';
}
void revstr(char *str) {
int i, len = strlen(str);
char t;
for (i = 0; i < len/2; ++i) {
t = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = t;
}
}
char* to_base(char s[], ull n, int b) {
int i = 0;
while (n) {
s[i++] = as_digit(n % b);
n /= b;
}
s[i] = '\0';
revstr(s);
return s;
}
ull uabs(ull a, ull b) {
return a > b ? a - b : b - a;
}
bool is_esthetic(ull n, int b) {
int i, j;
if (!n) return FALSE;
i = n % b;
n /= b;
while (n) {
j = n % b;
if (uabs(i, j) != 1) return FALSE;
n /= b;
i = j;
}
return TRUE;
}
ull esths[45000];
int le = 0;
void dfs(ull n, ull m, ull i) {
ull d, i1, i2;
if (i >= n && i <= m) esths[le++] = i;
if (i == 0 || i > m) return;
d = i % 10;
i1 = i * 10 + d - 1;
i2 = i1 + 2;
if (d == 0) {
dfs(n, m, i2);
} else if (d == 9) {
dfs(n, m, i1);
} else {
dfs(n, m, i1);
dfs(n, m, i2);
}
}
void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {
int i;
le = 0;
for (i = 0; i < 10; ++i) {
dfs(n2, m2, i);
}
printf("Base 10: %'d esthetic numbers between %'llu and %'llu:\n", le, n, m);
if (all) {
for (i = 0; i < le; ++i) {
printf("%llu ", esths[i]);
if (!(i+1)%per_line) printf("\n");
}
} else {
for (i = 0; i < per_line; ++i) printf("%llu ", esths[i]);
printf("\n............\n");
for (i = le - per_line; i < le; ++i) printf("%llu ", esths[i]);
}
printf("\n\n");
}
int main() {
ull n;
int b, c;
char ch[15] = {0};
for (b = 2; b <= 16; ++b) {
printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b);
for (n = 1, c = 0; c < 6 * b; ++n) {
if (is_esthetic(n, b)) {
if (++c >= 4 * b) printf("%s ", to_base(ch, n, b));
}
}
printf("\n\n");
}
char *oldLocale = setlocale(LC_NUMERIC, NULL);
setlocale(LC_NUMERIC, "");
list_esths(1000, 1010, 9999, 9898, 16, TRUE);
list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);
list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);
list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);
list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);
setlocale(LC_NUMERIC, oldLocale);
return 0;
}
|
Transform the following C++ implementation into C, maintaining the same output and logic. | #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;
}
| #include <stdio.h>
#include <string.h>
typedef struct { char v[16]; } deck;
typedef unsigned int uint;
uint n, d, best[16];
void tryswaps(deck *a, uint f, uint s) {
# define A a->v
# define B b.v
if (d > best[n]) best[n] = d;
while (1) {
if ((A[s] == s || (A[s] == -1 && !(f & 1U << s)))
&& (d + best[s] >= best[n] || A[s] == -1))
break;
if (d + best[s] <= best[n]) return;
if (!--s) return;
}
d++;
deck b = *a;
for (uint i = 1, k = 2; i <= s; k <<= 1, i++) {
if (A[i] != i && (A[i] != -1 || (f & k)))
continue;
for (uint j = B[0] = i; j--;) B[i - j] = A[j];
tryswaps(&b, f | k, s);
}
d--;
}
int main(void) {
deck x;
memset(&x, -1, sizeof(x));
x.v[0] = 0;
for (n = 1; n < 13; n++) {
tryswaps(&x, 1, n - 1);
printf("%2d: %d\n", n, best[n]);
}
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #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;
}
| #include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
#define UNITS_LENGTH 13
int main(int argC,char* argV[])
{
int i,reference;
char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"};
double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};
if(argC!=3)
printf("Usage : %s followed by length as <value> <unit>");
else{
for(i=0;argV[2][i]!=00;i++)
argV[2][i] = tolower(argV[2][i]);
for(i=0;i<UNITS_LENGTH;i++){
if(strstr(argV[2],units[i])!=NULL){
reference = i;
factor = atof(argV[1])*values[i];
break;
}
}
printf("%s %s is equal in length to : \n",argV[1],argV[2]);
for(i=0;i<UNITS_LENGTH;i++){
if(i!=reference)
printf("\n%lf %s",factor/values[i],units[i]);
}
}
return 0;
}
|
Change the following C++ code into C without altering its purpose. | #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;
}
| #include <stdio.h>
#include <time.h>
struct rate_state_s
{
time_t lastFlush;
time_t period;
size_t tickCount;
};
void tic_rate(struct rate_state_s* pRate)
{
pRate->tickCount += 1;
time_t now = time(NULL);
if((now - pRate->lastFlush) >= pRate->period)
{
size_t tps = 0.0;
if(pRate->tickCount > 0)
tps = pRate->tickCount / (now - pRate->lastFlush);
printf("%u tics per second.\n", tps);
pRate->tickCount = 0;
pRate->lastFlush = now;
}
}
void something_we_do()
{
volatile size_t anchor = 0;
size_t x = 0;
for(x = 0; x < 0xffff; ++x)
{
anchor = x;
}
}
int main()
{
time_t start = time(NULL);
struct rate_state_s rateWatch;
rateWatch.lastFlush = start;
rateWatch.tickCount = 0;
rateWatch.period = 5;
time_t latest = start;
for(latest = start; (latest - start) < 20; latest = time(NULL))
{
something_we_do();
tic_rate(&rateWatch);
}
return 0;
}
|
Write the same code in C as shown below in C++. | #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;
}
| #include <stdio.h>
#define MAX 15
int count_divisors(int n) {
int i, count = 0;
for (i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
int main() {
int i, next = 1;
printf("The first %d terms of the sequence are:\n", MAX);
for (i = 1; next <= MAX; ++i) {
if (next == count_divisors(i)) {
printf("%d ", i);
next++;
}
}
printf("\n");
return 0;
}
|
Write the same algorithm in C as shown in this C++ implementation. | #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;
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int pRec(int n) {
static int *memo = NULL;
static size_t curSize = 0;
if (curSize <= (size_t) n) {
size_t lastSize = curSize;
while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);
memo = realloc(memo, curSize * sizeof(int));
memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));
}
if (memo[n] == 0) {
if (n<=2) memo[n] = 1;
else memo[n] = pRec(n-2) + pRec(n-3);
}
return memo[n];
}
int pFloor(int n) {
long double p = 1.324717957244746025960908854;
long double s = 1.0453567932525329623;
return powl(p, n-1)/s + 0.5;
}
void nextLSystem(const char *prev, char *buf) {
while (*prev) {
switch (*prev++) {
case 'A': *buf++ = 'B'; break;
case 'B': *buf++ = 'C'; break;
case 'C': *buf++ = 'A'; *buf++ = 'B'; break;
}
}
*buf = '\0';
}
int main() {
#define BUFSZ 8192
char buf1[BUFSZ], buf2[BUFSZ];
int i;
printf("P_0 .. P_19: ");
for (i=0; i<20; i++) printf("%d ", pRec(i));
printf("\n");
printf("The floor- and recurrence-based functions ");
for (i=0; i<64; i++) {
if (pRec(i) != pFloor(i)) {
printf("do not match at %d: %d != %d.\n",
i, pRec(i), pFloor(i));
break;
}
}
if (i == 64) {
printf("match from P_0 to P_63.\n");
}
printf("\nThe first 10 L-system strings are:\n");
for (strcpy(buf1, "A"), i=0; i<10; i++) {
printf("%s\n", buf1);
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
printf("\nThe floor- and L-system-based functions ");
for (strcpy(buf1, "A"), i=0; i<32; i++) {
if ((int)strlen(buf1) != pFloor(i)) {
printf("do not match at %d: %d != %d\n",
i, (int)strlen(buf1), pFloor(i));
break;
}
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
if (i == 32) {
printf("match from P_0 to P_31.\n");
}
return 0;
}
|
Generate an equivalent C version of this C++ code. | #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;
}
| #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
typedef struct{
double x,y;
}point;
void pythagorasTree(point a,point b,int times){
point c,d,e;
c.x = b.x - (a.y - b.y);
c.y = b.y - (b.x - a.x);
d.x = a.x - (a.y - b.y);
d.y = a.y - (b.x - a.x);
e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2;
e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2;
if(times>0){
setcolor(rand()%15 + 1);
line(a.x,a.y,b.x,b.y);
line(c.x,c.y,b.x,b.y);
line(c.x,c.y,d.x,d.y);
line(a.x,a.y,d.x,d.y);
pythagorasTree(d,e,times-1);
pythagorasTree(e,c,times-1);
}
}
int main(){
point a,b;
double side;
int iter;
time_t t;
printf("Enter initial side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
scanf("%d",&iter);
a.x = 6*side/2 - side/2;
a.y = 4*side;
b.x = 6*side/2 + side/2;
b.y = 4*side;
initwindow(6*side,4*side,"Pythagoras Tree ?");
srand((unsigned)time(&t));
pythagorasTree(a,b,iter);
getch();
closegraph();
return 0;
}
|
Write the same code in C as shown below in C++. | #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;
}
| #include <stdio.h>
#include <ctype.h>
static int
owp(int odd)
{
int ch, ret;
ch = getc(stdin);
if (!odd) {
putc(ch, stdout);
if (ch == EOF || ch == '.')
return EOF;
if (ispunct(ch))
return 0;
owp(odd);
return 0;
} else {
if (ispunct(ch))
return ch;
ret = owp(odd);
putc(ch, stdout);
return ret;
}
}
int
main(int argc, char **argv)
{
int ch = 1;
while ((ch = owp(!ch)) != EOF) {
if (ch)
putc(ch, stdout);
if (ch == '.')
break;
}
return 0;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #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;
}
| #include <math.h>
#include <stdio.h>
#include <stdint.h>
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;
}
const static int64_t a1[3] = { 0, 1403580, -810728 };
const static int64_t m1 = (1LL << 32) - 209;
const static int64_t a2[3] = { 527612, 0, -1370589 };
const static int64_t m2 = (1LL << 32) - 22853;
const static int64_t d = (1LL << 32) - 209 + 1;
static int64_t x1[3];
static int64_t x2[3];
void seed(int64_t seed_state) {
x1[0] = seed_state;
x1[1] = 0;
x1[2] = 0;
x2[0] = seed_state;
x2[1] = 0;
x2[2] = 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[2] = x1[1];
x1[1] = x1[0];
x1[0] = x1i;
x2[2] = x2[1];
x2[1] = x2[0];
x2[0] = x2i;
return z + 1;
}
double next_float() {
return (double)next_int() / d;
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
seed(1234567);
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("%lld\n", next_int());
printf("\n");
seed(987654321);
for (i = 0; i < 100000; i++) {
int64_t value = floor(next_float() * 5);
counts[value]++;
}
for (i = 0; i < 5; i++) {
printf("%d: %d\n", i, counts[i]);
}
return 0;
}
|
Port the provided C++ code into C while preserving the original functionality. | #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;
}
| k=2; i=1; j=2;
while(k<nn);
k++; sb[k]=sb[k-i]+sb[k-j];
k++; sb[k]=sb[k-j];
i++; j++;
}
|
Convert this C++ snippet to C and keep its semantics consistent. | #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;
};
| #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
typedef struct{
double value;
double delta;
}imprecise;
#define SQR(x) ((x) * (x))
imprecise imprecise_add(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value + b.value;
ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));
return ret;
}
imprecise imprecise_mul(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value * b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));
return ret;
}
imprecise imprecise_div(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value / b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);
return ret;
}
imprecise imprecise_pow(imprecise a, double c)
{
imprecise ret;
ret.value = pow(a.value, c);
ret.delta = fabs(ret.value * c * a.delta / a.value);
return ret;
}
char* printImprecise(imprecise val)
{
char principal[30],error[30],*string,sign[2];
sign[0] = 241;
sign[1] = 00;
sprintf(principal,"%f",val.value);
sprintf(error,"%f",val.delta);
string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));
strcpy(string,principal);
strcat(string,sign);
strcat(string,error);
return string;
}
int main(void) {
imprecise x1 = {100, 1.1};
imprecise y1 = {50, 1.2};
imprecise x2 = {-200, 2.2};
imprecise y2 = {-100, 2.3};
imprecise d;
d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);
printf("Distance, d, between the following points :");
printf("\n( x1, y1) = ( %s, %s)",printImprecise(x1),printImprecise(y1));
printf("\n( x2, y2) = ( %s, %s)",printImprecise(x2),printImprecise(y2));
printf("\nis d = %s", printImprecise(d));
return 0;
}
|
Translate this program into C but keep the logic exactly as in C++. | #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;
};
| #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
typedef struct{
double value;
double delta;
}imprecise;
#define SQR(x) ((x) * (x))
imprecise imprecise_add(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value + b.value;
ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));
return ret;
}
imprecise imprecise_mul(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value * b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));
return ret;
}
imprecise imprecise_div(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value / b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);
return ret;
}
imprecise imprecise_pow(imprecise a, double c)
{
imprecise ret;
ret.value = pow(a.value, c);
ret.delta = fabs(ret.value * c * a.delta / a.value);
return ret;
}
char* printImprecise(imprecise val)
{
char principal[30],error[30],*string,sign[2];
sign[0] = 241;
sign[1] = 00;
sprintf(principal,"%f",val.value);
sprintf(error,"%f",val.delta);
string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));
strcpy(string,principal);
strcat(string,sign);
strcat(string,error);
return string;
}
int main(void) {
imprecise x1 = {100, 1.1};
imprecise y1 = {50, 1.2};
imprecise x2 = {-200, 2.2};
imprecise y2 = {-100, 2.3};
imprecise d;
d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);
printf("Distance, d, between the following points :");
printf("\n( x1, y1) = ( %s, %s)",printImprecise(x1),printImprecise(y1));
printf("\n( x2, y2) = ( %s, %s)",printImprecise(x2),printImprecise(y2));
printf("\nis d = %s", printImprecise(d));
return 0;
}
|
Write a version of this C++ function in C with identical behavior. | #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;
}
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint;
typedef unsigned long long tree;
#define B(x) (1ULL<<(x))
tree *list = 0;
uint cap = 0, len = 0;
uint offset[32] = {0, 1, 0};
void append(tree t)
{
if (len == cap) {
cap = cap ? cap*2 : 2;
list = realloc(list, cap*sizeof(tree));
}
list[len++] = 1 | t<<1;
}
void show(tree t, uint len)
{
for (; len--; t >>= 1)
putchar(t&1 ? '(' : ')');
}
void listtrees(uint n)
{
uint i;
for (i = offset[n]; i < offset[n+1]; i++) {
show(list[i], n*2);
putchar('\n');
}
}
void assemble(uint n, tree t, uint sl, uint pos, uint rem)
{
if (!rem) {
append(t);
return;
}
if (sl > rem)
pos = offset[sl = rem];
else if (pos >= offset[sl + 1]) {
if (!--sl) return;
pos = offset[sl];
}
assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);
assemble(n, t, sl, pos + 1, rem);
}
void mktrees(uint n)
{
if (offset[n + 1]) return;
if (n) mktrees(n - 1);
assemble(n, 0, n-1, offset[n-1], n-1);
offset[n+1] = len;
}
int main(int c, char**v)
{
int n;
if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;
append(0);
mktrees((uint)n);
fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]);
listtrees((uint)n);
return 0;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #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;
}
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint;
typedef unsigned long long tree;
#define B(x) (1ULL<<(x))
tree *list = 0;
uint cap = 0, len = 0;
uint offset[32] = {0, 1, 0};
void append(tree t)
{
if (len == cap) {
cap = cap ? cap*2 : 2;
list = realloc(list, cap*sizeof(tree));
}
list[len++] = 1 | t<<1;
}
void show(tree t, uint len)
{
for (; len--; t >>= 1)
putchar(t&1 ? '(' : ')');
}
void listtrees(uint n)
{
uint i;
for (i = offset[n]; i < offset[n+1]; i++) {
show(list[i], n*2);
putchar('\n');
}
}
void assemble(uint n, tree t, uint sl, uint pos, uint rem)
{
if (!rem) {
append(t);
return;
}
if (sl > rem)
pos = offset[sl = rem];
else if (pos >= offset[sl + 1]) {
if (!--sl) return;
pos = offset[sl];
}
assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);
assemble(n, t, sl, pos + 1, rem);
}
void mktrees(uint n)
{
if (offset[n + 1]) return;
if (n) mktrees(n - 1);
assemble(n, 0, n-1, offset[n-1], n-1);
offset[n+1] = len;
}
int main(int c, char**v)
{
int n;
if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;
append(0);
mktrees((uint)n);
fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]);
listtrees((uint)n);
return 0;
}
|
Please provide an equivalent version of this C++ code in C. | #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;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node_t {
char *elem;
int length;
struct node_t *next;
} node;
node *make_node(char *s) {
node *t = malloc(sizeof(node));
t->elem = s;
t->length = strlen(s);
t->next = NULL;
return t;
}
void append_node(node *head, node *elem) {
while (head->next != NULL) {
head = head->next;
}
head->next = elem;
}
void print_node(node *n) {
putc('[', stdout);
while (n != NULL) {
printf("`%s` ", n->elem);
n = n->next;
}
putc(']', stdout);
}
char *lcs(node *list) {
int minLen = INT_MAX;
int i;
char *res;
node *ptr;
if (list == NULL) {
return "";
}
if (list->next == NULL) {
return list->elem;
}
for (ptr = list; ptr != NULL; ptr = ptr->next) {
minLen = min(minLen, ptr->length);
}
if (minLen == 0) {
return "";
}
res = "";
for (i = 1; i < minLen; i++) {
char *suffix = &list->elem[list->length - i];
for (ptr = list->next; ptr != NULL; ptr = ptr->next) {
char *e = &ptr->elem[ptr->length - i];
if (strcmp(suffix, e) != 0) {
return res;
}
}
res = suffix;
}
return res;
}
void test(node *n) {
print_node(n);
printf(" -> `%s`\n", lcs(n));
}
void case1() {
node *n = make_node("baabababc");
append_node(n, make_node("baabc"));
append_node(n, make_node("bbbabc"));
test(n);
}
void case2() {
node *n = make_node("baabababc");
append_node(n, make_node("baabc"));
append_node(n, make_node("bbbazc"));
test(n);
}
void case3() {
node *n = make_node("Sunday");
append_node(n, make_node("Monday"));
append_node(n, make_node("Tuesday"));
append_node(n, make_node("Wednesday"));
append_node(n, make_node("Thursday"));
append_node(n, make_node("Friday"));
append_node(n, make_node("Saturday"));
test(n);
}
void case4() {
node *n = make_node("longest");
append_node(n, make_node("common"));
append_node(n, make_node("suffix"));
test(n);
}
void case5() {
node *n = make_node("suffix");
test(n);
}
void case6() {
node *n = make_node("");
test(n);
}
int main() {
case1();
case2();
case3();
case4();
case5();
case6();
return 0;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #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;
}
| #include<stdlib.h>
#include<stdio.h>
typedef struct{
int rows,cols;
int** dataSet;
}matrix;
matrix readMatrix(char* dataFile){
FILE* fp = fopen(dataFile,"r");
matrix rosetta;
int i,j;
fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols);
rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));
for(i=0;i<rosetta.rows;i++){
rosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));
for(j=0;j<rosetta.cols;j++)
fscanf(fp,"%d",&rosetta.dataSet[i][j]);
}
fclose(fp);
return rosetta;
}
void printMatrix(matrix rosetta){
int i,j;
for(i=0;i<rosetta.rows;i++){
printf("\n");
for(j=0;j<rosetta.cols;j++)
printf("%3d",rosetta.dataSet[i][j]);
}
}
int findSum(matrix rosetta){
int i,j,sum = 0;
for(i=1;i<rosetta.rows;i++){
for(j=0;j<i;j++){
sum += rosetta.dataSet[i][j];
}
}
return sum;
}
int main(int argC,char* argV[])
{
if(argC!=2)
return printf("Usage : %s <filename>",argV[0]);
matrix data = readMatrix(argV[1]);
printf("\n\nMatrix is : \n\n");
printMatrix(data);
printf("\n\nSum below main diagonal : %d",findSum(data));
return 0;
}
|
Translate the given C++ code snippet into C without altering its behavior. | #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;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("fasta.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
int state = 0;
while ((read = getline(&line, &len, fp)) != -1) {
if (line[read - 1] == '\n')
line[read - 1] = 0;
if (line[0] == '>') {
if (state == 1)
printf("\n");
printf("%s: ", line+1);
state = 1;
} else {
printf("%s", line);
}
}
printf("\n");
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
|
Change the following C++ code into C without altering its purpose. | #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;
}
| #include <stdio.h>
#include <limits.h>
typedef unsigned long long ull;
#define N (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))
void evolve(ull state, int rule)
{
int i, p, q, b;
for (p = 0; p < 10; p++) {
for (b = 0, q = 8; q--; ) {
ull st = state;
b |= (st&1) << q;
for (state = i = 0; i < N; i++)
if (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))
state |= B(i);
}
printf(" %d", b);
}
putchar('\n');
return;
}
int main(void)
{
evolve(1, 30);
return 0;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #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;
}
| #include <math.h>
#include <stdint.h>
#include <stdio.h>
const uint64_t N = 6364136223846793005;
static uint64_t state = 0x853c49e6748fea9b;
static uint64_t inc = 0xda3e39cb94b95bdb;
uint32_t pcg32_int() {
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 pcg32_float() {
return ((double)pcg32_int()) / (1LL << 32);
}
void pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {
state = 0;
inc = (seed_sequence << 1) | 1;
pcg32_int();
state = state + seed_state;
pcg32_int();
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
pcg32_seed(42, 54);
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("%u\n", pcg32_int());
printf("\n");
pcg32_seed(987654321, 1);
for (i = 0; i < 100000; i++) {
int j = (int)floor(pcg32_float() * 5.0);
counts[j]++;
}
printf("The counts for 100,000 repetitions are:\n");
for (i = 0; i < 5; i++) {
printf(" %d : %d\n", i, counts[i]);
}
return 0;
}
|
Produce a functionally identical C code for the snippet given in C++. | #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>";
}
| #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
#define pi M_PI
int main(){
time_t t;
double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
int i,iter,choice,numSides;
printf("Enter number of sides : ");
scanf("%d",&numSides);
printf("Enter polygon side length : ");
scanf("%lf",&side);
printf("Enter number of iterations : ");
scanf("%d",&iter);
initwindow(windowSide,windowSide,"Polygon Chaos");
vertices = (double**)malloc(numSides*sizeof(double*));
for(i=0;i<numSides;i++){
vertices[i] = (double*)malloc(2 * sizeof(double));
vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
sumX+= vertices[i][0];
sumY+= vertices[i][1];
putpixel(vertices[i][0],vertices[i][1],15);
}
srand((unsigned)time(&t));
seedX = sumX/numSides;
seedY = sumY/numSides;
putpixel(seedX,seedY,15);
for(i=0;i<iter;i++){
choice = rand()%numSides;
seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);
putpixel(seedX,seedY,15);
}
free(vertices);
getch();
closegraph();
return 0;
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #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 ;
}
| #include <stdio.h>
#include <string.h>
int repstr(char *str)
{
if (!str) return 0;
size_t sl = strlen(str) / 2;
while (sl > 0) {
if (strstr(str, str + sl) == str)
return sl;
--sl;
}
return 0;
}
int main(void)
{
char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111",
"0100101101", "0100100", "101", "11", "00", "1" };
size_t strslen = sizeof(strs) / sizeof(strs[0]);
size_t i;
for (i = 0; i < strslen; ++i) {
int n = repstr(strs[i]);
if (n)
printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]);
else
printf("\"%s\" = not a rep-string\n", strs[i]);
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #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;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 32
typedef struct string_tag {
size_t length;
char str[MAX_WORD_SIZE];
} string_t;
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
int hamming_distance(const string_t* str1, const string_t* str2) {
size_t len1 = str1->length;
size_t len2 = str2->length;
if (len1 != len2)
return 0;
int count = 0;
const char* s1 = str1->str;
const char* s2 = str2->str;
for (size_t i = 0; i < len1; ++i) {
if (s1[i] != s2[i])
++count;
if (count == 2)
break;
}
return count;
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* in = fopen(filename, "r");
if (!in) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
size_t size = 0, capacity = 1024;
string_t* dictionary = xmalloc(sizeof(string_t) * capacity);
while (fgets(line, sizeof(line), in)) {
if (size == capacity) {
capacity *= 2;
dictionary = xrealloc(dictionary, sizeof(string_t) * capacity);
}
size_t len = strlen(line) - 1;
if (len > 11) {
string_t* str = &dictionary[size];
str->length = len;
memcpy(str->str, line, len);
str->str[len] = '\0';
++size;
}
}
fclose(in);
printf("Changeable words in %s:\n", filename);
int n = 1;
for (size_t i = 0; i < size; ++i) {
const string_t* str1 = &dictionary[i];
for (size_t j = 0; j < size; ++j) {
const string_t* str2 = &dictionary[j];
if (i != j && hamming_distance(str1, str2) == 1)
printf("%2d: %-14s -> %s\n", n++, str1->str, str2->str);
}
}
free(dictionary);
return EXIT_SUCCESS;
}
|
Keep all operations the same but rewrite the snippet in C. | #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);
}
| #include <stdio.h>
#include <stdlib.h>
#define MONAD void*
#define INTBIND(f, g, x) (f((int*)g(x)))
#define RETURN(type,x) &((type)*)(x)
MONAD boundInt(int *x) {
return (MONAD)(x);
}
MONAD boundInt2str(int *x) {
char buf[100];
char*str= malloc(1+sprintf(buf, "%d", *x));
sprintf(str, "%d", *x);
return (MONAD)(str);
}
void task(int y) {
char *z= INTBIND(boundInt2str, boundInt, &y);
printf("%s\n", z);
free(z);
}
int main() {
task(13);
}
|
Change the following C++ code into C without altering its purpose. | #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;
}
| #include <math.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(int n) {
uint64_t result = 1;
int i;
for (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;
int i;
for (i = 1; i <= n; i++) {
result *= factorial(i);
}
return result;
}
uint64_t hyper_factorial(int n) {
uint64_t result = 1;
int i;
for (i = 1; i <= n; i++) {
result *= (uint64_t)powl(i, i);
}
return result;
}
uint64_t alternating_factorial(int n) {
uint64_t result = 0;
int i;
for (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;
int i;
for (i = 1; i <= n; i++) {
result = (uint64_t)powl(i, (long double)result);
}
return result;
}
void test_factorial(int count, uint64_t(*func)(int), char *name) {
int i;
printf("First %d %s:\n", count, name);
for (i = 0; i < count ; i++) {
printf("%llu ", func(i));
}
printf("\n");
}
void test_inverse(uint64_t f) {
int n = inverse_factorial(f);
if (n < 0) {
printf("rf(%llu) = No Solution\n", f);
} else {
printf("rf(%llu) = %d\n", f, n);
}
}
int main() {
int i;
test_factorial(9, super_factorial, "super factorials");
printf("\n");
test_factorial(8, super_factorial, "hyper factorials");
printf("\n");
test_factorial(10, alternating_factorial, "alternating factorials");
printf("\n");
test_factorial(5, exponential_factorial, "exponential factorials");
printf("\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;
}
|
Write the same algorithm in C as shown in this C++ implementation. | #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;
}
| #include <stdint.h>
#include <stdio.h>
#include <glib.h>
typedef struct named_number_tag {
const char* name;
uint64_t number;
} named_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(uint64_t n) {
const size_t names_len = sizeof(named_numbers)/sizeof(named_number);
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(GString* str, uint64_t n) {
static const char* small[] = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
static const char* tens[] = {
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};
size_t len = str->len;
if (n < 20) {
g_string_append(str, small[n]);
}
else if (n < 100) {
g_string_append(str, tens[n/10 - 2]);
if (n % 10 != 0) {
g_string_append_c(str, '-');
g_string_append(str, small[n % 10]);
}
} else {
const named_number* num = get_named_number(n);
uint64_t p = num->number;
append_number_name(str, n/p);
g_string_append_c(str, ' ');
g_string_append(str, num->name);
if (n % p != 0) {
g_string_append_c(str, ' ');
append_number_name(str, n % p);
}
}
return str->len - len;
}
GString* magic(uint64_t n) {
GString* str = g_string_new(NULL);
for (unsigned int i = 0; ; ++i) {
size_t count = append_number_name(str, n);
if (i == 0)
str->str[0] = g_ascii_toupper(str->str[0]);
if (n == 4) {
g_string_append(str, " is magic.");
break;
}
g_string_append(str, " is ");
append_number_name(str, count);
g_string_append(str, ", ");
n = count;
}
return str;
}
void test_magic(uint64_t n) {
GString* str = magic(n);
printf("%s\n", str->str);
g_string_free(str, TRUE);
}
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;
}
|
Translate the given C++ code snippet into C without altering its behavior. | #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;
}
| #include <stdio.h>
int findNumOfDec(double x) {
char buffer[128];
int pos, num;
sprintf(buffer, "%.14f", x);
pos = 0;
num = 0;
while (buffer[pos] != 0 && buffer[pos] != '.') {
pos++;
}
if (buffer[pos] != 0) {
pos++;
while (buffer[pos] != 0) {
pos++;
}
pos--;
while (buffer[pos] == '0') {
pos--;
}
while (buffer[pos] != '.') {
num++;
pos--;
}
}
return num;
}
void test(double x) {
int num = findNumOfDec(x);
printf("%f has %d decimals\n", x, num);
}
int main() {
test(12.0);
test(12.345);
test(12.345555555555);
test(12.3450);
test(12.34555555555555555555);
test(1.2345e+54);
return 0;
}
|
Port the provided C++ code into C while preserving the original functionality. | #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;
}
| #include <string.h>
#include <memory.h>
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal;
}
static unsigned int _parseHex ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor & 0x5f,
(chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) ||
(chNow >= 'A' && chNow <= 'F')
)
{
unsigned char nybbleValue;
chNow -= 0x10;
nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );
nVal <<= 4;
nVal += nybbleValue;
++*pchCursor;
}
return nVal;
}
int ParseIPv4OrIPv6 ( const char** ppszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
unsigned char* abyAddrLocal;
unsigned char abyDummyAddr[16];
const char* pchColon = strchr ( *ppszText, ':' );
const char* pchDot = strchr ( *ppszText, '.' );
const char* pchOpenBracket = strchr ( *ppszText, '[' );
const char* pchCloseBracket = NULL;
int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||
( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );
if ( bIsIPv6local )
{
pchCloseBracket = strchr ( *ppszText, ']' );
if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||
pchCloseBracket < pchOpenBracket ) )
return 0;
}
else
{
if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )
return 0;
}
if ( NULL != pbIsIPv6 )
*pbIsIPv6 = bIsIPv6local;
abyAddrLocal = abyAddr;
if ( NULL == abyAddrLocal )
abyAddrLocal = abyDummyAddr;
if ( ! bIsIPv6local )
{
unsigned char* pbyAddrCursor = abyAddrLocal;
unsigned int nVal;
const char* pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
if ( ':' == **ppszText && NULL != pnPort )
{
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
else
{
unsigned char* pbyAddrCursor;
unsigned char* pbyZerosLoc;
int bIPv4Detected;
int nIdx;
if ( NULL != pchOpenBracket )
*ppszText = pchOpenBracket + 1;
pbyAddrCursor = abyAddrLocal;
pbyZerosLoc = NULL;
bIPv4Detected = 0;
for ( nIdx = 0; nIdx < 8; ++nIdx )
{
const char* pszTextBefore = *ppszText;
unsigned nVal =_parseHex ( ppszText );
if ( pszTextBefore == *ppszText )
{
if ( NULL != pbyZerosLoc )
{
if ( pbyZerosLoc == pbyAddrCursor )
{
--nIdx;
break;
}
return 0;
}
if ( ':' != **ppszText )
return 0;
if ( 0 == nIdx )
{
++(*ppszText);
if ( ':' != **ppszText )
return 0;
}
pbyZerosLoc = pbyAddrCursor;
++(*ppszText);
}
else
{
if ( '.' == **ppszText )
{
const char* pszTextlocal = pszTextBefore;
unsigned char abyAddrlocal[16];
int bIsIPv6local;
int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );
*ppszText = pszTextlocal;
if ( ! bParseResultlocal || bIsIPv6local )
return 0;
*(pbyAddrCursor++) = abyAddrlocal[0];
*(pbyAddrCursor++) = abyAddrlocal[1];
*(pbyAddrCursor++) = abyAddrlocal[2];
*(pbyAddrCursor++) = abyAddrlocal[3];
++nIdx;
bIPv4Detected = 1;
break;
}
if ( nVal > 65535 )
return 0;
*(pbyAddrCursor++) = nVal >> 8;
*(pbyAddrCursor++) = nVal & 0xff;
if ( ':' == **ppszText )
{
++(*ppszText);
}
else
{
break;
}
}
}
if ( NULL != pbyZerosLoc )
{
int nHead = (int)( pbyZerosLoc - abyAddrLocal );
int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal );
int nZeros = 16 - nTail - nHead;
memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );
memset ( pbyZerosLoc, 0, nZeros );
}
if ( bIPv4Detected )
{
static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )
return 0;
}
if ( NULL != pchOpenBracket )
{
if ( ']' != **ppszText )
return 0;
++(*ppszText);
}
if ( ':' == **ppszText && NULL != pnPort )
{
const char* pszTextBefore;
unsigned int nVal;
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
}
int ParseIPv4OrIPv6_2 ( const char* pszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
const char* pszTextLocal = pszText;
return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);
}
|
Rewrite the snippet below in C so it works the same as the original C++ code. | #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;
}
| #include <string.h>
#include <memory.h>
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal;
}
static unsigned int _parseHex ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor & 0x5f,
(chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) ||
(chNow >= 'A' && chNow <= 'F')
)
{
unsigned char nybbleValue;
chNow -= 0x10;
nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );
nVal <<= 4;
nVal += nybbleValue;
++*pchCursor;
}
return nVal;
}
int ParseIPv4OrIPv6 ( const char** ppszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
unsigned char* abyAddrLocal;
unsigned char abyDummyAddr[16];
const char* pchColon = strchr ( *ppszText, ':' );
const char* pchDot = strchr ( *ppszText, '.' );
const char* pchOpenBracket = strchr ( *ppszText, '[' );
const char* pchCloseBracket = NULL;
int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||
( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );
if ( bIsIPv6local )
{
pchCloseBracket = strchr ( *ppszText, ']' );
if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||
pchCloseBracket < pchOpenBracket ) )
return 0;
}
else
{
if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )
return 0;
}
if ( NULL != pbIsIPv6 )
*pbIsIPv6 = bIsIPv6local;
abyAddrLocal = abyAddr;
if ( NULL == abyAddrLocal )
abyAddrLocal = abyDummyAddr;
if ( ! bIsIPv6local )
{
unsigned char* pbyAddrCursor = abyAddrLocal;
unsigned int nVal;
const char* pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
if ( ':' == **ppszText && NULL != pnPort )
{
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
else
{
unsigned char* pbyAddrCursor;
unsigned char* pbyZerosLoc;
int bIPv4Detected;
int nIdx;
if ( NULL != pchOpenBracket )
*ppszText = pchOpenBracket + 1;
pbyAddrCursor = abyAddrLocal;
pbyZerosLoc = NULL;
bIPv4Detected = 0;
for ( nIdx = 0; nIdx < 8; ++nIdx )
{
const char* pszTextBefore = *ppszText;
unsigned nVal =_parseHex ( ppszText );
if ( pszTextBefore == *ppszText )
{
if ( NULL != pbyZerosLoc )
{
if ( pbyZerosLoc == pbyAddrCursor )
{
--nIdx;
break;
}
return 0;
}
if ( ':' != **ppszText )
return 0;
if ( 0 == nIdx )
{
++(*ppszText);
if ( ':' != **ppszText )
return 0;
}
pbyZerosLoc = pbyAddrCursor;
++(*ppszText);
}
else
{
if ( '.' == **ppszText )
{
const char* pszTextlocal = pszTextBefore;
unsigned char abyAddrlocal[16];
int bIsIPv6local;
int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );
*ppszText = pszTextlocal;
if ( ! bParseResultlocal || bIsIPv6local )
return 0;
*(pbyAddrCursor++) = abyAddrlocal[0];
*(pbyAddrCursor++) = abyAddrlocal[1];
*(pbyAddrCursor++) = abyAddrlocal[2];
*(pbyAddrCursor++) = abyAddrlocal[3];
++nIdx;
bIPv4Detected = 1;
break;
}
if ( nVal > 65535 )
return 0;
*(pbyAddrCursor++) = nVal >> 8;
*(pbyAddrCursor++) = nVal & 0xff;
if ( ':' == **ppszText )
{
++(*ppszText);
}
else
{
break;
}
}
}
if ( NULL != pbyZerosLoc )
{
int nHead = (int)( pbyZerosLoc - abyAddrLocal );
int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal );
int nZeros = 16 - nTail - nHead;
memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail );
memset ( pbyZerosLoc, 0, nZeros );
}
if ( bIPv4Detected )
{
static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )
return 0;
}
if ( NULL != pchOpenBracket )
{
if ( ']' != **ppszText )
return 0;
++(*ppszText);
}
if ( ':' == **ppszText && NULL != pnPort )
{
const char* pszTextBefore;
unsigned int nVal;
unsigned short usPortNetwork;
++(*ppszText);
pszTextBefore = *ppszText;
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else
{
if ( NULL != pnPort )
*pnPort = 0;
return 1;
}
}
}
int ParseIPv4OrIPv6_2 ( const char* pszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
const char* pszTextLocal = pszText;
return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);
}
|
Translate this program into C but keep the logic exactly as in C++. | #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");
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
char text_char(char c) {
switch (c) {
case 'a': case 'b': case 'c':
return '2';
case 'd': case 'e': case 'f':
return '3';
case 'g': case 'h': case 'i':
return '4';
case 'j': case 'k': case 'l':
return '5';
case 'm': case 'n': case 'o':
return '6';
case 'p': case 'q': case 'r': case 's':
return '7';
case 't': case 'u': case 'v':
return '8';
case 'w': case 'x': case 'y': case 'z':
return '9';
default:
return 0;
}
}
bool text_string(const GString* word, GString* text) {
g_string_set_size(text, word->len);
for (size_t i = 0; i < word->len; ++i) {
char c = text_char(g_ascii_tolower(word->str[i]));
if (c == 0)
return false;
text->str[i] = c;
}
return true;
}
typedef struct textonym_tag {
const char* text;
size_t length;
GPtrArray* words;
} textonym_t;
int compare_by_text_length(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->length > t2->length)
return -1;
if (t1->length < t2->length)
return 1;
return strcmp(t1->text, t2->text);
}
int compare_by_word_count(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->words->len > t2->words->len)
return -1;
if (t1->words->len < t2->words->len)
return 1;
return strcmp(t1->text, t2->text);
}
void print_words(GPtrArray* words) {
for (guint i = 0, n = words->len; i < n; ++i) {
if (i > 0)
printf(", ");
printf("%s", g_ptr_array_index(words, i));
}
printf("\n");
}
void print_top_words(GArray* textonyms, guint top) {
for (guint i = 0; i < top; ++i) {
const textonym_t* t = &g_array_index(textonyms, textonym_t, i);
printf("%s = ", t->text);
print_words(t->words);
}
}
void free_strings(gpointer ptr) {
g_ptr_array_free(ptr, TRUE);
}
bool find_textonyms(const char* filename, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(filename, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return false;
}
GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, free_strings);
GString* word = g_string_sized_new(64);
GString* text = g_string_sized_new(64);
guint count = 0;
gsize term_pos;
while (g_io_channel_read_line_string(channel, word, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
g_string_truncate(word, term_pos);
if (!text_string(word, text))
continue;
GPtrArray* words = g_hash_table_lookup(ht, text->str);
if (words == NULL) {
words = g_ptr_array_new_full(1, g_free);
g_hash_table_insert(ht, g_strdup(text->str), words);
}
g_ptr_array_add(words, g_strdup(word->str));
++count;
}
g_io_channel_unref(channel);
g_string_free(word, TRUE);
g_string_free(text, TRUE);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_hash_table_destroy(ht);
return false;
}
GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, ht);
while (g_hash_table_iter_next(&iter, &key, &value)) {
GPtrArray* v = value;
if (v->len > 1) {
textonym_t textonym;
textonym.text = key;
textonym.length = strlen(key);
textonym.words = v;
g_array_append_val(words, textonym);
}
}
printf("There are %u words in '%s' which can be represented by the digit key mapping.\n",
count, filename);
guint size = g_hash_table_size(ht);
printf("They require %u digit combinations to represent them.\n", size);
guint textonyms = words->len;
printf("%u digit combinations represent Textonyms.\n", textonyms);
guint top = 5;
if (textonyms < top)
top = textonyms;
printf("\nTop %u by number of words:\n", top);
g_array_sort(words, compare_by_word_count);
print_top_words(words, top);
printf("\nTop %u by length:\n", top);
g_array_sort(words, compare_by_text_length);
print_top_words(words, top);
g_array_free(words, TRUE);
g_hash_table_destroy(ht);
return true;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s word-list\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
if (!find_textonyms(argv[1], &error)) {
if (error != NULL) {
fprintf(stderr, "%s: %s\n", argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Maintain the same structure and functionality when rewriting this code in C. | #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");
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
char text_char(char c) {
switch (c) {
case 'a': case 'b': case 'c':
return '2';
case 'd': case 'e': case 'f':
return '3';
case 'g': case 'h': case 'i':
return '4';
case 'j': case 'k': case 'l':
return '5';
case 'm': case 'n': case 'o':
return '6';
case 'p': case 'q': case 'r': case 's':
return '7';
case 't': case 'u': case 'v':
return '8';
case 'w': case 'x': case 'y': case 'z':
return '9';
default:
return 0;
}
}
bool text_string(const GString* word, GString* text) {
g_string_set_size(text, word->len);
for (size_t i = 0; i < word->len; ++i) {
char c = text_char(g_ascii_tolower(word->str[i]));
if (c == 0)
return false;
text->str[i] = c;
}
return true;
}
typedef struct textonym_tag {
const char* text;
size_t length;
GPtrArray* words;
} textonym_t;
int compare_by_text_length(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->length > t2->length)
return -1;
if (t1->length < t2->length)
return 1;
return strcmp(t1->text, t2->text);
}
int compare_by_word_count(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->words->len > t2->words->len)
return -1;
if (t1->words->len < t2->words->len)
return 1;
return strcmp(t1->text, t2->text);
}
void print_words(GPtrArray* words) {
for (guint i = 0, n = words->len; i < n; ++i) {
if (i > 0)
printf(", ");
printf("%s", g_ptr_array_index(words, i));
}
printf("\n");
}
void print_top_words(GArray* textonyms, guint top) {
for (guint i = 0; i < top; ++i) {
const textonym_t* t = &g_array_index(textonyms, textonym_t, i);
printf("%s = ", t->text);
print_words(t->words);
}
}
void free_strings(gpointer ptr) {
g_ptr_array_free(ptr, TRUE);
}
bool find_textonyms(const char* filename, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(filename, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return false;
}
GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, free_strings);
GString* word = g_string_sized_new(64);
GString* text = g_string_sized_new(64);
guint count = 0;
gsize term_pos;
while (g_io_channel_read_line_string(channel, word, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
g_string_truncate(word, term_pos);
if (!text_string(word, text))
continue;
GPtrArray* words = g_hash_table_lookup(ht, text->str);
if (words == NULL) {
words = g_ptr_array_new_full(1, g_free);
g_hash_table_insert(ht, g_strdup(text->str), words);
}
g_ptr_array_add(words, g_strdup(word->str));
++count;
}
g_io_channel_unref(channel);
g_string_free(word, TRUE);
g_string_free(text, TRUE);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_hash_table_destroy(ht);
return false;
}
GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, ht);
while (g_hash_table_iter_next(&iter, &key, &value)) {
GPtrArray* v = value;
if (v->len > 1) {
textonym_t textonym;
textonym.text = key;
textonym.length = strlen(key);
textonym.words = v;
g_array_append_val(words, textonym);
}
}
printf("There are %u words in '%s' which can be represented by the digit key mapping.\n",
count, filename);
guint size = g_hash_table_size(ht);
printf("They require %u digit combinations to represent them.\n", size);
guint textonyms = words->len;
printf("%u digit combinations represent Textonyms.\n", textonyms);
guint top = 5;
if (textonyms < top)
top = textonyms;
printf("\nTop %u by number of words:\n", top);
g_array_sort(words, compare_by_word_count);
print_top_words(words, top);
printf("\nTop %u by length:\n", top);
g_array_sort(words, compare_by_text_length);
print_top_words(words, top);
g_array_free(words, TRUE);
g_hash_table_destroy(ht);
return true;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s word-list\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
if (!find_textonyms(argv[1], &error)) {
if (error != NULL) {
fprintf(stderr, "%s: %s\n", argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Port the provided C++ code into C while preserving the original functionality. | #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;
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
int string_compare(gconstpointer p1, gconstpointer p2) {
const char* const* s1 = p1;
const char* const* s2 = p2;
return strcmp(*s1, *s2);
}
GPtrArray* load_dictionary(const char* file, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(file, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return NULL;
}
GPtrArray* dict = g_ptr_array_new_full(1024, g_free);
GString* line = g_string_sized_new(64);
gsize term_pos;
while (g_io_channel_read_line_string(channel, line, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
char* word = g_strdup(line->str);
word[term_pos] = '\0';
g_ptr_array_add(dict, word);
}
g_string_free(line, TRUE);
g_io_channel_unref(channel);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_ptr_array_free(dict, TRUE);
return NULL;
}
g_ptr_array_sort(dict, string_compare);
return dict;
}
void rotate(char* str, size_t len) {
char c = str[0];
memmove(str, str + 1, len - 1);
str[len - 1] = c;
}
char* dictionary_search(const GPtrArray* dictionary, const char* word) {
char** result = bsearch(&word, dictionary->pdata, dictionary->len,
sizeof(char*), string_compare);
return result != NULL ? *result : NULL;
}
void find_teacup_words(GPtrArray* dictionary) {
GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);
GPtrArray* teacup_words = g_ptr_array_new();
GString* temp = g_string_sized_new(8);
for (size_t i = 0, n = dictionary->len; i < n; ++i) {
char* word = g_ptr_array_index(dictionary, i);
size_t len = strlen(word);
if (len < 3 || g_hash_table_contains(found, word))
continue;
g_ptr_array_set_size(teacup_words, 0);
g_string_assign(temp, word);
bool is_teacup_word = true;
for (size_t i = 0; i < len - 1; ++i) {
rotate(temp->str, len);
char* w = dictionary_search(dictionary, temp->str);
if (w == NULL) {
is_teacup_word = false;
break;
}
if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))
g_ptr_array_add(teacup_words, w);
}
if (is_teacup_word && teacup_words->len > 0) {
printf("%s", word);
g_hash_table_add(found, word);
for (size_t i = 0; i < teacup_words->len; ++i) {
char* teacup_word = g_ptr_array_index(teacup_words, i);
printf(" %s", teacup_word);
g_hash_table_add(found, teacup_word);
}
printf("\n");
}
}
g_string_free(temp, TRUE);
g_ptr_array_free(teacup_words, TRUE);
g_hash_table_destroy(found);
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s dictionary\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
GPtrArray* dictionary = load_dictionary(argv[1], &error);
if (dictionary == NULL) {
if (error != NULL) {
fprintf(stderr, "Cannot load dictionary file '%s': %s\n",
argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
find_teacup_words(dictionary);
g_ptr_array_free(dictionary, TRUE);
return EXIT_SUCCESS;
}
|
Produce a language-to-language conversion: from C++ to C, same semantics. | #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;
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
int string_compare(gconstpointer p1, gconstpointer p2) {
const char* const* s1 = p1;
const char* const* s2 = p2;
return strcmp(*s1, *s2);
}
GPtrArray* load_dictionary(const char* file, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(file, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return NULL;
}
GPtrArray* dict = g_ptr_array_new_full(1024, g_free);
GString* line = g_string_sized_new(64);
gsize term_pos;
while (g_io_channel_read_line_string(channel, line, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
char* word = g_strdup(line->str);
word[term_pos] = '\0';
g_ptr_array_add(dict, word);
}
g_string_free(line, TRUE);
g_io_channel_unref(channel);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_ptr_array_free(dict, TRUE);
return NULL;
}
g_ptr_array_sort(dict, string_compare);
return dict;
}
void rotate(char* str, size_t len) {
char c = str[0];
memmove(str, str + 1, len - 1);
str[len - 1] = c;
}
char* dictionary_search(const GPtrArray* dictionary, const char* word) {
char** result = bsearch(&word, dictionary->pdata, dictionary->len,
sizeof(char*), string_compare);
return result != NULL ? *result : NULL;
}
void find_teacup_words(GPtrArray* dictionary) {
GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);
GPtrArray* teacup_words = g_ptr_array_new();
GString* temp = g_string_sized_new(8);
for (size_t i = 0, n = dictionary->len; i < n; ++i) {
char* word = g_ptr_array_index(dictionary, i);
size_t len = strlen(word);
if (len < 3 || g_hash_table_contains(found, word))
continue;
g_ptr_array_set_size(teacup_words, 0);
g_string_assign(temp, word);
bool is_teacup_word = true;
for (size_t i = 0; i < len - 1; ++i) {
rotate(temp->str, len);
char* w = dictionary_search(dictionary, temp->str);
if (w == NULL) {
is_teacup_word = false;
break;
}
if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))
g_ptr_array_add(teacup_words, w);
}
if (is_teacup_word && teacup_words->len > 0) {
printf("%s", word);
g_hash_table_add(found, word);
for (size_t i = 0; i < teacup_words->len; ++i) {
char* teacup_word = g_ptr_array_index(teacup_words, i);
printf(" %s", teacup_word);
g_hash_table_add(found, teacup_word);
}
printf("\n");
}
}
g_string_free(temp, TRUE);
g_ptr_array_free(teacup_words, TRUE);
g_hash_table_destroy(found);
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s dictionary\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
GPtrArray* dictionary = load_dictionary(argv[1], &error);
if (dictionary == NULL) {
if (error != NULL) {
fprintf(stderr, "Cannot load dictionary file '%s': %s\n",
argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
find_teacup_words(dictionary);
g_ptr_array_free(dictionary, TRUE);
return EXIT_SUCCESS;
}
|
Generate a C translation of this C++ snippet without changing its computational steps. | #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;
}
| #include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
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() {
setlocale(LC_ALL, "");
uint64_t previous = 1, gap = 0, sum = 0;
int niven_index = 0, gap_index = 1;
printf("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;
printf("%'9d %'4llu %'14d %'15llu\n", gap_index++,
gap, niven_index, previous);
}
previous = niven;
++niven_index;
}
}
return 0;
}
|
Produce a language-to-language conversion: from C++ to C, same semantics. | #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;
}
| #include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
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() {
setlocale(LC_ALL, "");
uint64_t previous = 1, gap = 0, sum = 0;
int niven_index = 0, gap_index = 1;
printf("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;
printf("%'9d %'4llu %'14d %'15llu\n", gap_index++,
gap, niven_index, previous);
}
previous = niven;
++niven_index;
}
}
return 0;
}
|
Produce a language-to-language conversion: from C++ to C, same semantics. | #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;
}
| #include <stdio.h>
#define DEBUG_INT(x) printf( #x " at line %d\nresult: %d\n\n", __LINE__, x)
int add(int x, int y) {
int result = x + y;
DEBUG_INT(x);
DEBUG_INT(y);
DEBUG_INT(result);
DEBUG_INT(result+1);
return result;
}
int main() {
add(2, 7);
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #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;
}
| #include <stdio.h>
#include <stdlib.h>
size_t rprint(char *s, int *x, int len)
{
#define sep (a > s ? "," : "")
#define ol (s ? 100 : 0)
int i, j;
char *a = s;
for (i = j = 0; i < len; i = ++j) {
for (; j < len - 1 && x[j + 1] == x[j] + 1; j++);
if (i + 1 < j)
a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]);
else
while (i <= j)
a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]);
}
return a - s;
#undef sep
#undef ol
}
int main()
{
int x[] = { 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 };
char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);
rprint(s, x, sizeof(x) / sizeof(int));
printf("%s\n", s);
return 0;
}
|
Convert this C++ snippet to C and keep its semantics consistent. | #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;
}
| #include <stdio.h>
#include <stdlib.h>
size_t rprint(char *s, int *x, int len)
{
#define sep (a > s ? "," : "")
#define ol (s ? 100 : 0)
int i, j;
char *a = s;
for (i = j = 0; i < len; i = ++j) {
for (; j < len - 1 && x[j + 1] == x[j] + 1; j++);
if (i + 1 < j)
a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]);
else
while (i <= j)
a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]);
}
return a - s;
#undef sep
#undef ol
}
int main()
{
int x[] = { 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 };
char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);
rprint(s, x, sizeof(x) / sizeof(int));
printf("%s\n", s);
return 0;
}
|
Please provide an equivalent version of this C++ code in C. | #include <iostream>
template <typename T>
auto typeString(const T&) {
return typeid(T).name();
}
class C {};
struct S {};
int main() {
std::cout << typeString(1) << '\n';
std::cout << typeString(1L) << '\n';
std::cout << typeString(1.0f) << '\n';
std::cout << typeString(1.0) << '\n';
std::cout << typeString('c') << '\n';
std::cout << typeString("string") << '\n';
std::cout << typeString(C{}) << '\n';
std::cout << typeString(S{}) << '\n';
std::cout << typeString(nullptr) << '\n';
}
| #include<stdio.h>
#include<ctype.h>
void typeDetector(char* str){
if(isalnum(str[0])!=0)
printf("\n%c is alphanumeric",str[0]);
if(isalpha(str[0])!=0)
printf("\n%c is alphabetic",str[0]);
if(iscntrl(str[0])!=0)
printf("\n%c is a control character",str[0]);
if(isdigit(str[0])!=0)
printf("\n%c is a digit",str[0]);
if(isprint(str[0])!=0)
printf("\n%c is printable",str[0]);
if(ispunct(str[0])!=0)
printf("\n%c is a punctuation character",str[0]);
if(isxdigit(str[0])!=0)
printf("\n%c is a hexadecimal digit",str[0]);
}
int main(int argC, char* argV[])
{
int i;
if(argC==1)
printf("Usage : %s <followed by ASCII characters>");
else{
for(i=1;i<argC;i++)
typeDetector(argV[i]);
}
return 0;
}
|
Write the same algorithm in C as shown in this C++ implementation. |
#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";
}
| #include <stdio.h>
#include <math.h>
#define max(x,y) ((x) > (y) ? (x) : (y))
int tri[] = {
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
};
int main(void)
{
const int len = sizeof(tri) / sizeof(tri[0]);
const int base = (sqrt(8*len + 1) - 1) / 2;
int step = base - 1;
int stepc = 0;
int i;
for (i = len - base - 1; i >= 0; --i) {
tri[i] += max(tri[i + step], tri[i + step + 1]);
if (++stepc == step) {
step--;
stepc = 0;
}
}
printf("%d\n", tri[0]);
return 0;
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. |
#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";
}
| #include <stdio.h>
#include <math.h>
#define max(x,y) ((x) > (y) ? (x) : (y))
int tri[] = {
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
};
int main(void)
{
const int len = sizeof(tri) / sizeof(tri[0]);
const int base = (sqrt(8*len + 1) - 1) / 2;
int step = base - 1;
int stepc = 0;
int i;
for (i = len - base - 1; i >= 0; --i) {
tri[i] += max(tri[i + step], tri[i + step + 1]);
if (++stepc == step) {
step--;
stepc = 0;
}
}
printf("%d\n", tri[0]);
return 0;
}
|
Transform the following C++ implementation into C, maintaining the same output and logic. | #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;
}
}
}
| #include <stdio.h>
int main() {
int i, gprev = 0;
int s[7] = {1, 2, 2, 3, 4, 4, 5};
for (i = 0; i < 7; ++i) {
int curr = s[i];
int prev = 0;
if (i > 0 && curr == prev) printf("%d\n", i);
prev = curr;
}
for (i = 0; i < 7; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) printf("%d\n", i);
gprev = curr;
}
return 0;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #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;
}
}
}
| #include <stdio.h>
int main() {
int i, gprev = 0;
int s[7] = {1, 2, 2, 3, 4, 4, 5};
for (i = 0; i < 7; ++i) {
int curr = s[i];
int prev = 0;
if (i > 0 && curr == prev) printf("%d\n", i);
prev = curr;
}
for (i = 0; i < 7; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) printf("%d\n", i);
gprev = curr;
}
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #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";
}
| #include <stdio.h>
int riseEqFall(int num) {
int rdigit = num % 10;
int netHeight = 0;
while (num /= 10) {
netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);
rdigit = num % 10;
}
return netHeight == 0;
}
int nextNum() {
static int num = 0;
do {num++;} while (!riseEqFall(num));
return num;
}
int main(void) {
int total, num;
printf("The first 200 numbers are: \n");
for (total = 0; total < 200; total++)
printf("%d ", nextNum());
printf("\n\nThe 10,000,000th number is: ");
for (; total < 10000000; total++) num = nextNum();
printf("%d\n", num);
return 0;
}
|
Please provide an equivalent version of this C++ code in C. |
#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;
}
| #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
typedef struct{
double x,y;
}point;
void kochCurve(point p1,point p2,int times){
point p3,p4,p5;
double theta = pi/3;
if(times>0){
p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};
p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};
p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};
kochCurve(p1,p3,times-1);
kochCurve(p3,p4,times-1);
kochCurve(p4,p5,times-1);
kochCurve(p5,p2,times-1);
}
else{
line(p1.x,p1.y,p2.x,p2.y);
}
}
int main(int argC, char** argV)
{
int w,h,r;
point p1,p2;
if(argC!=4){
printf("Usage : %s <window width> <window height> <recursion level>",argV[0]);
}
else{
w = atoi(argV[1]);
h = atoi(argV[2]);
r = atoi(argV[3]);
initwindow(w,h,"Koch Curve");
p1 = (point){10,h-10};
p2 = (point){w-10,h-10};
kochCurve(p1,p2,r);
getch();
closegraph();
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from C++ to C. | #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;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 80
#define MIN_LENGTH 9
#define WORD_SIZE (MIN_LENGTH + 1)
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
int word_compare(const void* p1, const void* p2) {
return memcmp(p1, p2, WORD_SIZE);
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* in = fopen(filename, "r");
if (!in) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
size_t size = 0, capacity = 1024;
char* words = xmalloc(WORD_SIZE * capacity);
while (fgets(line, sizeof(line), in)) {
size_t len = strlen(line) - 1;
if (len < MIN_LENGTH)
continue;
line[len] = '\0';
if (size == capacity) {
capacity *= 2;
words = xrealloc(words, WORD_SIZE * capacity);
}
memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);
++size;
}
fclose(in);
qsort(words, size, WORD_SIZE, word_compare);
int count = 0;
char prev_word[WORD_SIZE] = { 0 };
for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {
char word[WORD_SIZE] = { 0 };
for (size_t j = 0; j < MIN_LENGTH; ++j)
word[j] = words[(i + j) * WORD_SIZE + j];
if (word_compare(word, prev_word) == 0)
continue;
if (bsearch(word, words, size, WORD_SIZE, word_compare))
printf("%2d. %s\n", ++count, word);
memcpy(prev_word, word, WORD_SIZE);
}
free(words);
return EXIT_SUCCESS;
}
|
Change the following C++ code into C without altering its purpose. | #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;
}
| #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** oddMagicSquare(int n) {
if (n < 3 || n % 2 == 0)
return NULL;
int value = 0;
int squareSize = n * n;
int c = n / 2, r = 0,i;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
while (++value <= squareSize) {
result[r][c] = value;
if (r == 0) {
if (c == n - 1) {
r++;
} else {
r = n - 1;
c++;
}
} else if (c == n - 1) {
r--;
c = 0;
} else if (result[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
return result;
}
int** singlyEvenMagicSquare(int n) {
if (n < 6 || (n - 2) % 4 != 0)
return NULL;
int size = n * n;
int halfN = n / 2;
int subGridSize = size / 4, i;
int** subGrid = oddMagicSquare(halfN);
int gridFactors[] = {0, 2, 3, 1};
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int grid = (r / halfN) * 2 + (c / halfN);
result[r][c] = subGrid[r % halfN][c % halfN];
result[r][c] += gridFactors[grid] * subGridSize;
}
}
int nColsLeft = halfN / 2;
int nColsRight = nColsLeft - 1;
for (int r = 0; r < halfN; r++)
for (int c = 0; c < n; c++) {
if (c < nColsLeft || c >= n - nColsRight
|| (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft)
continue;
int tmp = result[r][c];
result[r][c] = result[r + halfN][c];
result[r + halfN][c] = tmp;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j;
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2);
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(singlyEvenMagicSquare(n),n);
}
return 0;
}
|
Please provide an equivalent version of this C++ code in C. | #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" );
}
| #include<stdlib.h>
#include<locale.h>
#include<wchar.h>
#include<stdio.h>
#include<time.h>
char rank[9];
int pos[8];
void swap(int i,int j){
int temp = pos[i];
pos[i] = pos[j];
pos[j] = temp;
}
void generateFirstRank(){
int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;
for(i=0;i<8;i++){
rank[i] = 'e';
pos[i] = i;
}
do{
kPos = rand()%8;
rPos1 = rand()%8;
rPos2 = rand()%8;
}while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));
rank[pos[rPos1]] = 'R';
rank[pos[kPos]] = 'K';
rank[pos[rPos2]] = 'R';
swap(rPos1,7);
swap(rPos2,6);
swap(kPos,5);
do{
bPos1 = rand()%5;
bPos2 = rand()%5;
}while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));
rank[pos[bPos1]] = 'B';
rank[pos[bPos2]] = 'B';
swap(bPos1,4);
swap(bPos2,3);
do{
qPos = rand()%3;
nPos1 = rand()%3;
}while(qPos==nPos1);
rank[pos[qPos]] = 'Q';
rank[pos[nPos1]] = 'N';
for(i=0;i<8;i++)
if(rank[i]=='e'){
rank[i] = 'N';
break;
}
}
void printRank(){
int i;
#ifdef _WIN32
printf("%s\n",rank);
#else
{
setlocale(LC_ALL,"");
printf("\n");
for(i=0;i<8;i++){
if(rank[i]=='K')
printf("%lc",(wint_t)9812);
else if(rank[i]=='Q')
printf("%lc",(wint_t)9813);
else if(rank[i]=='R')
printf("%lc",(wint_t)9814);
else if(rank[i]=='B')
printf("%lc",(wint_t)9815);
if(rank[i]=='N')
printf("%lc",(wint_t)9816);
}
}
#endif
}
int main()
{
int i;
srand((unsigned)time(NULL));
for(i=0;i<9;i++){
generateFirstRank();
printRank();
}
return 0;
}
|
Convert this C++ block to C, preserving its control flow and logic. | #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;
}
| #include<windows.h>
#include<string.h>
#include<stdio.h>
#define MAXORDER 25
int main(int argC, char* argV[])
{
char str[MAXORDER],commandString[1000],*startPath;
long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;
int i,j,len;
double scale;
FILE* fp;
if(argC==1)
printf("Usage : %s <followed by directory to start search from(. for current dir), followed by \n optional parameters (T or G) to show text or graph output>",argV[0]);
else{
if(strchr(argV[1],' ')!=NULL){
len = strlen(argV[1]);
startPath = (char*)malloc((len+2)*sizeof(char));
startPath[0] = '\"';
startPath[len+1]='\"';
strncpy(startPath+1,argV[1],len);
startPath[len+2] = argV[1][len];
sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",startPath);
}
else if(strlen(argV[1])==1 && argV[1][0]=='.')
strcpy(commandString,"forfiles /s /c \"cmd /c echo @fsize\" 2>&1");
else
sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",argV[1]);
fp = popen(commandString,"r");
while(fgets(str,100,fp)!=NULL){
if(str[0]=='0')
fileSizeLog[0]++;
else
fileSizeLog[strlen(str)]++;
}
if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){
for(i=0;i<MAXORDER;i++){
printf("\nSize Order < 10^%2d bytes : %Ld",i,fileSizeLog[i]);
}
}
else if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){
CONSOLE_SCREEN_BUFFER_INFO csbi;
int val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);
if(val)
{
max = fileSizeLog[0];
for(i=1;i<MAXORDER;i++)
(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;
(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);
for(i=0;i<MAXORDER;i++){
printf("\nSize Order < 10^%2d bytes |",i);
for(j=0;j<(int)(scale*fileSizeLog[i]);j++)
printf("%c",219);
printf("%Ld",fileSizeLog[i]);
}
}
}
return 0;
}
}
|
Translate the given C++ code snippet into C without altering its behavior. | #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;
}
| #include<windows.h>
#include<string.h>
#include<stdio.h>
#define MAXORDER 25
int main(int argC, char* argV[])
{
char str[MAXORDER],commandString[1000],*startPath;
long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;
int i,j,len;
double scale;
FILE* fp;
if(argC==1)
printf("Usage : %s <followed by directory to start search from(. for current dir), followed by \n optional parameters (T or G) to show text or graph output>",argV[0]);
else{
if(strchr(argV[1],' ')!=NULL){
len = strlen(argV[1]);
startPath = (char*)malloc((len+2)*sizeof(char));
startPath[0] = '\"';
startPath[len+1]='\"';
strncpy(startPath+1,argV[1],len);
startPath[len+2] = argV[1][len];
sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",startPath);
}
else if(strlen(argV[1])==1 && argV[1][0]=='.')
strcpy(commandString,"forfiles /s /c \"cmd /c echo @fsize\" 2>&1");
else
sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",argV[1]);
fp = popen(commandString,"r");
while(fgets(str,100,fp)!=NULL){
if(str[0]=='0')
fileSizeLog[0]++;
else
fileSizeLog[strlen(str)]++;
}
if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){
for(i=0;i<MAXORDER;i++){
printf("\nSize Order < 10^%2d bytes : %Ld",i,fileSizeLog[i]);
}
}
else if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){
CONSOLE_SCREEN_BUFFER_INFO csbi;
int val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);
if(val)
{
max = fileSizeLog[0];
for(i=1;i<MAXORDER;i++)
(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;
(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);
for(i=0;i<MAXORDER;i++){
printf("\nSize Order < 10^%2d bytes |",i);
for(j=0;j<(int)(scale*fileSizeLog[i]);j++)
printf("%c",219);
printf("%Ld",fileSizeLog[i]);
}
}
}
return 0;
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to C. | #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';
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
int cmpstr(const void *a, const void *b)
{
return strcmp(*(const char**)a, *(const char**)b);
}
int main(void)
{
DIR *basedir;
char path[PATH_MAX];
struct dirent *entry;
char **dirnames;
int diralloc = 128;
int dirsize = 0;
if (!(dirnames = malloc(diralloc * sizeof(char*)))) {
perror("malloc error:");
return 1;
}
if (!getcwd(path, PATH_MAX)) {
perror("getcwd error:");
return 1;
}
if (!(basedir = opendir(path))) {
perror("opendir error:");
return 1;
}
while ((entry = readdir(basedir))) {
if (dirsize >= diralloc) {
diralloc *= 2;
if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {
perror("realloc error:");
return 1;
}
}
dirnames[dirsize++] = strdup(entry->d_name);
}
qsort(dirnames, dirsize, sizeof(char*), cmpstr);
int i;
for (i = 0; i < dirsize; ++i) {
if (dirnames[i][0] != '.') {
printf("%s\n", dirnames[i]);
}
}
for (i = 0; i < dirsize; ++i)
free(dirnames[i]);
free(dirnames);
closedir(basedir);
return 0;
}
|
Generate an equivalent C version of this C++ code. | #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;
}
| #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** doublyEvenMagicSquare(int n) {
if (n < 4 || n % 4 != 0)
return NULL;
int bits = 38505;
int size = n * n;
int mult = n / 4,i,r,c,bitPos;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (r = 0, i = 0; r < n; r++) {
for (c = 0; c < n; c++, i++) {
bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j,baseWidth = numDigits(rows*rows) + 3;
printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2);
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(doublyEvenMagicSquare(n),n);
}
return 0;
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #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;
}
| #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** doublyEvenMagicSquare(int n) {
if (n < 4 || n % 4 != 0)
return NULL;
int bits = 38505;
int size = n * n;
int mult = n / 4,i,r,c,bitPos;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (r = 0, i = 0; r < n; r++) {
for (c = 0; c < n; c++, i++) {
bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j,baseWidth = numDigits(rows*rows) + 3;
printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2);
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(doublyEvenMagicSquare(n),n);
}
return 0;
}
|
Produce a language-to-language conversion: from C++ to C, same semantics. | #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;
}
| #include <math.h>
#include <stdint.h>
#include <stdio.h>
static uint64_t state;
static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;
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 * STATE_MAGIC) >> 32);
return answer;
}
float next_float() {
return (float)next_int() / (1LL << 32);
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
seed(1234567);
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("\n");
seed(987654321);
for (i = 0; i < 100000; i++) {
int j = (int)floor(next_float() * 5.0);
counts[j]++;
}
for (i = 0; i < 5; i++) {
printf("%d: %d\n", i, counts[i]);
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original C++ code. | #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);
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };
char *Lines[MAX_ROWS] = {
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ID |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" |QR| Opcode |AA|TC|RD|RA| Z | RCODE |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | QDCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ANCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | NSCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ARCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
};
typedef struct {
unsigned bit3s;
unsigned mask;
unsigned data;
char A[NAME_SZ+2];
}NAME_T;
NAME_T names[MAX_NAMES];
unsigned idx_name;
enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};
unsigned header[MAX_HDR];
unsigned idx_hdr;
int bit_hdr(char *pLine);
int bit_names(char *pLine);
void dump_names(void);
void make_test_hdr(void);
int main(void){
char *p1; int rv;
printf("Extract meta-data from bit-encoded text form\n");
make_test_hdr();
idx_name = 0;
for( int i=0; i<MAX_ROWS;i++ ){
p1 = Lines[i];
if( p1==NULL ) break;
if( rv = bit_hdr(Lines[i]), rv>0) continue;
if( rv = bit_names(Lines[i]),rv>0) continue;
}
dump_names();
}
int bit_hdr(char *pLine){
char *p1 = strchr(pLine,'+');
if( p1==NULL ) return 0;
int numbits=0;
for( int i=0; i<strlen(p1)-1; i+=3 ){
if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;
numbits++;
}
return numbits;
}
int bit_names(char *pLine){
char *p1,*p2 = pLine, tmp[80];
unsigned sz=0, maskbitcount = 15;
while(1){
p1 = strchr(p2,'|'); if( p1==NULL ) break;
p1++;
p2 = strchr(p1,'|'); if( p2==NULL ) break;
sz = p2-p1;
tmp[sz] = 0;
int k=0;
for(int j=0; j<sz;j++){
if( p1[j] > ' ') tmp[k++] = p1[j];
}
tmp[k]= 0; sz++;
NAME_T *pn = &names[idx_name++];
strcpy(&pn->A[0], &tmp[0]);
pn->bit3s = sz/3;
if( pn->bit3s < 16 ){
for( int i=0; i<pn->bit3s; i++){
pn->mask |= 1 << maskbitcount--;
}
pn->data = header[idx_hdr] & pn->mask;
unsigned m2 = pn->mask;
while( (m2 & 1)==0 ){
m2>>=1;
pn->data >>= 1;
}
if( pn->mask == 0xf ) idx_hdr++;
}
else{
pn->data = header[idx_hdr++];
}
}
return sz;
}
void dump_names(void){
NAME_T *pn;
printf("-name-bits-mask-data-\n");
for( int i=0; i<MAX_NAMES; i++ ){
pn = &names[i];
if( pn->bit3s < 1 ) break;
printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data);
}
puts("bye..");
}
void make_test_hdr(void){
header[ID] = 1024;
header[QDCOUNT] = 12;
header[ANCOUNT] = 34;
header[NSCOUNT] = 56;
header[ARCOUNT] = 78;
header[BITS] = 0xB50A;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #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);
}
| #include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
typedef struct {
ucontext_t caller, callee;
char stack[8192];
void *in, *out;
} co_t;
co_t * co_new(void(*f)(), void *data)
{
co_t * c = malloc(sizeof(*c));
getcontext(&c->callee);
c->in = data;
c->callee.uc_stack.ss_sp = c->stack;
c->callee.uc_stack.ss_size = sizeof(c->stack);
c->callee.uc_link = &c->caller;
makecontext(&c->callee, f, 1, (int)c);
return c;
}
void co_del(co_t *c)
{
free(c);
}
inline void
co_yield(co_t *c, void *data)
{
c->out = data;
swapcontext(&c->callee, &c->caller);
}
inline void *
co_collect(co_t *c)
{
c->out = 0;
swapcontext(&c->caller, &c->callee);
return c->out;
}
typedef struct node node;
struct node {
int v;
node *left, *right;
};
node *newnode(int v)
{
node *n = malloc(sizeof(node));
n->left = n->right = 0;
n->v = v;
return n;
}
void tree_insert(node **root, node *n)
{
while (*root) root = ((*root)->v > n->v)
? &(*root)->left
: &(*root)->right;
*root = n;
}
void tree_trav(int x)
{
co_t *c = (co_t *) x;
void trav(node *root) {
if (!root) return;
trav(root->left);
co_yield(c, root);
trav(root->right);
}
trav(c->in);
}
int tree_eq(node *t1, node *t2)
{
co_t *c1 = co_new(tree_trav, t1);
co_t *c2 = co_new(tree_trav, t2);
node *p = 0, *q = 0;
do {
p = co_collect(c1);
q = co_collect(c2);
} while (p && q && (p->v == q->v));
co_del(c1);
co_del(c2);
return !p && !q;
}
int main()
{
int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };
int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };
int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };
node *t1 = 0, *t2 = 0, *t3 = 0;
void mktree(int *buf, node **root) {
int i;
for (i = 0; buf[i] >= 0; i++)
tree_insert(root, newnode(buf[i]));
}
mktree(x, &t1);
mktree(y, &t2);
mktree(z, &t3);
printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no");
printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no");
return 0;
}
|
Convert this C++ block to C, preserving its control flow and logic. | #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);
}
| #include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
typedef struct {
ucontext_t caller, callee;
char stack[8192];
void *in, *out;
} co_t;
co_t * co_new(void(*f)(), void *data)
{
co_t * c = malloc(sizeof(*c));
getcontext(&c->callee);
c->in = data;
c->callee.uc_stack.ss_sp = c->stack;
c->callee.uc_stack.ss_size = sizeof(c->stack);
c->callee.uc_link = &c->caller;
makecontext(&c->callee, f, 1, (int)c);
return c;
}
void co_del(co_t *c)
{
free(c);
}
inline void
co_yield(co_t *c, void *data)
{
c->out = data;
swapcontext(&c->callee, &c->caller);
}
inline void *
co_collect(co_t *c)
{
c->out = 0;
swapcontext(&c->caller, &c->callee);
return c->out;
}
typedef struct node node;
struct node {
int v;
node *left, *right;
};
node *newnode(int v)
{
node *n = malloc(sizeof(node));
n->left = n->right = 0;
n->v = v;
return n;
}
void tree_insert(node **root, node *n)
{
while (*root) root = ((*root)->v > n->v)
? &(*root)->left
: &(*root)->right;
*root = n;
}
void tree_trav(int x)
{
co_t *c = (co_t *) x;
void trav(node *root) {
if (!root) return;
trav(root->left);
co_yield(c, root);
trav(root->right);
}
trav(c->in);
}
int tree_eq(node *t1, node *t2)
{
co_t *c1 = co_new(tree_trav, t1);
co_t *c2 = co_new(tree_trav, t2);
node *p = 0, *q = 0;
do {
p = co_collect(c1);
q = co_collect(c2);
} while (p && q && (p->v == q->v));
co_del(c1);
co_del(c2);
return !p && !q;
}
int main()
{
int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };
int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };
int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };
node *t1 = 0, *t2 = 0, *t3 = 0;
void mktree(int *buf, node **root) {
int i;
for (i = 0; buf[i] >= 0; i++)
tree_insert(root, newnode(buf[i]));
}
mktree(x, &t1);
mktree(y, &t2);
mktree(z, &t3);
printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no");
printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no");
return 0;
}
|
Please provide an equivalent version of this C++ code in C. | #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;
}
| #include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
enum Piece {
Empty,
Black,
White,
};
typedef struct Position_t {
int x, y;
} Position;
struct Node_t {
Position pos;
struct Node_t *next;
};
void releaseNode(struct Node_t *head) {
if (head == NULL) return;
releaseNode(head->next);
head->next = NULL;
free(head);
}
typedef struct List_t {
struct Node_t *head;
struct Node_t *tail;
size_t length;
} List;
List makeList() {
return (List) { NULL, NULL, 0 };
}
void releaseList(List *lst) {
if (lst == NULL) return;
releaseNode(lst->head);
lst->head = NULL;
lst->tail = NULL;
}
void addNode(List *lst, Position pos) {
struct Node_t *newNode;
if (lst == NULL) {
exit(EXIT_FAILURE);
}
newNode = malloc(sizeof(struct Node_t));
if (newNode == NULL) {
exit(EXIT_FAILURE);
}
newNode->next = NULL;
newNode->pos = pos;
if (lst->head == NULL) {
lst->head = lst->tail = newNode;
} else {
lst->tail->next = newNode;
lst->tail = newNode;
}
lst->length++;
}
void removeAt(List *lst, size_t pos) {
if (lst == NULL) return;
if (pos == 0) {
struct Node_t *temp = lst->head;
if (lst->tail == lst->head) {
lst->tail = NULL;
}
lst->head = lst->head->next;
temp->next = NULL;
free(temp);
lst->length--;
} else {
struct Node_t *temp = lst->head;
struct Node_t *rem;
size_t i = pos;
while (i-- > 1) {
temp = temp->next;
}
rem = temp->next;
if (rem == lst->tail) {
lst->tail = temp;
}
temp->next = rem->next;
rem->next = NULL;
free(rem);
lst->length--;
}
}
bool isAttacking(Position queen, Position pos) {
return queen.x == pos.x
|| queen.y == pos.y
|| abs(queen.x - pos.x) == abs(queen.y - pos.y);
}
bool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {
struct Node_t *queenNode;
bool placingBlack = true;
int i, j;
if (pBlackQueens == NULL || pWhiteQueens == NULL) {
exit(EXIT_FAILURE);
}
if (m == 0) return true;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
Position pos = { i, j };
queenNode = pBlackQueens->head;
while (queenNode != NULL) {
if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {
goto inner;
}
queenNode = queenNode->next;
}
queenNode = pWhiteQueens->head;
while (queenNode != NULL) {
if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {
goto inner;
}
queenNode = queenNode->next;
}
if (placingBlack) {
addNode(pBlackQueens, pos);
placingBlack = false;
} else {
addNode(pWhiteQueens, pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
removeAt(pBlackQueens, pBlackQueens->length - 1);
removeAt(pWhiteQueens, pWhiteQueens->length - 1);
placingBlack = true;
}
inner: {}
}
}
if (!placingBlack) {
removeAt(pBlackQueens, pBlackQueens->length - 1);
}
return false;
}
void printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {
size_t length = n * n;
struct Node_t *queenNode;
char *board;
size_t i, j, k;
if (pBlackQueens == NULL || pWhiteQueens == NULL) {
exit(EXIT_FAILURE);
}
board = calloc(length, sizeof(char));
if (board == NULL) {
exit(EXIT_FAILURE);
}
queenNode = pBlackQueens->head;
while (queenNode != NULL) {
board[queenNode->pos.x * n + queenNode->pos.y] = Black;
queenNode = queenNode->next;
}
queenNode = pWhiteQueens->head;
while (queenNode != NULL) {
board[queenNode->pos.x * n + queenNode->pos.y] = White;
queenNode = queenNode->next;
}
for (i = 0; i < length; i++) {
if (i != 0 && i % n == 0) {
printf("\n");
}
switch (board[i]) {
case Black:
printf("B ");
break;
case White:
printf("W ");
break;
default:
j = i / n;
k = i - j * n;
if (j % 2 == k % 2) {
printf(" ");
} else {
printf("# ");
}
break;
}
}
printf("\n\n");
}
void test(int n, int q) {
List blackQueens = makeList();
List whiteQueens = makeList();
printf("%d black and %d white queens on a %d x %d board:\n", q, q, n, n);
if (place(q, n, &blackQueens, &whiteQueens)) {
printBoard(n, &blackQueens, &whiteQueens);
} else {
printf("No solution exists.\n\n");
}
releaseList(&blackQueens);
releaseList(&whiteQueens);
}
int main() {
test(2, 1);
test(3, 1);
test(3, 2);
test(4, 1);
test(4, 2);
test(4, 3);
test(5, 1);
test(5, 2);
test(5, 3);
test(5, 4);
test(5, 5);
test(6, 1);
test(6, 2);
test(6, 3);
test(6, 4);
test(6, 5);
test(6, 6);
test(7, 1);
test(7, 2);
test(7, 3);
test(7, 4);
test(7, 5);
test(7, 6);
test(7, 7);
return EXIT_SUCCESS;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #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;
}
| #include <stdio.h>
#define LIMIT 100000
int digitset(int num, int base) {
int set;
for (set = 0; num; num /= base)
set |= 1 << num % base;
return set;
}
int main() {
int i, c = 0;
for (i = 0; i < LIMIT; i++)
if (digitset(i,10) == digitset(i,16))
printf("%6d%c", i, ++c%10 ? ' ' : '\n');
printf("\n");
return 0;
}
|
Produce a language-to-language conversion: from C++ to C, same semantics. | #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' : ' ');
}
}
| #include <stdio.h>
unsigned int lpd(unsigned int n) {
if (n<=1) return 1;
int i;
for (i=n-1; i>0; i--)
if (n%i == 0) return i;
}
int main() {
int i;
for (i=1; i<=100; i++) {
printf("%3d", lpd(i));
if (i % 10 == 0) printf("\n");
}
return 0;
}
|
Port the provided C++ code into C while preserving the original functionality. | #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' : ' ');
}
}
| #include <stdio.h>
unsigned int lpd(unsigned int n) {
if (n<=1) return 1;
int i;
for (i=n-1; i>0; i--)
if (n%i == 0) return i;
}
int main() {
int i;
for (i=1; i<=100; i++) {
printf("%3d", lpd(i));
if (i % 10 == 0) printf("\n");
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #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;
}
| #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 100
int move_to_front(char *str,char c)
{
char *q,*p;
int shift=0;
p=(char *)malloc(strlen(str)+1);
strcpy(p,str);
q=strchr(p,c);
shift=q-p;
strncpy(str+1,p,shift);
str[0]=c;
free(p);
return shift;
}
void decode(int* pass,int size,char *sym)
{
int i,index;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=table[pass[i]];
index=move_to_front(table,c);
if(pass[i]!=index) printf("there is an error");
sym[i]=c;
}
sym[size]='\0';
}
void encode(char *sym,int size,int *pass)
{
int i=0;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=sym[i];
pass[i]=move_to_front(table,c);
}
}
int check(char *sym,int size,int *pass)
{
int *pass2=malloc(sizeof(int)*size);
char *sym2=malloc(sizeof(char)*size);
int i,val=1;
encode(sym,size,pass2);
i=0;
while(i<size && pass[i]==pass2[i])i++;
if(i!=size)val=0;
decode(pass,size,sym2);
if(strcmp(sym,sym2)!=0)val=0;
free(sym2);
free(pass2);
return val;
}
int main()
{
char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"};
int pass[MAX_SIZE]={0};
int i,len,j;
for(i=0;i<3;i++)
{
len=strlen(sym[i]);
encode(sym[i],len,pass);
printf("%s : [",sym[i]);
for(j=0;j<len;j++)
printf("%d ",pass[j]);
printf("]\n");
if(check(sym[i],len,pass))
printf("Correct :)\n");
else
printf("Incorrect :(\n");
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from C++ to C. | #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;
}
| #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 100
int move_to_front(char *str,char c)
{
char *q,*p;
int shift=0;
p=(char *)malloc(strlen(str)+1);
strcpy(p,str);
q=strchr(p,c);
shift=q-p;
strncpy(str+1,p,shift);
str[0]=c;
free(p);
return shift;
}
void decode(int* pass,int size,char *sym)
{
int i,index;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=table[pass[i]];
index=move_to_front(table,c);
if(pass[i]!=index) printf("there is an error");
sym[i]=c;
}
sym[size]='\0';
}
void encode(char *sym,int size,int *pass)
{
int i=0;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=sym[i];
pass[i]=move_to_front(table,c);
}
}
int check(char *sym,int size,int *pass)
{
int *pass2=malloc(sizeof(int)*size);
char *sym2=malloc(sizeof(char)*size);
int i,val=1;
encode(sym,size,pass2);
i=0;
while(i<size && pass[i]==pass2[i])i++;
if(i!=size)val=0;
decode(pass,size,sym2);
if(strcmp(sym,sym2)!=0)val=0;
free(sym2);
free(pass2);
return val;
}
int main()
{
char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"};
int pass[MAX_SIZE]={0};
int i,len,j;
for(i=0;i<3;i++)
{
len=strlen(sym[i]);
encode(sym[i],len,pass);
printf("%s : [",sym[i]);
for(j=0;j<len;j++)
printf("%d ",pass[j]);
printf("]\n");
if(check(sym[i],len,pass))
printf("Correct :)\n");
else
printf("Incorrect :(\n");
}
return 0;
}
|
Convert this C++ block to C, preserving its control flow and logic. | #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);
}
| #include <stdio.h>
int main() {
for (int i = 0, sum = 0; i < 50; ++i) {
sum += i * i * i;
printf("%7d%c", sum, (i + 1) % 5 == 0 ? '\n' : ' ');
}
return 0;
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #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;
}
| #include <stdio.h>
#include <complex.h>
#include <math.h>
#define FMTSPEC(arg) _Generic((arg), \
float: "%f", double: "%f", \
long double: "%Lf", unsigned int: "%u", \
unsigned long: "%lu", unsigned long long: "%llu", \
int: "%d", long: "%ld", long long: "%lld", \
default: "(invalid type (%p)")
#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \
I * (long double)(y)))
#define TEST_CMPL(i, j)\
printf(FMTSPEC(i), i), printf(" + "), printf(FMTSPEC(j), j), \
printf("i = %s\n", (isint(CMPPARTS(i, j)) ? "true" : "false"))
#define TEST_REAL(i)\
printf(FMTSPEC(i), i), printf(" = %s\n", (isint(i) ? "true" : "false"))
static inline int isint(long double complex n)
{
return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);
}
int main(void)
{
TEST_REAL(0);
TEST_REAL(-0);
TEST_REAL(-2);
TEST_REAL(-2.00000000000001);
TEST_REAL(5);
TEST_REAL(7.3333333333333);
TEST_REAL(3.141592653589);
TEST_REAL(-9.223372036854776e18);
TEST_REAL(5e-324);
TEST_REAL(NAN);
TEST_CMPL(6, 0);
TEST_CMPL(0, 1);
TEST_CMPL(0, 0);
TEST_CMPL(3.4, 0);
double complex test1 = 5 + 0*I,
test2 = 3.4f,
test3 = 3,
test4 = 0 + 1.2*I;
printf("Test 1 (5+i) = %s\n", isint(test1) ? "true" : "false");
printf("Test 2 (3.4+0i) = %s\n", isint(test2) ? "true" : "false");
printf("Test 3 (3+0i) = %s\n", isint(test3) ? "true" : "false");
printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false");
}
|
Maintain the same structure and functionality when rewriting this code in C. | #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 });
}
| #include <stdio.h>
#include <stdlib.h>
struct node {
int val, len;
struct node *next;
};
void lis(int *v, int len)
{
int i;
struct node *p, *n = calloc(len, sizeof *n);
for (i = 0; i < len; i++)
n[i].val = v[i];
for (i = len; i--; ) {
for (p = n + i; p++ < n + len; ) {
if (p->val > n[i].val && p->len >= n[i].len) {
n[i].next = p;
n[i].len = p->len + 1;
}
}
}
for (i = 0, p = n; i < len; i++)
if (n[i].len > p->len) p = n + i;
do printf(" %d", p->val); while ((p = p->next));
putchar('\n');
free(n);
}
int main(void)
{
int x[] = { 3, 2, 6, 4, 5, 1 };
int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
lis(x, sizeof(x) / sizeof(int));
lis(y, sizeof(y) / sizeof(int));
return 0;
}
|
Port the following code from C++ to C with equivalent syntax and logic. | #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 });
}
| #include <stdio.h>
#include <stdlib.h>
struct node {
int val, len;
struct node *next;
};
void lis(int *v, int len)
{
int i;
struct node *p, *n = calloc(len, sizeof *n);
for (i = 0; i < len; i++)
n[i].val = v[i];
for (i = len; i--; ) {
for (p = n + i; p++ < n + len; ) {
if (p->val > n[i].val && p->len >= n[i].len) {
n[i].next = p;
n[i].len = p->len + 1;
}
}
}
for (i = 0, p = n; i < len; i++)
if (n[i].len > p->len) p = n + i;
do printf(" %d", p->val); while ((p = p->next));
putchar('\n');
free(n);
}
int main(void)
{
int x[] = { 3, 2, 6, 4, 5, 1 };
int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
lis(x, sizeof(x) / sizeof(int));
lis(y, sizeof(y) / sizeof(int));
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.