Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #include <vector>
#include <memory>
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;
typedef vector< int > IntRow;
typedef vector< IntRow > IntTable;
auto_ptr< IntTable > getSpiralArray( int dimension )
{
auto_ptr< IntTable > spiralArrayPtr( new IntTable(
dimension, IntRow( dimension ) ) );
int numConcentricSquares = static_cast< int >( ceil(
static_cast< double >( dimension ) / 2.0 ) );
int j;
int sideLen = dimension;
int currNum = 0;
for ( int i = 0; i < numConcentricSquares; i++ )
{
for ( j = 0; j < sideLen; j++ )
( *spiralArrayPtr )[ i ][ i + j ] = currNum++;
for ( j = 1; j < sideLen; j++ )
( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++;
for ( j = sideLen - 2; j > -1; j-- )
( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++;
for ( j = sideLen - 2; j > 0; j-- )
( *spiralArrayPtr )[ i + j ][ i ] = currNum++;
sideLen -= 2;
}
return spiralArrayPtr;
}
void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr )
{
size_t dimension = spiralArrayPtr->size();
int fieldWidth = static_cast< int >( floor( log10(
static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;
size_t col;
for ( size_t row = 0; row < dimension; row++ )
{
for ( col = 0; col < dimension; col++ )
cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ];
cout << endl;
}
}
int main()
{
printSpiralArray( getSpiralArray( 5 ) );
}
| #include <stdio.h>
#include <stdlib.h>
#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]
int main(int c, char **v)
{
int i, j, m = 0, n = 0;
if (c >= 2) m = atoi(v[1]);
if (c >= 3) n = atoi(v[2]);
if (m <= 0) m = 5;
if (n <= 0) n = m;
int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n);
s[0] = (int*)(s + m);
for (i = 1; i < m; i++) s[i] = s[i - 1] + n;
int dx = 1, dy = 0, val = 0, t;
for (i = j = 0; valid(i, j); i += dy, j += dx ) {
for (; valid(i, j); j += dx, i += dy)
s[i][j] = ++val;
j -= dx; i -= dy;
t = dy; dy = dx; dx = -t;
}
for (t = 2; val /= 10; t++);
for(i = 0; i < m; i++)
for(j = 0; j < n || !putchar('\n'); j++)
printf("%*d", t, s[i][j]);
return 0;
}
|
Translate this program into C but keep the logic exactly as in C++. | #include <vector>
#include <algorithm>
#include <string>
template <class T>
struct sort_table_functor {
typedef bool (*CompFun)(const T &, const T &);
const CompFun ordering;
const int column;
const bool reverse;
sort_table_functor(CompFun o, int c, bool r) :
ordering(o), column(c), reverse(r) { }
bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {
const T &a = x[column],
&b = y[column];
return reverse ? ordering(b, a)
: ordering(a, b);
}
};
template <class T>
bool myLess(const T &x, const T &y) { return x < y; }
template <class T>
void sort_table(std::vector<std::vector<T> > &table,
int column = 0, bool reverse = false,
bool (*ordering)(const T &, const T &) = myLess) {
std::sort(table.begin(), table.end(),
sort_table_functor<T>(ordering, column, reverse));
}
#include <iostream>
template <class T>
void print_matrix(std::vector<std::vector<T> > &data) {
for () {
for (int j = 0; j < 3; j++)
std::cout << data[i][j] << "\t";
std::cout << std::endl;
}
}
bool desc_len_comparator(const std::string &x, const std::string &y) {
return x.length() > y.length();
}
int main() {
std::string data_array[3][3] =
{
{"a", "b", "c"},
{"", "q", "z"},
{"zap", "zip", "Zot"}
};
std::vector<std::vector<std::string> > data_orig;
for (int i = 0; i < 3; i++) {
std::vector<std::string> row;
for (int j = 0; j < 3; j++)
row.push_back(data_array[i][j]);
data_orig.push_back(row);
}
print_matrix(data_orig);
std::vector<std::vector<std::string> > data = data_orig;
sort_table(data);
print_matrix(data);
data = data_orig;
sort_table(data, 2);
print_matrix(data);
data = data_orig;
sort_table(data, 1);
print_matrix(data);
data = data_orig;
sort_table(data, 1, true);
print_matrix(data);
data = data_orig;
sort_table(data, 0, false, desc_len_comparator);
print_matrix(data);
return 0;
}
| #include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
typedef const char * String;
typedef struct sTable {
String * *rows;
int n_rows,n_cols;
} *Table;
typedef int (*CompareFctn)(String a, String b);
struct {
CompareFctn compare;
int column;
int reversed;
} sortSpec;
int CmprRows( const void *aa, const void *bb)
{
String *rA = *(String *const *)aa;
String *rB = *(String *const *)bb;
int sortCol = sortSpec.column;
String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol];
String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol];
return sortSpec.compare( left, right );
}
int sortTable(Table tbl, const char* argSpec,... )
{
va_list vl;
const char *p;
int c;
sortSpec.compare = &strcmp;
sortSpec.column = 0;
sortSpec.reversed = 0;
va_start(vl, argSpec);
if (argSpec)
for (p=argSpec; *p; p++) {
switch (*p) {
case 'o':
sortSpec.compare = va_arg(vl,CompareFctn);
break;
case 'c':
c = va_arg(vl,int);
if ( 0<=c && c<tbl->n_cols)
sortSpec.column = c;
break;
case 'r':
sortSpec.reversed = (0!=va_arg(vl,int));
break;
}
}
va_end(vl);
qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows);
return 0;
}
void printTable( Table tbl, FILE *fout, const char *colFmts[])
{
int row, col;
for (row=0; row<tbl->n_rows; row++) {
fprintf(fout, " ");
for(col=0; col<tbl->n_cols; col++) {
fprintf(fout, colFmts[col], tbl->rows[row][col]);
}
fprintf(fout, "\n");
}
fprintf(fout, "\n");
}
int ord(char v)
{
return v-'0';
}
int cmprStrgs(String s1, String s2)
{
const char *p1 = s1;
const char *p2 = s2;
const char *mrk1, *mrk2;
while ((tolower(*p1) == tolower(*p2)) && *p1) {
p1++; p2++;
}
if (isdigit(*p1) && isdigit(*p2)) {
long v1, v2;
if ((*p1 == '0') ||(*p2 == '0')) {
while (p1 > s1) {
p1--; p2--;
if (*p1 != '0') break;
}
if (!isdigit(*p1)) {
p1++; p2++;
}
}
mrk1 = p1; mrk2 = p2;
v1 = 0;
while(isdigit(*p1)) {
v1 = 10*v1+ord(*p1);
p1++;
}
v2 = 0;
while(isdigit(*p2)) {
v2 = 10*v2+ord(*p2);
p2++;
}
if (v1 == v2)
return(p2-mrk2)-(p1-mrk1);
return v1 - v2;
}
if (tolower(*p1) != tolower(*p2))
return (tolower(*p1) - tolower(*p2));
for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++);
return (*p1 -*p2);
}
int main()
{
const char *colFmts[] = {" %-5.5s"," %-5.5s"," %-9.9s"};
String r1[] = { "a101", "red", "Java" };
String r2[] = { "ab40", "gren", "Smalltalk" };
String r3[] = { "ab9", "blue", "Fortran" };
String r4[] = { "ab09", "ylow", "Python" };
String r5[] = { "ab1a", "blak", "Factor" };
String r6[] = { "ab1b", "brwn", "C Sharp" };
String r7[] = { "Ab1b", "pink", "Ruby" };
String r8[] = { "ab1", "orng", "Scheme" };
String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 };
struct sTable table;
table.rows = rows;
table.n_rows = 8;
table.n_cols = 3;
sortTable(&table, "");
printf("sort on col 0, ascending\n");
printTable(&table, stdout, colFmts);
sortTable(&table, "ro", 1, &cmprStrgs);
printf("sort on col 0, reverse.special\n");
printTable(&table, stdout, colFmts);
sortTable(&table, "c", 1);
printf("sort on col 1, ascending\n");
printTable(&table, stdout, colFmts);
sortTable(&table, "cr", 2, 1);
printf("sort on col 2, reverse\n");
printTable(&table, stdout, colFmts);
return 0;
}
|
Port the following code from C++ to C with equivalent syntax and logic. | #include <windows.h>
#include <vector>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen_);
DeleteDC(hdc_);
DeleteObject(bmp_);
}
bool Create(int w, int h) {
BITMAPINFO bi;
ZeroMemory(&bi, sizeof(bi));
bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
void *bits_ptr = nullptr;
HDC dc = GetDC(GetConsoleWindow());
bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);
if (!bmp_) return false;
hdc_ = CreateCompatibleDC(dc);
SelectObject(hdc_, bmp_);
ReleaseDC(GetConsoleWindow(), dc);
width_ = w;
height_ = h;
return true;
}
void SetPenColor(DWORD clr) {
if (pen_) DeleteObject(pen_);
pen_ = CreatePen(PS_SOLID, 1, clr);
SelectObject(hdc_, pen_);
}
bool SaveBitmap(const char* path) {
HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
return false;
}
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
GetObject(bmp_, sizeof(bitmap), &bitmap);
DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory(dwp_bits, 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)dwp_bits, &infoheader, DIB_RGB_COLORS);
DWORD wb;
WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);
WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);
WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);
CloseHandle(file);
delete[] dwp_bits;
return true;
}
HDC hdc() { return hdc_; }
int width() { return width_; }
int height() { return height_; }
private:
HBITMAP bmp_;
HDC hdc_;
HPEN pen_;
int width_, height_;
};
static int DistanceSqrd(const Point& point, int x, int y) {
int xd = x - point.x;
int yd = y - point.y;
return (xd * xd) + (yd * yd);
}
class Voronoi {
public:
void Make(MyBitmap* bmp, int count) {
bmp_ = bmp;
CreatePoints(count);
CreateColors();
CreateSites();
SetSitesPoints();
}
private:
void CreateSites() {
int w = bmp_->width(), h = bmp_->height(), d;
for (int hh = 0; hh < h; hh++) {
for (int ww = 0; ww < w; ww++) {
int ind = -1, dist = INT_MAX;
for (size_t it = 0; it < points_.size(); it++) {
const Point& p = points_[it];
d = DistanceSqrd(p, ww, hh);
if (d < dist) {
dist = d;
ind = it;
}
}
if (ind > -1)
SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);
else
__asm nop
}
}
}
void SetSitesPoints() {
for (const auto& point : points_) {
int x = point.x, y = point.y;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
SetPixel(bmp_->hdc(), x + i, y + j, 0);
}
}
void CreatePoints(int count) {
const int w = bmp_->width() - 20, h = bmp_->height() - 20;
for (int i = 0; i < count; i++) {
points_.push_back({ rand() % w + 10, rand() % h + 10 });
}
}
void CreateColors() {
for (size_t i = 0; i < points_.size(); i++) {
DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);
colors_.push_back(c);
}
}
vector<Point> points_;
vector<DWORD> colors_;
MyBitmap* bmp_;
};
int main(int argc, char* argv[]) {
ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
srand(GetTickCount());
MyBitmap bmp;
bmp.Create(512, 512);
bmp.SetPenColor(0);
Voronoi v;
v.Make(&bmp, 50);
BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);
bmp.SaveBitmap("v.bmp");
system("pause");
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
int k, ret = 0;
double d, dist = 0;
for_k {
d = sq2(x - site[k][0], y - site[k][1]);
if (!k || d < dist) {
dist = d, ret = k;
}
}
return ret;
}
int at_edge(int *color, int y, int x)
{
int i, j, c = color[y * size_x + x];
for (i = y - 1; i <= y + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = x - 1; j <= x + 1; j++) {
if (j < 0 || j >= size_x) continue;
if (color[i * size_x + j] != c) return 1;
}
}
return 0;
}
#define AA_RES 4
void aa_color(unsigned char *pix, int y, int x)
{
int i, j, n;
double r = 0, g = 0, b = 0, xx, yy;
for (i = 0; i < AA_RES; i++) {
yy = y + 1. / AA_RES * i + .5;
for (j = 0; j < AA_RES; j++) {
xx = x + 1. / AA_RES * j + .5;
n = nearest_site(xx, yy);
r += rgb[n][0];
g += rgb[n][1];
b += rgb[n][2];
}
}
pix[0] = r / (AA_RES * AA_RES);
pix[1] = g / (AA_RES * AA_RES);
pix[2] = b / (AA_RES * AA_RES);
}
#define for_i for (i = 0; i < size_y; i++)
#define for_j for (j = 0; j < size_x; j++)
void gen_map()
{
int i, j, k;
int *nearest = malloc(sizeof(int) * size_y * size_x);
unsigned char *ptr, *buf, color;
ptr = buf = malloc(3 * size_x * size_y);
for_i for_j nearest[i * size_x + j] = nearest_site(j, i);
for_i for_j {
if (!at_edge(nearest, i, j))
memcpy(ptr, rgb[nearest[i * size_x + j]], 3);
else
aa_color(ptr, i, j);
ptr += 3;
}
for (k = 0; k < N_SITES; k++) {
color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;
for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {
if (j < 0 || j >= size_x) continue;
ptr = buf + 3 * (i * size_x + j);
ptr[0] = ptr[1] = ptr[2] = color;
}
}
}
printf("P6\n%d %d\n255\n", size_x, size_y);
fflush(stdout);
fwrite(buf, size_y * size_x * 3, 1, stdout);
}
#define frand(x) (rand() / (1. + RAND_MAX) * x)
int main()
{
int k;
for_k {
site[k][0] = frand(size_x);
site[k][1] = frand(size_y);
rgb [k][0] = frand(256);
rgb [k][1] = frand(256);
rgb [k][2] = frand(256);
}
gen_map();
return 0;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <windows.h>
#include <vector>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen_);
DeleteDC(hdc_);
DeleteObject(bmp_);
}
bool Create(int w, int h) {
BITMAPINFO bi;
ZeroMemory(&bi, sizeof(bi));
bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
void *bits_ptr = nullptr;
HDC dc = GetDC(GetConsoleWindow());
bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);
if (!bmp_) return false;
hdc_ = CreateCompatibleDC(dc);
SelectObject(hdc_, bmp_);
ReleaseDC(GetConsoleWindow(), dc);
width_ = w;
height_ = h;
return true;
}
void SetPenColor(DWORD clr) {
if (pen_) DeleteObject(pen_);
pen_ = CreatePen(PS_SOLID, 1, clr);
SelectObject(hdc_, pen_);
}
bool SaveBitmap(const char* path) {
HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
return false;
}
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
GetObject(bmp_, sizeof(bitmap), &bitmap);
DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory(dwp_bits, 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)dwp_bits, &infoheader, DIB_RGB_COLORS);
DWORD wb;
WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);
WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);
WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);
CloseHandle(file);
delete[] dwp_bits;
return true;
}
HDC hdc() { return hdc_; }
int width() { return width_; }
int height() { return height_; }
private:
HBITMAP bmp_;
HDC hdc_;
HPEN pen_;
int width_, height_;
};
static int DistanceSqrd(const Point& point, int x, int y) {
int xd = x - point.x;
int yd = y - point.y;
return (xd * xd) + (yd * yd);
}
class Voronoi {
public:
void Make(MyBitmap* bmp, int count) {
bmp_ = bmp;
CreatePoints(count);
CreateColors();
CreateSites();
SetSitesPoints();
}
private:
void CreateSites() {
int w = bmp_->width(), h = bmp_->height(), d;
for (int hh = 0; hh < h; hh++) {
for (int ww = 0; ww < w; ww++) {
int ind = -1, dist = INT_MAX;
for (size_t it = 0; it < points_.size(); it++) {
const Point& p = points_[it];
d = DistanceSqrd(p, ww, hh);
if (d < dist) {
dist = d;
ind = it;
}
}
if (ind > -1)
SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);
else
__asm nop
}
}
}
void SetSitesPoints() {
for (const auto& point : points_) {
int x = point.x, y = point.y;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
SetPixel(bmp_->hdc(), x + i, y + j, 0);
}
}
void CreatePoints(int count) {
const int w = bmp_->width() - 20, h = bmp_->height() - 20;
for (int i = 0; i < count; i++) {
points_.push_back({ rand() % w + 10, rand() % h + 10 });
}
}
void CreateColors() {
for (size_t i = 0; i < points_.size(); i++) {
DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);
colors_.push_back(c);
}
}
vector<Point> points_;
vector<DWORD> colors_;
MyBitmap* bmp_;
};
int main(int argc, char* argv[]) {
ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
srand(GetTickCount());
MyBitmap bmp;
bmp.Create(512, 512);
bmp.SetPenColor(0);
Voronoi v;
v.Make(&bmp, 50);
BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);
bmp.SaveBitmap("v.bmp");
system("pause");
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
int k, ret = 0;
double d, dist = 0;
for_k {
d = sq2(x - site[k][0], y - site[k][1]);
if (!k || d < dist) {
dist = d, ret = k;
}
}
return ret;
}
int at_edge(int *color, int y, int x)
{
int i, j, c = color[y * size_x + x];
for (i = y - 1; i <= y + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = x - 1; j <= x + 1; j++) {
if (j < 0 || j >= size_x) continue;
if (color[i * size_x + j] != c) return 1;
}
}
return 0;
}
#define AA_RES 4
void aa_color(unsigned char *pix, int y, int x)
{
int i, j, n;
double r = 0, g = 0, b = 0, xx, yy;
for (i = 0; i < AA_RES; i++) {
yy = y + 1. / AA_RES * i + .5;
for (j = 0; j < AA_RES; j++) {
xx = x + 1. / AA_RES * j + .5;
n = nearest_site(xx, yy);
r += rgb[n][0];
g += rgb[n][1];
b += rgb[n][2];
}
}
pix[0] = r / (AA_RES * AA_RES);
pix[1] = g / (AA_RES * AA_RES);
pix[2] = b / (AA_RES * AA_RES);
}
#define for_i for (i = 0; i < size_y; i++)
#define for_j for (j = 0; j < size_x; j++)
void gen_map()
{
int i, j, k;
int *nearest = malloc(sizeof(int) * size_y * size_x);
unsigned char *ptr, *buf, color;
ptr = buf = malloc(3 * size_x * size_y);
for_i for_j nearest[i * size_x + j] = nearest_site(j, i);
for_i for_j {
if (!at_edge(nearest, i, j))
memcpy(ptr, rgb[nearest[i * size_x + j]], 3);
else
aa_color(ptr, i, j);
ptr += 3;
}
for (k = 0; k < N_SITES; k++) {
color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;
for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {
if (j < 0 || j >= size_x) continue;
ptr = buf + 3 * (i * size_x + j);
ptr[0] = ptr[1] = ptr[2] = color;
}
}
}
printf("P6\n%d %d\n255\n", size_x, size_y);
fflush(stdout);
fwrite(buf, size_y * size_x * 3, 1, stdout);
}
#define frand(x) (rand() / (1. + RAND_MAX) * x)
int main()
{
int k;
for_k {
site[k][0] = frand(size_x);
site[k][1] = frand(size_y);
rgb [k][0] = frand(256);
rgb [k][1] = frand(256);
rgb [k][2] = frand(256);
}
gen_map();
return 0;
}
|
Transform the following C++ implementation into C, maintaining the same output and logic. | #include <windows.h>
#include <vector>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class MyBitmap {
public:
MyBitmap() : pen_(nullptr) {}
~MyBitmap() {
DeleteObject(pen_);
DeleteDC(hdc_);
DeleteObject(bmp_);
}
bool Create(int w, int h) {
BITMAPINFO bi;
ZeroMemory(&bi, sizeof(bi));
bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
bi.bmiHeader.biBitCount = sizeof(DWORD) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
void *bits_ptr = nullptr;
HDC dc = GetDC(GetConsoleWindow());
bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0);
if (!bmp_) return false;
hdc_ = CreateCompatibleDC(dc);
SelectObject(hdc_, bmp_);
ReleaseDC(GetConsoleWindow(), dc);
width_ = w;
height_ = h;
return true;
}
void SetPenColor(DWORD clr) {
if (pen_) DeleteObject(pen_);
pen_ = CreatePen(PS_SOLID, 1, clr);
SelectObject(hdc_, pen_);
}
bool SaveBitmap(const char* path) {
HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
return false;
}
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
GetObject(bmp_, sizeof(bitmap), &bitmap);
DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory(dwp_bits, 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)dwp_bits, &infoheader, DIB_RGB_COLORS);
DWORD wb;
WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr);
WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr);
WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr);
CloseHandle(file);
delete[] dwp_bits;
return true;
}
HDC hdc() { return hdc_; }
int width() { return width_; }
int height() { return height_; }
private:
HBITMAP bmp_;
HDC hdc_;
HPEN pen_;
int width_, height_;
};
static int DistanceSqrd(const Point& point, int x, int y) {
int xd = x - point.x;
int yd = y - point.y;
return (xd * xd) + (yd * yd);
}
class Voronoi {
public:
void Make(MyBitmap* bmp, int count) {
bmp_ = bmp;
CreatePoints(count);
CreateColors();
CreateSites();
SetSitesPoints();
}
private:
void CreateSites() {
int w = bmp_->width(), h = bmp_->height(), d;
for (int hh = 0; hh < h; hh++) {
for (int ww = 0; ww < w; ww++) {
int ind = -1, dist = INT_MAX;
for (size_t it = 0; it < points_.size(); it++) {
const Point& p = points_[it];
d = DistanceSqrd(p, ww, hh);
if (d < dist) {
dist = d;
ind = it;
}
}
if (ind > -1)
SetPixel(bmp_->hdc(), ww, hh, colors_[ind]);
else
__asm nop
}
}
}
void SetSitesPoints() {
for (const auto& point : points_) {
int x = point.x, y = point.y;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
SetPixel(bmp_->hdc(), x + i, y + j, 0);
}
}
void CreatePoints(int count) {
const int w = bmp_->width() - 20, h = bmp_->height() - 20;
for (int i = 0; i < count; i++) {
points_.push_back({ rand() % w + 10, rand() % h + 10 });
}
}
void CreateColors() {
for (size_t i = 0; i < points_.size(); i++) {
DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50);
colors_.push_back(c);
}
}
vector<Point> points_;
vector<DWORD> colors_;
MyBitmap* bmp_;
};
int main(int argc, char* argv[]) {
ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
srand(GetTickCount());
MyBitmap bmp;
bmp.Create(512, 512);
bmp.SetPenColor(0);
Voronoi v;
v.Make(&bmp, 50);
BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY);
bmp.SaveBitmap("v.bmp");
system("pause");
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
int k, ret = 0;
double d, dist = 0;
for_k {
d = sq2(x - site[k][0], y - site[k][1]);
if (!k || d < dist) {
dist = d, ret = k;
}
}
return ret;
}
int at_edge(int *color, int y, int x)
{
int i, j, c = color[y * size_x + x];
for (i = y - 1; i <= y + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = x - 1; j <= x + 1; j++) {
if (j < 0 || j >= size_x) continue;
if (color[i * size_x + j] != c) return 1;
}
}
return 0;
}
#define AA_RES 4
void aa_color(unsigned char *pix, int y, int x)
{
int i, j, n;
double r = 0, g = 0, b = 0, xx, yy;
for (i = 0; i < AA_RES; i++) {
yy = y + 1. / AA_RES * i + .5;
for (j = 0; j < AA_RES; j++) {
xx = x + 1. / AA_RES * j + .5;
n = nearest_site(xx, yy);
r += rgb[n][0];
g += rgb[n][1];
b += rgb[n][2];
}
}
pix[0] = r / (AA_RES * AA_RES);
pix[1] = g / (AA_RES * AA_RES);
pix[2] = b / (AA_RES * AA_RES);
}
#define for_i for (i = 0; i < size_y; i++)
#define for_j for (j = 0; j < size_x; j++)
void gen_map()
{
int i, j, k;
int *nearest = malloc(sizeof(int) * size_y * size_x);
unsigned char *ptr, *buf, color;
ptr = buf = malloc(3 * size_x * size_y);
for_i for_j nearest[i * size_x + j] = nearest_site(j, i);
for_i for_j {
if (!at_edge(nearest, i, j))
memcpy(ptr, rgb[nearest[i * size_x + j]], 3);
else
aa_color(ptr, i, j);
ptr += 3;
}
for (k = 0; k < N_SITES; k++) {
color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;
for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {
if (j < 0 || j >= size_x) continue;
ptr = buf + 3 * (i * size_x + j);
ptr[0] = ptr[1] = ptr[2] = color;
}
}
}
printf("P6\n%d %d\n255\n", size_x, size_y);
fflush(stdout);
fwrite(buf, size_y * size_x * 3, 1, stdout);
}
#define frand(x) (rand() / (1. + RAND_MAX) * x)
int main()
{
int k;
for_k {
site[k][0] = frand(size_x);
site[k][1] = frand(size_y);
rgb [k][0] = frand(256);
rgb [k][1] = frand(256);
rgb [k][2] = frand(256);
}
gen_map();
return 0;
}
|
Generate an equivalent C version of this C++ code. | FUNCTION MULTIPLY(X, Y)
DOUBLE PRECISION MULTIPLY, X, Y
|
#include <stdio.h>
void sayHello(char* name){
printf("Hello %s!\n", name);
}
int doubleNum(int num){
return num * 2;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #include <iostream>
#include <functional>
#include <vector>
#include <cstdlib>
#include <ctime>
template <typename T>
std::function<std::vector<T>(T)> s_of_n_creator(int n) {
std::vector<T> sample;
int i = 0;
return [=](T item) mutable {
i++;
if (i <= n) {
sample.push_back(item);
} else if (std::rand() % i < n) {
sample[std::rand() % n] = item;
}
return sample;
};
}
int main() {
std::srand(std::time(NULL));
int bin[10] = {0};
for (int trial = 0; trial < 100000; trial++) {
auto s_of_n = s_of_n_creator<int>(3);
std::vector<int> sample;
for (int i = 0; i < 10; i++)
sample = s_of_n(i);
for (int s : sample)
bin[s]++;
}
for (int x : bin)
std::cout << x << std::endl;
return 0;
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
struct s_env {
unsigned int n, i;
size_t size;
void *sample;
};
void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
s_env->i = 0;
s_env->n = n;
s_env->size = size;
s_env->sample = malloc(n * size);
}
void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}
void *s_of_n(struct s_env *s_env, void *item)
{
s_env->i++;
if (s_env->i <= s_env->n)
sample_set_i(s_env, s_env->i - 1, item);
else if ((rand() % s_env->i) < s_env->n)
sample_set_i(s_env, rand() % s_env->n, item);
return s_env->sample;
}
int *test(unsigned int n, int *items_set, unsigned int num_items)
{
int i;
struct s_env s_env;
s_of_n_init(&s_env, sizeof(items_set[0]), n);
for (i = 0; i < num_items; i++) {
s_of_n(&s_env, (void *) &items_set[i]);
}
return (int *)s_env.sample;
}
int main()
{
unsigned int i, j;
unsigned int n = 3;
unsigned int num_items = 10;
unsigned int *frequencies;
int *items_set;
srand(time(NULL));
items_set = malloc(num_items * sizeof(int));
frequencies = malloc(num_items * sizeof(int));
for (i = 0; i < num_items; i++) {
items_set[i] = i;
frequencies[i] = 0;
}
for (i = 0; i < 100000; i++) {
int *res = test(n, items_set, num_items);
for (j = 0; j < n; j++) {
frequencies[res[j]]++;
}
free(res);
}
for (i = 0; i < num_items; i++) {
printf(" %d", frequencies[i]);
}
puts("");
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #include <iostream>
#include <functional>
#include <vector>
#include <cstdlib>
#include <ctime>
template <typename T>
std::function<std::vector<T>(T)> s_of_n_creator(int n) {
std::vector<T> sample;
int i = 0;
return [=](T item) mutable {
i++;
if (i <= n) {
sample.push_back(item);
} else if (std::rand() % i < n) {
sample[std::rand() % n] = item;
}
return sample;
};
}
int main() {
std::srand(std::time(NULL));
int bin[10] = {0};
for (int trial = 0; trial < 100000; trial++) {
auto s_of_n = s_of_n_creator<int>(3);
std::vector<int> sample;
for (int i = 0; i < 10; i++)
sample = s_of_n(i);
for (int s : sample)
bin[s]++;
}
for (int x : bin)
std::cout << x << std::endl;
return 0;
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
struct s_env {
unsigned int n, i;
size_t size;
void *sample;
};
void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
s_env->i = 0;
s_env->n = n;
s_env->size = size;
s_env->sample = malloc(n * size);
}
void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}
void *s_of_n(struct s_env *s_env, void *item)
{
s_env->i++;
if (s_env->i <= s_env->n)
sample_set_i(s_env, s_env->i - 1, item);
else if ((rand() % s_env->i) < s_env->n)
sample_set_i(s_env, rand() % s_env->n, item);
return s_env->sample;
}
int *test(unsigned int n, int *items_set, unsigned int num_items)
{
int i;
struct s_env s_env;
s_of_n_init(&s_env, sizeof(items_set[0]), n);
for (i = 0; i < num_items; i++) {
s_of_n(&s_env, (void *) &items_set[i]);
}
return (int *)s_env.sample;
}
int main()
{
unsigned int i, j;
unsigned int n = 3;
unsigned int num_items = 10;
unsigned int *frequencies;
int *items_set;
srand(time(NULL));
items_set = malloc(num_items * sizeof(int));
frequencies = malloc(num_items * sizeof(int));
for (i = 0; i < num_items; i++) {
items_set[i] = i;
frequencies[i] = 0;
}
for (i = 0; i < 100000; i++) {
int *res = test(n, items_set, num_items);
for (j = 0; j < n; j++) {
frequencies[res[j]]++;
}
free(res);
}
for (i = 0; i < num_items; i++) {
printf(" %d", frequencies[i]);
}
puts("");
return 0;
}
|
Generate a C translation of this C++ snippet without changing its computational steps. | #include <iostream>
#include <functional>
#include <vector>
#include <cstdlib>
#include <ctime>
template <typename T>
std::function<std::vector<T>(T)> s_of_n_creator(int n) {
std::vector<T> sample;
int i = 0;
return [=](T item) mutable {
i++;
if (i <= n) {
sample.push_back(item);
} else if (std::rand() % i < n) {
sample[std::rand() % n] = item;
}
return sample;
};
}
int main() {
std::srand(std::time(NULL));
int bin[10] = {0};
for (int trial = 0; trial < 100000; trial++) {
auto s_of_n = s_of_n_creator<int>(3);
std::vector<int> sample;
for (int i = 0; i < 10; i++)
sample = s_of_n(i);
for (int s : sample)
bin[s]++;
}
for (int x : bin)
std::cout << x << std::endl;
return 0;
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
struct s_env {
unsigned int n, i;
size_t size;
void *sample;
};
void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
s_env->i = 0;
s_env->n = n;
s_env->size = size;
s_env->sample = malloc(n * size);
}
void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}
void *s_of_n(struct s_env *s_env, void *item)
{
s_env->i++;
if (s_env->i <= s_env->n)
sample_set_i(s_env, s_env->i - 1, item);
else if ((rand() % s_env->i) < s_env->n)
sample_set_i(s_env, rand() % s_env->n, item);
return s_env->sample;
}
int *test(unsigned int n, int *items_set, unsigned int num_items)
{
int i;
struct s_env s_env;
s_of_n_init(&s_env, sizeof(items_set[0]), n);
for (i = 0; i < num_items; i++) {
s_of_n(&s_env, (void *) &items_set[i]);
}
return (int *)s_env.sample;
}
int main()
{
unsigned int i, j;
unsigned int n = 3;
unsigned int num_items = 10;
unsigned int *frequencies;
int *items_set;
srand(time(NULL));
items_set = malloc(num_items * sizeof(int));
frequencies = malloc(num_items * sizeof(int));
for (i = 0; i < num_items; i++) {
items_set[i] = i;
frequencies[i] = 0;
}
for (i = 0; i < 100000; i++) {
int *res = test(n, items_set, num_items);
for (j = 0; j < n; j++) {
frequencies[res[j]]++;
}
free(res);
}
for (i = 0; i < num_items; i++) {
printf(" %d", frequencies[i]);
}
puts("");
return 0;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #include <exception>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
class Frac {
public:
Frac() : num(0), denom(1) {}
Frac(int n, int d) {
if (d == 0) {
throw std::runtime_error("d must not be zero");
}
int sign_of_d = d < 0 ? -1 : 1;
int g = std::gcd(n, d);
num = sign_of_d * n / g;
denom = sign_of_d * d / g;
}
Frac operator-() const {
return Frac(-num, denom);
}
Frac operator+(const Frac& rhs) const {
return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);
}
Frac operator-(const Frac& rhs) const {
return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);
}
Frac operator*(const Frac& rhs) const {
return Frac(num*rhs.num, denom*rhs.denom);
}
Frac operator*(int rhs) const {
return Frac(num * rhs, denom);
}
friend std::ostream& operator<<(std::ostream&, const Frac&);
private:
int num;
int denom;
};
std::ostream & operator<<(std::ostream & os, const Frac &f) {
if (f.num == 0 || f.denom == 1) {
return os << f.num;
}
std::stringstream ss;
ss << f.num << "/" << f.denom;
return os << ss.str();
}
Frac bernoulli(int n) {
if (n < 0) {
throw std::runtime_error("n may not be negative or zero");
}
std::vector<Frac> a;
for (int m = 0; m <= n; m++) {
a.push_back(Frac(1, m + 1));
for (int j = m; j >= 1; j--) {
a[j - 1] = (a[j - 1] - a[j]) * j;
}
}
if (n != 1) return a[0];
return -a[0];
}
int binomial(int n, int k) {
if (n < 0 || k < 0 || n < k) {
throw std::runtime_error("parameters are invalid");
}
if (n == 0 || k == 0) return 1;
int num = 1;
for (int i = k + 1; i <= n; i++) {
num *= i;
}
int denom = 1;
for (int i = 2; i <= n - k; i++) {
denom *= i;
}
return num / denom;
}
std::vector<Frac> faulhaberTraingle(int p) {
std::vector<Frac> coeffs(p + 1);
Frac q{ 1, p + 1 };
int sign = -1;
for (int j = 0; j <= p; j++) {
sign *= -1;
coeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);
}
return coeffs;
}
int main() {
for (int i = 0; i < 10; i++) {
std::vector<Frac> coeffs = faulhaberTraingle(i);
for (auto frac : coeffs) {
std::cout << std::right << std::setw(5) << frac << " ";
}
std::cout << std::endl;
}
return 0;
}
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int binomial(int n, int k) {
int num, denom, i;
if (n < 0 || k < 0 || n < k) return -1;
if (n == 0 || k == 0) return 1;
num = 1;
for (i = k + 1; i <= n; ++i) {
num = num * i;
}
denom = 1;
for (i = 2; i <= n - k; ++i) {
denom *= i;
}
return num / denom;
}
int gcd(int a, int b) {
int temp;
while (b != 0) {
temp = a % b;
a = b;
b = temp;
}
return a;
}
typedef struct tFrac {
int num, denom;
} Frac;
Frac makeFrac(int n, int d) {
Frac result;
int g;
if (d == 0) {
result.num = 0;
result.denom = 0;
return result;
}
if (n == 0) {
d = 1;
} else if (d < 0) {
n = -n;
d = -d;
}
g = abs(gcd(n, d));
if (g > 1) {
n = n / g;
d = d / g;
}
result.num = n;
result.denom = d;
return result;
}
Frac negateFrac(Frac f) {
return makeFrac(-f.num, f.denom);
}
Frac subFrac(Frac lhs, Frac rhs) {
return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom);
}
Frac multFrac(Frac lhs, Frac rhs) {
return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom);
}
bool equalFrac(Frac lhs, Frac rhs) {
return (lhs.num == rhs.num) && (lhs.denom == rhs.denom);
}
bool lessFrac(Frac lhs, Frac rhs) {
return (lhs.num * rhs.denom) < (rhs.num * lhs.denom);
}
void printFrac(Frac f) {
char buffer[7];
int len;
if (f.denom != 1) {
snprintf(buffer, 7, "%d/%d", f.num, f.denom);
} else {
snprintf(buffer, 7, "%d", f.num);
}
len = 7 - strlen(buffer);
while (len-- > 0) {
putc(' ', stdout);
}
printf(buffer);
}
Frac bernoulli(int n) {
Frac a[16];
int j, m;
if (n < 0) {
a[0].num = 0;
a[0].denom = 0;
return a[0];
}
for (m = 0; m <= n; ++m) {
a[m] = makeFrac(1, m + 1);
for (j = m; j >= 1; --j) {
a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1));
}
}
if (n != 1) {
return a[0];
}
return negateFrac(a[0]);
}
void faulhaber(int p) {
Frac q, *coeffs;
int j, sign;
coeffs = malloc(sizeof(Frac)*(p + 1));
q = makeFrac(1, p + 1);
sign = -1;
for (j = 0; j <= p; ++j) {
sign = -1 * sign;
coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j));
}
for (j = 0; j <= p; ++j) {
printFrac(coeffs[j]);
}
printf("\n");
free(coeffs);
}
int main() {
int i;
for (i = 0; i < 10; ++i) {
faulhaber(i);
}
return 0;
}
|
Write a version of this C++ function in C with identical behavior. | #include <iostream>
int main(int argc, char* argv[])
{
std::cout << "This program is named " << argv[0] << std::endl;
std::cout << "There are " << argc-1 << " arguments given." << std::endl;
for (int i = 1; i < argc; ++i)
std::cout << "the argument #" << i << " is " << argv[i] << std::endl;
return 0;
}
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
(void) printf("This program is named %s.\n", argv[0]);
for (i = 1; i < argc; ++i)
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}
|
Keep all operations the same but rewrite the snippet in C. | #include <iostream>
int main(int argc, char* argv[])
{
std::cout << "This program is named " << argv[0] << std::endl;
std::cout << "There are " << argc-1 << " arguments given." << std::endl;
for (int i = 1; i < argc; ++i)
std::cout << "the argument #" << i << " is " << argv[i] << std::endl;
return 0;
}
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
(void) printf("This program is named %s.\n", argv[0]);
for (i = 1; i < argc; ++i)
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}
|
Transform the following C++ implementation into C, maintaining the same output and logic. | #include <iostream>
int main(int argc, char* argv[])
{
std::cout << "This program is named " << argv[0] << std::endl;
std::cout << "There are " << argc-1 << " arguments given." << std::endl;
for (int i = 1; i < argc; ++i)
std::cout << "the argument #" << i << " is " << argv[i] << std::endl;
return 0;
}
| #include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
(void) printf("This program is named %s.\n", argv[0]);
for (i = 1; i < argc; ++i)
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}
|
Please provide an equivalent version of this C++ code in C. | #include <array>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
class letterset {
public:
letterset() {
count_.fill(0);
}
explicit letterset(const std::string& str) {
count_.fill(0);
for (char c : str)
add(c);
}
bool contains(const letterset& set) const {
for (size_t i = 0; i < count_.size(); ++i) {
if (set.count_[i] > count_[i])
return false;
}
return true;
}
unsigned int count(char c) const {
return count_[index(c)];
}
bool is_valid() const {
return count_[0] == 0;
}
void add(char c) {
++count_[index(c)];
}
private:
static bool is_letter(char c) { return c >= 'a' && c <= 'z'; }
static int index(char c) { return is_letter(c) ? c - 'a' + 1 : 0; }
std::array<unsigned int, 27> count_;
};
template <typename iterator, typename separator>
std::string join(iterator begin, iterator end, separator sep) {
std::string result;
if (begin != end) {
result += *begin++;
for (; begin != end; ++begin) {
result += sep;
result += *begin;
}
}
return result;
}
using dictionary = std::vector<std::pair<std::string, letterset>>;
dictionary load_dictionary(const std::string& filename, int min_length,
int max_length) {
std::ifstream in(filename);
if (!in)
throw std::runtime_error("Cannot open file " + filename);
std::string word;
dictionary result;
while (getline(in, word)) {
if (word.size() < min_length)
continue;
if (word.size() > max_length)
continue;
letterset set(word);
if (set.is_valid())
result.emplace_back(word, set);
}
return result;
}
void word_wheel(const dictionary& dict, const std::string& letters,
char central_letter) {
letterset set(letters);
if (central_letter == 0 && !letters.empty())
central_letter = letters.at(letters.size()/2);
std::map<size_t, std::vector<std::string>> words;
for (const auto& pair : dict) {
const auto& word = pair.first;
const auto& subset = pair.second;
if (subset.count(central_letter) > 0 && set.contains(subset))
words[word.size()].push_back(word);
}
size_t total = 0;
for (const auto& p : words) {
const auto& v = p.second;
auto n = v.size();
total += n;
std::cout << "Found " << n << " " << (n == 1 ? "word" : "words")
<< " of length " << p.first << ": "
<< join(v.begin(), v.end(), ", ") << '\n';
}
std::cout << "Number of words found: " << total << '\n';
}
void find_max_word_count(const dictionary& dict, int word_length) {
size_t max_count = 0;
std::vector<std::pair<std::string, char>> max_words;
for (const auto& pair : dict) {
const auto& word = pair.first;
if (word.size() != word_length)
continue;
const auto& set = pair.second;
dictionary subsets;
for (const auto& p : dict) {
if (set.contains(p.second))
subsets.push_back(p);
}
letterset done;
for (size_t index = 0; index < word_length; ++index) {
char central_letter = word[index];
if (done.count(central_letter) > 0)
continue;
done.add(central_letter);
size_t count = 0;
for (const auto& p : subsets) {
const auto& subset = p.second;
if (subset.count(central_letter) > 0)
++count;
}
if (count > max_count) {
max_words.clear();
max_count = count;
}
if (count == max_count)
max_words.emplace_back(word, central_letter);
}
}
std::cout << "Maximum word count: " << max_count << '\n';
std::cout << "Words of " << word_length << " letters producing this count:\n";
for (const auto& pair : max_words)
std::cout << pair.first << " with central letter " << pair.second << '\n';
}
constexpr const char* option_filename = "filename";
constexpr const char* option_wheel = "wheel";
constexpr const char* option_central = "central";
constexpr const char* option_min_length = "min-length";
constexpr const char* option_part2 = "part2";
int main(int argc, char** argv) {
const int word_length = 9;
int min_length = 3;
std::string letters = "ndeokgelw";
std::string filename = "unixdict.txt";
char central_letter = 0;
bool do_part2 = false;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
(option_filename, po::value<std::string>(), "name of dictionary file")
(option_wheel, po::value<std::string>(), "word wheel letters")
(option_central, po::value<char>(), "central letter (defaults to middle letter of word)")
(option_min_length, po::value<int>(), "minimum word length")
(option_part2, "include part 2");
try {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count(option_filename))
filename = vm[option_filename].as<std::string>();
if (vm.count(option_wheel))
letters = vm[option_wheel].as<std::string>();
if (vm.count(option_central))
central_letter = vm[option_central].as<char>();
if (vm.count(option_min_length))
min_length = vm[option_min_length].as<int>();
if (vm.count(option_part2))
do_part2 = true;
auto dict = load_dictionary(filename, min_length, word_length);
word_wheel(dict, letters, central_letter);
if (do_part2) {
std::cout << '\n';
find_max_word_count(dict, word_length);
}
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| #include <stdbool.h>
#include <stdio.h>
#define MAX_WORD 80
#define LETTERS 26
bool is_letter(char c) { return c >= 'a' && c <= 'z'; }
int index(char c) { return c - 'a'; }
void word_wheel(const char* letters, char central, int min_length, FILE* dict) {
int max_count[LETTERS] = { 0 };
for (const char* p = letters; *p; ++p) {
char c = *p;
if (is_letter(c))
++max_count[index(c)];
}
char word[MAX_WORD + 1] = { 0 };
while (fgets(word, MAX_WORD, dict)) {
int count[LETTERS] = { 0 };
for (const char* p = word; *p; ++p) {
char c = *p;
if (c == '\n') {
if (p >= word + min_length && count[index(central)] > 0)
printf("%s", word);
} else if (is_letter(c)) {
int i = index(c);
if (++count[i] > max_count[i]) {
break;
}
} else {
break;
}
}
}
}
int main(int argc, char** argv) {
const char* dict = argc == 2 ? argv[1] : "unixdict.txt";
FILE* in = fopen(dict, "r");
if (in == NULL) {
perror(dict);
return 1;
}
word_wheel("ndeokgelw", 'k', 3, in);
fclose(in);
return 0;
}
|
Convert this C++ snippet to C and keep its semantics consistent. | #include <vector>
#include <iostream>
int main()
{
std::vector<int> a(3), b(4);
a[0] = 11; a[1] = 12; a[2] = 13;
b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;
a.insert(a.end(), b.begin(), b.end());
for (int i = 0; i < a.size(); ++i)
std::cout << "a[" << i << "] = " << a[i] << "\n";
}
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
(TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));
void *array_concat(const void *a, size_t an,
const void *b, size_t bn, size_t s)
{
char *p = malloc(s * (an + bn));
memcpy(p, a, an*s);
memcpy(p + an*s, b, bn*s);
return p;
}
const int a[] = { 1, 2, 3, 4, 5 };
const int b[] = { 6, 7, 8, 9, 0 };
int main(void)
{
unsigned int i;
int *c = ARRAY_CONCAT(int, a, 5, b, 5);
for(i = 0; i < 10; i++)
printf("%d\n", c[i]);
free(c);
return EXIT_SUCCCESS;
}
|
Generate a C translation of this C++ snippet without changing its computational steps. | #include <iostream>
#include <string>
using namespace std;
int main()
{
long int integer_input;
string string_input;
cout << "Enter an integer: ";
cin >> integer_input;
cout << "Enter a string: ";
cin >> string_input;
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[BUFSIZ];
puts("Enter a string: ");
fgets(str, sizeof(str), stdin);
long num;
char buf[BUFSIZ];
do
{
puts("Enter 75000: ");
fgets(buf, sizeof(buf), stdin);
num = strtol(buf, NULL, 10);
} while (num != 75000);
return EXIT_SUCCESS;
}
|
Translate the given C++ code snippet into C without altering its behavior. | #include <iostream>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
typedef unsigned char byte;
typedef union
{
unsigned long word;
unsigned char data[4];
}
midi_msg;
class midi
{
public:
midi()
{
if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR )
{
std::cout << "Error opening MIDI Output..." << std::endl;
device = 0;
}
}
~midi()
{
midiOutReset( device );
midiOutClose( device );
}
bool isOpen() { return device != 0; }
void setInstrument( byte i )
{
message.data[0] = 0xc0; message.data[1] = i;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void playNote( byte n, unsigned i )
{
playNote( n ); Sleep( i ); stopNote( n );
}
private:
void playNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 127; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void stopNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
HMIDIOUT device;
midi_msg message;
};
int main( int argc, char* argv[] )
{
midi m;
if( m.isOpen() )
{
byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };
m.setInstrument( 42 );
for( int x = 0; x < 8; x++ )
m.playNote( notes[x], rand() % 100 + 158 );
Sleep( 1000 );
}
return 0;
}
| #include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
typedef struct{
char str[3];
int key;
}note;
note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};
int main(void)
{
int i=0;
while(!kbhit())
{
printf("\t%s",sequence[i].str);
sound(261.63*pow(2,sequence[i].key/12.0));
delay(sequence[i].key%12==0?500:1000);
i = (i+1)%8;
i==0?printf("\n"):printf("");
}
nosound();
return 0;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #include <iostream>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
typedef unsigned char byte;
typedef union
{
unsigned long word;
unsigned char data[4];
}
midi_msg;
class midi
{
public:
midi()
{
if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR )
{
std::cout << "Error opening MIDI Output..." << std::endl;
device = 0;
}
}
~midi()
{
midiOutReset( device );
midiOutClose( device );
}
bool isOpen() { return device != 0; }
void setInstrument( byte i )
{
message.data[0] = 0xc0; message.data[1] = i;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void playNote( byte n, unsigned i )
{
playNote( n ); Sleep( i ); stopNote( n );
}
private:
void playNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 127; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void stopNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
HMIDIOUT device;
midi_msg message;
};
int main( int argc, char* argv[] )
{
midi m;
if( m.isOpen() )
{
byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };
m.setInstrument( 42 );
for( int x = 0; x < 8; x++ )
m.playNote( notes[x], rand() % 100 + 158 );
Sleep( 1000 );
}
return 0;
}
| #include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
typedef struct{
char str[3];
int key;
}note;
note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};
int main(void)
{
int i=0;
while(!kbhit())
{
printf("\t%s",sequence[i].str);
sound(261.63*pow(2,sequence[i].key/12.0));
delay(sequence[i].key%12==0?500:1000);
i = (i+1)%8;
i==0?printf("\n"):printf("");
}
nosound();
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #include <iostream>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
typedef unsigned char byte;
typedef union
{
unsigned long word;
unsigned char data[4];
}
midi_msg;
class midi
{
public:
midi()
{
if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR )
{
std::cout << "Error opening MIDI Output..." << std::endl;
device = 0;
}
}
~midi()
{
midiOutReset( device );
midiOutClose( device );
}
bool isOpen() { return device != 0; }
void setInstrument( byte i )
{
message.data[0] = 0xc0; message.data[1] = i;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void playNote( byte n, unsigned i )
{
playNote( n ); Sleep( i ); stopNote( n );
}
private:
void playNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 127; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
void stopNote( byte n )
{
message.data[0] = 0x90; message.data[1] = n;
message.data[2] = 0; message.data[3] = 0;
midiOutShortMsg( device, message.word );
}
HMIDIOUT device;
midi_msg message;
};
int main( int argc, char* argv[] )
{
midi m;
if( m.isOpen() )
{
byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 };
m.setInstrument( 42 );
for( int x = 0; x < 8; x++ )
m.playNote( notes[x], rand() % 100 + 158 );
Sleep( 1000 );
}
return 0;
}
| #include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
typedef struct{
char str[3];
int key;
}note;
note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}};
int main(void)
{
int i=0;
while(!kbhit())
{
printf("\t%s",sequence[i].str);
sound(261.63*pow(2,sequence[i].key/12.0));
delay(sequence[i].key%12==0?500:1000);
i = (i+1)%8;
i==0?printf("\n"):printf("");
}
nosound();
return 0;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #include <vector>
#include <string>
#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <set>
int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & ,
std::set<int> & , const int ) ;
int main( ) {
std::vector<boost::tuple<std::string , int , int> > items ;
items.push_back( boost::make_tuple( "" , 0 , 0 ) ) ;
items.push_back( boost::make_tuple( "map" , 9 , 150 ) ) ;
items.push_back( boost::make_tuple( "compass" , 13 , 35 ) ) ;
items.push_back( boost::make_tuple( "water" , 153 , 200 ) ) ;
items.push_back( boost::make_tuple( "sandwich", 50 , 160 ) ) ;
items.push_back( boost::make_tuple( "glucose" , 15 , 60 ) ) ;
items.push_back( boost::make_tuple( "tin", 68 , 45 ) ) ;
items.push_back( boost::make_tuple( "banana", 27 , 60 ) ) ;
items.push_back( boost::make_tuple( "apple" , 39 , 40 ) ) ;
items.push_back( boost::make_tuple( "cheese" , 23 , 30 ) ) ;
items.push_back( boost::make_tuple( "beer" , 52 , 10 ) ) ;
items.push_back( boost::make_tuple( "suntan creme" , 11 , 70 ) ) ;
items.push_back( boost::make_tuple( "camera" , 32 , 30 ) ) ;
items.push_back( boost::make_tuple( "T-shirt" , 24 , 15 ) ) ;
items.push_back( boost::make_tuple( "trousers" , 48 , 10 ) ) ;
items.push_back( boost::make_tuple( "umbrella" , 73 , 40 ) ) ;
items.push_back( boost::make_tuple( "waterproof trousers" , 42 , 70 ) ) ;
items.push_back( boost::make_tuple( "waterproof overclothes" , 43 , 75 ) ) ;
items.push_back( boost::make_tuple( "note-case" , 22 , 80 ) ) ;
items.push_back( boost::make_tuple( "sunglasses" , 7 , 20 ) ) ;
items.push_back( boost::make_tuple( "towel" , 18 , 12 ) ) ;
items.push_back( boost::make_tuple( "socks" , 4 , 50 ) ) ;
items.push_back( boost::make_tuple( "book" , 30 , 10 ) ) ;
const int maximumWeight = 400 ;
std::set<int> bestItems ;
int bestValue = findBestPack( items , bestItems , maximumWeight ) ;
std::cout << "The best value that can be packed in the given knapsack is " <<
bestValue << " !\n" ;
int totalweight = 0 ;
std::cout << "The following items should be packed in the knapsack:\n" ;
for ( std::set<int>::const_iterator si = bestItems.begin( ) ;
si != bestItems.end( ) ; si++ ) {
std::cout << (items.begin( ) + *si)->get<0>( ) << "\n" ;
totalweight += (items.begin( ) + *si)->get<1>( ) ;
}
std::cout << "The total weight of all items is " << totalweight << " !\n" ;
return 0 ;
}
int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) {
const int n = items.size( ) ;
int bestValues [ n ][ weightlimit ] ;
std::set<int> solutionSets[ n ][ weightlimit ] ;
std::set<int> emptyset ;
for ( int i = 0 ; i < n ; i++ ) {
for ( int j = 0 ; j < weightlimit ; j++ ) {
bestValues[ i ][ j ] = 0 ;
solutionSets[ i ][ j ] = emptyset ;
}
}
for ( int i = 0 ; i < n ; i++ ) {
for ( int weight = 0 ; weight < weightlimit ; weight++ ) {
if ( i == 0 )
bestValues[ i ][ weight ] = 0 ;
else {
int itemweight = (items.begin( ) + i)->get<1>( ) ;
if ( weight < itemweight ) {
bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;
solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;
} else {
if ( bestValues[ i - 1 ][ weight - itemweight ] +
(items.begin( ) + i)->get<2>( ) >
bestValues[ i - 1 ][ weight ] ) {
bestValues[ i ][ weight ] =
bestValues[ i - 1 ][ weight - itemweight ] +
(items.begin( ) + i)->get<2>( ) ;
solutionSets[ i ][ weight ] =
solutionSets[ i - 1 ][ weight - itemweight ] ;
solutionSets[ i ][ weight ].insert( i ) ;
}
else {
bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;
solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;
}
}
}
}
}
bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;
return bestValues[ n - 1 ][ weightlimit - 1 ] ;
}
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int weight;
int value;
} item_t;
item_t items[] = {
{"map", 9, 150},
{"compass", 13, 35},
{"water", 153, 200},
{"sandwich", 50, 160},
{"glucose", 15, 60},
{"tin", 68, 45},
{"banana", 27, 60},
{"apple", 39, 40},
{"cheese", 23, 30},
{"beer", 52, 10},
{"suntan cream", 11, 70},
{"camera", 32, 30},
{"T-shirt", 24, 15},
{"trousers", 48, 10},
{"umbrella", 73, 40},
{"waterproof trousers", 42, 70},
{"waterproof overclothes", 43, 75},
{"note-case", 22, 80},
{"sunglasses", 7, 20},
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10},
};
int *knapsack (item_t *items, int n, int w) {
int i, j, a, b, *mm, **m, *s;
mm = calloc((n + 1) * (w + 1), sizeof (int));
m = malloc((n + 1) * sizeof (int *));
m[0] = mm;
for (i = 1; i <= n; i++) {
m[i] = &mm[i * (w + 1)];
for (j = 0; j <= w; j++) {
if (items[i - 1].weight > j) {
m[i][j] = m[i - 1][j];
}
else {
a = m[i - 1][j];
b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;
m[i][j] = a > b ? a : b;
}
}
}
s = calloc(n, sizeof (int));
for (i = n, j = w; i > 0; i--) {
if (m[i][j] > m[i - 1][j]) {
s[i - 1] = 1;
j -= items[i - 1].weight;
}
}
free(mm);
free(m);
return s;
}
int main () {
int i, n, tw = 0, tv = 0, *s;
n = sizeof (items) / sizeof (item_t);
s = knapsack(items, n, 400);
for (i = 0; i < n; i++) {
if (s[i]) {
printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value);
tw += items[i].weight;
tv += items[i].value;
}
}
printf("%-22s %5d %5d\n", "totals:", tw, tv);
return 0;
}
|
Transform the following C++ implementation into C, maintaining the same output and logic. | #include <algorithm>
#include <iostream>
#include <vector>
typedef unsigned long long integer;
std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) {
std::vector<integer> result;
for (integer a = ancestor[n]; a != 0 && a != n; ) {
n = a;
a = ancestor[n];
result.push_back(n);
}
return result;
}
void print_vector(const std::vector<integer>& vec) {
if (vec.empty()) {
std::cout << "none\n";
return;
}
auto i = vec.begin();
std::cout << *i++;
for (; i != vec.end(); ++i)
std::cout << ", " << *i;
std::cout << '\n';
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
for (integer p = 3; p * p <= n; p += 2) {
if (n % p == 0)
return false;
}
return true;
}
int main(int argc, char** argv) {
const size_t limit = 100;
std::vector<integer> ancestor(limit, 0);
std::vector<std::vector<integer>> descendants(limit);
for (size_t prime = 0; prime < limit; ++prime) {
if (!is_prime(prime))
continue;
descendants[prime].push_back(prime);
for (size_t i = 0; i + prime < limit; ++i) {
integer s = i + prime;
for (integer n : descendants[i]) {
integer prod = n * prime;
descendants[s].push_back(prod);
if (prod < limit)
ancestor[prod] = s;
}
}
}
size_t total_descendants = 0;
for (integer i = 1; i < limit; ++i) {
std::vector<integer> ancestors(get_ancestors(ancestor, i));
std::cout << "[" << i << "] Level: " << ancestors.size() << '\n';
std::cout << "Ancestors: ";
std::sort(ancestors.begin(), ancestors.end());
print_vector(ancestors);
std::cout << "Descendants: ";
std::vector<integer>& desc = descendants[i];
if (!desc.empty()) {
std::sort(desc.begin(), desc.end());
if (desc[0] == i)
desc.erase(desc.begin());
}
std::cout << desc.size() << '\n';
total_descendants += desc.size();
if (!desc.empty())
print_vector(desc);
std::cout << '\n';
}
std::cout << "Total descendants: " << total_descendants << '\n';
return 0;
}
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXPRIME 99
#define MAXPARENT 99
#define NBRPRIMES 30
#define NBRANCESTORS 10
FILE *FileOut;
char format[] = ", %lld";
int Primes[NBRPRIMES];
int iPrimes;
short Ancestors[NBRANCESTORS];
struct Children {
long long Child;
struct Children *pNext;
};
struct Children *Parents[MAXPARENT+1][2];
int CptDescendants[MAXPARENT+1];
long long MaxDescendant = (long long) pow(3.0, 33.0);
short GetParent(long long child);
struct Children *AppendChild(struct Children *node, long long child);
short GetAncestors(short child);
void PrintDescendants(struct Children *node);
int GetPrimes(int primes[], int maxPrime);
int main()
{
long long Child;
short i, Parent, Level;
int TotDesc = 0;
if ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0)
return 1;
for (Child = 1; Child <= MaxDescendant; Child++)
{
if (Parent = GetParent(Child))
{
Parents[Parent][1] = AppendChild(Parents[Parent][1], Child);
if (Parents[Parent][0] == NULL)
Parents[Parent][0] = Parents[Parent][1];
CptDescendants[Parent]++;
}
}
if (MAXPARENT > MAXPRIME)
if (GetPrimes(Primes, MAXPARENT) < 0)
return 1;
if (fopen_s(&FileOut, "Ancestors.txt", "w"))
return 1;
for (Parent = 1; Parent <= MAXPARENT; Parent++)
{
Level = GetAncestors(Parent);
fprintf(FileOut, "[%d] Level: %d\n", Parent, Level);
if (Level)
{
fprintf(FileOut, "Ancestors: %d", Ancestors[0]);
for (i = 1; i < Level; i++)
fprintf(FileOut, ", %d", Ancestors[i]);
}
else
fprintf(FileOut, "Ancestors: None");
if (CptDescendants[Parent])
{
fprintf(FileOut, "\nDescendants: %d\n", CptDescendants[Parent]);
strcpy_s(format, "%lld");
PrintDescendants(Parents[Parent][0]);
fprintf(FileOut, "\n");
}
else
fprintf(FileOut, "\nDescendants: None\n");
fprintf(FileOut, "\n");
TotDesc += CptDescendants[Parent];
}
fprintf(FileOut, "Total descendants %d\n\n", TotDesc);
if (fclose(FileOut))
return 1;
return 0;
}
short GetParent(long long child)
{
long long Child = child;
short Parent = 0;
short Index = 0;
while (Child > 1 && Parent <= MAXPARENT)
{
if (Index > iPrimes)
return 0;
while (Child % Primes[Index] == 0)
{
Child /= Primes[Index];
Parent += Primes[Index];
}
Index++;
}
if (Parent == child || Parent > MAXPARENT || child == 1)
return 0;
return Parent;
}
struct Children *AppendChild(struct Children *node, long long child)
{
static struct Children *NodeNew;
if (NodeNew = (struct Children *) malloc(sizeof(struct Children)))
{
NodeNew->Child = child;
NodeNew->pNext = NULL;
if (node != NULL)
node->pNext = NodeNew;
}
return NodeNew;
}
short GetAncestors(short child)
{
short Child = child;
short Parent = 0;
short Index = 0;
while (Child > 1)
{
while (Child % Primes[Index] == 0)
{
Child /= Primes[Index];
Parent += Primes[Index];
}
Index++;
}
if (Parent == child || child == 1)
return 0;
Index = GetAncestors(Parent);
Ancestors[Index] = Parent;
return ++Index;
}
void PrintDescendants(struct Children *node)
{
static struct Children *NodeCurr;
static struct Children *NodePrev;
NodeCurr = node;
NodePrev = NULL;
while (NodeCurr)
{
fprintf(FileOut, format, NodeCurr->Child);
strcpy_s(format, ", %lld");
NodePrev = NodeCurr;
NodeCurr = NodeCurr->pNext;
free(NodePrev);
}
return;
}
int GetPrimes(int primes[], int maxPrime)
{
if (maxPrime < 2)
return -1;
int Index = 0, Value = 1;
int Max, i;
primes[0] = 2;
while ((Value += 2) <= maxPrime)
{
Max = (int) floor(sqrt((double) Value));
for (i = 0; i <= Index; i++)
{
if (primes[i] > Max)
{
if (++Index >= NBRPRIMES)
return -1;
primes[Index] = Value;
break;
}
if (Value % primes[i] == 0)
break;
}
}
return Index;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #include <iostream>
#include <vector>
#include <algorithm>
void print(const std::vector<std::vector<int>>& v) {
std::cout << "{ ";
for (const auto& p : v) {
std::cout << "(";
for (const auto& e : p) {
std::cout << e << " ";
}
std::cout << ") ";
}
std::cout << "}" << std::endl;
}
auto product(const std::vector<std::vector<int>>& lists) {
std::vector<std::vector<int>> result;
if (std::find_if(std::begin(lists), std::end(lists),
[](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {
return result;
}
for (auto& e : lists[0]) {
result.push_back({ e });
}
for (size_t i = 1; i < lists.size(); ++i) {
std::vector<std::vector<int>> temp;
for (auto& e : result) {
for (auto f : lists[i]) {
auto e_tmp = e;
e_tmp.push_back(f);
temp.push_back(e_tmp);
}
}
result = temp;
}
return result;
}
int main() {
std::vector<std::vector<int>> prods[] = {
{ { 1, 2 }, { 3, 4 } },
{ { 3, 4 }, { 1, 2} },
{ { 1, 2 }, { } },
{ { }, { 1, 2 } },
{ { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },
{ { 1, 2, 3 }, { 30 }, { 500, 100 } },
{ { 1, 2, 3 }, { }, { 500, 100 } }
};
for (const auto& p : prods) {
print(product(p));
}
std::cin.ignore();
std::cin.get();
return 0;
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){
int i,j;
if(times==numSets){
printf("(");
for(i=0;i<times;i++){
printf("%d,",currentSet[i]);
}
printf("\b),");
}
else{
for(j=0;j<setLengths[times];j++){
currentSet[times] = sets[times][j];
cartesianProduct(sets,setLengths,currentSet,numSets,times+1);
}
}
}
void printSets(int** sets, int* setLengths, int numSets){
int i,j;
printf("\nNumber of sets : %d",numSets);
for(i=0;i<numSets+1;i++){
printf("\nSet %d : ",i+1);
for(j=0;j<setLengths[i];j++){
printf(" %d ",sets[i][j]);
}
}
}
void processInputString(char* str){
int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;
char *token,*holder,*holderToken;
for(i=0;str[i]!=00;i++)
if(str[i]=='x')
numSets++;
if(numSets==0){
printf("\n%s",str);
return;
}
currentSet = (int*)calloc(sizeof(int),numSets + 1);
setLengths = (int*)calloc(sizeof(int),numSets + 1);
sets = (int**)malloc((numSets + 1)*sizeof(int*));
token = strtok(str,"x");
while(token!=NULL){
holder = (char*)malloc(strlen(token)*sizeof(char));
j = 0;
for(i=0;token[i]!=00;i++){
if(token[i]>='0' && token[i]<='9')
holder[j++] = token[i];
else if(token[i]==',')
holder[j++] = ' ';
}
holder[j] = 00;
setLength = 0;
for(i=0;holder[i]!=00;i++)
if(holder[i]==' ')
setLength++;
if(setLength==0 && strlen(holder)==0){
printf("\n{}");
return;
}
setLengths[counter] = setLength+1;
sets[counter] = (int*)malloc((1+setLength)*sizeof(int));
k = 0;
start = 0;
for(l=0;holder[l]!=00;l++){
if(holder[l+1]==' '||holder[l+1]==00){
holderToken = (char*)malloc((l+1-start)*sizeof(char));
strncpy(holderToken,holder + start,l+1-start);
sets[counter][k++] = atoi(holderToken);
start = l+2;
}
}
counter++;
token = strtok(NULL,"x");
}
printf("\n{");
cartesianProduct(sets,setLengths,currentSet,numSets + 1,0);
printf("\b}");
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]);
else
processInputString(argV[1]);
return 0;
}
|
Generate a C translation of this C++ snippet without changing its computational steps. | #include <iostream>
#include <vector>
#include <algorithm>
void print(const std::vector<std::vector<int>>& v) {
std::cout << "{ ";
for (const auto& p : v) {
std::cout << "(";
for (const auto& e : p) {
std::cout << e << " ";
}
std::cout << ") ";
}
std::cout << "}" << std::endl;
}
auto product(const std::vector<std::vector<int>>& lists) {
std::vector<std::vector<int>> result;
if (std::find_if(std::begin(lists), std::end(lists),
[](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {
return result;
}
for (auto& e : lists[0]) {
result.push_back({ e });
}
for (size_t i = 1; i < lists.size(); ++i) {
std::vector<std::vector<int>> temp;
for (auto& e : result) {
for (auto f : lists[i]) {
auto e_tmp = e;
e_tmp.push_back(f);
temp.push_back(e_tmp);
}
}
result = temp;
}
return result;
}
int main() {
std::vector<std::vector<int>> prods[] = {
{ { 1, 2 }, { 3, 4 } },
{ { 3, 4 }, { 1, 2} },
{ { 1, 2 }, { } },
{ { }, { 1, 2 } },
{ { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },
{ { 1, 2, 3 }, { 30 }, { 500, 100 } },
{ { 1, 2, 3 }, { }, { 500, 100 } }
};
for (const auto& p : prods) {
print(product(p));
}
std::cin.ignore();
std::cin.get();
return 0;
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){
int i,j;
if(times==numSets){
printf("(");
for(i=0;i<times;i++){
printf("%d,",currentSet[i]);
}
printf("\b),");
}
else{
for(j=0;j<setLengths[times];j++){
currentSet[times] = sets[times][j];
cartesianProduct(sets,setLengths,currentSet,numSets,times+1);
}
}
}
void printSets(int** sets, int* setLengths, int numSets){
int i,j;
printf("\nNumber of sets : %d",numSets);
for(i=0;i<numSets+1;i++){
printf("\nSet %d : ",i+1);
for(j=0;j<setLengths[i];j++){
printf(" %d ",sets[i][j]);
}
}
}
void processInputString(char* str){
int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;
char *token,*holder,*holderToken;
for(i=0;str[i]!=00;i++)
if(str[i]=='x')
numSets++;
if(numSets==0){
printf("\n%s",str);
return;
}
currentSet = (int*)calloc(sizeof(int),numSets + 1);
setLengths = (int*)calloc(sizeof(int),numSets + 1);
sets = (int**)malloc((numSets + 1)*sizeof(int*));
token = strtok(str,"x");
while(token!=NULL){
holder = (char*)malloc(strlen(token)*sizeof(char));
j = 0;
for(i=0;token[i]!=00;i++){
if(token[i]>='0' && token[i]<='9')
holder[j++] = token[i];
else if(token[i]==',')
holder[j++] = ' ';
}
holder[j] = 00;
setLength = 0;
for(i=0;holder[i]!=00;i++)
if(holder[i]==' ')
setLength++;
if(setLength==0 && strlen(holder)==0){
printf("\n{}");
return;
}
setLengths[counter] = setLength+1;
sets[counter] = (int*)malloc((1+setLength)*sizeof(int));
k = 0;
start = 0;
for(l=0;holder[l]!=00;l++){
if(holder[l+1]==' '||holder[l+1]==00){
holderToken = (char*)malloc((l+1-start)*sizeof(char));
strncpy(holderToken,holder + start,l+1-start);
sets[counter][k++] = atoi(holderToken);
start = l+2;
}
}
counter++;
token = strtok(NULL,"x");
}
printf("\n{");
cartesianProduct(sets,setLengths,currentSet,numSets + 1,0);
printf("\b}");
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]);
else
processInputString(argV[1]);
return 0;
}
|
Convert this C++ snippet to C and keep its semantics consistent. | #include <iostream>
#include <vector>
#include <algorithm>
void print(const std::vector<std::vector<int>>& v) {
std::cout << "{ ";
for (const auto& p : v) {
std::cout << "(";
for (const auto& e : p) {
std::cout << e << " ";
}
std::cout << ") ";
}
std::cout << "}" << std::endl;
}
auto product(const std::vector<std::vector<int>>& lists) {
std::vector<std::vector<int>> result;
if (std::find_if(std::begin(lists), std::end(lists),
[](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {
return result;
}
for (auto& e : lists[0]) {
result.push_back({ e });
}
for (size_t i = 1; i < lists.size(); ++i) {
std::vector<std::vector<int>> temp;
for (auto& e : result) {
for (auto f : lists[i]) {
auto e_tmp = e;
e_tmp.push_back(f);
temp.push_back(e_tmp);
}
}
result = temp;
}
return result;
}
int main() {
std::vector<std::vector<int>> prods[] = {
{ { 1, 2 }, { 3, 4 } },
{ { 3, 4 }, { 1, 2} },
{ { 1, 2 }, { } },
{ { }, { 1, 2 } },
{ { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },
{ { 1, 2, 3 }, { 30 }, { 500, 100 } },
{ { 1, 2, 3 }, { }, { 500, 100 } }
};
for (const auto& p : prods) {
print(product(p));
}
std::cin.ignore();
std::cin.get();
return 0;
}
| #include<string.h>
#include<stdlib.h>
#include<stdio.h>
void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){
int i,j;
if(times==numSets){
printf("(");
for(i=0;i<times;i++){
printf("%d,",currentSet[i]);
}
printf("\b),");
}
else{
for(j=0;j<setLengths[times];j++){
currentSet[times] = sets[times][j];
cartesianProduct(sets,setLengths,currentSet,numSets,times+1);
}
}
}
void printSets(int** sets, int* setLengths, int numSets){
int i,j;
printf("\nNumber of sets : %d",numSets);
for(i=0;i<numSets+1;i++){
printf("\nSet %d : ",i+1);
for(j=0;j<setLengths[i];j++){
printf(" %d ",sets[i][j]);
}
}
}
void processInputString(char* str){
int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0;
char *token,*holder,*holderToken;
for(i=0;str[i]!=00;i++)
if(str[i]=='x')
numSets++;
if(numSets==0){
printf("\n%s",str);
return;
}
currentSet = (int*)calloc(sizeof(int),numSets + 1);
setLengths = (int*)calloc(sizeof(int),numSets + 1);
sets = (int**)malloc((numSets + 1)*sizeof(int*));
token = strtok(str,"x");
while(token!=NULL){
holder = (char*)malloc(strlen(token)*sizeof(char));
j = 0;
for(i=0;token[i]!=00;i++){
if(token[i]>='0' && token[i]<='9')
holder[j++] = token[i];
else if(token[i]==',')
holder[j++] = ' ';
}
holder[j] = 00;
setLength = 0;
for(i=0;holder[i]!=00;i++)
if(holder[i]==' ')
setLength++;
if(setLength==0 && strlen(holder)==0){
printf("\n{}");
return;
}
setLengths[counter] = setLength+1;
sets[counter] = (int*)malloc((1+setLength)*sizeof(int));
k = 0;
start = 0;
for(l=0;holder[l]!=00;l++){
if(holder[l+1]==' '||holder[l+1]==00){
holderToken = (char*)malloc((l+1-start)*sizeof(char));
strncpy(holderToken,holder + start,l+1-start);
sets[counter][k++] = atoi(holderToken);
start = l+2;
}
}
counter++;
token = strtok(NULL,"x");
}
printf("\n{");
cartesianProduct(sets,setLengths,currentSet,numSets + 1,0);
printf("\b}");
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]);
else
processInputString(argV[1]);
return 0;
}
|
Change the following C++ code into C without altering its purpose. | #include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;
typedef function<double(double)> FunType;
vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };
vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };
template <typename A, typename B, typename C>
function<C(A)> compose(function<C(B)> f, function<B(A)> g) {
return [f,g](A x) { return f(g(x)); };
}
int main() {
vector<FunType> composedFuns;
auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};
transform(B.begin(), B.end(),
A.begin(),
back_inserter(composedFuns),
compose<double, double, double>);
for (auto num: exNums)
for (auto fun: composedFuns)
cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;
return 0;
}
| #include <stdlib.h>
#include <stdio.h>
#include <math.h>
typedef double (*Class2Func)(double);
double functionA( double v)
{
return v*v*v;
}
double functionB(double v)
{
return exp(log(v)/3);
}
double Function1( Class2Func f2, double val )
{
return f2(val);
}
Class2Func WhichFunc( int idx)
{
return (idx < 4) ? &functionA : &functionB;
}
Class2Func funcListA[] = {&functionA, &sin, &cos, &tan };
Class2Func funcListB[] = {&functionB, &asin, &acos, &atan };
double InvokeComposed( Class2Func f1, Class2Func f2, double val )
{
return f1(f2(val));
}
typedef struct sComposition {
Class2Func f1;
Class2Func f2;
} *Composition;
Composition Compose( Class2Func f1, Class2Func f2)
{
Composition comp = malloc(sizeof(struct sComposition));
comp->f1 = f1;
comp->f2 = f2;
return comp;
}
double CallComposed( Composition comp, double val )
{
return comp->f1( comp->f2(val) );
}
int main(int argc, char *argv[])
{
int ix;
Composition c;
printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0));
for (ix=0; ix<4; ix++) {
c = Compose(funcListA[ix], funcListB[ix]);
printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9));
}
return 0;
}
|
Write the same code in C as shown below in C++. | #include <vector>
#include <iostream>
#include <algorithm>
std::vector<int> properDivisors ( int number ) {
std::vector<int> divisors ;
for ( int i = 1 ; i < number / 2 + 1 ; i++ )
if ( number % i == 0 )
divisors.push_back( i ) ;
return divisors ;
}
int main( ) {
std::vector<int> divisors ;
unsigned int maxdivisors = 0 ;
int corresponding_number = 0 ;
for ( int i = 1 ; i < 11 ; i++ ) {
divisors = properDivisors ( i ) ;
std::cout << "Proper divisors of " << i << ":\n" ;
for ( int number : divisors ) {
std::cout << number << " " ;
}
std::cout << std::endl ;
divisors.clear( ) ;
}
for ( int i = 11 ; i < 20001 ; i++ ) {
divisors = properDivisors ( i ) ;
if ( divisors.size( ) > maxdivisors ) {
maxdivisors = divisors.size( ) ;
corresponding_number = i ;
}
divisors.clear( ) ;
}
std::cout << "Most divisors has " << corresponding_number <<
" , it has " << maxdivisors << " divisors!\n" ;
return 0 ;
}
| #include <stdio.h>
#include <stdbool.h>
int proper_divisors(const int n, bool print_flag)
{
int count = 0;
for (int i = 1; i < n; ++i) {
if (n % i == 0) {
count++;
if (print_flag)
printf("%d ", i);
}
}
if (print_flag)
printf("\n");
return count;
}
int main(void)
{
for (int i = 1; i <= 10; ++i) {
printf("%d: ", i);
proper_divisors(i, true);
}
int max = 0;
int max_i = 1;
for (int i = 1; i <= 20000; ++i) {
int v = proper_divisors(i, false);
if (v >= max) {
max = v;
max_i = i;
}
}
printf("%d with %d divisors\n", max_i, max);
return 0;
}
|
Generate an equivalent C version of this C++ code. | #include <vector>
#include <utility>
#include <iostream>
#include <boost/algorithm/string.hpp>
std::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;
int main( ) {
std::vector<std::string> names , remarks ;
names.push_back( "April" ) ;
names.push_back( "Tam O'Shantor" ) ;
names.push_back ( "Emily" ) ;
remarks.push_back( "Bubbly, I'm > Tam and <= Emily" ) ;
remarks.push_back( "Burns: \"When chapman billies leave the street ...\"" ) ;
remarks.push_back( "Short & shrift" ) ;
std::cout << "This is in XML:\n" ;
std::cout << create_xml( names , remarks ) << std::endl ;
return 0 ;
}
std::string create_xml( std::vector<std::string> & names ,
std::vector<std::string> & remarks ) {
std::vector<std::pair<std::string , std::string> > entities ;
entities.push_back( std::make_pair( "&" , "&" ) ) ;
entities.push_back( std::make_pair( "<" , "<" ) ) ;
entities.push_back( std::make_pair( ">" , ">" ) ) ;
std::string xmlstring ( "<CharacterRemarks>\n" ) ;
std::vector<std::string>::iterator vsi = names.begin( ) ;
typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;
for ( ; vsi != names.end( ) ; vsi++ ) {
for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
boost::replace_all ( *vsi , vs->first , vs->second ) ;
}
}
for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {
for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
boost::replace_all ( *vsi , vs->first , vs->second ) ;
}
}
for ( int i = 0 ; i < names.size( ) ; i++ ) {
xmlstring.append( "\t<Character name=\"").append( names[ i ] ).append( "\">")
.append( remarks[ i ] ).append( "</Character>\n" ) ;
}
xmlstring.append( "</CharacterRemarks>" ) ;
return xmlstring ;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
const char *names[] = {
"April", "Tam O'Shanter", "Emily", NULL
};
const char *remarks[] = {
"Bubbly: I'm > Tam and <= Emily",
"Burns: \"When chapman billies leave the street ...\"",
"Short & shrift", NULL
};
int main()
{
xmlDoc *doc = NULL;
xmlNode *root = NULL, *node;
const char **next;
int a;
doc = xmlNewDoc("1.0");
root = xmlNewNode(NULL, "CharacterRemarks");
xmlDocSetRootElement(doc, root);
for(next = names, a = 0; *next != NULL; next++, a++) {
node = xmlNewNode(NULL, "Character");
(void)xmlNewProp(node, "name", *next);
xmlAddChild(node, xmlNewText(remarks[a]));
xmlAddChild(root, node);
}
xmlElemDump(stdout, doc, root);
xmlFreeDoc(doc);
xmlCleanupParser();
return EXIT_SUCCESS;
}
|
Preserve the algorithm and functionality while converting the code from C++ to C. | #include <windows.h>
#include <string>
#include <vector>
using namespace std;
const int HSTEP = 46, MWID = 40, MHEI = 471;
const float VSTEP = 2.3f;
class vector2
{
public:
vector2() { x = y = 0; }
vector2( float a, float b ) { x = a; y = b; }
void set( float a, float b ) { x = a; y = b; }
float x, y;
};
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteObject( brush );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) { clr = c; createPen(); }
void setPenWidth( int w ) { wid = w; createPen(); }
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
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 plot
{
public:
plot() { bmp.create( 512, 512 ); }
void draw( vector<vector2>* pairs )
{
bmp.clear( 0xff );
drawGraph( pairs );
plotIt( pairs );
HDC dc = GetDC( GetConsoleWindow() );
BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );
ReleaseDC( GetConsoleWindow(), dc );
}
private:
void drawGraph( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
bmp.setPenColor( RGB( 240, 240, 240 ) );
DWORD b = 11, c = 40, x;
RECT rc; char txt[8];
for( x = 0; x < pairs->size(); x++ )
{
MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );
MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );
wsprintf( txt, "%d", ( pairs->size() - x ) * 20 );
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
wsprintf( txt, "%d", x );
SetRect( &rc, c - 8, 472, c + 8, 492 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
c += 46; b += 46;
}
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
bmp.setPenColor( 0 ); bmp.setPenWidth( 3 );
MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );
MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );
}
void plotIt( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
HBRUSH br = CreateSolidBrush( 255 );
RECT rc;
bmp.setPenColor( 255 ); bmp.setPenWidth( 2 );
vector<vector2>::iterator it = pairs->begin();
int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
MoveToEx( dc, a, b, NULL );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );
it++;
for( ; it < pairs->end(); it++ )
{
a = MWID + HSTEP * static_cast<int>( ( *it ).x );
b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );
FillRect( dc, &rc, br ); LineTo( dc, a, b );
}
DeleteObject( br );
}
myBitmap bmp;
};
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
plot pt;
vector<vector2> pairs;
pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );
pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );
pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );
pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );
pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );
pt.draw( &pairs );
system( "pause" );
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <plot.h>
#define NP 10
double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
void minmax(double *x, double *y,
double *minx, double *maxx,
double *miny, double *maxy, int n)
{
int i;
*minx = *maxx = x[0];
*miny = *maxy = y[0];
for(i=1; i < n; i++) {
if ( x[i] < *minx ) *minx = x[i];
if ( x[i] > *maxx ) *maxx = x[i];
if ( y[i] < *miny ) *miny = y[i];
if ( y[i] > *maxy ) *maxy = y[i];
}
}
#define YLAB_HEIGHT_F 0.1
#define XLAB_WIDTH_F 0.2
#define XDIV (NP*1.0)
#define YDIV (NP*1.0)
#define EXTRA_W 0.01
#define EXTRA_H 0.01
#define DOTSCALE (1.0/150.0)
#define MAXLABLEN 32
#define PUSHSCALE(X,Y) pl_fscale((X),(Y))
#define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y))
#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)
int main()
{
int plotter, i;
double minx, miny, maxx, maxy;
double lx, ly;
double xticstep, yticstep, nx, ny;
double sx, sy;
char labs[MAXLABLEN+1];
plotter = pl_newpl("png", NULL, stdout, NULL);
if ( plotter < 0 ) exit(1);
pl_selectpl(plotter);
if ( pl_openpl() < 0 ) exit(1);
minmax(x, y, &minx, &maxx, &miny, &maxy, NP);
lx = maxx - minx;
ly = maxy - miny;
pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,
ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);
xticstep = (ceil(maxx) - floor(minx)) / XDIV;
yticstep = (ceil(maxy) - floor(miny)) / YDIV;
pl_flinewidth(0.25);
if ( lx < ly ) {
sx = lx/ly;
sy = 1.0;
} else {
sx = 1.0;
sy = ly/lx;
}
pl_erase();
pl_fbox(floor(minx), floor(miny),
ceil(maxx), ceil(maxy));
pl_fontname("HersheySerif");
for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {
pl_fline(floor(minx), ny, ceil(maxx), ny);
snprintf(labs, MAXLABLEN, "%6.2lf", ny);
FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);
PUSHSCALE(sx,sy);
pl_label(labs);
POPSCALE(sx,sy);
}
for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {
pl_fline(nx, floor(miny), nx, ceil(maxy));
snprintf(labs, MAXLABLEN, "%6.2lf", nx);
FMOVESCALE(nx, floor(miny));
PUSHSCALE(sx,sy);
pl_ftextangle(-90);
pl_alabel('l', 'b', labs);
POPSCALE(sx,sy);
}
pl_fillcolorname("red");
pl_filltype(1);
for(i=0; i < NP; i++)
{
pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,
x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);
}
pl_flushpl();
pl_closepl();
}
|
Convert this C++ snippet to C and keep its semantics consistent. | #include <windows.h>
#include <string>
#include <vector>
using namespace std;
const int HSTEP = 46, MWID = 40, MHEI = 471;
const float VSTEP = 2.3f;
class vector2
{
public:
vector2() { x = y = 0; }
vector2( float a, float b ) { x = a; y = b; }
void set( float a, float b ) { x = a; y = b; }
float x, y;
};
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteObject( brush );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) { clr = c; createPen(); }
void setPenWidth( int w ) { wid = w; createPen(); }
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
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 plot
{
public:
plot() { bmp.create( 512, 512 ); }
void draw( vector<vector2>* pairs )
{
bmp.clear( 0xff );
drawGraph( pairs );
plotIt( pairs );
HDC dc = GetDC( GetConsoleWindow() );
BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );
ReleaseDC( GetConsoleWindow(), dc );
}
private:
void drawGraph( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
bmp.setPenColor( RGB( 240, 240, 240 ) );
DWORD b = 11, c = 40, x;
RECT rc; char txt[8];
for( x = 0; x < pairs->size(); x++ )
{
MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );
MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );
wsprintf( txt, "%d", ( pairs->size() - x ) * 20 );
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
wsprintf( txt, "%d", x );
SetRect( &rc, c - 8, 472, c + 8, 492 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
c += 46; b += 46;
}
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
bmp.setPenColor( 0 ); bmp.setPenWidth( 3 );
MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );
MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );
}
void plotIt( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
HBRUSH br = CreateSolidBrush( 255 );
RECT rc;
bmp.setPenColor( 255 ); bmp.setPenWidth( 2 );
vector<vector2>::iterator it = pairs->begin();
int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
MoveToEx( dc, a, b, NULL );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );
it++;
for( ; it < pairs->end(); it++ )
{
a = MWID + HSTEP * static_cast<int>( ( *it ).x );
b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );
FillRect( dc, &rc, br ); LineTo( dc, a, b );
}
DeleteObject( br );
}
myBitmap bmp;
};
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
plot pt;
vector<vector2> pairs;
pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );
pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );
pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );
pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );
pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );
pt.draw( &pairs );
system( "pause" );
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <plot.h>
#define NP 10
double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
void minmax(double *x, double *y,
double *minx, double *maxx,
double *miny, double *maxy, int n)
{
int i;
*minx = *maxx = x[0];
*miny = *maxy = y[0];
for(i=1; i < n; i++) {
if ( x[i] < *minx ) *minx = x[i];
if ( x[i] > *maxx ) *maxx = x[i];
if ( y[i] < *miny ) *miny = y[i];
if ( y[i] > *maxy ) *maxy = y[i];
}
}
#define YLAB_HEIGHT_F 0.1
#define XLAB_WIDTH_F 0.2
#define XDIV (NP*1.0)
#define YDIV (NP*1.0)
#define EXTRA_W 0.01
#define EXTRA_H 0.01
#define DOTSCALE (1.0/150.0)
#define MAXLABLEN 32
#define PUSHSCALE(X,Y) pl_fscale((X),(Y))
#define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y))
#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)
int main()
{
int plotter, i;
double minx, miny, maxx, maxy;
double lx, ly;
double xticstep, yticstep, nx, ny;
double sx, sy;
char labs[MAXLABLEN+1];
plotter = pl_newpl("png", NULL, stdout, NULL);
if ( plotter < 0 ) exit(1);
pl_selectpl(plotter);
if ( pl_openpl() < 0 ) exit(1);
minmax(x, y, &minx, &maxx, &miny, &maxy, NP);
lx = maxx - minx;
ly = maxy - miny;
pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,
ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);
xticstep = (ceil(maxx) - floor(minx)) / XDIV;
yticstep = (ceil(maxy) - floor(miny)) / YDIV;
pl_flinewidth(0.25);
if ( lx < ly ) {
sx = lx/ly;
sy = 1.0;
} else {
sx = 1.0;
sy = ly/lx;
}
pl_erase();
pl_fbox(floor(minx), floor(miny),
ceil(maxx), ceil(maxy));
pl_fontname("HersheySerif");
for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {
pl_fline(floor(minx), ny, ceil(maxx), ny);
snprintf(labs, MAXLABLEN, "%6.2lf", ny);
FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);
PUSHSCALE(sx,sy);
pl_label(labs);
POPSCALE(sx,sy);
}
for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {
pl_fline(nx, floor(miny), nx, ceil(maxy));
snprintf(labs, MAXLABLEN, "%6.2lf", nx);
FMOVESCALE(nx, floor(miny));
PUSHSCALE(sx,sy);
pl_ftextangle(-90);
pl_alabel('l', 'b', labs);
POPSCALE(sx,sy);
}
pl_fillcolorname("red");
pl_filltype(1);
for(i=0; i < NP; i++)
{
pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,
x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);
}
pl_flushpl();
pl_closepl();
}
|
Convert this C++ snippet to C and keep its semantics consistent. | #include <windows.h>
#include <string>
#include <vector>
using namespace std;
const int HSTEP = 46, MWID = 40, MHEI = 471;
const float VSTEP = 2.3f;
class vector2
{
public:
vector2() { x = y = 0; }
vector2( float a, float b ) { x = a; y = b; }
void set( float a, float b ) { x = a; y = b; }
float x, y;
};
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteObject( brush );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) { clr = c; createPen(); }
void setPenWidth( int w ) { wid = w; createPen(); }
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
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 plot
{
public:
plot() { bmp.create( 512, 512 ); }
void draw( vector<vector2>* pairs )
{
bmp.clear( 0xff );
drawGraph( pairs );
plotIt( pairs );
HDC dc = GetDC( GetConsoleWindow() );
BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );
ReleaseDC( GetConsoleWindow(), dc );
}
private:
void drawGraph( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
bmp.setPenColor( RGB( 240, 240, 240 ) );
DWORD b = 11, c = 40, x;
RECT rc; char txt[8];
for( x = 0; x < pairs->size(); x++ )
{
MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );
MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );
wsprintf( txt, "%d", ( pairs->size() - x ) * 20 );
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
wsprintf( txt, "%d", x );
SetRect( &rc, c - 8, 472, c + 8, 492 );
DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
c += 46; b += 46;
}
SetRect( &rc, 0, b - 9, 36, b + 11 );
DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );
bmp.setPenColor( 0 ); bmp.setPenWidth( 3 );
MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );
MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );
}
void plotIt( vector<vector2>* pairs )
{
HDC dc = bmp.getDC();
HBRUSH br = CreateSolidBrush( 255 );
RECT rc;
bmp.setPenColor( 255 ); bmp.setPenWidth( 2 );
vector<vector2>::iterator it = pairs->begin();
int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
MoveToEx( dc, a, b, NULL );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );
it++;
for( ; it < pairs->end(); it++ )
{
a = MWID + HSTEP * static_cast<int>( ( *it ).x );
b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );
FillRect( dc, &rc, br ); LineTo( dc, a, b );
}
DeleteObject( br );
}
myBitmap bmp;
};
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
plot pt;
vector<vector2> pairs;
pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );
pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );
pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );
pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );
pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );
pt.draw( &pairs );
system( "pause" );
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <plot.h>
#define NP 10
double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
void minmax(double *x, double *y,
double *minx, double *maxx,
double *miny, double *maxy, int n)
{
int i;
*minx = *maxx = x[0];
*miny = *maxy = y[0];
for(i=1; i < n; i++) {
if ( x[i] < *minx ) *minx = x[i];
if ( x[i] > *maxx ) *maxx = x[i];
if ( y[i] < *miny ) *miny = y[i];
if ( y[i] > *maxy ) *maxy = y[i];
}
}
#define YLAB_HEIGHT_F 0.1
#define XLAB_WIDTH_F 0.2
#define XDIV (NP*1.0)
#define YDIV (NP*1.0)
#define EXTRA_W 0.01
#define EXTRA_H 0.01
#define DOTSCALE (1.0/150.0)
#define MAXLABLEN 32
#define PUSHSCALE(X,Y) pl_fscale((X),(Y))
#define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y))
#define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy)
int main()
{
int plotter, i;
double minx, miny, maxx, maxy;
double lx, ly;
double xticstep, yticstep, nx, ny;
double sx, sy;
char labs[MAXLABLEN+1];
plotter = pl_newpl("png", NULL, stdout, NULL);
if ( plotter < 0 ) exit(1);
pl_selectpl(plotter);
if ( pl_openpl() < 0 ) exit(1);
minmax(x, y, &minx, &maxx, &miny, &maxy, NP);
lx = maxx - minx;
ly = maxy - miny;
pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly,
ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly);
xticstep = (ceil(maxx) - floor(minx)) / XDIV;
yticstep = (ceil(maxy) - floor(miny)) / YDIV;
pl_flinewidth(0.25);
if ( lx < ly ) {
sx = lx/ly;
sy = 1.0;
} else {
sx = 1.0;
sy = ly/lx;
}
pl_erase();
pl_fbox(floor(minx), floor(miny),
ceil(maxx), ceil(maxy));
pl_fontname("HersheySerif");
for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) {
pl_fline(floor(minx), ny, ceil(maxx), ny);
snprintf(labs, MAXLABLEN, "%6.2lf", ny);
FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny);
PUSHSCALE(sx,sy);
pl_label(labs);
POPSCALE(sx,sy);
}
for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) {
pl_fline(nx, floor(miny), nx, ceil(maxy));
snprintf(labs, MAXLABLEN, "%6.2lf", nx);
FMOVESCALE(nx, floor(miny));
PUSHSCALE(sx,sy);
pl_ftextangle(-90);
pl_alabel('l', 'b', labs);
POPSCALE(sx,sy);
}
pl_fillcolorname("red");
pl_filltype(1);
for(i=0; i < NP; i++)
{
pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE,
x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE);
}
pl_flushpl();
pl_closepl();
}
|
Rewrite this program in C while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <string>
#include <iterator>
#include <regex>
int main()
{
std::regex re(".* string$");
std::string s = "Hi, I am a string";
if (std::regex_match(s, re))
std::cout << "The string matches.\n";
else
std::cout << "Oops - not found?\n";
std::regex re2(" a.*a");
std::smatch match;
if (std::regex_search(s, match, re2))
{
std::cout << "Matched " << match.length()
<< " characters starting at " << match.position() << ".\n";
std::cout << "Matched character sequence: \""
<< match.str() << "\"\n";
}
else
{
std::cout << "Oops - not found?\n";
}
std::string dest_string;
std::regex_replace(std::back_inserter(dest_string),
s.begin(), s.end(),
re2,
"'m now a changed");
std::cout << dest_string << std::endl;
}
| #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>
int main()
{
regex_t preg;
regmatch_t substmatch[1];
const char *tp = "string$";
const char *t1 = "this is a matching string";
const char *t2 = "this is not a matching string!";
const char *ss = "istyfied";
regcomp(&preg, "string$", REG_EXTENDED);
printf("'%s' %smatched with '%s'\n", t1,
(regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp);
printf("'%s' %smatched with '%s'\n", t2,
(regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp);
regfree(&preg);
regcomp(&preg, "a[a-z]+", REG_EXTENDED);
if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )
{
char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +
(strlen(t1) - substmatch[0].rm_eo) + 2);
memcpy(ns, t1, substmatch[0].rm_so+1);
memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));
memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],
strlen(&t1[substmatch[0].rm_eo]));
ns[ substmatch[0].rm_so + strlen(ss) +
strlen(&t1[substmatch[0].rm_eo]) ] = 0;
printf("mod string: '%s'\n", ns);
free(ns);
} else {
printf("the string '%s' is the same: no matching!\n", t1);
}
regfree(&preg);
return 0;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
struct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {
int i;
GuessNumberIterator() { }
GuessNumberIterator(int _i) : i(_i) { }
GuessNumberIterator& operator++() { ++i; return *this; }
GuessNumberIterator operator++(int) {
GuessNumberIterator tmp = *this; ++(*this); return tmp; }
bool operator==(const GuessNumberIterator& y) { return i == y.i; }
bool operator!=(const GuessNumberIterator& y) { return i != y.i; }
int operator*() {
std::cout << "Is your number less than or equal to " << i << "? ";
std::string s;
std::cin >> s;
return (s != "" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;
}
GuessNumberIterator& operator--() { --i; return *this; }
GuessNumberIterator operator--(int) {
GuessNumberIterator tmp = *this; --(*this); return tmp; }
GuessNumberIterator& operator+=(int n) { i += n; return *this; }
GuessNumberIterator& operator-=(int n) { i -= n; return *this; }
GuessNumberIterator operator+(int n) {
GuessNumberIterator tmp = *this; return tmp += n; }
GuessNumberIterator operator-(int n) {
GuessNumberIterator tmp = *this; return tmp -= n; }
int operator-(const GuessNumberIterator &y) { return i - y.i; }
int operator[](int n) { return *(*this + n); }
bool operator<(const GuessNumberIterator &y) { return i < y.i; }
bool operator>(const GuessNumberIterator &y) { return i > y.i; }
bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }
bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }
};
inline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }
const int lower = 0;
const int upper = 100;
int main() {
std::cout << "Instructions:\n"
<< "Think of integer number from " << lower << " (inclusive) to "
<< upper << " (exclusive) and\n"
<< "I will guess it. After each guess, I will ask you if it is less than\n"
<< "or equal to some number, and you will respond with \"yes\" or \"no\".\n";
int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;
std::cout << "Your number is " << answer << ".\n";
return 0;
}
| #include <stdio.h>
int main(){
int bounds[ 2 ] = {1, 100};
char input[ 2 ] = " ";
int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] );
do{
switch( input[ 0 ] ){
case 'H':
bounds[ 1 ] = choice;
break;
case 'L':
bounds[ 0 ] = choice;
break;
case 'Y':
printf( "\nAwwwright\n" );
return 0;
}
choice = (bounds[ 0 ] + bounds[ 1 ]) / 2;
printf( "Is the number %d? (Y/H/L) ", choice );
}while( scanf( "%1s", input ) == 1 );
return 0;
}
|
Transform the following C++ implementation into C, maintaining the same output and logic. | #include <unordered_map>
#include <string>
int main()
{
std::string keys[] = { "1", "2", "3" };
std::string vals[] = { "a", "b", "c" };
std::unordered_map<std::string, std::string> hash;
for( int i = 0 ; i < 3 ; i++ )
hash[ keys[i] ] = vals[i] ;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define KeyType const char *
#define ValType int
#define HASH_SIZE 4096
unsigned strhashkey( const char * key, int max)
{
unsigned h=0;
unsigned hl, hr;
while(*key) {
h += *key;
hl= 0x5C5 ^ (h&0xfff00000 )>>18;
hr =(h&0x000fffff );
h = hl ^ hr ^ *key++;
}
return h % max;
}
typedef struct sHme {
KeyType key;
ValType value;
struct sHme *link;
} *MapEntry;
typedef struct he {
MapEntry first, last;
} HashElement;
HashElement hash[HASH_SIZE];
typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);
typedef void (*ValCopyF)(ValType *vdest, ValType vsrc);
typedef unsigned (*KeyHashF)( KeyType key, int upperBound );
typedef int (*KeyCmprF)(KeyType key1, KeyType key2);
void HashAddH( KeyType key, ValType value,
KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
(*copyVal)(&m_ent->value, value);
}
else {
MapEntry last;
MapEntry hme = malloc(sizeof(struct sHme));
(*copyKey)(&hme->key, key);
(*copyVal)(&hme->value, value);
hme->link = NULL;
last = hash[hix].last;
if (last) {
last->link = hme;
}
else
hash[hix].first = hme;
hash[hix].last = hme;
}
}
int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
*val = m_ent->value;
}
return (m_ent != NULL);
}
void copyStr(const char**dest, const char *src)
{
*dest = strdup(src);
}
void copyInt( int *dest, int src)
{
*dest = src;
}
int strCompare( const char *key1, const char *key2)
{
return strcmp(key1, key2) == 0;
}
void HashAdd( KeyType key, ValType value )
{
HashAddH( key, value, ©Str, ©Int, &strhashkey, &strCompare);
}
int HashGet(ValType *val, KeyType key)
{
return HashGetH( val, key, &strhashkey, &strCompare);
}
int main()
{
static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" };
static int valuList[] = {1,43,640, 747, 42, 42};
int ix;
for (ix=0; ix<6; ix++) {
HashAdd(keyList[ix], valuList[ix]);
}
return 0;
}
|
Produce a functionally identical C code for the snippet given in C++. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> bins(const std::vector<int>& limits,
const std::vector<int>& data) {
std::vector<int> result(limits.size() + 1, 0);
for (int n : data) {
auto i = std::upper_bound(limits.begin(), limits.end(), n);
++result[i - limits.begin()];
}
return result;
}
void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {
size_t n = limits.size();
if (n == 0)
return;
assert(n + 1 == bins.size());
std::cout << " < " << std::setw(3) << limits[0] << ": "
<< std::setw(2) << bins[0] << '\n';
for (size_t i = 1; i < n; ++i)
std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < "
<< std::setw(3) << limits[i] << ": " << std::setw(2)
<< bins[i] << '\n';
std::cout << ">= " << std::setw(3) << limits[n - 1] << " : "
<< std::setw(2) << bins[n] << '\n';
}
int main() {
const std::vector<int> limits1{23, 37, 43, 53, 67, 83};
const std::vector<int> data1{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
std::cout << "Example 1:\n";
print_bins(limits1, bins(limits1, data1));
const std::vector<int> limits2{14, 18, 249, 312, 389,
392, 513, 591, 634, 720};
const std::vector<int> data2{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
std::cout << "\nExample 2:\n";
print_bins(limits2, bins(limits2, data2));
}
| #include <stdio.h>
#include <stdlib.h>
size_t upper_bound(const int* array, size_t n, int value) {
size_t start = 0;
while (n > 0) {
size_t step = n / 2;
size_t index = start + step;
if (value >= array[index]) {
start = index + 1;
n -= step + 1;
} else {
n = step;
}
}
return start;
}
int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {
int* result = calloc(nlimits + 1, sizeof(int));
if (result == NULL)
return NULL;
for (size_t i = 0; i < ndata; ++i)
++result[upper_bound(limits, nlimits, data[i])];
return result;
}
void print_bins(const int* limits, size_t n, const int* bins) {
if (n == 0)
return;
printf(" < %3d: %2d\n", limits[0], bins[0]);
for (size_t i = 1; i < n; ++i)
printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]);
printf(">= %3d : %2d\n", limits[n - 1], bins[n]);
}
int main() {
const int limits1[] = {23, 37, 43, 53, 67, 83};
const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,
5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,
8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,
40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
printf("Example 1:\n");
size_t n = sizeof(limits1) / sizeof(int);
int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits1, n, b);
free(b);
const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};
const int data2[] = {
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
printf("\nExample 2:\n");
n = sizeof(limits2) / sizeof(int);
b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits2, n, b);
free(b);
return EXIT_SUCCESS;
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> bins(const std::vector<int>& limits,
const std::vector<int>& data) {
std::vector<int> result(limits.size() + 1, 0);
for (int n : data) {
auto i = std::upper_bound(limits.begin(), limits.end(), n);
++result[i - limits.begin()];
}
return result;
}
void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {
size_t n = limits.size();
if (n == 0)
return;
assert(n + 1 == bins.size());
std::cout << " < " << std::setw(3) << limits[0] << ": "
<< std::setw(2) << bins[0] << '\n';
for (size_t i = 1; i < n; ++i)
std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < "
<< std::setw(3) << limits[i] << ": " << std::setw(2)
<< bins[i] << '\n';
std::cout << ">= " << std::setw(3) << limits[n - 1] << " : "
<< std::setw(2) << bins[n] << '\n';
}
int main() {
const std::vector<int> limits1{23, 37, 43, 53, 67, 83};
const std::vector<int> data1{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
std::cout << "Example 1:\n";
print_bins(limits1, bins(limits1, data1));
const std::vector<int> limits2{14, 18, 249, 312, 389,
392, 513, 591, 634, 720};
const std::vector<int> data2{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
std::cout << "\nExample 2:\n";
print_bins(limits2, bins(limits2, data2));
}
| #include <stdio.h>
#include <stdlib.h>
size_t upper_bound(const int* array, size_t n, int value) {
size_t start = 0;
while (n > 0) {
size_t step = n / 2;
size_t index = start + step;
if (value >= array[index]) {
start = index + 1;
n -= step + 1;
} else {
n = step;
}
}
return start;
}
int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {
int* result = calloc(nlimits + 1, sizeof(int));
if (result == NULL)
return NULL;
for (size_t i = 0; i < ndata; ++i)
++result[upper_bound(limits, nlimits, data[i])];
return result;
}
void print_bins(const int* limits, size_t n, const int* bins) {
if (n == 0)
return;
printf(" < %3d: %2d\n", limits[0], bins[0]);
for (size_t i = 1; i < n; ++i)
printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]);
printf(">= %3d : %2d\n", limits[n - 1], bins[n]);
}
int main() {
const int limits1[] = {23, 37, 43, 53, 67, 83};
const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,
5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,
8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,
40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
printf("Example 1:\n");
size_t n = sizeof(limits1) / sizeof(int);
int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits1, n, b);
free(b);
const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};
const int data2[] = {
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
printf("\nExample 2:\n");
n = sizeof(limits2) / sizeof(int);
b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits2, n, b);
free(b);
return EXIT_SUCCESS;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> bins(const std::vector<int>& limits,
const std::vector<int>& data) {
std::vector<int> result(limits.size() + 1, 0);
for (int n : data) {
auto i = std::upper_bound(limits.begin(), limits.end(), n);
++result[i - limits.begin()];
}
return result;
}
void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {
size_t n = limits.size();
if (n == 0)
return;
assert(n + 1 == bins.size());
std::cout << " < " << std::setw(3) << limits[0] << ": "
<< std::setw(2) << bins[0] << '\n';
for (size_t i = 1; i < n; ++i)
std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < "
<< std::setw(3) << limits[i] << ": " << std::setw(2)
<< bins[i] << '\n';
std::cout << ">= " << std::setw(3) << limits[n - 1] << " : "
<< std::setw(2) << bins[n] << '\n';
}
int main() {
const std::vector<int> limits1{23, 37, 43, 53, 67, 83};
const std::vector<int> data1{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
std::cout << "Example 1:\n";
print_bins(limits1, bins(limits1, data1));
const std::vector<int> limits2{14, 18, 249, 312, 389,
392, 513, 591, 634, 720};
const std::vector<int> data2{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
std::cout << "\nExample 2:\n";
print_bins(limits2, bins(limits2, data2));
}
| #include <stdio.h>
#include <stdlib.h>
size_t upper_bound(const int* array, size_t n, int value) {
size_t start = 0;
while (n > 0) {
size_t step = n / 2;
size_t index = start + step;
if (value >= array[index]) {
start = index + 1;
n -= step + 1;
} else {
n = step;
}
}
return start;
}
int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) {
int* result = calloc(nlimits + 1, sizeof(int));
if (result == NULL)
return NULL;
for (size_t i = 0; i < ndata; ++i)
++result[upper_bound(limits, nlimits, data[i])];
return result;
}
void print_bins(const int* limits, size_t n, const int* bins) {
if (n == 0)
return;
printf(" < %3d: %2d\n", limits[0], bins[0]);
for (size_t i = 1; i < n; ++i)
printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]);
printf(">= %3d : %2d\n", limits[n - 1], bins[n]);
}
int main() {
const int limits1[] = {23, 37, 43, 53, 67, 83};
const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57,
5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16,
8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98,
40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
printf("Example 1:\n");
size_t n = sizeof(limits1) / sizeof(int);
int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits1, n, b);
free(b);
const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720};
const int data2[] = {
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
printf("\nExample 2:\n");
n = sizeof(limits2) / sizeof(int);
b = bins(limits2, n, data2, sizeof(data2) / sizeof(int));
if (b == NULL) {
fprintf(stderr, "Out of memory\n");
return EXIT_FAILURE;
}
print_bins(limits2, n, b);
free(b);
return EXIT_SUCCESS;
}
|
Produce a language-to-language conversion: from C++ to C, same semantics. | #include <windows.h>
#include <string>
#include <math.h>
using namespace std;
const float PI = 3.1415926536f;
class myBitmap
{
public:
myBitmap() : pen( NULL ) {}
~myBitmap()
{
DeleteObject( pen );
DeleteDC( hdc );
DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
void *pBits;
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 setPenColor( DWORD clr )
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, 1, clr );
SelectObject( hdc, pen );
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD* dwpBits;
DWORD wb;
HANDLE file;
GetObject( bmp, sizeof( bitmap ), &bitmap );
dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() { return hdc; }
int getWidth() { return width; }
int getHeight() { return height; }
private:
HBITMAP bmp;
HDC hdc;
HPEN pen;
int width, height;
};
class vector2
{
public:
vector2() { x = y = 0; }
vector2( int a, int b ) { x = a; y = b; }
void set( int a, int b ) { x = a; y = b; }
void rotate( float angle_r )
{
float _x = static_cast<float>( x ),
_y = static_cast<float>( y ),
s = sinf( angle_r ),
c = cosf( angle_r ),
a = _x * c - _y * s,
b = _x * s + _y * c;
x = static_cast<int>( a );
y = static_cast<int>( b );
}
int x, y;
};
class fractalTree
{
public:
fractalTree() { _ang = DegToRadian( 24.0f ); }
float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }
void create( myBitmap* bmp )
{
_bmp = bmp;
float line_len = 130.0f;
vector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );
MoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );
sp.y -= static_cast<int>( line_len );
LineTo( _bmp->getDC(), sp.x, sp.y);
drawRL( &sp, line_len, 0, true );
drawRL( &sp, line_len, 0, false );
}
private:
void drawRL( vector2* sp, float line_len, float a, bool rg )
{
line_len *= .75f;
if( line_len < 2.0f ) return;
MoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );
vector2 r( 0, static_cast<int>( line_len ) );
if( rg ) a -= _ang;
else a += _ang;
r.rotate( a );
r.x += sp->x; r.y = sp->y - r.y;
LineTo( _bmp->getDC(), r.x, r.y );
drawRL( &r, line_len, a, true );
drawRL( &r, line_len, a, false );
}
myBitmap* _bmp;
float _ang;
};
int main( int argc, char* argv[] )
{
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
myBitmap bmp;
bmp.create( 640, 512 );
bmp.setPenColor( RGB( 255, 255, 0 ) );
fractalTree tree;
tree.create( &bmp );
BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );
bmp.saveBitmap( "f:
system( "pause" );
return 0;
}
| #include <SDL/SDL.h>
#ifdef WITH_CAIRO
#include <cairo.h>
#else
#include <SDL/sge.h>
#endif
#include <cairo.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#ifdef WITH_CAIRO
#define PI 3.1415926535
#endif
#define SIZE 800
#define SCALE 5
#define BRANCHES 14
#define ROTATION_SCALE 0.75
#define INITIAL_LENGTH 50
double rand_fl(){
return (double)rand() / (double)RAND_MAX;
}
void draw_tree(SDL_Surface * surface, double offsetx, double offsety,
double directionx, double directiony, double size,
double rotation, int depth) {
#ifdef WITH_CAIRO
cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,
CAIRO_FORMAT_RGB24,
surface->w, surface->h,
surface->pitch );
cairo_t *ct = cairo_create(surf);
cairo_set_line_width(ct, 1);
cairo_set_source_rgba(ct, 0,0,0,1);
cairo_move_to(ct, (int)offsetx, (int)offsety);
cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));
cairo_stroke(ct);
#else
sge_AALine(surface,
(int)offsetx, (int)offsety,
(int)(offsetx + directionx * size), (int)(offsety + directiony * size),
SDL_MapRGB(surface->format, 0, 0, 0));
#endif
if (depth > 0){
draw_tree(surface,
offsetx + directionx * size,
offsety + directiony * size,
directionx * cos(rotation) + directiony * sin(rotation),
directionx * -sin(rotation) + directiony * cos(rotation),
size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
rotation * ROTATION_SCALE,
depth - 1);
draw_tree(surface,
offsetx + directionx * size,
offsety + directiony * size,
directionx * cos(-rotation) + directiony * sin(-rotation),
directionx * -sin(-rotation) + directiony * cos(-rotation),
size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE,
rotation * ROTATION_SCALE,
depth - 1);
}
}
void render(SDL_Surface * surface){
SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));
draw_tree(surface,
surface->w / 2.0,
surface->h - 10.0,
0.0, -1.0,
INITIAL_LENGTH,
PI / 8,
BRANCHES);
SDL_UpdateRect(surface, 0, 0, 0, 0);
}
int main(){
SDL_Surface * screen;
SDL_Event evt;
SDL_Init(SDL_INIT_VIDEO);
srand((unsigned)time(NULL));
screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);
render(screen);
while(1){
if (SDL_PollEvent(&evt)){
if(evt.type == SDL_QUIT) break;
}
SDL_Delay(1);
}
SDL_Quit();
return 0;
}
|
Write a version of this C++ function in C with identical behavior. | #include <windows.h>
class pinstripe
{
public:
pinstripe() { createColors(); }
void setDimensions( int x, int y ) { _mw = x; _mh = y; }
void createColors()
{
colors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 );
colors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 );
colors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 );
colors[7] = RGB( 255, 255, 255 );
}
void draw( HDC dc )
{
HPEN pen;
int lh = _mh / 4, row, cp;
for( int lw = 1; lw < 5; lw++ )
{
cp = 0;
row = ( lw - 1 ) * lh;
for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw )
{
pen = CreatePen( PS_SOLID, lw, colors[cp] );
++cp %= 8;
SelectObject( dc, pen );
MoveToEx( dc, x, row, NULL );
LineTo( dc, x, row + lh );
DeleteObject( pen );
}
}
}
private:
int _mw, _mh;
DWORD colors[8];
};
pinstripe pin;
void PaintWnd( HWND hWnd )
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint( hWnd, &ps );
pin.draw( hdc );
EndPaint( hWnd, &ps );
}
LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY: PostQuitMessage( 0 ); break;
case WM_PAINT: PaintWnd( hWnd ); break;
default:
return DefWindowProc( hWnd, msg, wParam, lParam );
}
return 0;
}
HWND InitAll( HINSTANCE hInstance )
{
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_CLR_PS_";
RegisterClassEx( &wcex );
return CreateWindow( "_CLR_PS_", ".: Clr Pinstripe -- PJorente :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL );
}
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
srand( GetTickCount() );
HWND hwnd = InitAll( hInstance );
if( !hwnd ) return -1;
int mw = GetSystemMetrics( SM_CXSCREEN ),
mh = GetSystemMetrics( SM_CYSCREEN );
pin.setDimensions( mw, mh );
RECT rc = { 0, 0, mw, mh };
AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 );
int w = rc.right - rc.left,
h = rc.bottom - rc.top;
int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ),
posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 );
SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER );
ShowWindow( hwnd, nCmdShow );
UpdateWindow( hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return UnregisterClass( "_CLR_PS_", hInstance );
}
| #include<graphics.h>
#include<conio.h>
#define sections 4
int main()
{
int d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1;
initgraph(&d,&m,"c:/turboc3/bgi");
maxX = getmaxx();
maxY = getmaxy();
for(y=0;y<maxY;y+=maxY/sections)
{
for(x=0;x<maxX;x+=increment)
{
setfillstyle(SOLID_FILL,(colour++)%16);
bar(x,y,x+increment,y+maxY/sections);
}
increment++;
colour = 0;
}
getch();
closegraph();
return 0;
}
|
Please provide an equivalent version of this C++ code in C. | #include <iostream>
#include <cstdint>
struct Date {
std::uint16_t year;
std::uint8_t month;
std::uint8_t day;
};
constexpr bool leap(int year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const std::string& weekday(const Date& date) {
static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
static const std::string days[] = {
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"
};
unsigned const c = date.year/100, r = date.year%100;
unsigned const s = r/12, t = r%12;
unsigned const c_anchor = (5 * (c%4) + 2) % 7;
unsigned const doom = (s + t + t/4 + c_anchor) % 7;
unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
return days[(doom+date.day-anchor+7)%7];
}
int main(void) {
const std::string months[] = {"",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
const Date dates[] = {
{1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
{2077,2,12}, {2101,4,2}
};
for (const Date& d : dates) {
std::cout << months[d.month] << " " << (int)d.day << ", " << d.year;
std::cout << (d.year > 2021 ? " will be " : " was ");
std::cout << "on a " << weekday(d) << std::endl;
}
return 0;
}
| #include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
typedef struct {
uint16_t year;
uint8_t month;
uint8_t day;
} Date;
bool leap(uint16_t year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const char *weekday(Date date) {
static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
static const char *days[] = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
unsigned c = date.year/100, r = date.year%100;
unsigned s = r/12, t = r%12;
unsigned c_anchor = (5 * (c%4) + 2) % 7;
unsigned doom = (s + t + (t/4) + c_anchor) % 7;
unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
return days[(doom+date.day-anchor+7)%7];
}
int main(void) {
const char *past = "was", *future = "will be";
const char *months[] = { "",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
const Date dates[] = {
{1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
{2077,2,12}, {2101,4,2}
};
int i;
for (i=0; i < sizeof(dates)/sizeof(Date); i++) {
printf("%s %d, %d %s on a %s.\n",
months[dates[i].month], dates[i].day, dates[i].year,
dates[i].year > 2021 ? future : past,
weekday(dates[i]));
}
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original C++ code. | #include <iostream>
#include <cstdint>
struct Date {
std::uint16_t year;
std::uint8_t month;
std::uint8_t day;
};
constexpr bool leap(int year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const std::string& weekday(const Date& date) {
static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
static const std::string days[] = {
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"
};
unsigned const c = date.year/100, r = date.year%100;
unsigned const s = r/12, t = r%12;
unsigned const c_anchor = (5 * (c%4) + 2) % 7;
unsigned const doom = (s + t + t/4 + c_anchor) % 7;
unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
return days[(doom+date.day-anchor+7)%7];
}
int main(void) {
const std::string months[] = {"",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
const Date dates[] = {
{1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
{2077,2,12}, {2101,4,2}
};
for (const Date& d : dates) {
std::cout << months[d.month] << " " << (int)d.day << ", " << d.year;
std::cout << (d.year > 2021 ? " will be " : " was ");
std::cout << "on a " << weekday(d) << std::endl;
}
return 0;
}
| #include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
typedef struct {
uint16_t year;
uint8_t month;
uint8_t day;
} Date;
bool leap(uint16_t year) {
return year%4==0 && (year%100!=0 || year%400==0);
}
const char *weekday(Date date) {
static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5};
static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5};
static const char *days[] = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
unsigned c = date.year/100, r = date.year%100;
unsigned s = r/12, t = r%12;
unsigned c_anchor = (5 * (c%4) + 2) % 7;
unsigned doom = (s + t + (t/4) + c_anchor) % 7;
unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1];
return days[(doom+date.day-anchor+7)%7];
}
int main(void) {
const char *past = "was", *future = "will be";
const char *months[] = { "",
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
const Date dates[] = {
{1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14},
{2077,2,12}, {2101,4,2}
};
int i;
for (i=0; i < sizeof(dates)/sizeof(Date); i++) {
printf("%s %d, %d %s on a %s.\n",
months[dates[i].month], dates[i].day, dates[i].year,
dates[i].year > 2021 ? future : past,
weekday(dates[i]));
}
return 0;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <vector>
template <typename iterator>
void cocktail_shaker_sort(iterator begin, iterator end) {
if (begin == end)
return;
for (--end; begin < end; ) {
iterator new_begin = end;
iterator new_end = begin;
for (iterator i = begin; i < end; ++i) {
iterator j = i + 1;
if (*j < *i) {
std::iter_swap(i, j);
new_end = i;
}
}
end = new_end;
for (iterator i = end; i > begin; --i) {
iterator j = i - 1;
if (*i < *j) {
std::iter_swap(i, j);
new_begin = i;
}
}
begin = new_begin;
}
}
template <typename iterator>
void print(iterator begin, iterator end) {
if (begin == end)
return;
std::cout << *begin++;
while (begin != end)
std::cout << ' ' << *begin++;
std::cout << '\n';
}
int main() {
std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};
std::cout << "before: ";
print(v.begin(), v.end());
cocktail_shaker_sort(v.begin(), v.end());
assert(std::is_sorted(v.begin(), v.end()));
std::cout << "after: ";
print(v.begin(), v.end());
return 0;
}
| #include <stdio.h>
#include <string.h>
void swap(char* p1, char* p2, size_t size) {
for (; size-- > 0; ++p1, ++p2) {
char tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
}
void cocktail_shaker_sort(void* base, size_t count, size_t size,
int (*cmp)(const void*, const void*)) {
char* begin = base;
char* end = base + size * count;
if (end == begin)
return;
for (end -= size; begin < end; ) {
char* new_begin = end;
char* new_end = begin;
for (char* p = begin; p < end; p += size) {
char* q = p + size;
if (cmp(p, q) > 0) {
swap(p, q, size);
new_end = p;
}
}
end = new_end;
for (char* p = end; p > begin; p -= size) {
char* q = p - size;
if (cmp(q, p) > 0) {
swap(p, q, size);
new_begin = p;
}
}
begin = new_begin;
}
}
int string_compare(const void* p1, const void* p2) {
const char* const* s1 = p1;
const char* const* s2 = p2;
return strcmp(*s1, *s2);
}
void print(const char** a, size_t len) {
for (size_t i = 0; i < len; ++i)
printf("%s ", a[i]);
printf("\n");
}
int main() {
const char* a[] = { "one", "two", "three", "four", "five",
"six", "seven", "eight" };
const size_t len = sizeof(a)/sizeof(a[0]);
printf("before: ");
print(a, len);
cocktail_shaker_sort(a, len, sizeof(char*), string_compare);
printf("after: ");
print(a, len);
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? | #ifndef __wxPendulumDlg_h__
#define __wxPendulumDlg_h__
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/dialog.h>
#else
#include <wx/wxprec.h>
#endif
#include <wx/timer.h>
#include <wx/dcbuffer.h>
#include <cmath>
class wxPendulumDlgApp : public wxApp
{
public:
bool OnInit();
int OnExit();
};
class wxPendulumDlg : public wxDialog
{
public:
wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("wxPendulum"),
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);
virtual ~wxPendulumDlg();
void wxPendulumDlgPaint(wxPaintEvent& event);
void wxPendulumDlgSize(wxSizeEvent& event);
void OnTimer(wxTimerEvent& event);
private:
wxTimer *m_timer;
unsigned int m_uiLength;
double m_Angle;
double m_AngleVelocity;
enum wxIDs
{
ID_WXTIMER1 = 1001,
ID_DUMMY_VALUE_
};
void OnClose(wxCloseEvent& event);
void CreateGUIControls();
DECLARE_EVENT_TABLE()
};
#endif
| #include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <sys/time.h>
#define length 5
#define g 9.8
double alpha, accl, omega = 0, E;
struct timeval tv;
double elappsed() {
struct timeval now;
gettimeofday(&now, 0);
int ret = (now.tv_sec - tv.tv_sec) * 1000000
+ now.tv_usec - tv.tv_usec;
tv = now;
return ret / 1.e6;
}
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, 1);
}
void render()
{
double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);
resize(640, 320);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2d(320, 0);
glVertex2d(x, y);
glEnd();
glFlush();
double us = elappsed();
alpha += (omega + us * accl / 2) * us;
omega += accl * us;
if (length * g * (1 - cos(alpha)) >= E) {
alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);
omega = 0;
}
accl = -g / length * sin(alpha);
}
void init_gfx(int *c, char **v)
{
glutInit(c, v);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(640, 320);
glutIdleFunc(render);
glutCreateWindow("Pendulum");
}
int main(int c, char **v)
{
alpha = 4 * atan2(1, 1) / 2.1;
E = length * g * (1 - cos(alpha));
accl = -g / length * sin(alpha);
omega = 0;
gettimeofday(&tv, 0);
init_gfx(&c, v);
glutMainLoop();
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the C++ version. | #include <bitset>
#include <iostream>
#include <string>
#include <assert.h>
uint32_t gray_encode(uint32_t b)
{
return b ^ (b >> 1);
}
uint32_t gray_decode(uint32_t g)
{
for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)
{
if (g & bit) g ^= bit >> 1;
}
return g;
}
std::string to_binary(int value)
{
const std::bitset<32> bs(value);
const std::string str(bs.to_string());
const size_t pos(str.find('1'));
return pos == std::string::npos ? "0" : str.substr(pos);
}
int main()
{
std::cout << "Number\tBinary\tGray\tDecoded\n";
for (uint32_t n = 0; n < 32; ++n)
{
uint32_t g = gray_encode(n);
assert(gray_decode(g) == n);
std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
}
}
| int gray_encode(int n) {
return n ^ (n >> 1);
}
int gray_decode(int n) {
int p = n;
while (n >>= 1) p ^= n;
return p;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <bitset>
#include <iostream>
#include <string>
#include <assert.h>
uint32_t gray_encode(uint32_t b)
{
return b ^ (b >> 1);
}
uint32_t gray_decode(uint32_t g)
{
for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)
{
if (g & bit) g ^= bit >> 1;
}
return g;
}
std::string to_binary(int value)
{
const std::bitset<32> bs(value);
const std::string str(bs.to_string());
const size_t pos(str.find('1'));
return pos == std::string::npos ? "0" : str.substr(pos);
}
int main()
{
std::cout << "Number\tBinary\tGray\tDecoded\n";
for (uint32_t n = 0; n < 32; ++n)
{
uint32_t g = gray_encode(n);
assert(gray_decode(g) == n);
std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
}
}
| int gray_encode(int n) {
return n ^ (n >> 1);
}
int gray_decode(int n) {
int p = n;
while (n >>= 1) p ^= n;
return p;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <iostream>
#include <fstream>
#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif
int main() {
std::filebuf fb;
fb.open(FILENAME,std::ios::out);
std::ostream os(&fb);
os << "Hello World\n";
fb.close();
return 0;
}
| #include<stdio.h>
int main()
{
FILE* fp = fopen("TAPE.FILE","w");
fprintf(fp,"This code should be able to write a file to magnetic tape.\n");
fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n");
fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n");
fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n");
fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n");
fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n");
fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n");
fprintf(fp,"EOF");
fclose(fp);
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original C++ code. | #include <algorithm>
#include <iterator>
#include <iostream>
template<typename RandomAccessIterator>
void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {
std::make_heap(begin, end);
std::sort_heap(begin, end);
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
heap_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
| #include <stdio.h>
int max (int *a, int n, int i, int j, int k) {
int m = i;
if (j < n && a[j] > a[m]) {
m = j;
}
if (k < n && a[k] > a[m]) {
m = k;
}
return m;
}
void downheap (int *a, int n, int i) {
while (1) {
int j = max(a, n, i, 2 * i + 1, 2 * i + 2);
if (j == i) {
break;
}
int t = a[i];
a[i] = a[j];
a[j] = t;
i = j;
}
}
void heapsort (int *a, int n) {
int i;
for (i = (n - 2) / 2; i >= 0; i--) {
downheap(a, n, i);
}
for (i = 0; i < n; i++) {
int t = a[n - i - 1];
a[n - i - 1] = a[0];
a[0] = t;
downheap(a, n - i - 1, 0);
}
}
int main () {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
heapsort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
|
Produce a functionally identical C code for the snippet given in C++. | #include <deque>
#include <algorithm>
#include <ostream>
#include <iterator>
namespace cards
{
class card
{
public:
enum pip_type { two, three, four, five, six, seven, eight, nine, ten,
jack, queen, king, ace, pip_count };
enum suite_type { hearts, spades, diamonds, clubs, suite_count };
enum { unique_count = pip_count * suite_count };
card(suite_type s, pip_type p): value(s + suite_count * p) {}
explicit card(unsigned char v = 0): value(v) {}
pip_type pip() { return pip_type(value / suite_count); }
suite_type suite() { return suite_type(value % suite_count); }
private:
unsigned char value;
};
const char* const pip_names[] =
{ "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"jack", "queen", "king", "ace" };
std::ostream& operator<<(std::ostream& os, card::pip_type pip)
{
return os << pip_names[pip];
}
const char* const suite_names[] =
{ "hearts", "spades", "diamonds", "clubs" };
std::ostream& operator<<(std::ostream& os, card::suite_type suite)
{
return os << suite_names[suite];
}
std::ostream& operator<<(std::ostream& os, card c)
{
return os << c.pip() << " of " << c.suite();
}
class deck
{
public:
deck()
{
for (int i = 0; i < card::unique_count; ++i) {
cards.push_back(card(i));
}
}
void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }
card deal() { card c = cards.front(); cards.pop_front(); return c; }
typedef std::deque<card>::const_iterator const_iterator;
const_iterator begin() const { return cards.cbegin(); }
const_iterator end() const { return cards.cend(); }
private:
std::deque<card> cards;
};
inline std::ostream& operator<<(std::ostream& os, const deck& d)
{
std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n"));
return os;
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int locale_ok = 0;
wchar_t s_suits[] = L"♠♥♦♣";
const char *s_suits_ascii[] = { "S", "H", "D", "C" };
const char *s_nums[] = { "WHAT",
"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K",
"OVERFLOW"
};
typedef struct { int suit, number, _s; } card_t, *card;
typedef struct { int n; card_t cards[52]; } deck_t, *deck;
void show_card(card c)
{
if (locale_ok)
printf(" %lc%s", s_suits[c->suit], s_nums[c->number]);
else
printf(" %s%s", s_suits_ascii[c->suit], s_nums[c->number]);
}
deck new_deck()
{
int i, j, k;
deck d = malloc(sizeof(deck_t));
d->n = 52;
for (i = k = 0; i < 4; i++)
for (j = 1; j <= 13; j++, k++) {
d->cards[k].suit = i;
d->cards[k].number = j;
}
return d;
}
void show_deck(deck d)
{
int i;
printf("%d cards:", d->n);
for (i = 0; i < d->n; i++)
show_card(d->cards + i);
printf("\n");
}
int cmp_card(const void *a, const void *b)
{
int x = ((card)a)->_s, y = ((card)b)->_s;
return x < y ? -1 : x > y;
}
card deal_card(deck d)
{
if (!d->n) return 0;
return d->cards + --d->n;
}
void shuffle_deck(deck d)
{
int i;
for (i = 0; i < d->n; i++)
d->cards[i]._s = rand();
qsort(d->cards, d->n, sizeof(card_t), cmp_card);
}
int main()
{
int i, j;
deck d = new_deck();
locale_ok = (0 != setlocale(LC_CTYPE, ""));
printf("New deck, "); show_deck(d);
printf("\nShuffle and deal to three players:\n");
shuffle_deck(d);
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++)
show_card(deal_card(d));
printf("\n");
}
printf("Left in deck "); show_deck(d);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from C++ to C. | #include <array>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
template <typename Array>
void demonstrate(Array& array)
{
array[2] = "Three";
array.at(1) = "Two";
std::reverse(begin(array), end(array));
std::for_each(begin(array), end(array),
[](typename Array::value_type const& element)
{
std::cout << element << ' ';
});
std::cout << '\n';
}
int main()
{
auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" };
auto dynamic_array = std::vector<std::string>{ "One", "Four" };
dynamic_array.push_back("Eight");
demonstrate(fixed_size_array);
demonstrate(dynamic_array);
}
| char foo()
{
char array[5] = {3,6,9,12,15};
return array[2];
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? |
#include <cstdint>
#include <cstdlib>
#include <cstdio>
static constexpr int32_t bct_low_bits = 0x55555555;
static int32_t bct_decrement(int32_t v) {
--v;
return v ^ (v & (v>>1) & bct_low_bits);
}
int main (int argc, char *argv[])
{
const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;
if (n < 0 || 9 < n) {
std::printf("N out of range (use 0..9): %ld\n", long(n));
return 1;
}
const int32_t size_bct = 1<<(n*2);
int32_t y = size_bct;
do {
y = bct_decrement(y);
int32_t x = size_bct;
do {
x = bct_decrement(x);
std::putchar((x & y & bct_low_bits) ? ' ' : '#');
} while (0 < x);
std::putchar('\n');
} while (0 < y);
return 0;
}
| #include <stdio.h>
int main()
{
int i, j, dim, d;
int depth = 3;
for (i = 0, dim = 1; i < depth; i++, dim *= 3);
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
for (d = dim / 3; d; d /= 3)
if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1)
break;
printf(d ? " " : "##");
}
printf("\n");
}
return 0;
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
template <typename RandomAccessIterator, typename Predicate>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,
Predicate p) {
std::random_device rd;
std::mt19937 generator(rd());
while (!std::is_sorted(begin, end, p)) {
std::shuffle(begin, end, generator);
}
}
template <typename RandomAccessIterator>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {
bogo_sort(
begin, end,
std::less<
typename std::iterator_traits<RandomAccessIterator>::value_type>());
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
bogo_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
| #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool is_sorted(int *a, int n)
{
while ( --n >= 1 ) {
if ( a[n] < a[n-1] ) return false;
}
return true;
}
void shuffle(int *a, int n)
{
int i, t, r;
for(i=0; i < n; i++) {
t = a[i];
r = rand() % n;
a[i] = a[r];
a[r] = t;
}
}
void bogosort(int *a, int n)
{
while ( !is_sorted(a, n) ) shuffle(a, n);
}
int main()
{
int numbers[] = { 1, 10, 9, 7, 3, 0 };
int i;
bogosort(numbers, 6);
for (i=0; i < 6; i++) printf("%d ", numbers[i]);
printf("\n");
}
|
Maintain the same structure and functionality when rewriting this code in C. | #include <iostream>
#include <optional>
#include <ranges>
#include <string>
#include <vector>
using namespace std;
struct Patient
{
string ID;
string LastName;
};
struct Visit
{
string PatientID;
string Date;
optional<float> Score;
};
int main(void)
{
auto patients = vector<Patient> {
{"1001", "Hopper"},
{"4004", "Wirth"},
{"3003", "Kemeny"},
{"2002", "Gosling"},
{"5005", "Kurtz"}};
auto visits = vector<Visit> {
{"2002", "2020-09-10", 6.8},
{"1001", "2020-09-17", 5.5},
{"4004", "2020-09-24", 8.4},
{"2002", "2020-10-08", },
{"1001", "" , 6.6},
{"3003", "2020-11-12", },
{"4004", "2020-11-05", 7.0},
{"1001", "2020-11-19", 5.3}};
sort(patients.begin(), patients.end(),
[](const auto& a, const auto&b){ return a.ID < b.ID;});
cout << "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n";
for(const auto& patient : patients)
{
string lastVisit;
float sum = 0;
int numScores = 0;
auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};
for(const auto& visit : visits | views::filter( patientFilter ))
{
if(visit.Score)
{
sum += *visit.Score;
numScores++;
}
lastVisit = max(lastVisit, visit.Date);
}
cout << "| " << patient.ID << " | ";
cout.width(8); cout << patient.LastName << " | ";
cout.width(10); cout << lastVisit << " | ";
if(numScores > 0)
{
cout.width(9); cout << sum << " | ";
cout.width(9); cout << (sum / float(numScores));
}
else cout << " | ";
cout << " |\n";
}
}
|
#include <ctime>
#include <cstdint>
extern "C" {
int64_t from date(const char* string) {
struct tm tmInfo = {0};
strptime(string, "%Y-%m-%d", &tmInfo);
return mktime(&tmInfo);
}
}
|
Rewrite this program in C while keeping its functionality equivalent to the C++ version. | #include <iomanip>
#include <iostream>
typedef double F(double,double);
void euler(F f, double y0, double a, double b, double h)
{
double y = y0;
for (double t = a; t < b; t += h)
{
std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n";
y += h * f(t, y);
}
std::cout << "done\n";
}
double newtonCoolingLaw(double, double t)
{
return -0.07 * (t - 20);
}
int main()
{
euler(newtonCoolingLaw, 100, 0, 100, 2);
euler(newtonCoolingLaw, 100, 0, 100, 5);
euler(newtonCoolingLaw, 100, 0, 100, 10);
}
| #include <stdio.h>
#include <math.h>
typedef double (*deriv_f)(double, double);
#define FMT " %7.3f"
void ivp_euler(deriv_f f, double y, int step, int end_t)
{
int t = 0;
printf(" Step %2d: ", (int)step);
do {
if (t % 10 == 0) printf(FMT, y);
y += step * f(t, y);
} while ((t += step) <= end_t);
printf("\n");
}
void analytic()
{
double t;
printf(" Time: ");
for (t = 0; t <= 100; t += 10) printf(" %7g", t);
printf("\nAnalytic: ");
for (t = 0; t <= 100; t += 10)
printf(FMT, 20 + 80 * exp(-0.07 * t));
printf("\n");
}
double cooling(double t, double temp)
{
return -0.07 * (temp - 20);
}
int main()
{
analytic();
ivp_euler(cooling, 100, 2, 100);
ivp_euler(cooling, 100, 5, 100);
ivp_euler(cooling, 100, 10, 100);
return 0;
}
|
Convert the following code from C++ to C, ensuring the logic remains intact. | #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <boost/bind.hpp>
#include <iterator>
double nextNumber( double number ) {
return number + floor( 0.5 + sqrt( number ) ) ;
}
int main( ) {
std::vector<double> non_squares ;
typedef std::vector<double>::iterator SVI ;
non_squares.reserve( 1000000 ) ;
for ( double i = 1.0 ; i < 100001.0 ; i += 1 )
non_squares.push_back( nextNumber( i ) ) ;
std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,
std::ostream_iterator<double>(std::cout, " " ) ) ;
std::cout << '\n' ;
SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,
boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;
if ( found != non_squares.end( ) ) {
std::cout << "Found a square number in the sequence!\n" ;
std::cout << "It is " << *found << " !\n" ;
}
else {
std::cout << "Up to 1000000, found no square number in the sequence!\n" ;
}
return 0 ;
}
| #include <math.h>
#include <stdio.h>
#include <assert.h>
int nonsqr(int n) {
return n + (int)(0.5 + sqrt(n));
}
int main() {
int i;
for (i = 1; i < 23; i++)
printf("%d ", nonsqr(i));
printf("\n");
for (i = 1; i < 1000000; i++) {
double j = sqrt(nonsqr(i));
assert(j != floor(j));
}
return 0;
}
|
Port the following code from C++ to C with equivalent syntax and logic. | #include <iostream>
#include <string>
int main()
{
std::string s = "0123456789";
int const n = 3;
int const m = 4;
char const c = '2';
std::string const sub = "456";
std::cout << s.substr(n, m)<< "\n";
std::cout << s.substr(n) << "\n";
std::cout << s.substr(0, s.size()-1) << "\n";
std::cout << s.substr(s.find(c), m) << "\n";
std::cout << s.substr(s.find(sub), m) << "\n";
}
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void putm(char* string, size_t m)
{
while(*string && m--)
putchar(*string++);
}
int main(void)
{
char string[] =
"Programs for other encodings (such as 8-bit ASCII, or EUC-JP)."
int n = 3;
int m = 4;
char knownCharacter = '(';
char knownSubstring[] = "encodings";
putm(string+n-1, m ); putchar('\n');
puts(string+n+1); putchar('\n');
putm(string, strlen(string)-1); putchar('\n');
putm(strchr(string, knownCharacter), m ); putchar('\n');
putm(strstr(string, knownSubstring), m ); putchar('\n');
return EXIT_SUCCESS;
}
|
Ensure the translated C code behaves exactly like the original C++ snippet. | #include <algorithm>
#include <string>
#include <iostream>
#include <iterator>
class jortSort {
public:
template<class T>
bool jort_sort( T* o, size_t s ) {
T* n = copy_array( o, s );
sort_array( n, s );
bool r = false;
if( n ) {
r = check( o, n, s );
delete [] n;
}
return r;
}
private:
template<class T>
T* copy_array( T* o, size_t s ) {
T* z = new T[s];
memcpy( z, o, s * sizeof( T ) );
return z;
}
template<class T>
void sort_array( T* n, size_t s ) {
std::sort( n, n + s );
}
template<class T>
bool check( T* n, T* o, size_t s ) {
for( size_t x = 0; x < s; x++ )
if( n[x] != o[x] ) return false;
return true;
}
};
jortSort js;
template<class T>
void displayTest( T* o, size_t s ) {
std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) );
std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n";
}
int main( int argc, char* argv[] ) {
const size_t s = 5;
std::string oStr[] = { "5", "A", "D", "R", "S" };
displayTest( oStr, s );
std::swap( oStr[0], oStr[1] );
displayTest( oStr, s );
int oInt[] = { 1, 2, 3, 4, 5 };
displayTest( oInt, s );
std::swap( oInt[0], oInt[1] );
displayTest( oInt, s );
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
int number_of_digits(int x){
int NumberOfDigits;
for(NumberOfDigits=0;x!=0;NumberOfDigits++){
x=x/10;
}
return NumberOfDigits;
}
int* convert_array(char array[], int NumberOfElements)
{
int *convertedArray=malloc(NumberOfElements*sizeof(int));
int originalElement, convertedElement;
for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)
{
convertedArray[convertedElement]=atoi(&array[originalElement]);
originalElement+=number_of_digits(convertedArray[convertedElement])+1;
}
return convertedArray;
}
int isSorted(int array[], int numberOfElements){
int sorted=1;
for(int counter=0;counter<numberOfElements;counter++){
if(counter!=0 && array[counter-1]>array[counter]) sorted--;
}
return sorted;
}
int main(int argc, char* argv[])
{
int* convertedArray;
convertedArray=convert_array(*(argv+1), argc-1);
if(isSorted(convertedArray, argc-1)==1) printf("Did you forgot to turn on your brain?! This array is already sorted!\n");
else if(argc-1<=10) printf("Am I really supposed to sort this? Sort it by yourself!\n");
else printf("Am I really supposed to sort this? Bhahahaha!\n");
free(convertedArray);
return 0;
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #include <iostream>
bool is_leap_year(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
int main() {
for (auto year : {1900, 1994, 1996, 1997, 2000}) {
std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n";
}
}
| #include <stdio.h>
int is_leap_year(unsigned year)
{
return !(year & (year % 100 ? 3 : 15));
}
int main(void)
{
const unsigned test_case[] = {
1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100
};
const unsigned n = sizeof test_case / sizeof test_case[0];
for (unsigned i = 0; i != n; ++i) {
unsigned year = test_case[i];
printf("%u is %sa leap year.\n", year, is_leap_year(year) ? "" : "not ");
}
return 0;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <boost/multiprecision/gmp.hpp>
#include <iostream>
using namespace boost::multiprecision;
mpz_int p(uint n, uint p) {
mpz_int r = 1;
mpz_int k = n - p;
while (n > k)
r *= n--;
return r;
}
mpz_int c(uint n, uint k) {
mpz_int r = p(n, k);
while (k)
r /= k--;
return r;
}
int main() {
for (uint i = 1u; i < 12u; i++)
std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl;
for (uint i = 10u; i < 60u; i += 10u)
std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl;
return 0;
}
| #include <gmp.h>
void perm(mpz_t out, int n, int k)
{
mpz_set_ui(out, 1);
k = n - k;
while (n > k) mpz_mul_ui(out, out, n--);
}
void comb(mpz_t out, int n, int k)
{
perm(out, n, k);
while (k) mpz_divexact_ui(out, out, k--);
}
int main(void)
{
mpz_t x;
mpz_init(x);
perm(x, 1000, 969);
gmp_printf("P(1000,969) = %Zd\n", x);
comb(x, 1000, 969);
gmp_printf("C(1000,969) = %Zd\n", x);
return 0;
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
void lexicographical_sort(std::vector<int>& numbers) {
std::vector<std::string> strings(numbers.size());
std::transform(numbers.begin(), numbers.end(), strings.begin(),
[](int i) { return std::to_string(i); });
std::sort(strings.begin(), strings.end());
std::transform(strings.begin(), strings.end(), numbers.begin(),
[](const std::string& s) { return std::stoi(s); });
}
std::vector<int> lexicographically_sorted_vector(int n) {
std::vector<int> numbers(n >= 1 ? n : 2 - n);
std::iota(numbers.begin(), numbers.end(), std::min(1, n));
lexicographical_sort(numbers);
return numbers;
}
template <typename T>
void print_vector(std::ostream& out, const std::vector<T>& v) {
out << '[';
if (!v.empty()) {
auto i = v.begin();
out << *i++;
for (; i != v.end(); ++i)
out << ',' << *i;
}
out << "]\n";
}
int main(int argc, char** argv) {
for (int i : { 0, 5, 13, 21, -22 }) {
std::cout << i << ": ";
print_vector(std::cout, lexicographically_sorted_vector(i));
}
return 0;
}
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compareStrings(const void *a, const void *b) {
const char **aa = (const char **)a;
const char **bb = (const char **)b;
return strcmp(*aa, *bb);
}
void lexOrder(int n, int *ints) {
char **strs;
int i, first = 1, last = n, k = n, len;
if (n < 1) {
first = n; last = 1; k = 2 - n;
}
strs = malloc(k * sizeof(char *));
for (i = first; i <= last; ++i) {
if (i >= 1) len = (int)log10(i) + 2;
else if (i == 0) len = 2;
else len = (int)log10(-i) + 3;
strs[i-first] = malloc(len);
sprintf(strs[i-first], "%d", i);
}
qsort(strs, k, sizeof(char *), compareStrings);
for (i = 0; i < k; ++i) {
ints[i] = atoi(strs[i]);
free(strs[i]);
}
free(strs);
}
int main() {
int i, j, k, n, *ints;
int numbers[5] = {0, 5, 13, 21, -22};
printf("In lexicographical order:\n\n");
for (i = 0; i < 5; ++i) {
k = n = numbers[i];
if (k < 1) k = 2 - k;
ints = malloc(k * sizeof(int));
lexOrder(n, ints);
printf("%3d: [", n);
for (j = 0; j < k; ++j) {
printf("%d ", ints[j]);
}
printf("\b]\n");
free(ints);
}
return 0;
}
|
Convert this C++ block to C, preserving its control flow and logic. | #include <string>
#include <iostream>
using std::string;
const char* smallNumbers[] = {
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
string spellHundreds(unsigned n) {
string res;
if (n > 99) {
res = smallNumbers[n/100];
res += " hundred";
n %= 100;
if (n) res += " and ";
}
if (n >= 20) {
static const char* Decades[] = {
"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"
};
res += Decades[n/10];
n %= 10;
if (n) res += "-";
}
if (n < 20 && n > 0)
res += smallNumbers[n];
return res;
}
const char* thousandPowers[] = {
" billion", " million", " thousand", "" };
typedef unsigned long Spellable;
string spell(Spellable n) {
if (n < 20) return smallNumbers[n];
string res;
const char** pScaleName = thousandPowers;
Spellable scaleFactor = 1000000000;
while (scaleFactor > 0) {
if (n >= scaleFactor) {
Spellable h = n / scaleFactor;
res += spellHundreds(h) + *pScaleName;
n %= scaleFactor;
if (n) res += ", ";
}
scaleFactor /= 1000;
++pScaleName;
}
return res;
}
int main() {
#define SPELL_IT(x) std::cout << #x " " << spell(x) << std::endl;
SPELL_IT( 99);
SPELL_IT( 300);
SPELL_IT( 310);
SPELL_IT( 1501);
SPELL_IT( 12609);
SPELL_IT( 512609);
SPELL_IT(43112609);
SPELL_IT(1234567890);
return 0;
}
| #include <stdio.h>
#include <string.h>
const char *ones[] = { 0, "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
const char *tens[] = { 0, "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
const char *llions[] = { 0, "thousand", "million", "billion", "trillion",
};
const int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3;
int say_hundred(const char *s, int len, int depth, int has_lead)
{
int c[3], i;
for (i = -3; i < 0; i++) {
if (len + i >= 0) c[i + 3] = s[len + i] - '0';
else c[i + 3] = 0;
}
if (!(c[0] + c[1] + c[2])) return 0;
if (c[0]) {
printf("%s hundred", ones[c[0]]);
has_lead = 1;
}
if (has_lead && (c[1] || c[2]))
printf((!depth || c[0]) && (!c[0] || !c[1]) ? "and " :
c[0] ? " " : "");
if (c[1] < 2) {
if (c[1] || c[2]) printf("%s", ones[c[1] * 10 + c[2]]);
} else {
if (c[1]) {
printf("%s", tens[c[1]]);
if (c[2]) putchar('-');
}
if (c[2]) printf("%s", ones[c[2]]);
}
return 1;
}
int say_maxillion(const char *s, int len, int depth, int has_lead)
{
int n = len / 3, r = len % 3;
if (!r) {
n--;
r = 3;
}
const char *e = s + r;
do {
if (say_hundred(s, r, n, has_lead) && n) {
has_lead = 1;
printf(" %s", llions[n]);
if (!depth) printf(", ");
else printf(" ");
}
s = e; e += 3;
} while (r = 3, n--);
return 1;
}
void say_number(const char *s)
{
int len, i, got_sign = 0;
while (*s == ' ') s++;
if (*s < '0' || *s > '9') {
if (*s == '-') got_sign = -1;
else if (*s == '+') got_sign = 1;
else goto nan;
s++;
} else
got_sign = 1;
while (*s == '0') {
s++;
if (*s == '\0') {
printf("zero\n");
return;
}
}
len = strlen(s);
if (!len) goto nan;
for (i = 0; i < len; i++) {
if (s[i] < '0' || s[i] > '9') {
printf("(not a number)");
return;
}
}
if (got_sign == -1) printf("minus ");
int n = len / maxillion;
int r = len % maxillion;
if (!r) {
r = maxillion;
n--;
}
const char *end = s + len - n * maxillion;
int has_lead = 0;
do {
if ((has_lead = say_maxillion(s, r, n, has_lead))) {
for (i = 0; i < n; i++)
printf(" %s", llions[maxillion / 3]);
if (n) printf(", ");
}
n--;
r = maxillion;
s = end;
end += r;
} while (n >= 0);
printf("\n");
return;
nan: printf("not a number\n");
return;
}
int main()
{
say_number("-42");
say_number("1984");
say_number("10000");
say_number("1024");
say_number("1001001001001");
say_number("123456789012345678901234567890123456789012345678900000001");
return 0;
}
|
Translate the given C++ code snippet into C without altering its behavior. | #include <iostream>
#include <algorithm>
#include <string>
#include <list>
using namespace std;
bool cmp(const string& a, const string& b)
{
return b.length() < a.length();
}
void compareAndReportStringsLength(list<string> listOfStrings)
{
if (!listOfStrings.empty())
{
char Q = '"';
string has_length(" has length ");
string predicate_max(" and is the longest string");
string predicate_min(" and is the shortest string");
string predicate_ave(" and is neither the longest nor the shortest string");
list<string> ls(listOfStrings);
ls.sort(cmp);
int max = ls.front().length();
int min = ls.back().length();
for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)
{
int length = s->length();
string* predicate;
if (length == max)
predicate = &predicate_max;
else if (length == min)
predicate = &predicate_min;
else
predicate = &predicate_ave;
cout << Q << *s << Q << has_length << length << *predicate << endl;
}
}
}
int main(int argc, char* argv[])
{
list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(listOfStrings);
return EXIT_SUCCESS;
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const int* a, const int* b)
{
return *b - *a;
}
void compareAndReportStringsLength(const char* strings[], const int n)
{
if (n > 0)
{
char* has_length = "has length";
char* predicate_max = "and is the longest string";
char* predicate_min = "and is the shortest string";
char* predicate_ave = "and is neither the longest nor the shortest string";
int* si = malloc(2 * n * sizeof(int));
if (si != NULL)
{
for (int i = 0; i < n; i++)
{
si[2 * i] = strlen(strings[i]);
si[2 * i + 1] = i;
}
qsort(si, n, 2 * sizeof(int), cmp);
int max = si[0];
int min = si[2 * (n - 1)];
for (int i = 0; i < n; i++)
{
int length = si[2 * i];
char* string = strings[si[2 * i + 1]];
char* predicate;
if (length == max)
predicate = predicate_max;
else if (length == min)
predicate = predicate_min;
else
predicate = predicate_ave;
printf("\"%s\" %s %d %s\n",
string, has_length, length, predicate);
}
free(si);
}
else
{
fputs("unable allocate memory buffer", stderr);
}
}
}
int main(int argc, char* argv[])
{
char* list[] = { "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(list, 4);
return EXIT_SUCCESS;
}
|
Write the same code in C as shown below in C++. | #include <time.h>
#include <iostream>
using namespace std;
const int MAX = 126;
class shell
{
public:
shell()
{ _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }
void sort( int* a, int count )
{
_cnt = count;
for( int x = 0; x < 9; x++ )
if( count > _gap[x] )
{ _idx = x; break; }
sortIt( a );
}
private:
void sortIt( int* arr )
{
bool sorted = false;
while( true )
{
sorted = true;
int st = 0;
for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )
{
if( arr[st] > arr[x] )
{ swap( arr[st], arr[x] ); sorted = false; }
st = x;
}
if( ++_idx >= 8 ) _idx = 8;
if( sorted && _idx == 8 ) break;
}
}
void swap( int& a, int& b ) { int t = a; a = b; b = t; }
int _gap[9], _idx, _cnt;
};
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];
for( int x = 0; x < MAX; x++ )
arr[x] = rand() % MAX - rand() % MAX;
cout << " Before: \n=========\n";
for( int x = 0; x < 7; x++ )
{
for( int a = 0; a < 18; a++ )
{ cout << arr[x * 18 + a] << " "; }
cout << endl;
}
cout << endl; shell s; s.sort( arr, MAX );
cout << " After: \n========\n";
for( int x = 0; x < 7; x++ )
{
for( int a = 0; a < 18; a++ )
{ cout << arr[x * 18 + a] << " "; }
cout << endl;
}
cout << endl << endl; return system( "pause" );
}
| #include <stdio.h>
void shell_sort (int *a, int n) {
int h, i, j, t;
for (h = n; h /= 2;) {
for (i = h; i < n; i++) {
t = a[i];
for (j = i; j >= h && t < a[j - h]; j -= h) {
a[j] = a[j - h];
}
a[j] = t;
}
}
}
int main (int ac, char **av) {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
shell_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
|
Write the same algorithm in C as shown in this C++ implementation. | #include <iostream>
#include <list>
int main ()
{
std::list<int> numbers {1, 5, 7, 0, 3, 2};
numbers.insert(numbers.begin(), 9);
numbers.insert(numbers.end(), 4);
auto it = std::next(numbers.begin(), numbers.size() / 2);
numbers.insert(it, 6);
for(const auto& i: numbers)
std::cout << i << ' ';
std::cout << '\n';
}
|
#include <stdio.h>
#include <stdlib.h>
struct List {
struct MNode *head;
struct MNode *tail;
struct MNode *tail_pred;
};
struct MNode {
struct MNode *succ;
struct MNode *pred;
};
typedef struct MNode *NODE;
typedef struct List *LIST;
LIST newList(void);
int isEmpty(LIST);
NODE getTail(LIST);
NODE getHead(LIST);
NODE addTail(LIST, NODE);
NODE addHead(LIST, NODE);
NODE remHead(LIST);
NODE remTail(LIST);
NODE insertAfter(LIST, NODE, NODE);
NODE removeNode(LIST, NODE);
LIST newList(void)
{
LIST tl = malloc(sizeof(struct List));
if ( tl != NULL )
{
tl->tail_pred = (NODE)&tl->head;
tl->tail = NULL;
tl->head = (NODE)&tl->tail;
return tl;
}
return NULL;
}
int isEmpty(LIST l)
{
return (l->head->succ == 0);
}
NODE getHead(LIST l)
{
return l->head;
}
NODE getTail(LIST l)
{
return l->tail_pred;
}
NODE addTail(LIST l, NODE n)
{
n->succ = (NODE)&l->tail;
n->pred = l->tail_pred;
l->tail_pred->succ = n;
l->tail_pred = n;
return n;
}
NODE addHead(LIST l, NODE n)
{
n->succ = l->head;
n->pred = (NODE)&l->head;
l->head->pred = n;
l->head = n;
return n;
}
NODE remHead(LIST l)
{
NODE h;
h = l->head;
l->head = l->head->succ;
l->head->pred = (NODE)&l->head;
return h;
}
NODE remTail(LIST l)
{
NODE t;
t = l->tail_pred;
l->tail_pred = l->tail_pred->pred;
l->tail_pred->succ = (NODE)&l->tail;
return t;
}
NODE insertAfter(LIST l, NODE r, NODE n)
{
n->pred = r; n->succ = r->succ;
n->succ->pred = n; r->succ = n;
return n;
}
NODE removeNode(LIST l, NODE n)
{
n->pred->succ = n->succ;
n->succ->pred = n->pred;
return n;
}
|
Port the following code from C++ to C with equivalent syntax and logic. | #include <fstream>
#include <iostream>
int main()
{
std::ifstream input("filename.txt", std::ios_base::binary);
if (!input)
{
std::cerr << "error: can't open file\n";
return -1;
}
size_t count[256];
std::fill_n(count, 256, 0);
for (char c; input.get(c); ++count[uint8_t(c)])
;
for (size_t i = 0; i < 256; ++i)
{
if (count[i] && isgraph(i))
{
std::cout << char(i) << " = " << count[i] << '\n';
}
}
}
|
int frequency[26];
int ch;
FILE* txt_file = fopen ("a_text_file.txt", "rt");
for (ch = 0; ch < 26; ch++)
frequency[ch] = 0;
while (1) {
ch = fgetc(txt_file);
if (ch == EOF) break;
if ('a' <= ch && ch <= 'z')
frequency[ch-'a']++;
else if ('A' <= ch && ch <= 'Z')
frequency[ch-'A']++;
}
|
Write a version of this C++ function in C with identical behavior. | #include<iostream>
#include<vector>
#include<numeric>
#include<functional>
class
{
public:
int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}
private:
int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }
int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}
}combinations;
int main()
{
static constexpr int treatment = 9;
const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };
int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);
std::function<int (int, int, int)> pick;
pick = [&](int n, int from, int accumulated)
{
if(n == 0)
return accumulated > treated ? 1 : 0;
else
return pick(n - 1, from - 1, accumulated + data[from - 1]) +
(from > n ? pick(n, from - 1, accumulated) : 0);
};
int total = combinations(data.size(), treatment);
int greater = pick(treatment, data.size(), 0);
int lesser = total - greater;
std::cout << "<= : " << 100.0 * lesser / total << "% " << lesser << std::endl
<< " > : " << 100.0 * greater / total << "% " << greater << std::endl;
}
| #include <stdio.h>
int data[] = { 85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };
int pick(int at, int remain, int accu, int treat)
{
if (!remain) return (accu > treat) ? 1 : 0;
return pick(at - 1, remain - 1, accu + data[at - 1], treat) +
( at > remain ? pick(at - 1, remain, accu, treat) : 0 );
}
int main()
{
int treat = 0, i;
int le, gt;
double total = 1;
for (i = 0; i < 9; i++) treat += data[i];
for (i = 19; i > 10; i--) total *= i;
for (i = 9; i > 0; i--) total /= i;
gt = pick(19, 9, 0, treat);
le = total - gt;
printf("<= : %f%% %d\n > : %f%% %d\n",
100 * le / total, le, 100 * gt / total, gt);
return 0;
}
|
Translate this program into C but keep the logic exactly as in C++. | #include <iomanip>
#include <iostream>
#include <vector>
constexpr int MU_MAX = 1'000'000;
std::vector<int> MU;
int mobiusFunction(int n) {
if (!MU.empty()) {
return MU[n];
}
MU.resize(MU_MAX + 1, 1);
int root = sqrt(MU_MAX);
for (int i = 2; i <= root; i++) {
if (MU[i] == 1) {
for (int j = i; j <= MU_MAX; j += i) {
MU[j] *= -i;
}
for (int j = i * i; j <= MU_MAX; j += i * i) {
MU[j] = 0;
}
}
}
for (int i = 2; i <= MU_MAX; i++) {
if (MU[i] == i) {
MU[i] = 1;
} else if (MU[i] == -i) {
MU[i] = -1;
} else if (MU[i] < 0) {
MU[i] = 1;
} else if (MU[i] > 0) {
MU[i] = -1;
}
}
return MU[n];
}
int main() {
std::cout << "First 199 terms of the möbius function are as follows:\n ";
for (int n = 1; n < 200; n++) {
std::cout << std::setw(2) << mobiusFunction(n) << " ";
if ((n + 1) % 20 == 0) {
std::cout << '\n';
}
}
return 0;
}
| #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
const int MU_MAX = 1000000;
int i, j;
int *mu;
int sqroot;
sqroot = (int)sqrt(MU_MAX);
mu = malloc((MU_MAX + 1) * sizeof(int));
for (i = 0; i < MU_MAX;i++) {
mu[i] = 1;
}
for (i = 2; i <= sqroot; i++) {
if (mu[i] == 1) {
for (j = i; j <= MU_MAX; j += i) {
mu[j] *= -i;
}
for (j = i * i; j <= MU_MAX; j += i * i) {
mu[j] = 0;
}
}
}
for (i = 2; i <= MU_MAX; i++) {
if (mu[i] == i) {
mu[i] = 1;
} else if (mu[i] == -i) {
mu[i] = -1;
} else if (mu[i] < 0) {
mu[i] = 1;
} else if (mu[i] > 0) {
mu[i] = -1;
}
}
printf("First 199 terms of the möbius function are as follows:\n ");
for (i = 1; i < 200; i++) {
printf("%2d ", mu[i]);
if ((i + 1) % 20 == 0) {
printf("\n");
}
}
free(mu);
return 0;
}
|
Can you help me rewrite this code in C instead of C++, keeping it the same logically? |
#include <cstdlib>
#include <string>
#include <sstream>
std::string s = "12345";
int i;
std::istringstream(s) >> i;
i++;
std::ostringstream oss;
if (oss << i) s = oss.str();
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * incr(char *s)
{
int i, begin, tail, len;
int neg = (*s == '-');
char tgt = neg ? '0' : '9';
if (!strcmp(s, "-1")) {
s[0] = '0', s[1] = '\0';
return s;
}
len = strlen(s);
begin = (*s == '-' || *s == '+') ? 1 : 0;
for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);
if (tail < begin && !neg) {
if (!begin) s = realloc(s, len + 2);
s[0] = '1';
for (i = 1; i <= len - begin; i++) s[i] = '0';
s[len + 1] = '\0';
} else if (tail == begin && neg && s[1] == '1') {
for (i = 1; i < len - begin; i++) s[i] = '9';
s[len - 1] = '\0';
} else {
for (i = len - 1; i > tail; i--)
s[i] = neg ? '9' : '0';
s[tail] += neg ? -1 : 1;
}
return s;
}
void string_test(const char *s)
{
char *ret = malloc(strlen(s));
strcpy(ret, s);
printf("text: %s\n", ret);
printf(" ->: %s\n", ret = incr(ret));
free(ret);
}
int main()
{
string_test("+0");
string_test("-1");
string_test("-41");
string_test("+41");
string_test("999");
string_test("+999");
string_test("109999999999999999999999999999999999999999");
string_test("-100000000000000000000000000000000000000000000");
return 0;
}
|
Port the provided C++ code into C while preserving the original functionality. | #include <algorithm>
#include <iostream>
#include <string>
std::string stripchars(std::string str, const std::string &chars)
{
str.erase(
std::remove_if(str.begin(), str.end(), [&](char c){
return chars.find(c) != std::string::npos;
}),
str.end()
);
return str;
}
int main()
{
std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n';
return 0;
}
| #include <string.h>
#include <stdio.h>
#include <stdlib.h>
char *strip_chars(const char *string, const char *chars)
{
char * newstr = malloc(strlen(string) + 1);
int counter = 0;
for ( ; *string; string++) {
if (!strchr(chars, *string)) {
newstr[ counter ] = *string;
++ counter;
}
}
newstr[counter] = 0;
return newstr;
}
int main(void)
{
char *new = strip_chars("She was a soul stripper. She took my heart!", "aei");
printf("%s\n", new);
free(new);
return 0;
}
|
Change the programming language of this snippet from C++ to C without modifying what it does. | #include <algorithm>
template<typename ForwardIterator>
void permutation_sort(ForwardIterator begin, ForwardIterator end)
{
while (std::next_permutation(begin, end))
{
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int(*cmp_func)(const void*, const void*);
void perm_sort(void *a, int n, size_t msize, cmp_func _cmp)
{
char *p, *q, *tmp = malloc(msize);
# define A(i) ((char *)a + msize * (i))
# define swap(a, b) {\
memcpy(tmp, a, msize);\
memcpy(a, b, msize);\
memcpy(b, tmp, msize); }
while (1) {
for (p = A(n - 1); (void*)p > a; p = q)
if (_cmp(q = p - msize, p) > 0)
break;
if ((void*)p <= a) break;
for (p = A(n - 1); p > q; p-= msize)
if (_cmp(q, p) > 0) break;
swap(p, q);
for (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)
swap(p, q);
}
free(tmp);
}
int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }
int main()
{
int i;
const char *strs[] = { "spqr", "abc", "giant squid", "stuff", "def" };
perm_sort(strs, 5, sizeof(*strs), scmp);
for (i = 0; i < 5; i++)
printf("%s\n", strs[i]);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from C++ to C. | #include <vector>
double mean(const std::vector<double>& numbers)
{
if (numbers.size() == 0)
return 0;
double sum = 0;
for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)
sum += *i;
return sum / numbers.size();
}
| #include <stdio.h>
double mean(double *v, int len)
{
double sum = 0;
int i;
for (i = 0; i < len; i++)
sum += v[i];
return sum / len;
}
int main(void)
{
double v[] = {1, 2, 2.718, 3, 3.142};
int i, len;
for (len = 5; len >= 0; len--) {
printf("mean[");
for (i = 0; i < len; i++)
printf(i ? ", %g" : "%g", v[i]);
printf("] = %g\n", mean(v, len));
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
bool parse_integer(const std::string& word, int& value) {
try {
size_t pos;
int i = std::stoi(word, &pos, 10);
if (pos < word.length())
return false;
value = i;
return true;
} catch (const std::exception& ex) {
return false;
}
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::istringstream is(table);
std::string word;
std::vector<std::string> words;
while (is >> word) {
uppercase(word);
words.push_back(word);
}
for (size_t i = 0, n = words.size(); i < n; ++i) {
word = words[i];
int len = word.length();
if (i + 1 < n && parse_integer(words[i + 1], len))
++i;
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
| #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
typedef struct command_tag {
char* cmd;
size_t length;
size_t min_len;
struct command_tag* next;
} command_t;
bool command_match(const command_t* command, const char* str) {
size_t olen = strlen(str);
return olen >= command->min_len && olen <= command->length
&& strncmp(str, command->cmd, olen) == 0;
}
char* uppercase(char* str, size_t n) {
for (size_t i = 0; i < n; ++i)
str[i] = toupper((unsigned char)str[i]);
return str;
}
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;
}
char** split_into_words(const char* str, size_t* count) {
size_t size = 0;
size_t capacity = 16;
char** words = xmalloc(capacity * sizeof(char*));
size_t len = strlen(str);
for (size_t begin = 0; begin < len; ) {
size_t i = begin;
for (; i < len && isspace((unsigned char)str[i]); ++i) {}
begin = i;
for (; i < len && !isspace((unsigned char)str[i]); ++i) {}
size_t word_len = i - begin;
if (word_len == 0)
break;
char* word = xmalloc(word_len + 1);
memcpy(word, str + begin, word_len);
word[word_len] = 0;
begin += word_len;
if (capacity == size) {
capacity *= 2;
words = xrealloc(words, capacity * sizeof(char*));
}
words[size++] = word;
}
*count = size;
return words;
}
command_t* make_command_list(const char* table) {
command_t* cmd = NULL;
size_t count = 0;
char** words = split_into_words(table, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
command_t* new_cmd = xmalloc(sizeof(command_t));
size_t word_len = strlen(word);
new_cmd->length = word_len;
new_cmd->min_len = word_len;
new_cmd->cmd = uppercase(word, word_len);
if (i + 1 < count) {
char* eptr = 0;
unsigned long min_len = strtoul(words[i + 1], &eptr, 10);
if (min_len > 0 && *eptr == 0) {
free(words[i + 1]);
new_cmd->min_len = min_len;
++i;
}
}
new_cmd->next = cmd;
cmd = new_cmd;
}
free(words);
return cmd;
}
void free_command_list(command_t* cmd) {
while (cmd != NULL) {
command_t* next = cmd->next;
free(cmd->cmd);
free(cmd);
cmd = next;
}
}
const command_t* find_command(const command_t* commands, const char* word) {
for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {
if (command_match(cmd, word))
return cmd;
}
return NULL;
}
void test(const command_t* commands, const char* input) {
printf(" input: %s\n", input);
printf("output:");
size_t count = 0;
char** words = split_into_words(input, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
uppercase(word, strlen(word));
const command_t* cmd_ptr = find_command(commands, word);
printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*");
free(word);
}
free(words);
printf("\n");
}
int main() {
command_t* commands = make_command_list(command_table);
const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
test(commands, input);
free_command_list(commands);
return 0;
}
|
Change the following C++ code into C without altering its purpose. | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
bool parse_integer(const std::string& word, int& value) {
try {
size_t pos;
int i = std::stoi(word, &pos, 10);
if (pos < word.length())
return false;
value = i;
return true;
} catch (const std::exception& ex) {
return false;
}
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::istringstream is(table);
std::string word;
std::vector<std::string> words;
while (is >> word) {
uppercase(word);
words.push_back(word);
}
for (size_t i = 0, n = words.size(); i < n; ++i) {
word = words[i];
int len = word.length();
if (i + 1 < n && parse_integer(words[i + 1], len))
++i;
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
| #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* command_table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
typedef struct command_tag {
char* cmd;
size_t length;
size_t min_len;
struct command_tag* next;
} command_t;
bool command_match(const command_t* command, const char* str) {
size_t olen = strlen(str);
return olen >= command->min_len && olen <= command->length
&& strncmp(str, command->cmd, olen) == 0;
}
char* uppercase(char* str, size_t n) {
for (size_t i = 0; i < n; ++i)
str[i] = toupper((unsigned char)str[i]);
return str;
}
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;
}
char** split_into_words(const char* str, size_t* count) {
size_t size = 0;
size_t capacity = 16;
char** words = xmalloc(capacity * sizeof(char*));
size_t len = strlen(str);
for (size_t begin = 0; begin < len; ) {
size_t i = begin;
for (; i < len && isspace((unsigned char)str[i]); ++i) {}
begin = i;
for (; i < len && !isspace((unsigned char)str[i]); ++i) {}
size_t word_len = i - begin;
if (word_len == 0)
break;
char* word = xmalloc(word_len + 1);
memcpy(word, str + begin, word_len);
word[word_len] = 0;
begin += word_len;
if (capacity == size) {
capacity *= 2;
words = xrealloc(words, capacity * sizeof(char*));
}
words[size++] = word;
}
*count = size;
return words;
}
command_t* make_command_list(const char* table) {
command_t* cmd = NULL;
size_t count = 0;
char** words = split_into_words(table, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
command_t* new_cmd = xmalloc(sizeof(command_t));
size_t word_len = strlen(word);
new_cmd->length = word_len;
new_cmd->min_len = word_len;
new_cmd->cmd = uppercase(word, word_len);
if (i + 1 < count) {
char* eptr = 0;
unsigned long min_len = strtoul(words[i + 1], &eptr, 10);
if (min_len > 0 && *eptr == 0) {
free(words[i + 1]);
new_cmd->min_len = min_len;
++i;
}
}
new_cmd->next = cmd;
cmd = new_cmd;
}
free(words);
return cmd;
}
void free_command_list(command_t* cmd) {
while (cmd != NULL) {
command_t* next = cmd->next;
free(cmd->cmd);
free(cmd);
cmd = next;
}
}
const command_t* find_command(const command_t* commands, const char* word) {
for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {
if (command_match(cmd, word))
return cmd;
}
return NULL;
}
void test(const command_t* commands, const char* input) {
printf(" input: %s\n", input);
printf("output:");
size_t count = 0;
char** words = split_into_words(input, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
uppercase(word, strlen(word));
const command_t* cmd_ptr = find_command(commands, word);
printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*");
free(word);
}
free(words);
printf("\n");
}
int main() {
command_t* commands = make_command_list(command_table);
const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
test(commands, input);
free_command_list(commands);
return 0;
}
|
Generate a C translation of this C++ snippet without changing its computational steps. | #include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>
double log2( double number ) {
return log( number ) / log( 2 ) ;
}
int main( int argc , char *argv[ ] ) {
std::string teststring( argv[ 1 ] ) ;
std::map<char , int> frequencies ;
for ( char c : teststring )
frequencies[ c ] ++ ;
int numlen = teststring.length( ) ;
double infocontent = 0 ;
for ( std::pair<char , int> p : frequencies ) {
double freq = static_cast<double>( p.second ) / numlen ;
infocontent -= freq * log2( freq ) ;
}
std::cout << "The information content of " << teststring
<< " is " << infocontent << std::endl ;
return 0 ;
}
| #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#define MAXLEN 100
int makehist(unsigned char *S,int *hist,int len){
int wherechar[256];
int i,histlen;
histlen=0;
for(i=0;i<256;i++)wherechar[i]=-1;
for(i=0;i<len;i++){
if(wherechar[(int)S[i]]==-1){
wherechar[(int)S[i]]=histlen;
histlen++;
}
hist[wherechar[(int)S[i]]]++;
}
return histlen;
}
double entropy(int *hist,int histlen,int len){
int i;
double H;
H=0;
for(i=0;i<histlen;i++){
H-=(double)hist[i]/len*log2((double)hist[i]/len);
}
return H;
}
int main(void){
unsigned char S[MAXLEN];
int len,*hist,histlen;
double H;
scanf("%[^\n]",S);
len=strlen(S);
hist=(int*)calloc(len,sizeof(int));
histlen=makehist(S,hist,len);
H=entropy(hist,histlen,len);
printf("%lf\n",H);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | #include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
vector<string> tokenize(const string& input, char seperator, char escape) {
vector<string> output;
string token;
bool inEsc = false;
for (char ch : input) {
if (inEsc) {
inEsc = false;
} else if (ch == escape) {
inEsc = true;
continue;
} else if (ch == seperator) {
output.push_back(token);
token = "";
continue;
}
token += ch;
}
if (inEsc)
throw new invalid_argument("Invalid terminal escape");
output.push_back(token);
return output;
}
int main() {
string sample = "one^|uno||three^^^^|four^^^|^cuatro|";
cout << sample << endl;
cout << '[';
for (auto t : tokenize(sample, '|', '^')) {
cout << '"' << t << "\", ";
}
cout << ']' << endl;
return 0;
}
| #include <stdlib.h>
#include <stdio.h>
#define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|"
#define SEP '|'
#define ESC '^'
typedef char* Str;
unsigned int ElQ( const char *s, char sep, char esc );
Str *Tokenize( char *s, char sep, char esc, unsigned int *q );
int main() {
char s[] = STR_DEMO;
unsigned int i, q;
Str *list = Tokenize( s, SEP, ESC, &q );
if( list != NULL ) {
printf( "\n Original string: %s\n\n", STR_DEMO );
printf( " %d tokens:\n\n", q );
for( i=0; i<q; ++i )
printf( " %4d. %s\n", i+1, list[i] );
free( list );
}
return 0;
}
unsigned int ElQ( const char *s, char sep, char esc ) {
unsigned int q, e;
const char *p;
for( e=0, q=1, p=s; *p; ++p ) {
if( *p == esc )
e = !e;
else if( *p == sep )
q += !e;
else e = 0;
}
return q;
}
Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) {
Str *list = NULL;
*q = ElQ( s, sep, esc );
list = malloc( *q * sizeof(Str) );
if( list != NULL ) {
unsigned int e, i;
char *p;
i = 0;
list[i++] = s;
for( e=0, p=s; *p; ++p ) {
if( *p == esc ) {
e = !e;
}
else if( *p == sep && !e ) {
list[i++] = p+1;
*p = '\0';
}
else {
e = 0;
}
}
}
return list;
}
|
Change the following C++ code into C without altering its purpose. | #include <iostream>
int main () {
std::cout << "Hello world!" << std::endl;
}
| const hello = "Hello world!\n"
print(hello)
|
Port the provided C code into PHP while preserving the original functionality. | void bitwise(int a, int b)
{
printf("a and b: %d\n", a & b);
printf("a or b: %d\n", a | b);
printf("a xor b: %d\n", a ^ b);
printf("not a: %d\n", ~a);
printf("a << n: %d\n", a << b);
printf("a >> n: %d\n", a >> b);
unsigned int c = a;
printf("c >> b: %d\n", c >> b);
return 0;
}
| function bitwise($a, $b)
{
function zerofill($a,$b) {
if($a>=0) return $a>>$b;
if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens
return ((~$a)>>$b)^(0x7fffffff>>($b-1));
echo '$a AND $b: ' . $a & $b . '\n';
echo '$a OR $b: ' . $a | $b . '\n';
echo '$a XOR $b: ' . $a ^ $b . '\n';
echo 'NOT $a: ' . ~$a . '\n';
echo '$a << $b: ' . $a << $b . '\n'; // left shift
echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift
}
|
Convert this C snippet to PHP and keep its semantics consistent. |
#include <conio.h>
#include <stdio.h>
int main()
{
int n1, n2, n3;
printf( "\n Introduzca el primer n%cmero (entero): ", 163 );
scanf( "%d", &n1 );
printf( "\n Introduzca el segundo n%cmero (entero): ", 163 );
scanf( "%d", &n2 );
printf( "\n Introduzca el tercer n%cmero (entero): ", 163 );
scanf( "%d", &n3 );
if ( n1 >= n2 && n1 >= n3 )
printf( "\n %d es el mayor.", n1 );
else
if ( n2 > n3 )
printf( "\n %d es el mayor.", n2 );
else
printf( "\n %d es el mayor.", n3 );
getch();
return 0;
}
| <?php
$file = fopen(__FILE__, 'r'); // read current file
while ($line = fgets($file)) {
$line = rtrim($line); // removes linebreaks and spaces at end
echo strrev($line) . "\n"; // reverse line and upload it
}
|
Can you help me rewrite this code in PHP instead of C, keeping it the same logically? | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
char *to_base(int64_t num, int base)
{
char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz";
char buf[66] = {'\0'};
char *out;
uint64_t n;
int i, len = 0, neg = 0;
if (base > 36) {
fprintf(stderr, "base %d too large\n", base);
return 0;
}
n = ((neg = num < 0)) ? (~num) + 1 : num;
do { buf[len++] = tbl[n % base]; } while(n /= base);
out = malloc(len + neg + 1);
for (i = neg; len > 0; i++) out[i] = buf[--len];
if (neg) out[0] = '-';
return out;
}
long from_base(const char *num_str, int base)
{
char *endptr;
int result = strtol(num_str, &endptr, base);
return result;
}
int main()
{
int64_t x;
x = ~(1LL << 63) + 1;
printf("%lld in base 2: %s\n", x, to_base(x, 2));
x = 383;
printf("%lld in base 16: %s\n", x, to_base(x, 16));
return 0;
}
| base_convert("26", 10, 16); // returns "1a"
|
Can you help me rewrite this code in PHP instead of C, keeping it the same logically? | #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
| function findFiles($dir = '.', $pattern = '/./'){
$prefix = $dir . '/';
$dir = dir($dir);
while (false !== ($file = $dir->read())){
if ($file === '.' || $file === '..') continue;
$file = $prefix . $file;
if (is_dir($file)) findFiles($file, $pattern);
if (preg_match($pattern, $file)){
echo $file . "\n";
}
}
}
findFiles('./foo', '/\.bar$/');
|
Generate an equivalent PHP version of this C code. | #include <stdio.h>
#include <string.h>
#include <zlib.h>
int main()
{
const char *s = "The quick brown fox jumps over the lazy dog";
printf("%lX\n", crc32(0, (const void*)s, strlen(s)));
return 0;
}
| printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));
|
Write a version of this C function in PHP with identical behavior. | #include <stdlib.h>
typedef struct sMyClass
{
int variable;
} *MyClass;
MyClass MyClass_new()
{
MyClass pthis = malloc(sizeof *pthis);
pthis->variable = 0;
return pthis;
}
void MyClass_delete(MyClass* pthis)
{
if (pthis)
{
free(*pthis);
*pthis = NULL;
}
}
void MyClass_someMethod(MyClass pthis)
{
pthis->variable = 1;
}
MyClass obj = MyClass_new();
MyClass_someMethod(obj);
MyClass_delete(&obj);
| class MyClass {
public static $classVar;
public $instanceVar; // can also initialize it here
function __construct() {
$this->instanceVar = 0;
}
function someMethod() {
$this->instanceVar = 1;
self::$classVar = 3;
}
}
$myObj = new MyClass();
|
Port the following code from C to PHP with equivalent syntax and logic. | #include <stdio.h>
#include <stdint.h>
typedef uint64_t ulong;
int kaprekar(ulong n, int base)
{
ulong nn = n * n, r, tens = 1;
if ((nn - n) % (base - 1)) return 0;
while (tens < n) tens *= base;
if (n == tens) return 1 == n;
while ((r = nn % tens) < n) {
if (nn / tens + r == n) return tens;
tens *= base;
}
return 0;
}
void print_num(ulong n, int base)
{
ulong q, div = base;
while (div < n) div *= base;
while (n && (div /= base)) {
q = n / div;
if (q < 10) putchar(q + '0');
else putchar(q + 'a' - 10);
n -= q * div;
}
}
int main()
{
ulong i, tens;
int cnt = 0;
int base = 10;
printf("base 10:\n");
for (i = 1; i < 1000000; i++)
if (kaprekar(i, base))
printf("%3d: %llu\n", ++cnt, i);
base = 17;
printf("\nbase %d:\n 1: 1\n", base);
for (i = 2, cnt = 1; i < 1000000; i++)
if ((tens = kaprekar(i, base))) {
printf("%3d: %llu", ++cnt, i);
printf(" \t"); print_num(i, base);
printf("\t"); print_num(i * i, base);
printf("\t"); print_num(i * i / tens, base);
printf(" + "); print_num(i * i % tens, base);
printf("\n");
}
return 0;
}
| set_time_limit(300);
print_r(array_filter(range(1, 10000), 'isKaprekar'));
echo count(array_filter(range(1, 1000000), 'isKaprekar'));
function isKaprekar($n) {
$a = $n * $n;
$b = bcmod("$a", "10");
for ($d = 1, $t = 0; $a > 0; $d *= 10) {
$b += $t * $d;
if ($b > $n) break;
$a = floor($a / 10);
if ($b && $a + $b == $n)
return true;
$t = bcmod("$a", "10");
}
return false;
}
|
Maintain the same structure and functionality when rewriting this code in PHP. | #include <stdio.h>
#include <stdint.h>
typedef uint64_t ulong;
int kaprekar(ulong n, int base)
{
ulong nn = n * n, r, tens = 1;
if ((nn - n) % (base - 1)) return 0;
while (tens < n) tens *= base;
if (n == tens) return 1 == n;
while ((r = nn % tens) < n) {
if (nn / tens + r == n) return tens;
tens *= base;
}
return 0;
}
void print_num(ulong n, int base)
{
ulong q, div = base;
while (div < n) div *= base;
while (n && (div /= base)) {
q = n / div;
if (q < 10) putchar(q + '0');
else putchar(q + 'a' - 10);
n -= q * div;
}
}
int main()
{
ulong i, tens;
int cnt = 0;
int base = 10;
printf("base 10:\n");
for (i = 1; i < 1000000; i++)
if (kaprekar(i, base))
printf("%3d: %llu\n", ++cnt, i);
base = 17;
printf("\nbase %d:\n 1: 1\n", base);
for (i = 2, cnt = 1; i < 1000000; i++)
if ((tens = kaprekar(i, base))) {
printf("%3d: %llu", ++cnt, i);
printf(" \t"); print_num(i, base);
printf("\t"); print_num(i * i, base);
printf("\t"); print_num(i * i / tens, base);
printf(" + "); print_num(i * i % tens, base);
printf("\n");
}
return 0;
}
| set_time_limit(300);
print_r(array_filter(range(1, 10000), 'isKaprekar'));
echo count(array_filter(range(1, 1000000), 'isKaprekar'));
function isKaprekar($n) {
$a = $n * $n;
$b = bcmod("$a", "10");
for ($d = 1, $t = 0; $a > 0; $d *= 10) {
$b += $t * $d;
if ($b > $n) break;
$a = floor($a / 10);
if ($b && $a + $b == $n)
return true;
$t = bcmod("$a", "10");
}
return false;
}
|
Produce a language-to-language conversion: from C to PHP, same semantics. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
void* mem_alloc(size_t item_size, size_t n_item)
{
size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size);
x[0] = item_size;
x[1] = n_item;
return x + 2;
}
void* mem_extend(void *m, size_t new_n)
{
size_t *x = (size_t*)m - 2;
x = realloc(x, sizeof(size_t) * 2 + *x * new_n);
if (new_n > x[1])
memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1]));
x[1] = new_n;
return x + 2;
}
inline void _clear(void *m)
{
size_t *x = (size_t*)m - 2;
memset(m, 0, x[0] * x[1]);
}
#define _new(type, n) mem_alloc(sizeof(type), n)
#define _del(m) { free((size_t*)(m) - 2); m = 0; }
#define _len(m) *((size_t*)m - 1)
#define _setsize(m, n) m = mem_extend(m, n)
#define _extend(m) m = mem_extend(m, _len(m) * 2)
typedef uint8_t byte;
typedef uint16_t ushort;
#define M_CLR 256
#define M_EOD 257
#define M_NEW 258
typedef struct {
ushort next[256];
} lzw_enc_t;
typedef struct {
ushort prev, back;
byte c;
} lzw_dec_t;
byte* lzw_encode(byte *in, int max_bits)
{
int len = _len(in), bits = 9, next_shift = 512;
ushort code, c, nc, next_code = M_NEW;
lzw_enc_t *d = _new(lzw_enc_t, 512);
if (max_bits > 15) max_bits = 15;
if (max_bits < 9 ) max_bits = 12;
byte *out = _new(ushort, 4);
int out_len = 0, o_bits = 0;
uint32_t tmp = 0;
inline void write_bits(ushort x) {
tmp = (tmp << bits) | x;
o_bits += bits;
if (_len(out) <= out_len) _extend(out);
while (o_bits >= 8) {
o_bits -= 8;
out[out_len++] = tmp >> o_bits;
tmp &= (1 << o_bits) - 1;
}
}
for (code = *(in++); --len; ) {
c = *(in++);
if ((nc = d[code].next[c]))
code = nc;
else {
write_bits(code);
nc = d[code].next[c] = next_code++;
code = c;
}
if (next_code == next_shift) {
if (++bits > max_bits) {
write_bits(M_CLR);
bits = 9;
next_shift = 512;
next_code = M_NEW;
_clear(d);
} else
_setsize(d, next_shift *= 2);
}
}
write_bits(code);
write_bits(M_EOD);
if (tmp) write_bits(tmp);
_del(d);
_setsize(out, out_len);
return out;
}
byte* lzw_decode(byte *in)
{
byte *out = _new(byte, 4);
int out_len = 0;
inline void write_out(byte c)
{
while (out_len >= _len(out)) _extend(out);
out[out_len++] = c;
}
lzw_dec_t *d = _new(lzw_dec_t, 512);
int len, j, next_shift = 512, bits = 9, n_bits = 0;
ushort code, c, t, next_code = M_NEW;
uint32_t tmp = 0;
inline void get_code() {
while(n_bits < bits) {
if (len > 0) {
len --;
tmp = (tmp << 8) | *(in++);
n_bits += 8;
} else {
tmp = tmp << (bits - n_bits);
n_bits = bits;
}
}
n_bits -= bits;
code = tmp >> n_bits;
tmp &= (1 << n_bits) - 1;
}
inline void clear_table() {
_clear(d);
for (j = 0; j < 256; j++) d[j].c = j;
next_code = M_NEW;
next_shift = 512;
bits = 9;
};
clear_table();
for (len = _len(in); len;) {
get_code();
if (code == M_EOD) break;
if (code == M_CLR) {
clear_table();
continue;
}
if (code >= next_code) {
fprintf(stderr, "Bad sequence\n");
_del(out);
goto bail;
}
d[next_code].prev = c = code;
while (c > 255) {
t = d[c].prev; d[t].back = c; c = t;
}
d[next_code - 1].c = c;
while (d[c].back) {
write_out(d[c].c);
t = d[c].back; d[c].back = 0; c = t;
}
write_out(d[c].c);
if (++next_code >= next_shift) {
if (++bits > 16) {
fprintf(stderr, "Too many bits\n");
_del(out);
goto bail;
}
_setsize(d, next_shift *= 2);
}
}
if (code != M_EOD) fputs("Bits did not end in EOD\n", stderr);
_setsize(out, out_len);
bail: _del(d);
return out;
}
int main()
{
int i, fd = open("unixdict.txt", O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Can't read file\n");
return 1;
};
struct stat st;
fstat(fd, &st);
byte *in = _new(char, st.st_size);
read(fd, in, st.st_size);
_setsize(in, st.st_size);
close(fd);
printf("input size: %d\n", _len(in));
byte *enc = lzw_encode(in, 9);
printf("encoded size: %d\n", _len(enc));
byte *dec = lzw_decode(enc);
printf("decoded size: %d\n", _len(dec));
for (i = 0; i < _len(dec); i++)
if (dec[i] != in[i]) {
printf("bad decode at %d\n", i);
break;
}
if (i == _len(dec)) printf("Decoded ok\n");
_del(in);
_del(enc);
_del(dec);
return 0;
}
| class LZW
{
function compress($unc) {
$i;$c;$wc;
$w = "";
$dictionary = array();
$result = array();
$dictSize = 256;
for ($i = 0; $i < 256; $i += 1) {
$dictionary[chr($i)] = $i;
}
for ($i = 0; $i < strlen($unc); $i++) {
$c = $unc[$i];
$wc = $w.$c;
if (array_key_exists($w.$c, $dictionary)) {
$w = $w.$c;
} else {
array_push($result,$dictionary[$w]);
$dictionary[$wc] = $dictSize++;
$w = (string)$c;
}
}
if ($w !== "") {
array_push($result,$dictionary[$w]);
}
return implode(",",$result);
}
function decompress($com) {
$com = explode(",",$com);
$i;$w;$k;$result;
$dictionary = array();
$entry = "";
$dictSize = 256;
for ($i = 0; $i < 256; $i++) {
$dictionary[$i] = chr($i);
}
$w = chr($com[0]);
$result = $w;
for ($i = 1; $i < count($com);$i++) {
$k = $com[$i];
if (isset($dictionary[$k])) {
$entry = $dictionary[$k];
} else {
if ($k === $dictSize) {
$entry = $w.$w[0];
} else {
return null;
}
}
$result .= $entry;
$dictionary[$dictSize++] = $w . $entry[0];
$w = $entry;
}
return $result;
}
}
$str = 'TOBEORNOTTOBEORTOBEORNOT';
$lzw = new LZW();
$com = $lzw->compress($str);
$dec = $lzw->decompress($com);
echo $com . "<br>" . $dec;
|
Change the following C code into PHP without altering its purpose. | #include <stdio.h>
long fib(long x)
{
long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); };
if (x < 0) {
printf("Bad argument: fib(%ld)\n", x);
return -1;
}
return fib_i(x);
}
long fib_i(long n)
{
printf("This is not the fib you are looking for\n");
return -1;
}
int main()
{
long x;
for (x = -1; x < 4; x ++)
printf("fib %ld = %ld\n", x, fib(x));
printf("calling fib_i from outside fib:\n");
fib_i(3);
return 0;
}
| <?php
function fib($n) {
if ($n < 0)
throw new Exception('Negative numbers not allowed');
$f = function($n) { // This function must be called using call_user_func() only
if ($n < 2)
return 1;
else {
$g = debug_backtrace()[1]['args'][0];
return call_user_func($g, $n-1) + call_user_func($g, $n-2);
}
};
return call_user_func($f, $n);
}
echo fib(8), "\n";
?>
|
Produce a functionally identical PHP code for the snippet given in C. | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char ** argv ){
const char * str_a = "knight";
const char * str_b = "socks";
const char * str_c = "brooms";
char * new_a = malloc( strlen( str_a ) - 1 );
char * new_b = malloc( strlen( str_b ) - 1 );
char * new_c = malloc( strlen( str_c ) - 2 );
strcpy( new_a, str_a + 1 );
strncpy( new_b, str_b, strlen( str_b ) - 1 );
strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );
printf( "%s\n%s\n%s\n", new_a, new_b, new_c );
free( new_a );
free( new_b );
free( new_c );
return 0;
}
| <?php
echo substr("knight", 1), "\n"; // strip first character
echo substr("socks", 0, -1), "\n"; // strip last character
echo substr("brooms", 1, -1), "\n"; // strip both first and last characters
?>
|
Convert this C block to PHP, preserving its control flow and logic. | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char ** argv ){
const char * str_a = "knight";
const char * str_b = "socks";
const char * str_c = "brooms";
char * new_a = malloc( strlen( str_a ) - 1 );
char * new_b = malloc( strlen( str_b ) - 1 );
char * new_c = malloc( strlen( str_c ) - 2 );
strcpy( new_a, str_a + 1 );
strncpy( new_b, str_b, strlen( str_b ) - 1 );
strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );
printf( "%s\n%s\n%s\n", new_a, new_b, new_c );
free( new_a );
free( new_b );
free( new_c );
return 0;
}
| <?php
echo substr("knight", 1), "\n"; // strip first character
echo substr("socks", 0, -1), "\n"; // strip last character
echo substr("brooms", 1, -1), "\n"; // strip both first and last characters
?>
|
Change the following C code into PHP without altering its purpose. | #include <stdio.h>
#include <string.h>
int cmp(const char *p, const char *q)
{
while (*p && *q) p = &p[1], q = &q[1];
return *p;
}
int main()
{
char line[65536];
char buf[1000000] = {0};
char *last = buf;
char *next = buf;
while (gets(line)) {
strcat(line, "\n");
if (cmp(last, line)) continue;
if (cmp(line, last)) next = buf;
last = next;
strcpy(next, line);
while (*next) next = &next[1];
}
printf("%s", buf);
return 0;
}
| <?php
echo 'Enter strings (empty string to finish) :', PHP_EOL;
$output = $previous = readline();
while ($current = readline()) {
$p = $previous;
$c = $current;
while ($p and $c) {
$p = substr($p, 1);
$c = substr($c, 1);
}
if (!$p and !$c) {
$output .= PHP_EOL . $current;
}
if ($c) {
$output = $previous = $current;
}
}
echo 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;
|
Rewrite this program in PHP while keeping its functionality equivalent to the C version. | #include <stdio.h>
int main() {
FILE *fh = fopen("output.txt", "w");
fclose(fh);
return 0;
}
| <?php
touch('output.txt');
mkdir('docs');
touch('/output.txt');
mkdir('/docs');
?>
|
Convert this C snippet to PHP and keep its semantics consistent. | #include <stdio.h>
typedef struct node_t *node, node_t;
struct node_t { int v; node next; };
typedef struct { node head, tail; } slist;
void push(slist *l, node e) {
if (!l->head) l->head = e;
if (l->tail) l->tail->next = e;
l->tail = e;
}
node removehead(slist *l) {
node e = l->head;
if (e) {
l->head = e->next;
e->next = 0;
}
return e;
}
void join(slist *a, slist *b) {
push(a, b->head);
a->tail = b->tail;
}
void merge(slist *a, slist *b) {
slist r = {0};
while (a->head && b->head)
push(&r, removehead(a->head->v <= b->head->v ? a : b));
join(&r, a->head ? a : b);
*a = r;
b->head = b->tail = 0;
}
void sort(int *ar, int len)
{
node_t all[len];
for (int i = 0; i < len; i++)
all[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0;
slist list = {all, all + len - 1}, rem, strand = {0}, res = {0};
for (node e = 0; list.head; list = rem) {
rem.head = rem.tail = 0;
while ((e = removehead(&list)))
push((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e);
merge(&res, &strand);
}
for (int i = 0; res.head; i++, res.head = res.head->next)
ar[i] = res.head->v;
}
void show(const char *title, int *x, int len)
{
printf("%s ", title);
for (int i = 0; i < len; i++)
printf("%3d ", x[i]);
putchar('\n');
}
int main(void)
{
int x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};
# define SIZE sizeof(x)/sizeof(int)
show("before sort:", x, SIZE);
sort(x, sizeof(x)/sizeof(int));
show("after sort: ", x, SIZE);
return 0;
}
| $lst = new SplDoublyLinkedList();
foreach (array(1,20,64,72,48,75,96,55,42,74) as $v)
$lst->push($v);
foreach (strandSort($lst) as $v)
echo "$v ";
function strandSort(SplDoublyLinkedList $lst) {
$result = new SplDoublyLinkedList();
while (!$lst->isEmpty()) {
$sorted = new SplDoublyLinkedList();
$remain = new SplDoublyLinkedList();
$sorted->push($lst->shift());
foreach ($lst as $item) {
if ($sorted->top() <= $item) {
$sorted->push($item);
} else {
$remain->push($item);
}
}
$result = _merge($sorted, $result);
$lst = $remain;
}
return $result;
}
function _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {
$res = new SplDoublyLinkedList();
while (!$left->isEmpty() && !$right->isEmpty()) {
if ($left->bottom() <= $right->bottom()) {
$res->push($left->shift());
} else {
$res->push($right->shift());
}
}
foreach ($left as $v) $res->push($v);
foreach ($right as $v) $res->push($v);
return $res;
}
|
Change the following C code into PHP without altering its purpose. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef const char * (*Responder)( int p1);
typedef struct sDelegate {
Responder operation;
} *Delegate;
Delegate NewDelegate( Responder rspndr )
{
Delegate dl = malloc(sizeof(struct sDelegate));
dl->operation = rspndr;
return dl;
}
const char *DelegateThing(Delegate dl, int p1)
{
return (dl->operation)? (*dl->operation)(p1) : NULL;
}
typedef struct sDelegator {
int param;
char *phrase;
Delegate delegate;
} *Delegator;
const char * defaultResponse( int p1)
{
return "default implementation";
}
static struct sDelegate defaultDel = { &defaultResponse };
Delegator NewDelegator( int p, char *phrase)
{
Delegator d = malloc(sizeof(struct sDelegator));
d->param = p;
d->phrase = phrase;
d->delegate = &defaultDel;
return d;
}
const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)
{
const char *rtn;
if (delroy) {
rtn = DelegateThing(delroy, p1);
if (!rtn) {
rtn = DelegateThing(theDelegator->delegate, p1);
}
}
else
rtn = DelegateThing(theDelegator->delegate, p1);
printf("%s\n", theDelegator->phrase );
return rtn;
}
const char *thing1( int p1)
{
printf("We're in thing1 with value %d\n" , p1);
return "delegate implementation";
}
int main()
{
Delegate del1 = NewDelegate(&thing1);
Delegate del2 = NewDelegate(NULL);
Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby.");
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, NULL));
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, del1));
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, del2));
return 0;
}
| class Delegator {
function __construct() {
$this->delegate = NULL ;
}
function operation() {
if(method_exists($this->delegate, "thing"))
return $this->delegate->thing() ;
return 'default implementation' ;
}
}
class Delegate {
function thing() {
return 'Delegate Implementation' ;
}
}
$a = new Delegator() ;
print "{$a->operation()}\n" ;
$a->delegate = 'A delegate may be any object' ;
print "{$a->operation()}\n" ;
$a->delegate = new Delegate() ;
print "{$a->operation()}\n" ;
|
Produce a functionally identical PHP code for the snippet given in C. | #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
typedef struct command_tag {
char* cmd;
size_t length;
size_t min_len;
struct command_tag* next;
} command_t;
bool command_match(const command_t* command, const char* str) {
size_t olen = strlen(str);
return olen >= command->min_len && olen <= command->length
&& strncmp(str, command->cmd, olen) == 0;
}
char* uppercase(char* str, size_t n) {
for (size_t i = 0; i < n; ++i)
str[i] = toupper((unsigned char)str[i]);
return str;
}
size_t get_min_length(const char* str, size_t n) {
size_t len = 0;
while (len < n && isupper((unsigned char)str[len]))
++len;
return len;
}
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;
}
char** split_into_words(const char* str, size_t* count) {
size_t size = 0;
size_t capacity = 16;
char** words = xmalloc(capacity * sizeof(char*));
size_t len = strlen(str);
for (size_t begin = 0; begin < len; ) {
size_t i = begin;
for (; i < len && isspace((unsigned char)str[i]); ++i) {}
begin = i;
for (; i < len && !isspace((unsigned char)str[i]); ++i) {}
size_t word_len = i - begin;
if (word_len == 0)
break;
char* word = xmalloc(word_len + 1);
memcpy(word, str + begin, word_len);
word[word_len] = 0;
begin += word_len;
if (capacity == size) {
capacity *= 2;
words = xrealloc(words, capacity * sizeof(char*));
}
words[size++] = word;
}
*count = size;
return words;
}
command_t* make_command_list(const char* table) {
command_t* cmd = NULL;
size_t count = 0;
char** words = split_into_words(table, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
command_t* new_cmd = xmalloc(sizeof(command_t));
size_t word_len = strlen(word);
new_cmd->length = word_len;
new_cmd->min_len = get_min_length(word, word_len);
new_cmd->cmd = uppercase(word, word_len);
new_cmd->next = cmd;
cmd = new_cmd;
}
free(words);
return cmd;
}
void free_command_list(command_t* cmd) {
while (cmd != NULL) {
command_t* next = cmd->next;
free(cmd->cmd);
free(cmd);
cmd = next;
}
}
const command_t* find_command(const command_t* commands, const char* word) {
for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {
if (command_match(cmd, word))
return cmd;
}
return NULL;
}
void test(const command_t* commands, const char* input) {
printf(" input: %s\n", input);
printf("output:");
size_t count = 0;
char** words = split_into_words(input, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
uppercase(word, strlen(word));
const command_t* cmd_ptr = find_command(commands, word);
printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*");
free(word);
}
free(words);
printf("\n");
}
int main() {
command_t* commands = make_command_list(command_table);
const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
test(commands, input);
free_command_list(commands);
return 0;
}
|
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up';
$input = 'riG rePEAT copies put mo rest types fup. 6 poweRin';
$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';
$table = makeCommandTable($commands);
$table_keys = array_keys($table);
$inputTable = processInput($input);
foreach ($inputTable as $word) {
$rs = searchCommandTable($word, $table);
if ($rs) {
$output[] = $rs;
} else {
$output[] = '*error*';
}
}
echo 'Input: '. $input. PHP_EOL;
echo 'Output: '. implode(' ', $output). PHP_EOL;
function searchCommandTable($search, $table) {
foreach ($table as $key => $value) {
if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {
return $key;
}
}
return false;
}
function processInput($input) {
$input = preg_replace('!\s+!', ' ', $input);
$pieces = explode(' ', trim($input));
return $pieces;
}
function makeCommandTable($commands) {
$commands = preg_replace('!\s+!', ' ', $commands);
$pieces = explode(' ', trim($commands));
foreach ($pieces as $word) {
$rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)];
}
return $rs;
}
|
Write a version of this C function in PHP with identical behavior. | #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
typedef struct command_tag {
char* cmd;
size_t length;
size_t min_len;
struct command_tag* next;
} command_t;
bool command_match(const command_t* command, const char* str) {
size_t olen = strlen(str);
return olen >= command->min_len && olen <= command->length
&& strncmp(str, command->cmd, olen) == 0;
}
char* uppercase(char* str, size_t n) {
for (size_t i = 0; i < n; ++i)
str[i] = toupper((unsigned char)str[i]);
return str;
}
size_t get_min_length(const char* str, size_t n) {
size_t len = 0;
while (len < n && isupper((unsigned char)str[len]))
++len;
return len;
}
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;
}
char** split_into_words(const char* str, size_t* count) {
size_t size = 0;
size_t capacity = 16;
char** words = xmalloc(capacity * sizeof(char*));
size_t len = strlen(str);
for (size_t begin = 0; begin < len; ) {
size_t i = begin;
for (; i < len && isspace((unsigned char)str[i]); ++i) {}
begin = i;
for (; i < len && !isspace((unsigned char)str[i]); ++i) {}
size_t word_len = i - begin;
if (word_len == 0)
break;
char* word = xmalloc(word_len + 1);
memcpy(word, str + begin, word_len);
word[word_len] = 0;
begin += word_len;
if (capacity == size) {
capacity *= 2;
words = xrealloc(words, capacity * sizeof(char*));
}
words[size++] = word;
}
*count = size;
return words;
}
command_t* make_command_list(const char* table) {
command_t* cmd = NULL;
size_t count = 0;
char** words = split_into_words(table, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
command_t* new_cmd = xmalloc(sizeof(command_t));
size_t word_len = strlen(word);
new_cmd->length = word_len;
new_cmd->min_len = get_min_length(word, word_len);
new_cmd->cmd = uppercase(word, word_len);
new_cmd->next = cmd;
cmd = new_cmd;
}
free(words);
return cmd;
}
void free_command_list(command_t* cmd) {
while (cmd != NULL) {
command_t* next = cmd->next;
free(cmd->cmd);
free(cmd);
cmd = next;
}
}
const command_t* find_command(const command_t* commands, const char* word) {
for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) {
if (command_match(cmd, word))
return cmd;
}
return NULL;
}
void test(const command_t* commands, const char* input) {
printf(" input: %s\n", input);
printf("output:");
size_t count = 0;
char** words = split_into_words(input, &count);
for (size_t i = 0; i < count; ++i) {
char* word = words[i];
uppercase(word, strlen(word));
const command_t* cmd_ptr = find_command(commands, word);
printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*");
free(word);
}
free(words);
printf("\n");
}
int main() {
command_t* commands = make_command_list(command_table);
const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
test(commands, input);
free_command_list(commands);
return 0;
}
|
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up';
$input = 'riG rePEAT copies put mo rest types fup. 6 poweRin';
$expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT';
$table = makeCommandTable($commands);
$table_keys = array_keys($table);
$inputTable = processInput($input);
foreach ($inputTable as $word) {
$rs = searchCommandTable($word, $table);
if ($rs) {
$output[] = $rs;
} else {
$output[] = '*error*';
}
}
echo 'Input: '. $input. PHP_EOL;
echo 'Output: '. implode(' ', $output). PHP_EOL;
function searchCommandTable($search, $table) {
foreach ($table as $key => $value) {
if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) {
return $key;
}
}
return false;
}
function processInput($input) {
$input = preg_replace('!\s+!', ' ', $input);
$pieces = explode(' ', trim($input));
return $pieces;
}
function makeCommandTable($commands) {
$commands = preg_replace('!\s+!', ' ', $commands);
$pieces = explode(' ', trim($commands));
foreach ($pieces as $word) {
$rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)];
}
return $rs;
}
|
Port the provided C code into PHP while preserving the original functionality. | #define PI 3.14159265358979323
#define MINSIZE 10
#define MAXSIZE 100
| define("PI", 3.14159265358);
define("MSG", "Hello World");
|
Write the same code in PHP as shown below in C. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct { double x, y; } vec_t, *vec;
inline double dot(vec a, vec b)
{
return a->x * b->x + a->y * b->y;
}
inline double cross(vec a, vec b)
{
return a->x * b->y - a->y * b->x;
}
inline vec vsub(vec a, vec b, vec res)
{
res->x = a->x - b->x;
res->y = a->y - b->y;
return res;
}
int left_of(vec a, vec b, vec c)
{
vec_t tmp1, tmp2;
double x;
vsub(b, a, &tmp1);
vsub(c, b, &tmp2);
x = cross(&tmp1, &tmp2);
return x < 0 ? -1 : x > 0;
}
int line_sect(vec x0, vec x1, vec y0, vec y1, vec res)
{
vec_t dx, dy, d;
vsub(x1, x0, &dx);
vsub(y1, y0, &dy);
vsub(x0, y0, &d);
double dyx = cross(&dy, &dx);
if (!dyx) return 0;
dyx = cross(&d, &dx) / dyx;
if (dyx <= 0 || dyx >= 1) return 0;
res->x = y0->x + dyx * dy.x;
res->y = y0->y + dyx * dy.y;
return 1;
}
typedef struct { int len, alloc; vec v; } poly_t, *poly;
poly poly_new()
{
return (poly)calloc(1, sizeof(poly_t));
}
void poly_free(poly p)
{
free(p->v);
free(p);
}
void poly_append(poly p, vec v)
{
if (p->len >= p->alloc) {
p->alloc *= 2;
if (!p->alloc) p->alloc = 4;
p->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);
}
p->v[p->len++] = *v;
}
int poly_winding(poly p)
{
return left_of(p->v, p->v + 1, p->v + 2);
}
void poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)
{
int i, side0, side1;
vec_t tmp;
vec v0 = sub->v + sub->len - 1, v1;
res->len = 0;
side0 = left_of(x0, x1, v0);
if (side0 != -left) poly_append(res, v0);
for (i = 0; i < sub->len; i++) {
v1 = sub->v + i;
side1 = left_of(x0, x1, v1);
if (side0 + side1 == 0 && side0)
if (line_sect(x0, x1, v0, v1, &tmp))
poly_append(res, &tmp);
if (i == sub->len - 1) break;
if (side1 != -left) poly_append(res, v1);
v0 = v1;
side0 = side1;
}
}
poly poly_clip(poly sub, poly clip)
{
int i;
poly p1 = poly_new(), p2 = poly_new(), tmp;
int dir = poly_winding(clip);
poly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);
for (i = 0; i < clip->len - 1; i++) {
tmp = p2; p2 = p1; p1 = tmp;
if(p1->len == 0) {
p2->len = 0;
break;
}
poly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);
}
poly_free(p1);
return p2;
}
int main()
{
int i;
vec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};
vec_t s[] = { {50,150}, {200,50}, {350,150},
{350,300},{250,300},{200,250},
{150,350},{100,250},{100,200}};
#define clen (sizeof(c)/sizeof(vec_t))
#define slen (sizeof(s)/sizeof(vec_t))
poly_t clipper = {clen, 0, c};
poly_t subject = {slen, 0, s};
poly res = poly_clip(&subject, &clipper);
for (i = 0; i < res->len; i++)
printf("%g %g\n", res->v[i].x, res->v[i].y);
FILE * eps = fopen("test.eps", "w");
fprintf(eps, "%%!PS-Adobe-3.0\n%%%%BoundingBox: 40 40 360 360\n"
"/l {lineto} def /m{moveto} def /s{setrgbcolor} def"
"/c {closepath} def /gs {fill grestore stroke} def\n");
fprintf(eps, "0 setlinewidth %g %g m ", c[0].x, c[0].y);
for (i = 1; i < clen; i++)
fprintf(eps, "%g %g l ", c[i].x, c[i].y);
fprintf(eps, "c .5 0 0 s gsave 1 .7 .7 s gs\n");
fprintf(eps, "%g %g m ", s[0].x, s[0].y);
for (i = 1; i < slen; i++)
fprintf(eps, "%g %g l ", s[i].x, s[i].y);
fprintf(eps, "c 0 .2 .5 s gsave .4 .7 1 s gs\n");
fprintf(eps, "2 setlinewidth [10 8] 0 setdash %g %g m ",
res->v[0].x, res->v[0].y);
for (i = 1; i < res->len; i++)
fprintf(eps, "%g %g l ", res->v[i].x, res->v[i].y);
fprintf(eps, "c .5 0 .5 s gsave .7 .3 .8 s gs\n");
fprintf(eps, "%%%%EOF");
fclose(eps);
printf("test.eps written\n");
return 0;
}
| <?php
function clip ($subjectPolygon, $clipPolygon) {
function inside ($p, $cp1, $cp2) {
return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);
}
function intersection ($cp1, $cp2, $e, $s) {
$dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];
$dp = [ $s[0] - $e[0], $s[1] - $e[1] ];
$n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];
$n2 = $s[0] * $e[1] - $s[1] * $e[0];
$n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);
return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];
}
$outputList = $subjectPolygon;
$cp1 = end($clipPolygon);
foreach ($clipPolygon as $cp2) {
$inputList = $outputList;
$outputList = [];
$s = end($inputList);
foreach ($inputList as $e) {
if (inside($e, $cp1, $cp2)) {
if (!inside($s, $cp1, $cp2)) {
$outputList[] = intersection($cp1, $cp2, $e, $s);
}
$outputList[] = $e;
}
else if (inside($s, $cp1, $cp2)) {
$outputList[] = intersection($cp1, $cp2, $e, $s);
}
$s = $e;
}
$cp1 = $cp2;
}
return $outputList;
}
$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];
$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];
$clippedPolygon = clip($subjectPolygon, $clipPolygon);
echo json_encode($clippedPolygon);
echo "\n";
?>
|
Produce a functionally identical PHP code for the snippet given in C. |
#include <stdio.h>
void sayHello(char* name){
printf("Hello %s!\n", name);
}
int doubleNum(int num){
return num * 2;
}
| $ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll");
$cstr = $ffi->_strdup("success");
$str = FFI::string($cstr);
echo $str;
FFI::free($cstr);
|
Please provide an equivalent version of this C code in PHP. | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
struct s_env {
unsigned int n, i;
size_t size;
void *sample;
};
void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
s_env->i = 0;
s_env->n = n;
s_env->size = size;
s_env->sample = malloc(n * size);
}
void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}
void *s_of_n(struct s_env *s_env, void *item)
{
s_env->i++;
if (s_env->i <= s_env->n)
sample_set_i(s_env, s_env->i - 1, item);
else if ((rand() % s_env->i) < s_env->n)
sample_set_i(s_env, rand() % s_env->n, item);
return s_env->sample;
}
int *test(unsigned int n, int *items_set, unsigned int num_items)
{
int i;
struct s_env s_env;
s_of_n_init(&s_env, sizeof(items_set[0]), n);
for (i = 0; i < num_items; i++) {
s_of_n(&s_env, (void *) &items_set[i]);
}
return (int *)s_env.sample;
}
int main()
{
unsigned int i, j;
unsigned int n = 3;
unsigned int num_items = 10;
unsigned int *frequencies;
int *items_set;
srand(time(NULL));
items_set = malloc(num_items * sizeof(int));
frequencies = malloc(num_items * sizeof(int));
for (i = 0; i < num_items; i++) {
items_set[i] = i;
frequencies[i] = 0;
}
for (i = 0; i < 100000; i++) {
int *res = test(n, items_set, num_items);
for (j = 0; j < n; j++) {
frequencies[res[j]]++;
}
free(res);
}
for (i = 0; i < num_items; i++) {
printf(" %d", frequencies[i]);
}
puts("");
return 0;
}
| <?php
function s_of_n_creator($n) {
$sample = array();
$i = 0;
return function($item) use (&$sample, &$i, $n) {
$i++;
if ($i <= $n) {
$sample[] = $item;
} else if (rand(0, $i-1) < $n) {
$sample[rand(0, $n-1)] = $item;
}
return $sample;
};
}
$items = range(0, 9);
for ($trial = 0; $trial < 100000; $trial++) {
$s_of_n = s_of_n_creator(3);
foreach ($items as $item)
$sample = $s_of_n($item);
foreach ($sample as $s)
$bin[$s]++;
}
print_r($bin);
?>
|
Rewrite this program in PHP while keeping its functionality equivalent to the C version. | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
struct s_env {
unsigned int n, i;
size_t size;
void *sample;
};
void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
s_env->i = 0;
s_env->n = n;
s_env->size = size;
s_env->sample = malloc(n * size);
}
void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}
void *s_of_n(struct s_env *s_env, void *item)
{
s_env->i++;
if (s_env->i <= s_env->n)
sample_set_i(s_env, s_env->i - 1, item);
else if ((rand() % s_env->i) < s_env->n)
sample_set_i(s_env, rand() % s_env->n, item);
return s_env->sample;
}
int *test(unsigned int n, int *items_set, unsigned int num_items)
{
int i;
struct s_env s_env;
s_of_n_init(&s_env, sizeof(items_set[0]), n);
for (i = 0; i < num_items; i++) {
s_of_n(&s_env, (void *) &items_set[i]);
}
return (int *)s_env.sample;
}
int main()
{
unsigned int i, j;
unsigned int n = 3;
unsigned int num_items = 10;
unsigned int *frequencies;
int *items_set;
srand(time(NULL));
items_set = malloc(num_items * sizeof(int));
frequencies = malloc(num_items * sizeof(int));
for (i = 0; i < num_items; i++) {
items_set[i] = i;
frequencies[i] = 0;
}
for (i = 0; i < 100000; i++) {
int *res = test(n, items_set, num_items);
for (j = 0; j < n; j++) {
frequencies[res[j]]++;
}
free(res);
}
for (i = 0; i < num_items; i++) {
printf(" %d", frequencies[i]);
}
puts("");
return 0;
}
| <?php
function s_of_n_creator($n) {
$sample = array();
$i = 0;
return function($item) use (&$sample, &$i, $n) {
$i++;
if ($i <= $n) {
$sample[] = $item;
} else if (rand(0, $i-1) < $n) {
$sample[rand(0, $n-1)] = $item;
}
return $sample;
};
}
$items = range(0, 9);
for ($trial = 0; $trial < 100000; $trial++) {
$s_of_n = s_of_n_creator(3);
foreach ($items as $item)
$sample = $s_of_n($item);
foreach ($sample as $s)
$bin[$s]++;
}
print_r($bin);
?>
|
Change the programming language of this snippet from C to PHP without modifying what it does. | #include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
(void) printf("This program is named %s.\n", argv[0]);
for (i = 1; i < argc; ++i)
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}
| <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
|
Ensure the translated PHP code behaves exactly like the original C snippet. | #include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
(void) printf("This program is named %s.\n", argv[0]);
for (i = 1; i < argc; ++i)
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}
| <?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
|
Produce a functionally identical PHP code for the snippet given in C. | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
(TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));
void *array_concat(const void *a, size_t an,
const void *b, size_t bn, size_t s)
{
char *p = malloc(s * (an + bn));
memcpy(p, a, an*s);
memcpy(p + an*s, b, bn*s);
return p;
}
const int a[] = { 1, 2, 3, 4, 5 };
const int b[] = { 6, 7, 8, 9, 0 };
int main(void)
{
unsigned int i;
int *c = ARRAY_CONCAT(int, a, 5, b, 5);
for(i = 0; i < 10; i++)
printf("%d\n", c[i]);
free(c);
return EXIT_SUCCCESS;
}
| $arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.