Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the programming language of this snippet from C++ to C without modifying what it does.
#include <algorithm> #include <array> #include <cstdint> #include <iostream> #include <tuple> std::tuple<int, int> minmax(const int * numbers, const std::size_t num) { const auto maximum = std::max_element(numbers, numbers + num); const auto minimum = std::min_element(numbers, numbers + num); return std::make_tuple(*minimum, *maximum) ; } int main( ) { const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}}; int min{}; int max{}; std::tie(min, max) = minmax(numbers.data(), numbers.size()); std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ; }
#include<stdio.h> typedef struct{ int integer; float decimal; char letter; char string[100]; double bigDecimal; }Composite; Composite example() { Composite C = {1, 2.3, 'a', "Hello World", 45.678}; return C; } int main() { Composite C = example(); printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}\n", C.integer, C.decimal, C.letter, C.string, C.bigDecimal); return 0; }
Write the same code in C as shown below in C++.
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
#include <stdlib.h> #include <stdio.h> int main(int argc, const char *argv[]) { const int max = 1000; int *a = malloc(max * sizeof(int)); for (int n = 0; n < max - 1; n ++) { for (int m = n - 1; m >= 0; m --) { if (a[m] == a[n]) { a[n+1] = n - m; break; } } } printf("The first ten terms of the Van Eck sequence are:\n"); for (int i = 0; i < 10; i ++) printf("%d ", a[i]); printf("\n\nTerms 991 to 1000 of the sequence are:\n"); for (int i = 990; i < 1000; i ++) printf("%d ", a[i]); putchar('\n'); return 0; }
Translate the given C++ code snippet into C without altering its behavior.
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
#include <stdlib.h> #include <stdio.h> int main(int argc, const char *argv[]) { const int max = 1000; int *a = malloc(max * sizeof(int)); for (int n = 0; n < max - 1; n ++) { for (int m = n - 1; m >= 0; m --) { if (a[m] == a[n]) { a[n+1] = n - m; break; } } } printf("The first ten terms of the Van Eck sequence are:\n"); for (int i = 0; i < 10; i ++) printf("%d ", a[i]); printf("\n\nTerms 991 to 1000 of the sequence are:\n"); for (int i = 990; i < 1000; i ++) printf("%d ", a[i]); putchar('\n'); return 0; }
Ensure the translated C code behaves exactly like the original C++ snippet.
#include <iostream> #include <string> #include <cstring> #include <fstream> #include <sys/stat.h> #include <ftplib.h> #include <ftp++.hpp> int stat(const char *pathname, struct stat *buf); char *strerror(int errnum); char *basename(char *path); namespace stl { using std::cout; using std::cerr; using std::string; using std::ifstream; using std::remove; }; using namespace stl; using Mode = ftp::Connection::Mode; Mode PASV = Mode::PASSIVE; Mode PORT = Mode::PORT; using TransferMode = ftp::Connection::TransferMode; TransferMode BINARY = TransferMode::BINARY; TransferMode TEXT = TransferMode::TEXT; struct session { const string server; const string port; const string user; const string pass; Mode mode; TransferMode txmode; string dir; }; ftp::Connection connect_ftp( const session& sess); size_t get_ftp( ftp::Connection& conn, string const& path); string readFile( const string& filename); string login_ftp(ftp::Connection& conn, const session& sess); string dir_listing( ftp::Connection& conn, const string& path); string readFile( const string& filename) { struct stat stat_buf; string contents; errno = 0; if (stat(filename.c_str() , &stat_buf) != -1) { size_t len = stat_buf.st_size; string bytes(len+1, '\0'); ifstream ifs(filename); ifs.read(&bytes[0], len); if (! ifs.fail() ) contents.swap(bytes); ifs.close(); } else { cerr << "stat error: " << strerror(errno); } return contents; } ftp::Connection connect_ftp( const session& sess) try { string constr = sess.server + ":" + sess.port; cerr << "connecting to " << constr << " ...\n"; ftp::Connection conn{ constr.c_str() }; cerr << "connected to " << constr << "\n"; conn.setConnectionMode(sess.mode); return conn; } catch (ftp::ConnectException e) { cerr << "FTP error: could not connect to server" << "\n"; } string login_ftp(ftp::Connection& conn, const session& sess) { conn.login(sess.user.c_str() , sess.pass.c_str() ); return conn.getLastResponse(); } string dir_listing( ftp::Connection& conn, const string& path) try { const char* dirdata = "/dev/shm/dirdata"; conn.getList(dirdata, path.c_str() ); string dir_string = readFile(dirdata); cerr << conn.getLastResponse() << "\n"; errno = 0; if ( remove(dirdata) != 0 ) { cerr << "error: " << strerror(errno) << "\n"; } return dir_string; } catch (...) { cerr << "error: getting dir contents: \n" << strerror(errno) << "\n"; } size_t get_ftp( ftp::Connection& conn, const string& r_path) { size_t received = 0; const char* path = r_path.c_str(); unsigned remotefile_size = conn.size(path , BINARY); const char* localfile = basename(path); conn.get(localfile, path, BINARY); cerr << conn.getLastResponse() << "\n"; struct stat stat_buf; errno = 0; if (stat(localfile, &stat_buf) != -1) received = stat_buf.st_size; else cerr << strerror(errno); return received; } const session sonic { "mirrors.sonic.net", "21" , "anonymous", "xxxx@nohost.org", PASV, BINARY, "/pub/OpenBSD" }; int main(int argc, char* argv[], char * env[] ) { const session remote = sonic; try { ftp::Connection conn = connect_ftp(remote); cerr << login_ftp(conn, remote); cout << "System type: " << conn.getSystemType() << "\n"; cerr << conn.getLastResponse() << "\n"; conn.cd(remote.dir.c_str()); cerr << conn.getLastResponse() << "\n"; string pwdstr = conn.getDirectory(); cout << "PWD: " << pwdstr << "\n"; cerr << conn.getLastResponse() << "\n"; string dirlist = dir_listing(conn, pwdstr.c_str() ); cout << dirlist << "\n"; string filename = "ftplist"; auto pos = dirlist.find(filename); auto notfound = string::npos; if (pos != notfound) { size_t received = get_ftp(conn, filename.c_str() ); if (received == 0) cerr << "got 0 bytes\n"; else cerr << "got " << filename << " (" << received << " bytes)\n"; } else { cerr << "file " << filename << "not found on server. \n"; } } catch (ftp::ConnectException e) { cerr << "FTP error: could not connect to server" << "\n"; } catch (ftp::Exception e) { cerr << "FTP error: " << e << "\n"; } catch (...) { cerr << "error: " << strerror(errno) << "\n"; } return 0; }
#include <ftplib.h> int main(void) { netbuf *nbuf; FtpInit(); FtpConnect("kernel.org", &nbuf); FtpLogin("anonymous", "", nbuf); FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf); FtpChdir("pub/linux/kernel", nbuf); FtpDir((void*)0, ".", nbuf); FtpGet("ftp.README", "README", FTPLIB_ASCII, nbuf); FtpQuit(nbuf); return 0; }
Change the programming language of this snippet from C++ to C without modifying what it does.
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); stk.push(f(a, b)); } void parse(char c) { if(c >= '0' && c <= '9') { stk.push(c - '0'); digits.insert(c - '0'); } else if(c == '+') op([](double a, double b) {return a+b;}); else if(c == '-') op([](double a, double b) {return a-b;}); else if(c == '*') op([](double a, double b) {return a*b;}); else if(c == '/') op([](double a, double b) {return a/b;}); } void parse(string s) { for(int i = 0; i < s.size(); ++i) parse(s[i]); } double getResult() { if(stk.size() != 1) throw "Improperly written expression"; return stk.top(); } }; int main() { random_device seed; mt19937 engine(seed()); uniform_int_distribution<> distribution(1, 9); auto rnd = bind(distribution, engine); multiset<int> digits; cout << "Make 24 with the digits: "; for(int i = 0; i < 4; ++i) { int n = rnd(); cout << " " << n; digits.insert(n); } cout << endl; RPNParse parser; try { string input; getline(cin, input); parser.parse(input); if(digits != parser.digits) cout << "Error: Not using the given digits" << endl; else { double r = parser.getResult(); cout << "Result: " << r << endl; if(r > 23.999 && r < 24.001) cout << "Good job!" << endl; else cout << "Try again." << endl; } } catch(char* e) { cout << "Error: " << e << endl; } return 0; }
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t digits[N_DIGITS]; void gen_digits() { int i; for (i = 0; i < N_DIGITS; i++) digits[i].val = 1 + rand() % 9; } #define MAX_INPUT 64 char str[MAX_INPUT]; int pos; #define POOL_SIZE 8 expr_t pool[POOL_SIZE]; int pool_ptr; void reset() { int i; msg = 0; pool_ptr = pos = 0; for (i = 0; i < POOL_SIZE; i++) { pool[i].op = OP_NONE; pool[i].left = pool[i].right = 0; } for (i = 0; i < N_DIGITS; i++) digits[i].used = 0; } void bail(const char *s) { msg = s; longjmp(ctx, 1); } expr new_expr() { if (pool_ptr < POOL_SIZE) return pool + pool_ptr++; return 0; } int next_tok() { while (isspace(str[pos])) pos++; return str[pos]; } int take() { if (str[pos] != '\0') return ++pos; return 0; } expr get_fact(); expr get_term(); expr get_expr(); expr get_expr() { int c; expr l, r, ret; if (!(ret = get_term())) bail("Expected term"); while ((c = next_tok()) == '+' || c == '-') { if (!take()) bail("Unexpected end of input"); if (!(r = get_term())) bail("Expected term"); l = ret; ret = new_expr(); ret->op = (c == '+') ? OP_ADD : OP_SUB; ret->left = l; ret->right = r; } return ret; } expr get_term() { int c; expr l, r, ret; ret = get_fact(); while((c = next_tok()) == '*' || c == '/') { if (!take()) bail("Unexpected end of input"); r = get_fact(); l = ret; ret = new_expr(); ret->op = (c == '*') ? OP_MUL : OP_DIV; ret->left = l; ret->right = r; } return ret; } expr get_digit() { int i, c = next_tok(); expr ret; if (c >= '0' && c <= '9') { take(); ret = new_expr(); ret->op = OP_NUM; ret->val = c - '0'; for (i = 0; i < N_DIGITS; i++) if (digits[i].val == ret->val && !digits[i].used) { digits[i].used = 1; return ret; } bail("Invalid digit"); } return 0; } expr get_fact() { int c; expr l = get_digit(); if (l) return l; if ((c = next_tok()) == '(') { take(); l = get_expr(); if (next_tok() != ')') bail("Unbalanced parens"); take(); return l; } return 0; } expr parse() { int i; expr ret = get_expr(); if (next_tok() != '\0') bail("Trailing garbage"); for (i = 0; i < N_DIGITS; i++) if (!digits[i].used) bail("Not all digits are used"); return ret; } typedef struct frac_t frac_t, *frac; struct frac_t { int denom, num; }; int gcd(int m, int n) { int t; while (m) { t = m; m = n % m; n = t; } return n; } void eval_tree(expr e, frac res) { frac_t l, r; int t; if (e->op == OP_NUM) { res->num = e->val; res->denom = 1; return; } eval_tree(e->left, &l); eval_tree(e->right, &r); switch(e->op) { case OP_ADD: res->num = l.num * r.denom + l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_SUB: res->num = l.num * r.denom - l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_MUL: res->num = l.num * r.num; res->denom = l.denom * r.denom; break; case OP_DIV: res->num = l.num * r.denom; res->denom = l.denom * r.num; break; } if ((t = gcd(res->denom, res->num))) { res->denom /= t; res->num /= t; } } void get_input() { int i; reinput: reset(); printf("\nAvailable digits are:"); for (i = 0; i < N_DIGITS; i++) printf(" %d", digits[i].val); printf(". Type an expression and I'll check it for you, or make new numbers.\n" "Your choice? [Expr/n/q] "); while (1) { for (i = 0; i < MAX_INPUT; i++) str[i] = '\n'; fgets(str, MAX_INPUT, stdin); if (*str == '\0') goto reinput; if (str[MAX_INPUT - 1] != '\n') bail("string too long"); for (i = 0; i < MAX_INPUT; i++) if (str[i] == '\n') str[i] = '\0'; if (str[0] == 'q') { printf("Bye\n"); exit(0); } if (str[0] == 'n') { gen_digits(); goto reinput; } return; } } int main() { frac_t f; srand(time(0)); gen_digits(); while(1) { get_input(); setjmp(ctx); if (msg) { printf("%s at '%.*s'\n", msg, pos, str); continue; } eval_tree(parse(), &f); if (f.denom == 0) bail("Divide by zero"); if (f.denom == 1 && f.num == 24) printf("You got 24. Very good.\n"); else { if (f.denom == 1) printf("Eval to: %d, ", f.num); else printf("Eval to: %d/%d, ", f.num, f.denom); printf("no good. Try again.\n"); } } return 0; }
Translate this program into C but keep the logic exactly as in C++.
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); stk.push(f(a, b)); } void parse(char c) { if(c >= '0' && c <= '9') { stk.push(c - '0'); digits.insert(c - '0'); } else if(c == '+') op([](double a, double b) {return a+b;}); else if(c == '-') op([](double a, double b) {return a-b;}); else if(c == '*') op([](double a, double b) {return a*b;}); else if(c == '/') op([](double a, double b) {return a/b;}); } void parse(string s) { for(int i = 0; i < s.size(); ++i) parse(s[i]); } double getResult() { if(stk.size() != 1) throw "Improperly written expression"; return stk.top(); } }; int main() { random_device seed; mt19937 engine(seed()); uniform_int_distribution<> distribution(1, 9); auto rnd = bind(distribution, engine); multiset<int> digits; cout << "Make 24 with the digits: "; for(int i = 0; i < 4; ++i) { int n = rnd(); cout << " " << n; digits.insert(n); } cout << endl; RPNParse parser; try { string input; getline(cin, input); parser.parse(input); if(digits != parser.digits) cout << "Error: Not using the given digits" << endl; else { double r = parser.getResult(); cout << "Result: " << r << endl; if(r > 23.999 && r < 24.001) cout << "Good job!" << endl; else cout << "Try again." << endl; } } catch(char* e) { cout << "Error: " << e << endl; } return 0; }
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <setjmp.h> #include <time.h> jmp_buf ctx; const char *msg; enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV }; typedef struct expr_t *expr, expr_t; struct expr_t { int op, val, used; expr left, right; }; #define N_DIGITS 4 expr_t digits[N_DIGITS]; void gen_digits() { int i; for (i = 0; i < N_DIGITS; i++) digits[i].val = 1 + rand() % 9; } #define MAX_INPUT 64 char str[MAX_INPUT]; int pos; #define POOL_SIZE 8 expr_t pool[POOL_SIZE]; int pool_ptr; void reset() { int i; msg = 0; pool_ptr = pos = 0; for (i = 0; i < POOL_SIZE; i++) { pool[i].op = OP_NONE; pool[i].left = pool[i].right = 0; } for (i = 0; i < N_DIGITS; i++) digits[i].used = 0; } void bail(const char *s) { msg = s; longjmp(ctx, 1); } expr new_expr() { if (pool_ptr < POOL_SIZE) return pool + pool_ptr++; return 0; } int next_tok() { while (isspace(str[pos])) pos++; return str[pos]; } int take() { if (str[pos] != '\0') return ++pos; return 0; } expr get_fact(); expr get_term(); expr get_expr(); expr get_expr() { int c; expr l, r, ret; if (!(ret = get_term())) bail("Expected term"); while ((c = next_tok()) == '+' || c == '-') { if (!take()) bail("Unexpected end of input"); if (!(r = get_term())) bail("Expected term"); l = ret; ret = new_expr(); ret->op = (c == '+') ? OP_ADD : OP_SUB; ret->left = l; ret->right = r; } return ret; } expr get_term() { int c; expr l, r, ret; ret = get_fact(); while((c = next_tok()) == '*' || c == '/') { if (!take()) bail("Unexpected end of input"); r = get_fact(); l = ret; ret = new_expr(); ret->op = (c == '*') ? OP_MUL : OP_DIV; ret->left = l; ret->right = r; } return ret; } expr get_digit() { int i, c = next_tok(); expr ret; if (c >= '0' && c <= '9') { take(); ret = new_expr(); ret->op = OP_NUM; ret->val = c - '0'; for (i = 0; i < N_DIGITS; i++) if (digits[i].val == ret->val && !digits[i].used) { digits[i].used = 1; return ret; } bail("Invalid digit"); } return 0; } expr get_fact() { int c; expr l = get_digit(); if (l) return l; if ((c = next_tok()) == '(') { take(); l = get_expr(); if (next_tok() != ')') bail("Unbalanced parens"); take(); return l; } return 0; } expr parse() { int i; expr ret = get_expr(); if (next_tok() != '\0') bail("Trailing garbage"); for (i = 0; i < N_DIGITS; i++) if (!digits[i].used) bail("Not all digits are used"); return ret; } typedef struct frac_t frac_t, *frac; struct frac_t { int denom, num; }; int gcd(int m, int n) { int t; while (m) { t = m; m = n % m; n = t; } return n; } void eval_tree(expr e, frac res) { frac_t l, r; int t; if (e->op == OP_NUM) { res->num = e->val; res->denom = 1; return; } eval_tree(e->left, &l); eval_tree(e->right, &r); switch(e->op) { case OP_ADD: res->num = l.num * r.denom + l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_SUB: res->num = l.num * r.denom - l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_MUL: res->num = l.num * r.num; res->denom = l.denom * r.denom; break; case OP_DIV: res->num = l.num * r.denom; res->denom = l.denom * r.num; break; } if ((t = gcd(res->denom, res->num))) { res->denom /= t; res->num /= t; } } void get_input() { int i; reinput: reset(); printf("\nAvailable digits are:"); for (i = 0; i < N_DIGITS; i++) printf(" %d", digits[i].val); printf(". Type an expression and I'll check it for you, or make new numbers.\n" "Your choice? [Expr/n/q] "); while (1) { for (i = 0; i < MAX_INPUT; i++) str[i] = '\n'; fgets(str, MAX_INPUT, stdin); if (*str == '\0') goto reinput; if (str[MAX_INPUT - 1] != '\n') bail("string too long"); for (i = 0; i < MAX_INPUT; i++) if (str[i] == '\n') str[i] = '\0'; if (str[0] == 'q') { printf("Bye\n"); exit(0); } if (str[0] == 'n') { gen_digits(); goto reinput; } return; } } int main() { frac_t f; srand(time(0)); gen_digits(); while(1) { get_input(); setjmp(ctx); if (msg) { printf("%s at '%.*s'\n", msg, pos, str); continue; } eval_tree(parse(), &f); if (f.denom == 0) bail("Divide by zero"); if (f.denom == 1 && f.num == 24) printf("You got 24. Very good.\n"); else { if (f.denom == 1) printf("Eval to: %d, ", f.num); else printf("Eval to: %d/%d, ", f.num, f.denom); printf("no good. Try again.\n"); } } return 0; }
Port the provided C++ code into C while preserving the original functionality.
for(int i = 1;i <= 10; i++){ cout << i; if(i % 5 == 0){ cout << endl; continue; } cout << ", "; }
for(int i = 1;i <= 10; i++){ printf("%d", i); if(i % 5 == 0){ printf("\n"); continue; } printf(", "); }
Keep all operations the same but rewrite the snippet in C.
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> class QPaintEvent ; class MyWidget : public QWidget { public : MyWidget( ) ; protected : void paintEvent( QPaintEvent * ) ; private : int width ; int height ; const int colornumber ; } ; #endif
#include<conio.h> #define COLOURS 8 int main() { int colour=0,i,j,MAXROW,MAXCOL; struct text_info tInfo; gettextinfo(&tInfo); MAXROW = tInfo.screenheight; MAXCOL = tInfo.screenwidth; textbackground(BLACK); clrscr(); for(colour=0;colour<COLOURS;colour++) { getch(); gotoxy(1+colour*MAXCOL/COLOURS,1); textbackground(colour); for(j=0;j<MAXROW;j++){ for(i=0;i<MAXCOL/COLOURS;i++){ cprintf(" "); } gotoxy(1+colour*MAXCOL/COLOURS,1+j); } } getch(); textbackground(BLACK); return 0; }
Change the programming language of this snippet from C++ to C without modifying what it does.
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> class QPaintEvent ; class MyWidget : public QWidget { public : MyWidget( ) ; protected : void paintEvent( QPaintEvent * ) ; private : int width ; int height ; const int colornumber ; } ; #endif
#include<conio.h> #define COLOURS 8 int main() { int colour=0,i,j,MAXROW,MAXCOL; struct text_info tInfo; gettextinfo(&tInfo); MAXROW = tInfo.screenheight; MAXCOL = tInfo.screenwidth; textbackground(BLACK); clrscr(); for(colour=0;colour<COLOURS;colour++) { getch(); gotoxy(1+colour*MAXCOL/COLOURS,1); textbackground(colour); for(j=0;j<MAXROW;j++){ for(i=0;i<MAXCOL/COLOURS;i++){ cprintf(" "); } gotoxy(1+colour*MAXCOL/COLOURS,1+j); } } getch(); textbackground(BLACK); return 0; }
Transform the following C++ implementation into C, maintaining the same output and logic.
#include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <limits> #include <numeric> #include <sstream> #include <vector> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, scalar_type value) : rows_(rows), columns_(columns), elements_(rows * columns, value) {} matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<scalar_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[i]); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const scalar_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } scalar_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } private: size_t rows_; size_t columns_; std::vector<scalar_type> elements_; }; template <typename scalar_type> void print(std::wostream& out, const matrix<scalar_type>& a) { const wchar_t* box_top_left = L"\x23a1"; const wchar_t* box_top_right = L"\x23a4"; const wchar_t* box_left = L"\x23a2"; const wchar_t* box_right = L"\x23a5"; const wchar_t* box_bottom_left = L"\x23a3"; const wchar_t* box_bottom_right = L"\x23a6"; const int precision = 5; size_t rows = a.rows(), columns = a.columns(); std::vector<size_t> width(columns); for (size_t column = 0; column < columns; ++column) { size_t max_width = 0; for (size_t row = 0; row < rows; ++row) { std::ostringstream str; str << std::fixed << std::setprecision(precision) << a(row, column); max_width = std::max(max_width, str.str().length()); } width[column] = max_width; } out << std::fixed << std::setprecision(precision); for (size_t row = 0; row < rows; ++row) { const bool top(row == 0), bottom(row + 1 == rows); out << (top ? box_top_left : (bottom ? box_bottom_left : box_left)); for (size_t column = 0; column < columns; ++column) { if (column > 0) out << L' '; out << std::setw(width[column]) << a(row, column); } out << (top ? box_top_right : (bottom ? box_bottom_right : box_right)); out << L'\n'; } } template <typename scalar_type> auto lu_decompose(const matrix<scalar_type>& input) { assert(input.rows() == input.columns()); size_t n = input.rows(); std::vector<size_t> perm(n); std::iota(perm.begin(), perm.end(), 0); matrix<scalar_type> lower(n, n); matrix<scalar_type> upper(n, n); matrix<scalar_type> input1(input); for (size_t j = 0; j < n; ++j) { size_t max_index = j; scalar_type max_value = 0; for (size_t i = j; i < n; ++i) { scalar_type value = std::abs(input1(perm[i], j)); if (value > max_value) { max_index = i; max_value = value; } } if (max_value <= std::numeric_limits<scalar_type>::epsilon()) throw std::runtime_error("matrix is singular"); if (j != max_index) std::swap(perm[j], perm[max_index]); size_t jj = perm[j]; for (size_t i = j + 1; i < n; ++i) { size_t ii = perm[i]; input1(ii, j) /= input1(jj, j); for (size_t k = j + 1; k < n; ++k) input1(ii, k) -= input1(ii, j) * input1(jj, k); } } for (size_t j = 0; j < n; ++j) { lower(j, j) = 1; for (size_t i = j + 1; i < n; ++i) lower(i, j) = input1(perm[i], j); for (size_t i = 0; i <= j; ++i) upper(i, j) = input1(perm[i], j); } matrix<scalar_type> pivot(n, n); for (size_t i = 0; i < n; ++i) pivot(i, perm[i]) = 1; return std::make_tuple(lower, upper, pivot); } template <typename scalar_type> void show_lu_decomposition(const matrix<scalar_type>& input) { try { std::wcout << L"A\n"; print(std::wcout, input); auto result(lu_decompose(input)); std::wcout << L"\nL\n"; print(std::wcout, std::get<0>(result)); std::wcout << L"\nU\n"; print(std::wcout, std::get<1>(result)); std::wcout << L"\nP\n"; print(std::wcout, std::get<2>(result)); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; } } int main() { std::wcout.imbue(std::locale("")); std::wcout << L"Example 1:\n"; matrix<double> matrix1(3, 3, {{1, 3, 5}, {2, 4, 7}, {1, 1, 0}}); show_lu_decomposition(matrix1); std::wcout << '\n'; std::wcout << L"Example 2:\n"; matrix<double> matrix2(4, 4, {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}}); show_lu_decomposition(matrix2); std::wcout << '\n'; std::wcout << L"Example 3:\n"; matrix<double> matrix3(3, 3, {{-5, -6, -3}, {-1, 0, -2}, {-3, -4, -7}}); show_lu_decomposition(matrix3); std::wcout << '\n'; std::wcout << L"Example 4:\n"; matrix<double> matrix4(3, 3, {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}); show_lu_decomposition(matrix4); return 0; }
#include <stdio.h> #include <stdlib.h> #include <math.h> #define foreach(a, b, c) for (int a = b; a < c; a++) #define for_i foreach(i, 0, n) #define for_j foreach(j, 0, n) #define for_k foreach(k, 0, n) #define for_ij for_i for_j #define for_ijk for_ij for_k #define _dim int n #define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; } #define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; } typedef double **mat; #define _zero(a) mat_zero(a, n) void mat_zero(mat x, int n) { for_ij x[i][j] = 0; } #define _new(a) a = mat_new(n) mat mat_new(_dim) { mat x = malloc(sizeof(double*) * n); x[0] = malloc(sizeof(double) * n * n); for_i x[i] = x[0] + n * i; _zero(x); return x; } #define _copy(a) mat_copy(a, n) mat mat_copy(void *s, _dim) { mat x = mat_new(n); for_ij x[i][j] = ((double (*)[n])s)[i][j]; return x; } #define _del(x) mat_del(x) void mat_del(mat x) { free(x[0]); free(x); } #define _QUOT(x) #x #define QUOTE(x) _QUOT(x) #define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n) void mat_show(mat x, char *fmt, _dim) { if (!fmt) fmt = "%8.4g"; for_i { printf(i ? " " : " [ "); for_j { printf(fmt, x[i][j]); printf(j < n - 1 ? " " : i == n - 1 ? " ]\n" : "\n"); } } } #define _mul(a, b) mat_mul(a, b, n) mat mat_mul(mat a, mat b, _dim) { mat c = _new(c); for_ijk c[i][j] += a[i][k] * b[k][j]; return c; } #define _pivot(a, b) mat_pivot(a, b, n) void mat_pivot(mat a, mat p, _dim) { for_ij { p[i][j] = (i == j); } for_i { int max_j = i; foreach(j, i, n) if (fabs(a[j][i]) > fabs(a[max_j][i])) max_j = j; if (max_j != i) for_k { _swap(p[i][k], p[max_j][k]); } } } #define _LU(a, l, u, p) mat_LU(a, l, u, p, n) void mat_LU(mat A, mat L, mat U, mat P, _dim) { _zero(L); _zero(U); _pivot(A, P); mat Aprime = _mul(P, A); for_i { L[i][i] = 1; } for_ij { double s; if (j <= i) { _sum_k(0, j, L[j][k] * U[k][i], s) U[j][i] = Aprime[j][i] - s; } if (j >= i) { _sum_k(0, i, L[j][k] * U[k][i], s); L[j][i] = (Aprime[j][i] - s) / U[i][i]; } } _del(Aprime); } double A3[][3] = {{ 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 }}; double A4[][4] = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}}; int main() { int n = 3; mat A, L, P, U; _new(L); _new(P); _new(U); A = _copy(A3); _LU(A, L, U, P); _show(A); _show(L); _show(U); _show(P); _del(A); _del(L); _del(U); _del(P); printf("\n"); n = 4; _new(L); _new(P); _new(U); A = _copy(A4); _LU(A, L, U, P); _show(A); _show(L); _show(U); _show(P); _del(A); _del(L); _del(U); _del(P); return 0; }
Ensure the translated C code behaves exactly like the original C++ snippet.
#include <algorithm> #include <iostream> #include <vector> #include <string> class pair { public: pair( int s, std::string z ) { p = std::make_pair( s, z ); } bool operator < ( const pair& o ) const { return i() < o.i(); } int i() const { return p.first; } std::string s() const { return p.second; } private: std::pair<int, std::string> p; }; void gFizzBuzz( int c, std::vector<pair>& v ) { bool output; for( int x = 1; x <= c; x++ ) { output = false; for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) { if( !( x % ( *i ).i() ) ) { std::cout << ( *i ).s(); output = true; } } if( !output ) std::cout << x; std::cout << "\n"; } } int main( int argc, char* argv[] ) { std::vector<pair> v; v.push_back( pair( 7, "Baxx" ) ); v.push_back( pair( 3, "Fizz" ) ); v.push_back( pair( 5, "Buzz" ) ); std::sort( v.begin(), v.end() ); gFizzBuzz( 20, v ); return 0; }
#include <stdio.h> #include <stdlib.h> struct replace_info { int n; char *text; }; int compare(const void *a, const void *b) { struct replace_info *x = (struct replace_info *) a; struct replace_info *y = (struct replace_info *) b; return x->n - y->n; } void generic_fizz_buzz(int max, struct replace_info *info, int info_length) { int i, it; int found_word; for (i = 1; i < max; ++i) { found_word = 0; for (it = 0; it < info_length; ++it) { if (0 == i % info[it].n) { printf("%s", info[it].text); found_word = 1; } } if (0 == found_word) printf("%d", i); printf("\n"); } } int main(void) { struct replace_info info[3] = { {5, "Buzz"}, {7, "Baxx"}, {3, "Fizz"} }; qsort(info, 3, sizeof(struct replace_info), compare); generic_fizz_buzz(20, info, 3); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look at ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ; std::getline( std::cin , input ) ; int linenumber = std::stoi( input ) ; int lines_read = 0 ; std::string line ; if ( infile.is_open( ) ) { while ( infile ) { getline( infile , line ) ; lines_read++ ; if ( lines_read == linenumber ) { std::cout << line << std::endl ; break ; } } infile.close( ) ; if ( lines_read < linenumber ) std::cout << "No " << linenumber << " lines in " << file << " !\n" ; return 0 ; } else { std::cerr << "Could not find file " << file << " !\n" ; return 1 ; } }
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1){ warn("line_no too small"); return 0; } line_no--; fd = open(path, O_RDONLY); fstat(fd, &s); buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); madvise(buf, s.st_size, MADV_SEQUENTIAL); for (i = ln = 0; i < s.st_size && ln <= line_no; i++) { if (buf[i] != '\n') continue; if (++ln == line_no) start = i + 1; else if (ln == line_no + 1) end = i + 1; } if (start >= s.st_size || start < 0) { warn("file does not have line %d", line_no + 1); ret = 0; } else { } munmap(buf, s.st_size); close(fd); return ret; }
Write the same code in C as shown below in C++.
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look at ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ; std::getline( std::cin , input ) ; int linenumber = std::stoi( input ) ; int lines_read = 0 ; std::string line ; if ( infile.is_open( ) ) { while ( infile ) { getline( infile , line ) ; lines_read++ ; if ( lines_read == linenumber ) { std::cout << line << std::endl ; break ; } } infile.close( ) ; if ( lines_read < linenumber ) std::cout << "No " << linenumber << " lines in " << file << " !\n" ; return 0 ; } else { std::cerr << "Could not find file " << file << " !\n" ; return 1 ; } }
#include <unistd.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <err.h> int read_file_line(const char *path, int line_no) { struct stat s; char *buf; off_t start = -1, end = -1; size_t i; int ln, fd, ret = 1; if (line_no == 1) start = 0; else if (line_no < 1){ warn("line_no too small"); return 0; } line_no--; fd = open(path, O_RDONLY); fstat(fd, &s); buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0); madvise(buf, s.st_size, MADV_SEQUENTIAL); for (i = ln = 0; i < s.st_size && ln <= line_no; i++) { if (buf[i] != '\n') continue; if (++ln == line_no) start = i + 1; else if (ln == line_no + 1) end = i + 1; } if (start >= s.st_size || start < 0) { warn("file does not have line %d", line_no + 1); ret = 0; } else { } munmap(buf, s.st_size); close(fd); return ret; }
Transform the following C++ implementation into C, maintaining the same output and logic.
#include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <vector> bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) { const size_t n1 = str.length(); const size_t n2 = suffix.length(); if (n1 < n2) return false; return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(), [](char c1, char c2) { return std::tolower(static_cast<unsigned char>(c1)) == std::tolower(static_cast<unsigned char>(c2)); }); } bool filenameHasExtension(const std::string& filename, const std::vector<std::string>& extensions) { return std::any_of(extensions.begin(), extensions.end(), [&filename](const std::string& extension) { return endsWithIgnoreCase(filename, "." + extension); }); } void test(const std::string& filename, const std::vector<std::string>& extensions) { std::cout << std::setw(20) << std::left << filename << ": " << std::boolalpha << filenameHasExtension(filename, extensions) << '\n'; } int main() { const std::vector<std::string> extensions{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}; test("MyData.a##", extensions); test("MyData.tar.Gz", extensions); test("MyData.gzip", extensions); test("MyData.7z.backup", extensions); test("MyData...", extensions); test("MyData", extensions); test("MyData_v1.0.tar.bz2", extensions); test("MyData_v1.0.bz2", extensions); return 0; }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
#include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <vector> bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) { const size_t n1 = str.length(); const size_t n2 = suffix.length(); if (n1 < n2) return false; return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(), [](char c1, char c2) { return std::tolower(static_cast<unsigned char>(c1)) == std::tolower(static_cast<unsigned char>(c2)); }); } bool filenameHasExtension(const std::string& filename, const std::vector<std::string>& extensions) { return std::any_of(extensions.begin(), extensions.end(), [&filename](const std::string& extension) { return endsWithIgnoreCase(filename, "." + extension); }); } void test(const std::string& filename, const std::vector<std::string>& extensions) { std::cout << std::setw(20) << std::left << filename << ": " << std::boolalpha << filenameHasExtension(filename, extensions) << '\n'; } int main() { const std::vector<std::string> extensions{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}; test("MyData.a##", extensions); test("MyData.tar.Gz", extensions); test("MyData.gzip", extensions); test("MyData.7z.backup", extensions); test("MyData...", extensions); test("MyData", extensions); test("MyData_v1.0.tar.bz2", extensions); test("MyData_v1.0.bz2", extensions); return 0; }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
Can you help me rewrite this code in C instead of C++, keeping it the same logically?
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::string operation) { bool printOperation(false); for(const Digit& number : d) { if(printOperation) std::cout << operation; else printOperation = true; std::cout << number; } std::cout << std::endl; } void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") { std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl; } int main() { std::mt19937_64 randomGenerator; std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit}; for(int trial{10}; trial; --trial) { for(Digit& digit : d) { digit = digitDistro(randomGenerator); std::cout << digit << " "; } std::cout << std::endl; std::sort(d.begin(), d.end()); if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal) printTrivialOperation(" + "); if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal) printTrivialOperation(" * "); do { if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - "); if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + "); if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + "); if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )"); if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + "); if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )"); if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )"); if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - "); if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )"); if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )"); if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - "); if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - "); if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + "); if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )"); if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + "); if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / "); if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - "); if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / "); if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )"); if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / "); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )"); if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )"); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", ""); } while(std::next_permutation(d.begin(), d.end())); } return 0; }
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ int a[4] = {8, 3, 8, 3}; float t = 24; nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
Port the following code from C++ to C with equivalent syntax and logic.
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::string operation) { bool printOperation(false); for(const Digit& number : d) { if(printOperation) std::cout << operation; else printOperation = true; std::cout << number; } std::cout << std::endl; } void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") { std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl; } int main() { std::mt19937_64 randomGenerator; std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit}; for(int trial{10}; trial; --trial) { for(Digit& digit : d) { digit = digitDistro(randomGenerator); std::cout << digit << " "; } std::cout << std::endl; std::sort(d.begin(), d.end()); if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal) printTrivialOperation(" + "); if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal) printTrivialOperation(" * "); do { if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - "); if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + "); if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + "); if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )"); if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + "); if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )"); if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )"); if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - "); if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )"); if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )"); if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - "); if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - "); if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + "); if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )"); if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + "); if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / "); if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - "); if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / "); if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )"); if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / "); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )"); if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )"); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", ""); } while(std::next_permutation(d.begin(), d.end())); } return 0; }
#include <stdio.h> typedef struct {int val, op, left, right;} Node; Node nodes[10000]; int iNodes; int b; float eval(Node x){ if (x.op != -1){ float l = eval(nodes[x.left]), r = eval(nodes[x.right]); switch(x.op){ case 0: return l+r; case 1: return l-r; case 2: return r-l; case 3: return l*r; case 4: return r?l/r:(b=1,0); case 5: return l?r/l:(b=1,0); } } else return x.val*1.; } void show(Node x){ if (x.op != -1){ printf("("); switch(x.op){ case 0: show(nodes[x.left]); printf(" + "); show(nodes[x.right]); break; case 1: show(nodes[x.left]); printf(" - "); show(nodes[x.right]); break; case 2: show(nodes[x.right]); printf(" - "); show(nodes[x.left]); break; case 3: show(nodes[x.left]); printf(" * "); show(nodes[x.right]); break; case 4: show(nodes[x.left]); printf(" / "); show(nodes[x.right]); break; case 5: show(nodes[x.right]); printf(" / "); show(nodes[x.left]); break; } printf(")"); } else printf("%d", x.val); } int float_fix(float x){ return x < 0.00001 && x > -0.00001; } void solutions(int a[], int n, float t, int s){ if (s == n){ b = 0; float e = eval(nodes[0]); if (!b && float_fix(e-t)){ show(nodes[0]); printf("\n"); } } else{ nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1}; for (int op = 0; op < 6; op++){ int k = iNodes-1; for (int i = 0; i < k; i++){ nodes[iNodes++] = nodes[i]; nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2}; solutions(a, n, t, s+1); nodes[i] = nodes[--iNodes]; } } iNodes--; } }; int main(){ int a[4] = {8, 3, 8, 3}; float t = 24; nodes[0] = (typeof(Node)){a[0],-1,-1,-1}; iNodes = 1; solutions(a, sizeof(a)/sizeof(int), t, 1); return 0; }
Convert this C++ snippet to C and keep its semantics consistent.
#include <iostream> #include <chrono> #include <atomic> #include <mutex> #include <random> #include <thread> std::mutex cout_lock; class Latch { std::atomic<int> semafor; public: Latch(int limit) : semafor(limit) {} void wait() { semafor.fetch_sub(1); while(semafor.load() > 0) std::this_thread::yield(); } }; struct Worker { static void do_work(int how_long, Latch& barrier, std::string name) { std::this_thread::sleep_for(std::chrono::milliseconds(how_long)); { std::lock_guard<std::mutex> lock(cout_lock); std::cout << "Worker " << name << " finished work\n"; } barrier.wait(); { std::lock_guard<std::mutex> lock(cout_lock); std::cout << "Worker " << name << " finished assembly\n"; } } }; int main() { Latch latch(5); std::mt19937 rng(std::random_device{}()); std::uniform_int_distribution<> dist(300, 3000); std::thread threads[] { std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"), std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"}, }; for(auto& t: threads) t.join(); std::cout << "Assembly is finished"; }
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <omp.h> int main() { int jobs = 41, tid; omp_set_num_threads(5); #pragma omp parallel shared(jobs) private(tid) { tid = omp_get_thread_num(); while (jobs > 0) { #pragma omp barrier if (!jobs) break; printf("%d: taking job %d\n", tid, jobs--); usleep(100000 + rand() / (double) RAND_MAX * 3000000); printf("%d: done job\n", tid); } printf("[%d] leaving\n", tid); #pragma omp barrier } return 0; }
Transform the following C++ implementation into C, maintaining the same output and logic.
#include <iomanip> #include <iostream> #include <vector> std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) { auto it = v.cbegin(); auto end = v.cend(); os << "[ "; if (it != end) { os << std::setfill('0') << std::setw(2) << (uint32_t)*it; it = std::next(it); } while (it != end) { os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it; it = std::next(it); } return os << " ]"; } std::vector<uint8_t> to_seq(uint64_t x) { int i; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) { break; } } std::vector<uint8_t> out; for (int j = 0; j <= i; j++) { out.push_back(((x >> ((i - j) * 7)) & 127) | 128); } out[i] ^= 128; return out; } uint64_t from_seq(const std::vector<uint8_t> &seq) { uint64_t r = 0; for (auto b : seq) { r = (r << 7) | (b & 127); } return r; } int main() { std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL }; for (auto x : src) { auto s = to_seq(x); std::cout << std::hex; std::cout << "seq from " << x << ' ' << s << " back: " << from_seq(s) << '\n'; std::cout << std::dec; } return 0; }
#include <stdio.h> #include <stdint.h> void to_seq(uint64_t x, uint8_t *out) { int i, j; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) break; } for (j = 0; j <= i; j++) out[j] = ((x >> ((i - j) * 7)) & 127) | 128; out[i] ^= 128; } uint64_t from_seq(uint8_t *in) { uint64_t r = 0; do { r = (r << 7) | (uint64_t)(*in & 127); } while (*in++ & 128); return r; } int main() { uint8_t s[10]; uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL}; int i, j; for (j = 0; j < sizeof(x)/8; j++) { to_seq(x[j], s); printf("seq from %llx: [ ", x[j]); i = 0; do { printf("%02x ", s[i]); } while ((s[i++] & 128)); printf("] back: %llx\n", from_seq(s)); } return 0; }
Port the provided C++ code into C while preserving the original functionality.
#include <iostream> #include <string> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) using namespace std; class recorder { public: void start() { paused = rec = false; action = "IDLE"; while( true ) { cout << endl << "==" << action << "==" << endl << endl; cout << "1) Record" << endl << "2) Play" << endl << "3) Pause" << endl << "4) Stop" << endl << "5) Quit" << endl; char c; cin >> c; if( c > '0' && c < '6' ) { switch( c ) { case '1': record(); break; case '2': play(); break; case '3': pause(); break; case '4': stop(); break; case '5': stop(); return; } } } } private: void record() { if( mciExecute( "open new type waveaudio alias my_sound") ) { mciExecute( "record my_sound" ); action = "RECORDING"; rec = true; } } void play() { if( paused ) mciExecute( "play my_sound" ); else if( mciExecute( "open tmp.wav alias my_sound" ) ) mciExecute( "play my_sound" ); action = "PLAYING"; paused = false; } void pause() { if( rec ) return; mciExecute( "pause my_sound" ); paused = true; action = "PAUSED"; } void stop() { if( rec ) { mciExecute( "stop my_sound" ); mciExecute( "save my_sound tmp.wav" ); mciExecute( "close my_sound" ); action = "IDLE"; rec = false; } else { mciExecute( "stop my_sound" ); mciExecute( "close my_sound" ); action = "IDLE"; } } bool mciExecute( string cmd ) { if( mciSendString( cmd.c_str(), NULL, 0, NULL ) ) { cout << "Can't do this: " << cmd << endl; return false; } return true; } bool paused, rec; string action; }; int main( int argc, char* argv[] ) { recorder r; r.start(); return 0; }
#include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> void * record(size_t bytes) { int fd; if (-1 == (fd = open("/dev/dsp", O_RDONLY))) return 0; void *a = malloc(bytes); read(fd, a, bytes); close(fd); return a; } int play(void *buf, size_t len) { int fd; if (-1 == (fd = open("/dev/dsp", O_WRONLY))) return 0; write(fd, buf, len); close(fd); return 1; } int main() { void *p = record(65536); play(p, 65536); return 0; }
Can you help me rewrite this code in C instead of C++, keeping it the same logically?
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <vector> #include <openssl/sha.h> class sha256_exception : public std::exception { public: const char* what() const noexcept override { return "SHA-256 error"; } }; class sha256 { public: sha256() { reset(); } sha256(const sha256&) = delete; sha256& operator=(const sha256&) = delete; void reset() { if (SHA256_Init(&context_) == 0) throw sha256_exception(); } void update(const void* data, size_t length) { if (SHA256_Update(&context_, data, length) == 0) throw sha256_exception(); } std::vector<unsigned char> digest() { std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH); if (SHA256_Final(digest.data(), &context_) == 0) throw sha256_exception(); return digest; } private: SHA256_CTX context_; }; std::string digest_to_string(const std::vector<unsigned char>& digest) { std::ostringstream out; out << std::hex << std::setfill('0'); for (size_t i = 0; i < digest.size(); ++i) out << std::setw(2) << static_cast<int>(digest[i]); return out.str(); } std::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) { std::vector<std::vector<unsigned char>> hashes; std::vector<char> buffer(block_size); sha256 md; while (in) { in.read(buffer.data(), block_size); size_t bytes = in.gcount(); if (bytes == 0) break; md.reset(); md.update(buffer.data(), bytes); hashes.push_back(md.digest()); } if (hashes.empty()) return {}; size_t length = hashes.size(); while (length > 1) { size_t j = 0; for (size_t i = 0; i < length; i += 2, ++j) { auto& digest1 = hashes[i]; auto& digest_out = hashes[j]; if (i + 1 < length) { auto& digest2 = hashes[i + 1]; md.reset(); md.update(digest1.data(), digest1.size()); md.update(digest2.data(), digest2.size()); digest_out = md.digest(); } else { digest_out = digest1; } } length = j; } return hashes[0]; } int main(int argc, char** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " filename\n"; return EXIT_FAILURE; } std::ifstream in(argv[1], std::ios::binary); if (!in) { std::cerr << "Cannot open file " << argv[1] << ".\n"; return EXIT_FAILURE; } try { std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\n'; } catch (const std::exception& ex) { std::cerr << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
#include <glib.h> #include <stdlib.h> #include <stdio.h> #include <string.h> guchar* sha256_merkle_tree(FILE* in, size_t block_size) { gchar* buffer = g_malloc(block_size); GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free); gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256); GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256); size_t bytes; while ((bytes = fread(buffer, 1, block_size, in)) > 0) { g_checksum_reset(checksum); g_checksum_update(checksum, (guchar*)buffer, bytes); gsize len = digest_length; guchar* digest = g_malloc(len); g_checksum_get_digest(checksum, digest, &len); g_ptr_array_add(hashes, digest); } g_free(buffer); guint hashes_length = hashes->len; if (hashes_length == 0) { g_ptr_array_free(hashes, TRUE); g_checksum_free(checksum); return NULL; } while (hashes_length > 1) { guint j = 0; for (guint i = 0; i < hashes_length; i += 2, ++j) { guchar* digest1 = g_ptr_array_index(hashes, i); guchar* digest_out = g_ptr_array_index(hashes, j); if (i + 1 < hashes_length) { guchar* digest2 = g_ptr_array_index(hashes, i + 1); g_checksum_reset(checksum); g_checksum_update(checksum, digest1, digest_length); g_checksum_update(checksum, digest2, digest_length); gsize len = digest_length; g_checksum_get_digest(checksum, digest_out, &len); } else { memcpy(digest_out, digest1, digest_length); } } hashes_length = j; } guchar* result = g_ptr_array_steal_index(hashes, 0); g_ptr_array_free(hashes, TRUE); g_checksum_free(checksum); return result; } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s filename\n", argv[0]); return EXIT_FAILURE; } FILE* in = fopen(argv[1], "rb"); if (in) { guchar* digest = sha256_merkle_tree(in, 1024); fclose(in); if (digest) { gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256); for (gssize i = 0; i < length; ++i) printf("%02x", digest[i]); printf("\n"); g_free(digest); } } else { perror(argv[1]); return EXIT_FAILURE; } return EXIT_SUCCESS; }
Please provide an equivalent version of this C++ code in C.
#include <algorithm> #include <string> #include <cctype> void str_toupper(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::toupper); } void str_tolower(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::tolower); }
#include <ctype.h> #include <stdio.h> void str_toupper(char *s) { while(*s) { *s=toupper(*s); s++; } } void str_tolower(char *s) { while(*s) { *s=tolower(*s); s++; } } int main(int argc, char *argv[]) { char t[255]="alphaBETA"; str_toupper(t); printf("uppercase: %s\n", t); str_tolower(t); printf("lowercase: %s\n", t); return 0; }
Generate a C translation of this C++ snippet without changing its computational steps.
#ifndef TASK_H #define TASK_H #include <QWidget> class QLabel ; class QLineEdit ; class QVBoxLayout ; class QHBoxLayout ; class EntryWidget : public QWidget { Q_OBJECT public : EntryWidget( QWidget *parent = 0 ) ; private : QHBoxLayout *upperpart , *lowerpart ; QVBoxLayout *entryLayout ; QLineEdit *stringinput ; QLineEdit *numberinput ; QLabel *stringlabel ; QLabel *numberlabel ; } ; #endif
#include <gtk/gtk.h> void ok_hit(GtkButton *o, GtkWidget **w) { GtkMessageDialog *msg; gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]); const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]); msg = (GtkMessageDialog *) gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "You wrote '%s' and selected the number %d%s", c, (gint)v, (v==75000) ? "" : " which is wrong (75000 expected)!"); gtk_widget_show_all(GTK_WIDGET(msg)); (void)gtk_dialog_run(GTK_DIALOG(msg)); gtk_widget_destroy(GTK_WIDGET(msg)); if ( v==75000 ) gtk_main_quit(); } int main(int argc, char **argv) { GtkWindow *win; GtkEntry *entry; GtkSpinButton *spin; GtkButton *okbutton; GtkLabel *entry_l, *spin_l; GtkHBox *hbox[2]; GtkVBox *vbox; GtkWidget *widgs[2]; gtk_init(&argc, &argv); win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(win, "Insert values"); entry_l = (GtkLabel *)gtk_label_new("Insert a string"); spin_l = (GtkLabel *)gtk_label_new("Insert 75000"); entry = (GtkEntry *)gtk_entry_new(); spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1); widgs[0] = GTK_WIDGET(entry); widgs[1] = GTK_WIDGET(spin); okbutton = (GtkButton *)gtk_button_new_with_label("Ok"); hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1); hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1); vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l)); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin)); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox)); g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL); g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
Preserve the algorithm and functionality while converting the code from C++ to C.
#include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; struct point { double x; double y; }; std::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(3*(size - 1) + 1); double x0, y0, x1, y1; size_t j = 0; for (size_t i = 0; i + 1 < size; ++i, j += 3) { x0 = points[i].x; y0 = points[i].y; x1 = points[i + 1].x; y1 = points[i + 1].y; double dx = x1 - x0; output[j] = {x0, y0}; if (y0 == y1) { double d = dx * sqrt3_2/2; if (d < 0) d = -d; output[j + 1] = {x0 + dx/4, y0 - d}; output[j + 2] = {x1 - dx/4, y0 - d}; } else if (y1 < y0) { output[j + 1] = {x1, y0}; output[j + 2] = {x1 + dx/2, (y0 + y1)/2}; } else { output[j + 1] = {x0 - dx/2, (y0 + y1)/2}; output[j + 2] = {x0, y1}; } } output[j] = {x1, y1}; return output; } void write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) { out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; const double margin = 20.0; const double side = size - 2.0 * margin; const double x = margin; const double y = 0.5 * size + 0.5 * sqrt3_2 * side; std::vector<point> points{{x, y}, {x + side, y}}; for (int i = 0; i < iterations; ++i) points = sierpinski_arrowhead_next(points); for (size_t i = 0, n = points.size(); i < n; ++i) out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n'; out << "'/>\n</svg>\n"; } int main() { std::ofstream out("sierpinski_arrowhead.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); return EXIT_SUCCESS; }
#include <math.h> #include <stdio.h> #include <stdlib.h> typedef struct cursor_tag { double x; double y; int angle; } cursor_t; void turn(cursor_t* cursor, int angle) { cursor->angle = (cursor->angle + angle) % 360; } void draw_line(FILE* out, cursor_t* cursor, double length) { double theta = (M_PI * cursor->angle)/180.0; cursor->x += length * cos(theta); cursor->y += length * sin(theta); fprintf(out, "L%g,%g\n", cursor->x, cursor->y); } void curve(FILE* out, int order, double length, cursor_t* cursor, int angle) { if (order == 0) { draw_line(out, cursor, length); } else { curve(out, order - 1, length/2, cursor, -angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, -angle); } } void write_sierpinski_arrowhead(FILE* out, int size, int order) { const double margin = 20.0; const double side = size - 2.0 * margin; cursor_t cursor; cursor.angle = 0; cursor.x = margin; cursor.y = 0.5 * size + 0.25 * sqrt(3) * side; if ((order & 1) != 0) turn(&cursor, -60); fprintf(out, "<svg xmlns='http: size, size); fprintf(out, "<rect width='100%%' height='100%%' fill='white'/>\n"); fprintf(out, "<path stroke-width='1' stroke='black' fill='none' d='"); fprintf(out, "M%g,%g\n", cursor.x, cursor.y); curve(out, order, side, &cursor, 60); fprintf(out, "'/>\n</svg>\n"); } int main(int argc, char** argv) { const char* filename = "sierpinski_arrowhead.svg"; if (argc == 2) filename = argv[1]; FILE* out = fopen(filename, "w"); if (!out) { perror(filename); return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); fclose(out); return EXIT_SUCCESS; }
Produce a functionally identical C code for the snippet given in C++.
#include <iostream> #include <fstream> #include <string> #include <vector> #include <iomanip> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> using std::cout; using std::endl; const int NumFlags = 24; int main() { std::fstream file("readings.txt"); int badCount = 0; std::string badDate; int badCountMax = 0; while(true) { std::string line; getline(file, line); if(!file.good()) break; std::vector<std::string> tokens; boost::algorithm::split(tokens, line, boost::is_space()); if(tokens.size() != NumFlags * 2 + 1) { cout << "Bad input file." << endl; return 0; } double total = 0.0; int accepted = 0; for(size_t i = 1; i < tokens.size(); i += 2) { double val = boost::lexical_cast<double>(tokens[i]); int flag = boost::lexical_cast<int>(tokens[i+1]); if(flag > 0) { total += val; ++accepted; badCount = 0; } else { ++badCount; if(badCount > badCountMax) { badCountMax = badCount; badDate = tokens[0]; } } } cout << tokens[0]; cout << " Reject: " << std::setw(2) << (NumFlags - accepted); cout << " Accept: " << std::setw(2) << accepted; cout << " Average: " << std::setprecision(5) << total / accepted << endl; } cout << endl; cout << "Maximum number of consecutive bad readings is " << badCountMax << endl; cout << "Ends on date " << badDate << endl; }
#include <stdio.h> #include <stdlib.h> #include <string.h> static int badHrs, maxBadHrs; static double hrsTot = 0.0; static int rdgsTot = 0; char bhEndDate[40]; int mungeLine( char *line, int lno, FILE *fout ) { char date[40], *tkn; int dHrs, flag, hrs2, hrs; double hrsSum; int hrsCnt = 0; double avg; tkn = strtok(line, "."); if (tkn) { int n = sscanf(tkn, "%s %d", &date, &hrs2); if (n<2) { printf("badly formated line - %d %s\n", lno, tkn); return 0; } hrsSum = 0.0; while( tkn= strtok(NULL, ".")) { n = sscanf(tkn,"%d %d %d", &dHrs, &flag, &hrs); if (n>=2) { if (flag > 0) { hrsSum += 1.0*hrs2 + .001*dHrs; hrsCnt += 1; if (maxBadHrs < badHrs) { maxBadHrs = badHrs; strcpy(bhEndDate, date); } badHrs = 0; } else { badHrs += 1; } hrs2 = hrs; } else { printf("bad file syntax line %d: %s\n",lno, tkn); } } avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0; fprintf(fout, "%s Reject: %2d Accept: %2d Average: %7.3f\n", date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt); hrsTot += hrsSum; rdgsTot += hrsCnt; } return 1; } int main() { FILE *infile, *outfile; int lineNo = 0; char line[512]; const char *ifilename = "readings.txt"; outfile = fopen("V0.txt", "w"); infile = fopen(ifilename, "rb"); if (!infile) { printf("Can't open %s\n", ifilename); exit(1); } while (NULL != fgets(line, 512, infile)) { lineNo += 1; if (0 == mungeLine(line, lineNo, outfile)) printf("Bad line at %d",lineNo); } fclose(infile); fprintf(outfile, "File: %s\n", ifilename); fprintf(outfile, "Total:  %.3f\n", hrsTot); fprintf(outfile, "Readings: %d\n", rdgsTot); fprintf(outfile, "Average:  %.3f\n", hrsTot/rdgsTot); fprintf(outfile, "\nMaximum number of consecutive bad readings is %d\n", maxBadHrs); fprintf(outfile, "Ends on date %s\n", bhEndDate); fclose(outfile); return 0; }
Write the same algorithm in C as shown in this C++ implementation.
#include <string> #include <iostream> #include "Poco/MD5Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::MD5Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ; MD5Engine md5 ; DigestOutputStream outstr( md5 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = md5.digest( ) ; std::cout << myphrase << " as a MD5 digest :\n" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h> const char *string = "The quick brown fox jumped over the lazy dog's back"; int main() { int i; unsigned char result[MD5_DIGEST_LENGTH]; MD5(string, strlen(string), result); for(i = 0; i < MD5_DIGEST_LENGTH; i++) printf("%02x", result[i]); printf("\n"); return EXIT_SUCCESS; }
Convert this C++ block to C, preserving its control flow and logic.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } void classify_aliquot_sequence(integer n) { constexpr int limit = 16; integer terms[limit]; terms[0] = n; std::string classification("non-terminating"); int length = 1; for (int i = 1; i < limit; ++i) { ++length; terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1]; if (terms[i] == n) { classification = (i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable")); break; } int j = 1; for (; j < i; ++j) { if (terms[i] == terms[i - j]) break; } if (j < i) { classification = (j == 1 ? "aspiring" : "cyclic"); break; } if (terms[i] == 0) { classification = "terminating"; break; } } std::cout << n << ": " << classification << ", sequence: " << terms[0]; for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i) std::cout << ' ' << terms[i]; std::cout << '\n'; } int main() { for (integer i = 1; i <= 10; ++i) classify_aliquot_sequence(i); for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}) classify_aliquot_sequence(i); classify_aliquot_sequence(15355717786080); classify_aliquot_sequence(153557177860800); return 0; }
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Preserve the algorithm and functionality while converting the code from C++ to C.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } void classify_aliquot_sequence(integer n) { constexpr int limit = 16; integer terms[limit]; terms[0] = n; std::string classification("non-terminating"); int length = 1; for (int i = 1; i < limit; ++i) { ++length; terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1]; if (terms[i] == n) { classification = (i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable")); break; } int j = 1; for (; j < i; ++j) { if (terms[i] == terms[i - j]) break; } if (j < i) { classification = (j == 1 ? "aspiring" : "cyclic"); break; } if (terms[i] == 0) { classification = "terminating"; break; } } std::cout << n << ": " << classification << ", sequence: " << terms[0]; for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i) std::cout << ' ' << terms[i]; std::cout << '\n'; } int main() { for (integer i = 1; i <= 10; ++i) classify_aliquot_sequence(i); for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}) classify_aliquot_sequence(i); classify_aliquot_sequence(15355717786080); classify_aliquot_sequence(153557177860800); return 0; }
#include<stdlib.h> #include<string.h> #include<stdio.h> unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0; for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i; return sum; } void printSeries(unsigned long long* arr,int size,char* type){ int i; printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); for(i=0;i<size-1;i++) printf("%llu, ",arr[i]); printf("%llu",arr[i]); } void aliquotClassifier(unsigned long long n){ unsigned long long arr[16]; int i,j; arr[0] = n; for(i=1;i<16;i++){ arr[i] = bruteForceProperDivisorSum(arr[i-1]); if(arr[i]==0||arr[i]==n||(arr[i]==arr[i-1] && arr[i]!=n)){ printSeries(arr,i+1,(arr[i]==0)?"Terminating":(arr[i]==n && i==1)?"Perfect":(arr[i]==n && i==2)?"Amicable":(arr[i]==arr[i-1] && arr[i]!=n)?"Aspiring":"Sociable"); return; } for(j=1;j<i;j++){ if(arr[j]==arr[i]){ printSeries(arr,i+1,"Cyclic"); return; } } } printSeries(arr,i+1,"Non-Terminating"); } void processFile(char* fileName){ FILE* fp = fopen(fileName,"r"); char str[21]; while(fgets(str,21,fp)!=NULL) aliquotClassifier(strtoull(str,(char**)NULL,10)); fclose(fp); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <positive integer>",argV[0]); else{ if(strchr(argV[1],'.')!=NULL) processFile(argV[1]); else aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); } return 0; }
Produce a language-to-language conversion: from C++ to C, same semantics.
#include <string> #include <iostream> #include <boost/date_time/local_time/local_time.hpp> #include <sstream> #include <boost/date_time/gregorian/gregorian.hpp> #include <vector> #include <boost/algorithm/string.hpp> #include <cstdlib> #include <locale> int main( ) { std::string datestring ("March 7 2009 7:30pm EST" ) ; std::vector<std::string> elements ; boost::split( elements , datestring , boost::is_any_of( " " ) ) ; std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " + elements[ 2 ] ; std::string timepart = elements[ 3 ] ; std::string timezone = elements[ 4 ] ; const char meridians[ ] = { 'a' , 'p' } ; std::string::size_type found = timepart.find_first_of( meridians, 0 ) ; std::string twelve_hour ( timepart.substr( found , 1 ) ) ; timepart = timepart.substr( 0 , found ) ; elements.clear( ) ; boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ; long hour = std::atol( (elements.begin( ))->c_str( ) ) ; if ( twelve_hour == "p" ) hour += 12 ; long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; boost::local_time::tz_database tz_db ; tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ; boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ; boost::gregorian::date_input_facet *f = new boost::gregorian::date_input_facet( "%B %d %Y" ) ; std::stringstream ss ; ss << datepart ; ss.imbue( std::locale( std::locale::classic( ) , f ) ) ; boost::gregorian::date d ; ss >> d ; boost::posix_time::time_duration td ( hour , minute , 0 ) ; boost::local_time::local_date_time lt ( d , td , dyc , boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ; std::cout << "local time: " << lt << '\n' ; ss.str( "" ) ; ss << lt ; boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ; boost::local_time::local_date_time ltlater = lt + td2 ; boost::gregorian::date_facet *f2 = new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ; std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ; std::cout << "12 hours after " << ss.str( ) << " it is " << ltlater << " !\n" ; boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ; std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ; std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ; return 0 ; }
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { struct tm ts; time_t t; const char *d = "March 7 2009 7:30pm EST"; strptime(d, "%B %d %Y %I:%M%p %Z", &ts); t = mktime(&ts); t += 12*60*60; printf("%s", ctime(&t)); return EXIT_SUCCESS; }
Generate an equivalent C version of this C++ code.
#include <chrono> #include <iostream> #include <thread> #include <vector> int main(int argc, char* argv[]) { std::vector<std::thread> threads; for (int i = 1; i < argc; ++i) { threads.emplace_back([i, &argv]() { int arg = std::stoi(argv[i]); std::this_thread::sleep_for(std::chrono::seconds(arg)); std::cout << argv[i] << std::endl; }); } for (auto& thread : threads) { thread.join(); } }
>>>>>,----------[++++++++ ++[->+>+<<]>+>[-<<+>>]+++ +++++[-<------>]>>+>,---- ------<<+[->>>>>+<<<<<]>> ]>>>[<<<<[<<<[->>+<<[->+> [-]<<]]>[-<+>]>[-<<<.>>>> ->>>>>[>>>>>]<-<<<<[<<<<< ]+<]<<<<]>>>>>[>>>>>]<]
Ensure the translated C code behaves exactly like the original C++ snippet.
#include<cstdlib> #include<ctime> #include<iostream> using namespace std; int main() { int arr[10][10]; srand(time(NULL)); for(auto& row: arr) for(auto& col: row) col = rand() % 20 + 1; ([&](){ for(auto& row : arr) for(auto& col: row) { cout << col << endl; if(col == 20)return; } })(); return 0; }
#include <stdlib.h> #include <time.h> #include <stdio.h> int main() { int a[10][10], i, j; srand(time(NULL)); for (i = 0; i < 10; i++) for (j = 0; j < 10; j++) a[i][j] = rand() % 20 + 1; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf(" %d", a[i][j]); if (a[i][j] == 20) goto Done; } printf("\n"); } Done: printf("\n"); return 0; }
Produce a language-to-language conversion: from C++ to C, same semantics.
#include <cmath> #include <iostream> #include <numeric> #include <tuple> #include <vector> using namespace std; auto CountTriplets(unsigned long long maxPerimeter) { unsigned long long totalCount = 0; unsigned long long primitveCount = 0; auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1; for(unsigned long long m = 2; m < max_M; ++m) { for(unsigned long long n = 1 + m % 2; n < m; n+=2) { if(gcd(m,n) != 1) { continue; } auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto perimeter = a + b + c; if(perimeter <= maxPerimeter) { primitveCount++; totalCount+= maxPerimeter / perimeter; } } } return tuple(totalCount, primitveCount); } int main() { vector<unsigned long long> inputs{100, 1000, 10'000, 100'000, 1000'000, 10'000'000, 100'000'000, 1000'000'000, 10'000'000'000}; for(auto maxPerimeter : inputs) { auto [total, primitive] = CountTriplets(maxPerimeter); cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ; } }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the C++ version.
#include <cmath> #include <iostream> #include <numeric> #include <tuple> #include <vector> using namespace std; auto CountTriplets(unsigned long long maxPerimeter) { unsigned long long totalCount = 0; unsigned long long primitveCount = 0; auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1; for(unsigned long long m = 2; m < max_M; ++m) { for(unsigned long long n = 1 + m % 2; n < m; n+=2) { if(gcd(m,n) != 1) { continue; } auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto perimeter = a + b + c; if(perimeter <= maxPerimeter) { primitveCount++; totalCount+= maxPerimeter / perimeter; } } } return tuple(totalCount, primitveCount); } int main() { vector<unsigned long long> inputs{100, 1000, 10'000, 100'000, 1000'000, 10'000'000, 100'000'000, 1000'000'000, 10'000'000'000}; for(auto maxPerimeter : inputs) { auto [total, primitive] = CountTriplets(maxPerimeter); cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ; } }
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef unsigned long ulong; inline ulong gcd(ulong m, ulong n) { ulong t; while (n) { t = n; n = m % n; m = t; } return m; } int main() { ulong a, b, c, pytha = 0, prim = 0, max_p = 100; xint aa, bb, cc; for (a = 1; a <= max_p / 3; a++) { aa = (xint)a * a; printf("a = %lu\r", a); fflush(stdout); for (b = a + 1; b < max_p/2; b++) { bb = (xint)b * b; for (c = b + 1; c < max_p/2; c++) { cc = (xint)c * c; if (aa + bb < cc) break; if (a + b + c > max_p) break; if (aa + bb == cc) { pytha++; if (gcd(a, b) == 1) prim++; } } } } printf("Up to %lu, there are %lu triples, of which %lu are primitive\n", max_p, pytha, prim); return 0; }
Change the following C++ code into C without altering its purpose.
#include <set> #include <iostream> using namespace std; int main() { typedef set<int> TySet; int data[] = {1, 2, 3, 2, 3, 4}; TySet unique_set(data, data + 6); cout << "Set items:" << endl; for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++) cout << *iter << " "; cout << endl; }
#include <stdio.h> #include <stdlib.h> struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int i = 1 ; i < alen ; ++i) {node *n = start; for (;; n = n->next) {if (a[i] == n->x) break; if (n->next == NULL) {n->next = malloc(sizeof(node)); n = n->next; if (n == NULL) exit(EXIT_FAILURE); n->x = a[i]; n->next = NULL; break;}}} return start;} int main(void) {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}; for (node *n = uniq(a, 10) ; n != NULL ; n = n->next) printf("%d ", n->x); puts(""); return 0;}
Convert this C++ block to C, preserving its control flow and logic.
#include <iostream> #include <sstream> #include <string> std::string lookandsay(const std::string& s) { std::ostringstream r; for (std::size_t i = 0; i != s.length();) { auto new_i = s.find_first_not_of(s[i], i + 1); if (new_i == std::string::npos) new_i = s.length(); r << new_i - i << s[i]; i = new_i; } return r.str(); } int main() { std::string laf = "1"; std::cout << laf << '\n'; for (int i = 0; i < 10; ++i) { laf = lookandsay(laf); std::cout << laf << '\n'; } }
#include <stdio.h> #include <stdlib.h> int main() { char *a = malloc(2), *b = 0, *x, c; int cnt, len = 1; for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { puts(x = a); for (len = 0, cnt = 1; (c = *a); ) { if (c == *++a) cnt++; else if (c) { len += sprintf(b + len, "%d%c", cnt, c); cnt = 1; } } } return 0; }
Write a version of this C++ function in C with identical behavior.
#include <stack>
#include <stdio.h> #include <stdlib.h> #define DECL_STACK_TYPE(type, name) \ typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \ stk_##name stk_##name##_create(size_t init_size) { \ stk_##name s; if (!init_size) init_size = 4; \ s = malloc(sizeof(struct stk_##name##_t)); \ if (!s) return 0; \ s->buf = malloc(sizeof(type) * init_size); \ if (!s->buf) { free(s); return 0; } \ s->len = 0, s->alloc = init_size; \ return s; } \ int stk_##name##_push(stk_##name s, type item) { \ type *tmp; \ if (s->len >= s->alloc) { \ tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ if (!tmp) return -1; s->buf = tmp; \ s->alloc *= 2; } \ s->buf[s->len++] = item; \ return s->len; } \ type stk_##name##_pop(stk_##name s) { \ type tmp; \ if (!s->len) abort(); \ tmp = s->buf[--s->len]; \ if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ s->alloc /= 2; \ s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ return tmp; } \ void stk_##name##_delete(stk_##name s) { \ free(s->buf); free(s); } #define stk_empty(s) (!(s)->len) #define stk_size(s) ((s)->len) DECL_STACK_TYPE(int, int) int main(void) { int i; stk_int stk = stk_int_create(0); printf("pushing: "); for (i = 'a'; i <= 'z'; i++) { printf(" %c", i); stk_int_push(stk, i); } printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); printf("\npoppoing:"); while (stk_size(stk)) printf(" %c", stk_int_pop(stk)); printf("\nsize now: %d", stk_size(stk)); printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); stk_int_delete(stk); return 0; }
Can you help me rewrite this code in C instead of C++, keeping it the same logically?
#include <cassert> #include <iomanip> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) continue; for (int j = i; j <= max; j += i) totient_[j] -= totient_[j] / i; } } int totient(int n) const { assert (n >= 1 && n < totient_.size()); return totient_[n]; } bool is_prime(int n) const { return totient(n) == n - 1; } private: std::vector<int> totient_; }; int count_primes(const totient_calculator& tc, int min, int max) { int count = 0; for (int i = min; i <= max; ++i) { if (tc.is_prime(i)) ++count; } return count; } int main() { const int max = 10000000; totient_calculator tc(max); std::cout << " n totient prime?\n"; for (int i = 1; i <= 25; ++i) { std::cout << std::setw(2) << i << std::setw(9) << tc.totient(i) << std::setw(8) << (tc.is_prime(i) ? "yes" : "no") << '\n'; } for (int n = 100; n <= max; n *= 10) { std::cout << "Count of primes up to " << n << ": " << count_primes(tc, 1, n) << '\n'; } return 0; }
#include<stdio.h> int totient(int n){ int tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } int main() { int count = 0,n,tot; printf(" n %c prime",237); printf("\n---------------\n"); for(n=1;n<=25;n++){ tot = totient(n); if(n-1 == tot) count++; printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False"); } printf("\nNumber of primes up to %6d =%4d\n", 25,count); for(n = 26; n <= 100000; n++){ tot = totient(n); if(tot == n-1) count++; if(n == 100 || n == 1000 || n%10000 == 0){ printf("\nNumber of primes up to %6d = %4d\n", n, count); } } return 0; }
Write the same code in C as shown below in C++.
template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse; template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType> { typedef ThenType type; }; template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType> { typedef ElseType type; }; ifthenelse<INT_MAX == 32767, long int, int> ::type myvar;
int a = 3; if (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } unless (a == 2) { puts ("a is 2"); } else if (a == 3) { puts ("a is 3"); } else { puts("a is 4"); } switch (a) { case 2: puts ("a is 2"); break; case 3: puts ("a is 3"); break; case 4: puts ("a is 4"); break; default: puts("is neither"); }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <iostream> #include <string> #include <random> int main() { std::random_device rd; std::uniform_int_distribution<int> dist(1, 10); std::mt19937 mt(rd()); std::cout << "Random Number (hardware): " << dist(rd) << std::endl; std::cout << "Mersenne twister (hardware seeded): " << dist(mt) << std::endl; }
#include <stdio.h> #include <stdlib.h> int main() { int i; srand(time(NULL)); for (i = 0; i < 10; i++) puts((rand() % 2) ? "heads" : "tails"); return 0; }
Preserve the algorithm and functionality while converting the code from C++ to C.
#include <iostream> #include <string> #include <random> int main() { std::random_device rd; std::uniform_int_distribution<int> dist(1, 10); std::mt19937 mt(rd()); std::cout << "Random Number (hardware): " << dist(rd) << std::endl; std::cout << "Mersenne twister (hardware seeded): " << dist(mt) << std::endl; }
#include <stdio.h> #include <stdlib.h> int main() { int i; srand(time(NULL)); for (i = 0; i < 10; i++) puts((rand() % 2) ? "heads" : "tails"); return 0; }
Change the following C++ code into C without altering its purpose.
#include <iostream> #include <string> #include <random> int main() { std::random_device rd; std::uniform_int_distribution<int> dist(1, 10); std::mt19937 mt(rd()); std::cout << "Random Number (hardware): " << dist(rd) << std::endl; std::cout << "Mersenne twister (hardware seeded): " << dist(mt) << std::endl; }
#include <stdio.h> #include <stdlib.h> int main() { int i; srand(time(NULL)); for (i = 0; i < 10; i++) puts((rand() % 2) ? "heads" : "tails"); return 0; }
Please provide an equivalent version of this C++ code in C.
#include <iostream> #include <sstream> #include <iterator> #include <vector> #include <cmath> using namespace std; class fractran { public: void run( std::string p, int s, int l ) { start = s; limit = l; istringstream iss( p ); vector<string> tmp; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) ); string item; vector< pair<float, float> > v; pair<float, float> a; for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ ) { string::size_type pos = ( *i ).find( '/', 0 ); if( pos != std::string::npos ) { a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) ); v.push_back( a ); } } exec( &v ); } private: void exec( vector< pair<float, float> >* v ) { int cnt = 0; while( cnt < limit ) { cout << cnt << " : " << start << "\n"; cnt++; vector< pair<float, float> >::iterator it = v->begin(); bool found = false; float r; while( it != v->end() ) { r = start * ( ( *it ).first / ( *it ).second ); if( r == floor( r ) ) { found = true; break; } ++it; } if( found ) start = ( int )r; else break; } } int start, limit; }; int main( int argc, char* argv[] ) { fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 ); cin.get(); return 0; }
#include <stdio.h> #include <stdlib.h> #include <gmp.h> typedef struct frac_s *frac; struct frac_s { int n, d; frac next; }; frac parse(char *s) { int offset = 0; struct frac_s h = {0}, *p = &h; while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { s += offset; p = p->next = malloc(sizeof *p); *p = h; p->next = 0; } return h.next; } int run(int v, char *s) { frac n, p = parse(s); mpz_t val; mpz_init_set_ui(val, v); loop: n = p; if (mpz_popcount(val) == 1) gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); else gmp_printf(" %Zd", val); for (n = p; n; n = n->next) { if (!mpz_divisible_ui_p(val, n->d)) continue; mpz_divexact_ui(val, val, n->d); mpz_mul_ui(val, val, n->n); goto loop; } gmp_printf("\nhalt: %Zd has no divisors\n", val); mpz_clear(val); while (p) { n = p->next; free(p); p = n; } return 0; } int main(void) { run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 " "77/19 1/17 11/13 13/11 15/14 15/2 55/1"); return 0; }
Keep all operations the same but rewrite the snippet in C.
#include <iostream> #include <time.h> using namespace std; class stooge { public: void sort( int* arr, int start, int end ) { if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] ); int n = end - start; if( n > 2 ) { n /= 3; sort( arr, start, end - n ); sort( arr, start + n, end ); sort( arr, start, end - n ); } } }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; cout << "before:\n"; for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20; cout << a[x] << " "; } s.sort( a, 0, m ); cout << "\n\nafter:\n"; for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n"; return system( "pause" ); }
#include <stdio.h> #define SWAP(r,s) do{ t=r; r=s; s=t; } while(0) void StoogeSort(int a[], int i, int j) { int t; if (a[j] < a[i]) SWAP(a[i], a[j]); if (j - i > 1) { t = (j - i + 1) / 3; StoogeSort(a, i, j - t); StoogeSort(a, i + t, j); StoogeSort(a, i, j - t); } } int main(int argc, char *argv[]) { int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7}; int i, n; n = sizeof(nums)/sizeof(int); StoogeSort(nums, 0, n-1); for(i = 0; i <= n-1; i++) printf("%5d", nums[i]); return 0; }
Generate a C translation of this C++ snippet without changing its computational steps.
#include "stdafx.h" #include <windows.h> #include <stdlib.h> const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class point { public: int x; float y; void set( int a, float b ) { x = a; y = b; } }; typedef struct { point position, offset; bool alive, start; }ball; class galton { public : galton() { bmp.create( BMP_WID, BMP_HEI ); initialize(); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } void simulate() { draw(); update(); Sleep( 1 ); } private: void draw() { bmp.clear(); bmp.setPenColor( RGB( 0, 255, 0 ) ); bmp.setBrushColor( RGB( 0, 255, 0 ) ); int xx, yy; for( int y = 3; y < 14; y++ ) { yy = 10 * y; for( int x = 0; x < 41; x++ ) { xx = 10 * x; if( pins[y][x] ) Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 ); } } bmp.setPenColor( RGB( 255, 0, 0 ) ); bmp.setBrushColor( RGB( 255, 0, 0 ) ); ball* b; for( int x = 0; x < MAX_BALLS; x++ ) { b = &balls[x]; if( b->alive ) Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) ); } for( int x = 0; x < 70; x++ ) { if( cols[x] > 0 ) { xx = 10 * x; Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] ); } } HDC dc = GetDC( _hwnd ); BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( _hwnd, dc ); } void update() { ball* b; for( int x = 0; x < MAX_BALLS; x++ ) { b = &balls[x]; if( b->alive ) { b->position.x += b->offset.x; b->position.y += b->offset.y; if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) { b->start = true; balls[x + 1].alive = true; } int c = ( int )b->position.x, d = ( int )b->position.y + 6; if( d > 10 || d < 41 ) { if( pins[d / 10][c / 10] ) { if( rand() % 30 < 15 ) b->position.x -= 10; else b->position.x += 10; } } if( b->position.y > 160 ) { b->alive = false; cols[c / 10] += 1; } } } } void initialize() { for( int x = 0; x < MAX_BALLS; x++ ) { balls[x].position.set( 200, -10 ); balls[x].offset.set( 0, 0.5f ); balls[x].alive = balls[x].start = false; } balls[0].alive = true; for( int x = 0; x < 70; x++ ) cols[x] = 0; for( int y = 0; y < 70; y++ ) for( int x = 0; x < 41; x++ ) pins[x][y] = false; int p; for( int y = 0; y < 11; y++ ) { p = ( 41 / 2 ) - y; for( int z = 0; z < y + 1; z++ ) { pins[3 + y][p] = true; p += 2; } } } myBitmap bmp; HWND _hwnd; bool pins[70][40]; ball balls[MAX_BALLS]; int cols[70]; }; class wnd { public: int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _gtn.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else _gtn.simulate(); } return UnregisterClass( "_GALTON_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_GALTON_"; RegisterClassEx( &wcex ); RECT rc; SetRect( &rc, 0, 0, BMP_WID, BMP_HEI ); AdjustWindowRect( &rc, WS_CAPTION, FALSE ); return CreateWindow( "_GALTON_", ".: Galton Box -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL ); } HINSTANCE _hInst; HWND _hwnd; galton _gtn; }; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BALLS 1024 int n, w, h = 45, *x, *y, cnt = 0; char *b; #define B(y, x) b[(y)*w + x] #define C(y, x) ' ' == b[(y)*w + x] #define V(i) B(y[i], x[i]) inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; } void show_board() { int i, j; for (puts("\033[H"), i = 0; i < h; i++, putchar('\n')) for (j = 0; j < w; j++, putchar(' ')) printf(B(i, j) == '*' ? C(i - 1, j) ? "\033[32m%c\033[m" : "\033[31m%c\033[m" : "%c", B(i, j)); } void init() { int i, j; puts("\033[H\033[J"); b = malloc(w * h); memset(b, ' ', w * h); x = malloc(sizeof(int) * BALLS * 2); y = x + BALLS; for (i = 0; i < n; i++) for (j = -i; j <= i; j += 2) B(2 * i+2, j + w/2) = '*'; srand(time(0)); } void move(int idx) { int xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0; if (yy < 0) return; if (yy == h - 1) { y[idx] = -1; return; } switch(c = B(yy + 1, xx)) { case ' ': yy++; break; case '*': sl = 1; default: if (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1)) if (!rnd(sl++)) o = 1; if (xx && C(yy, xx - 1) && C(yy + 1, xx - 1)) if (!rnd(sl++)) o = -1; if (!o) kill = 1; xx += o; } c = V(idx); V(idx) = ' '; idx[y] = yy, idx[x] = xx; B(yy, xx) = c; if (kill) idx[y] = -1; } int run(void) { static int step = 0; int i; for (i = 0; i < cnt; i++) move(i); if (2 == ++step && cnt < BALLS) { step = 0; x[cnt] = w/2; y[cnt] = 0; if (V(cnt) != ' ') return 0; V(cnt) = rnd(80) + 43; cnt++; } return 1; } int main(int c, char **v) { if (c < 2 || (n = atoi(v[1])) <= 3) n = 5; if (n >= 20) n = 20; w = n * 2 + 1; init(); do { show_board(), usleep(60000); } while (run()); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
#include <iostream> int circlesort(int* arr, int lo, int hi, int swaps) { if(lo == hi) { return swaps; } int high = hi; int low = lo; int mid = (high - low) / 2; while(lo < hi) { if(arr[lo] > arr[hi]) { int temp = arr[lo]; arr[lo] = arr[hi]; arr[hi] = temp; swaps++; } lo++; hi--; } if(lo == hi) { if(arr[lo] > arr[hi+1]) { int temp = arr[lo]; arr[lo] = arr[hi+1]; arr[hi+1] = temp; swaps++; } } swaps = circlesort(arr, low, low+mid, swaps); swaps = circlesort(arr, low+mid+1, high, swaps); return swaps; } void circlesortDriver(int* arr, int n) { do { for(int i = 0; i < n; i++) { std::cout << arr[i] << ' '; } std::cout << std::endl; } while(circlesort(arr, 0, n-1, 0)); } int main() { int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 }; circlesortDriver(arr, sizeof(arr)/sizeof(int)); return 0; }
#include <stdio.h> int circle_sort_inner(int *start, int *end) { int *p, *q, t, swapped; if (start == end) return 0; for (swapped = 0, p = start, q = end; p<q || (p==q && ++q); p++, q--) if (*p > *q) t = *p, *p = *q, *q = t, swapped = 1; return swapped | circle_sort_inner(start, q) | circle_sort_inner(p, end); } void circle_sort(int *x, int n) { do { int i; for (i = 0; i < n; i++) printf("%d ", x[i]); putchar('\n'); } while (circle_sort_inner(x, x + (n - 1))); } int main(void) { int x[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}; circle_sort(x, sizeof(x) / sizeof(*x)); return 0; }
Keep all operations the same but rewrite the snippet in C.
#include <cassert> #include <vector> #include <QImage> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<scalar_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[i]); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const scalar_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } scalar_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } private: size_t rows_; size_t columns_; std::vector<scalar_type> elements_; }; template <typename scalar_type> matrix<scalar_type> kronecker_product(const matrix<scalar_type>& a, const matrix<scalar_type>& b) { size_t arows = a.rows(); size_t acolumns = a.columns(); size_t brows = b.rows(); size_t bcolumns = b.columns(); matrix<scalar_type> c(arows * brows, acolumns * bcolumns); for (size_t i = 0; i < arows; ++i) for (size_t j = 0; j < acolumns; ++j) for (size_t k = 0; k < brows; ++k) for (size_t l = 0; l < bcolumns; ++l) c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l); return c; } bool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) { matrix<unsigned char> result = m; for (int i = 0; i < order; ++i) result = kronecker_product(result, m); size_t height = result.rows(); size_t width = result.columns(); size_t bytesPerLine = 4 * ((width + 3)/4); std::vector<uchar> imageData(bytesPerLine * height); for (size_t i = 0; i < height; ++i) for (size_t j = 0; j < width; ++j) imageData[i * bytesPerLine + j] = result(i, j); QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8); QVector<QRgb> colours(2); colours[0] = qRgb(0, 0, 0); colours[1] = qRgb(255, 255, 255); image.setColorTable(colours); return image.save(fileName); } int main() { matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}}); matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}}); matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}}); kronecker_fractal("vicsek.png", matrix1, 5); kronecker_fractal("sierpinski_carpet.png", matrix2, 5); kronecker_fractal("sierpinski_triangle.png", matrix3, 8); return 0; }
#include<graphics.h> #include<stdlib.h> #include<stdio.h> typedef struct{ int row, col; }cell; int ROW,COL,SUM=0; unsigned long raiseTo(int base,int power){ if(power==0) return 1; else return base*raiseTo(base,power-1); } cell* kroneckerProduct(char* inputFile,int power){ FILE* fp = fopen(inputFile,"r"); int i,j,k,l; unsigned long prod; int** matrix; cell *coreList,*tempList,*resultList; fscanf(fp,"%d%d",&ROW,&COL); matrix = (int**)malloc(ROW*sizeof(int*)); for(i=0;i<ROW;i++){ matrix[i] = (int*)malloc(COL*sizeof(int)); for(j=0;j<COL;j++){ fscanf(fp,"%d",&matrix[i][j]); if(matrix[i][j]==1) SUM++; } } coreList = (cell*)malloc(SUM*sizeof(cell)); resultList = (cell*)malloc(SUM*sizeof(cell)); k = 0; for(i=0;i<ROW;i++){ for(j=0;j<COL;j++){ if(matrix[i][j]==1){ coreList[k].row = i+1; coreList[k].col = j+1; resultList[k].row = i+1; resultList[k].col = j+1; k++; } } } prod = k; for(i=2;i<=power;i++){ tempList = (cell*)malloc(prod*k*sizeof(cell)); l = 0; for(j=0;j<prod;j++){ for(k=0;k<SUM;k++){ tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row; tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col; l++; } } free(resultList); prod *= k; resultList = (cell*)malloc(prod*sizeof(cell)); for(j=0;j<prod;j++){ resultList[j].row = tempList[j].row; resultList[j].col = tempList[j].col; } free(tempList); } return resultList; } int main(){ char fileName[100]; int power,i,length; cell* resultList; printf("Enter input file name : "); scanf("%s",fileName); printf("Enter power : "); scanf("%d",&power); resultList = kroneckerProduct(fileName,power); initwindow(raiseTo(ROW,power),raiseTo(COL,power),"Kronecker Product Fractal"); length = raiseTo(SUM,power); for(i=0;i<length;i++){ putpixel(resultList[i].row,resultList[i].col,15); } getch(); closegraph(); return 0; }
Port the following code from C++ to C with equivalent syntax and logic.
#include "stdafx.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string/case_conv.hpp> using namespace std; using namespace boost; typedef boost::tokenizer<boost::char_separator<char> > Tokenizer; static const char_separator<char> sep(" ","#;,"); struct configs{ string fullname; string favoritefruit; bool needspelling; bool seedsremoved; vector<string> otherfamily; } conf; void parseLine(const string &line, configs &conf) { if (line[0] == '#' || line.empty()) return; Tokenizer tokenizer(line, sep); vector<string> tokens; for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++) tokens.push_back(*iter); if (tokens[0] == ";"){ algorithm::to_lower(tokens[1]); if (tokens[1] == "needspeeling") conf.needspelling = false; if (tokens[1] == "seedsremoved") conf.seedsremoved = false; } algorithm::to_lower(tokens[0]); if (tokens[0] == "needspeeling") conf.needspelling = true; if (tokens[0] == "seedsremoved") conf.seedsremoved = true; if (tokens[0] == "fullname"){ for (unsigned int i=1; i<tokens.size(); i++) conf.fullname += tokens[i] + " "; conf.fullname.erase(conf.fullname.size() -1, 1); } if (tokens[0] == "favouritefruit") for (unsigned int i=1; i<tokens.size(); i++) conf.favoritefruit += tokens[i]; if (tokens[0] == "otherfamily"){ unsigned int i=1; string tmp; while (i<=tokens.size()){ if ( i == tokens.size() || tokens[i] ==","){ tmp.erase(tmp.size()-1, 1); conf.otherfamily.push_back(tmp); tmp = ""; i++; } else{ tmp += tokens[i]; tmp += " "; i++; } } } } int _tmain(int argc, TCHAR* argv[]) { if (argc != 2) { wstring tmp = argv[0]; wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl; return -1; } ifstream file (argv[1]); if (file.is_open()) while(file.good()) { char line[255]; file.getline(line, 255); string linestring(line); parseLine(linestring, conf); } else { cout << "Unable to open the file" << endl; return -2; } cout << "Fullname= " << conf.fullname << endl; cout << "Favorite Fruit= " << conf.favoritefruit << endl; cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl; cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl; string otherFamily; for (unsigned int i = 0; i < conf.otherfamily.size(); i++) otherFamily += conf.otherfamily[i] + ", "; otherFamily.erase(otherFamily.size()-2, 2); cout << "Other Family= " << otherFamily << endl; return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <confini.h> #define rosetta_uint8_t unsigned char #define FALSE 0 #define TRUE 1 #define CONFIGS_TO_READ 5 #define INI_ARRAY_DELIMITER ',' struct configs { char *fullname; char *favouritefruit; rosetta_uint8_t needspeeling; rosetta_uint8_t seedsremoved; char **otherfamily; size_t otherfamily_len; size_t _configs_left_; }; static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) { *arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format); char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL; if (!dest) { return NULL; } memcpy(dest + *arrlen, src, buffsize); char * iter = (char *) (dest + *arrlen); for (size_t idx = 0; idx < *arrlen; idx++) { dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format); ini_string_parse(dest[idx], ini_format); } return dest; } static int configs_member_handler (IniDispatch *this, void *v_confs) { struct configs *confs = (struct configs *) v_confs; if (this->type != INI_KEY) { return 0; } if (ini_string_match_si("FULLNAME", this->data, this->format)) { if (confs->fullname) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->fullname = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) { if (confs->favouritefruit) { return 0; } this->v_len = ini_string_parse(this->value, this->format); confs->favouritefruit = strndup(this->value, this->v_len); confs->_configs_left_--; } else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) { if (~confs->needspeeling & 0x80) { return 0; } confs->needspeeling = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) { if (~confs->seedsremoved & 0x80) { return 0; } confs->seedsremoved = ini_get_bool(this->value, TRUE); confs->_configs_left_--; } else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) { if (confs->otherfamily) { return 0; } this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format); confs->_configs_left_--; } return !confs->_configs_left_; } static int populate_configs (struct configs * confs) { IniFormat config_format = { .delimiter_symbol = INI_ANY_SPACE, .case_sensitive = FALSE, .semicolon_marker = INI_IGNORE, .hash_marker = INI_IGNORE, .multiline_nodes = INI_NO_MULTILINE, .section_paths = INI_NO_SECTIONS, .no_single_quotes = FALSE, .no_double_quotes = FALSE, .no_spaces_in_names = TRUE, .implicit_is_not_empty = TRUE, .do_not_collapse_values = FALSE, .preserve_empty_quotes = FALSE, .disabled_after_space = TRUE, .disabled_can_be_implicit = FALSE }; *confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ }; if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) { fprintf(stderr, "Sorry, something went wrong :-(\n"); return 1; } confs->needspeeling &= 0x7F; confs->seedsremoved &= 0x7F; return 0; } int main () { struct configs confs; ini_global_set_implicit_value("YES", 0); if (populate_configs(&confs)) { return 1; } printf( "Full name: %s\n" "Favorite fruit: %s\n" "Need spelling: %s\n" "Seeds removed: %s\n", confs.fullname, confs.favouritefruit, confs.needspeeling ? "True" : "False", confs.seedsremoved ? "True" : "False" ); for (size_t idx = 0; idx < confs.otherfamily_len; idx++) { printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]); } #define FREE_NON_NULL(PTR) if (PTR) { free(PTR); } FREE_NON_NULL(confs.fullname); FREE_NON_NULL(confs.favouritefruit); FREE_NON_NULL(confs.otherfamily); return 0; }
Produce a functionally identical C code for the snippet given in C++.
#include <algorithm> #include <string> #include <cctype> struct icompare_char { bool operator()(char c1, char c2) { return std::toupper(c1) < std::toupper(c2); } }; struct compare { bool operator()(std::string const& s1, std::string const& s2) { if (s1.length() > s2.length()) return true; if (s1.length() < s2.length()) return false; return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), icompare_char()); } }; int main() { std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; std::sort(strings, strings+8, compare()); return 0; }
#include <stdlib.h> #include <string.h> #include <strings.h> int mycmp(const void *s1, const void *s2) { const char *l = *(const char **)s1, *r = *(const char **)s2; size_t ll = strlen(l), lr = strlen(r); if (ll > lr) return -1; if (ll < lr) return 1; return strcasecmp(l, r); } int main() { const char *strings[] = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp); return 0; }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <cstdint> #include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_prime(const integer& n, int reps = 50) { return mpz_probab_prime_p(n.get_mpz_t(), reps); } std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } bool is_circular_prime(const integer& p) { if (!is_prime(p)) return false; std::string str(to_string(p)); for (size_t i = 0, n = str.size(); i + 1 < n; ++i) { std::rotate(str.begin(), str.begin() + 1, str.end()); integer p2(str, 10); if (p2 < p || !is_prime(p2)) return false; } return true; } integer next_repunit(const integer& n) { integer p = 1; while (p < n) p = 10 * p + 1; return p; } integer repunit(int digits) { std::string str(digits, '1'); integer p(str); return p; } void test_repunit(int digits) { if (is_prime(repunit(digits), 10)) std::cout << "R(" << digits << ") is probably prime\n"; else std::cout << "R(" << digits << ") is not prime\n"; } int main() { integer p = 2; std::cout << "First 19 circular primes:\n"; for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) std::cout << ", "; std::cout << p; ++count; } } std::cout << '\n'; std::cout << "Next 4 circular primes:\n"; p = next_repunit(p); std::string str(to_string(p)); int digits = str.size(); for (int count = 0; count < 4; ) { if (is_prime(p, 15)) { if (count > 0) std::cout << ", "; std::cout << "R(" << digits << ")"; ++count; } p = repunit(++digits); } std::cout << '\n'; test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> bool is_prime(uint32_t n) { if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; for (uint32_t p = 3; p * p <= n; p += 2) { if (n % p == 0) return false; } return true; } uint32_t cycle(uint32_t n) { uint32_t m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } bool is_circular_prime(uint32_t p) { if (!is_prime(p)) return false; uint32_t p2 = cycle(p); while (p2 != p) { if (p2 < p || !is_prime(p2)) return false; p2 = cycle(p2); } return true; } void test_repunit(uint32_t digits) { char* str = malloc(digits + 1); if (str == 0) { fprintf(stderr, "Out of memory\n"); exit(1); } memset(str, '1', digits); str[digits] = 0; mpz_t bignum; mpz_init_set_str(bignum, str, 10); free(str); if (mpz_probab_prime_p(bignum, 10)) printf("R(%u) is probably prime.\n", digits); else printf("R(%u) is not prime.\n", digits); mpz_clear(bignum); } int main() { uint32_t p = 2; printf("First 19 circular primes:\n"); for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) printf(", "); printf("%u", p); ++count; } } printf("\n"); printf("Next 4 circular primes:\n"); uint32_t repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; mpz_t bignum; mpz_init_set_ui(bignum, repunit); for (int count = 0; count < 4; ) { if (mpz_probab_prime_p(bignum, 15)) { if (count > 0) printf(", "); printf("R(%u)", digits); ++count; } ++digits; mpz_mul_ui(bignum, bignum, 10); mpz_add_ui(bignum, bignum, 1); } mpz_clear(bignum); printf("\n"); test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
Produce a language-to-language conversion: from C++ to C, same semantics.
#include "animationwidget.h" #include <QLabel> #include <QTimer> #include <QVBoxLayout> #include <algorithm> AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) { setWindowTitle(tr("Animation")); QFont font("Courier", 24); QLabel* label = new QLabel("Hello World! "); label->setFont(font); QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(label); QTimer* timer = new QTimer(this); connect(timer, &QTimer::timeout, this, [label,this]() { QString text = label->text(); std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end()); label->setText(text); }); timer->start(200); } void AnimationWidget::mousePressEvent(QMouseEvent*) { right_ = !right_; }
#include <stdlib.h> #include <string.h> #include <gtk/gtk.h> const gchar *hello = "Hello World! "; gint direction = -1; gint cx=0; gint slen=0; GtkLabel *label; void change_dir(GtkLayout *o, gpointer d) { direction = -direction; } gchar *rotateby(const gchar *t, gint q, gint l) { gint i, cl = l, j; gchar *r = malloc(l+1); for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++) r[j] = t[i]; r[l] = 0; return r; } gboolean scroll_it(gpointer data) { if ( direction > 0 ) cx = (cx + 1) % slen; else cx = (cx + slen - 1 ) % slen; gchar *scrolled = rotateby(hello, cx, slen); gtk_label_set_text(label, scrolled); free(scrolled); return TRUE; } int main(int argc, char **argv) { GtkWidget *win; GtkButton *button; PangoFontDescription *pd; gtk_init(&argc, &argv); win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(win), "Basic Animation"); g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL); label = (GtkLabel *)gtk_label_new(hello); pd = pango_font_description_new(); pango_font_description_set_family(pd, "monospace"); gtk_widget_modify_font(GTK_WIDGET(label), pd); button = (GtkButton *)gtk_button_new(); gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label)); gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button)); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL); slen = strlen(hello); g_timeout_add(125, scroll_it, NULL); gtk_widget_show_all(GTK_WIDGET(win)); gtk_main(); return 0; }
Can you help me rewrite this code in C instead of C++, keeping it the same logically?
#include <algorithm> #include <iostream> #include <iterator> class radix_test { const int bit; public: radix_test(int offset) : bit(offset) {} bool operator()(int value) const { if (bit == 31) return value < 0; else return !(value & (1 << bit)); } }; void lsd_radix_sort(int *first, int *last) { for (int lsb = 0; lsb < 32; ++lsb) { std::stable_partition(first, last, radix_test(lsb)); } } void msd_radix_sort(int *first, int *last, int msb = 31) { if (first != last && msb >= 0) { int *mid = std::partition(first, last, radix_test(msb)); msb--; msd_radix_sort(first, mid, msb); msd_radix_sort(mid, last, msb); } } int main() { int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 }; lsd_radix_sort(data, data + 8); std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, " ")); return 0; }
#include <stdio.h> #include <limits.h> #include <stdlib.h> #include <time.h> #define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR) #define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1)); static void swap(unsigned *a, unsigned *b) { unsigned tmp = *a; *a = *b; *b = tmp; } static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit) { if (!bit || to < from + 1) return; unsigned *ll = from, *rr = to - 1; for (;;) { while (ll < rr && !(*ll & bit)) ll++; while (ll < rr && (*rr & bit)) rr--; if (ll >= rr) break; swap(ll, rr); } if (!(bit & *ll) && ll < to) ll++; bit >>= 1; rad_sort_u(from, ll, bit); rad_sort_u(ll, to, bit); } static void radix_sort(int *a, const size_t len) { size_t i; unsigned *x = (unsigned*) a; for (i = 0; i < len; i++) x[i] ^= INT_MIN; rad_sort_u(x, x + len, INT_MIN); for (i = 0; i < len; i++) x[i] ^= INT_MIN; } int main(void) { srand(time(NULL)); int x[16]; for (size_t i = 0; i < ARR_LEN(x); i++) x[i] = RAND_RNG(-128,127) radix_sort(x, ARR_LEN(x)); for (size_t i = 0; i < ARR_LEN(x); i++) printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n'); }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <vector> #include <cmath> #include <iostream> #include <algorithm> #include <iterator> void list_comprehension( std::vector<int> & , int ) ; int main( ) { std::vector<int> triangles ; list_comprehension( triangles , 20 ) ; std::copy( triangles.begin( ) , triangles.end( ) , std::ostream_iterator<int>( std::cout , " " ) ) ; std::cout << std::endl ; return 0 ; } void list_comprehension( std::vector<int> & numbers , int upper_border ) { for ( int a = 1 ; a < upper_border ; a++ ) { for ( int b = a + 1 ; b < upper_border ; b++ ) { double c = pow( a * a + b * b , 0.5 ) ; if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) { if ( c == floor( c ) ) { numbers.push_back( a ) ; numbers.push_back( b ) ; numbers.push_back( static_cast<int>( c ) ) ; } } } } }
for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
Ensure the translated C code behaves exactly like the original C++ snippet.
#include <algorithm> #include <iterator> #include <iostream> template<typename ForwardIterator> void selection_sort(ForwardIterator begin, ForwardIterator end) { for(auto i = begin; i != end; ++i) { std::iter_swap(i, std::min_element(i, end)); } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; selection_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
#include <stdio.h> void selection_sort (int *a, int n) { int i, j, m, t; for (i = 0; i < n; i++) { for (j = i, m = i; j < n; j++) { if (a[j] < a[m]) { m = j; } } t = a[i]; a[i] = a[m]; a[m] = t; } } 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" : " "); selection_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
Keep all operations the same but rewrite the snippet in C.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t; } std::swap(n, k); if (n % 4 == 3 && k % 4 == 3) t = -t; n %= k; } return k == 1 ? t : 0; } void print_table(std::ostream& out, int kmax, int nmax) { out << "n\\k|"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << k; out << "\n----"; for (int k = 0; k <= kmax; ++k) out << "---"; out << '\n'; for (int n = 1; n <= nmax; n += 2) { out << std::setw(2) << n << " |"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << jacobi(k, n); out << '\n'; } } int main() { print_table(std::cout, 20, 21); return 0; }
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
Ensure the translated C code behaves exactly like the original C++ snippet.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t; } std::swap(n, k); if (n % 4 == 3 && k % 4 == 3) t = -t; n %= k; } return k == 1 ? t : 0; } void print_table(std::ostream& out, int kmax, int nmax) { out << "n\\k|"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << k; out << "\n----"; for (int k = 0; k <= kmax; ++k) out << "---"; out << '\n'; for (int n = 1; n <= nmax; n += 2) { out << std::setw(2) << n << " |"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << jacobi(k, n); out << '\n'; } } int main() { print_table(std::cout, 20, 21); return 0; }
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
Change the programming language of this snippet from C++ to C without modifying what it does.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t; } std::swap(n, k); if (n % 4 == 3 && k % 4 == 3) t = -t; n %= k; } return k == 1 ? t : 0; } void print_table(std::ostream& out, int kmax, int nmax) { out << "n\\k|"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << k; out << "\n----"; for (int k = 0; k <= kmax; ++k) out << "---"; out << '\n'; for (int n = 1; n <= nmax; n += 2) { out << std::setw(2) << n << " |"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << jacobi(k, n); out << '\n'; } } int main() { print_table(std::cout, 20, 21); return 0; }
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
Rewrite the snippet below in C so it works the same as the original C++ code.
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { size_t n = std::min(dimensions, list.size()); std::copy_n(list.begin(), n, coords_.begin()); } coordinate_type get(size_t index) const { return coords_[index]; } double distance(const point& pt) const { double dist = 0; for (size_t i = 0; i < dimensions; ++i) { double d = get(i) - pt.get(i); dist += d * d; } return dist; } private: std::array<coordinate_type, dimensions> coords_; }; template<typename coordinate_type, size_t dimensions> std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) { out << '('; for (size_t i = 0; i < dimensions; ++i) { if (i > 0) out << ", "; out << pt.get(i); } out << ')'; return out; } template<typename coordinate_type, size_t dimensions> class kdtree { public: typedef point<coordinate_type, dimensions> point_type; private: struct node { node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {} coordinate_type get(size_t index) const { return point_.get(index); } double distance(const point_type& pt) const { return point_.distance(pt); } point_type point_; node* left_; node* right_; }; node* root_ = nullptr; node* best_ = nullptr; double best_dist_ = 0; size_t visited_ = 0; std::vector<node> nodes_; struct node_cmp { node_cmp(size_t index) : index_(index) {} bool operator()(const node& n1, const node& n2) const { return n1.point_.get(index_) < n2.point_.get(index_); } size_t index_; }; node* make_tree(size_t begin, size_t end, size_t index) { if (end <= begin) return nullptr; size_t n = begin + (end - begin)/2; auto i = nodes_.begin(); std::nth_element(i + begin, i + n, i + end, node_cmp(index)); index = (index + 1) % dimensions; nodes_[n].left_ = make_tree(begin, n, index); nodes_[n].right_ = make_tree(n + 1, end, index); return &nodes_[n]; } void nearest(node* root, const point_type& point, size_t index) { if (root == nullptr) return; ++visited_; double d = root->distance(point); if (best_ == nullptr || d < best_dist_) { best_dist_ = d; best_ = root; } if (best_dist_ == 0) return; double dx = root->get(index) - point.get(index); index = (index + 1) % dimensions; nearest(dx > 0 ? root->left_ : root->right_, point, index); if (dx * dx >= best_dist_) return; nearest(dx > 0 ? root->right_ : root->left_, point, index); } public: kdtree(const kdtree&) = delete; kdtree& operator=(const kdtree&) = delete; template<typename iterator> kdtree(iterator begin, iterator end) : nodes_(begin, end) { root_ = make_tree(0, nodes_.size(), 0); } template<typename func> kdtree(func&& f, size_t n) { nodes_.reserve(n); for (size_t i = 0; i < n; ++i) nodes_.push_back(f()); root_ = make_tree(0, nodes_.size(), 0); } bool empty() const { return nodes_.empty(); } size_t visited() const { return visited_; } double distance() const { return std::sqrt(best_dist_); } const point_type& nearest(const point_type& pt) { if (root_ == nullptr) throw std::logic_error("tree is empty"); best_ = nullptr; visited_ = 0; best_dist_ = 0; nearest(root_, pt, 0); return best_->point_; } }; void test_wikipedia() { typedef point<int, 2> point2d; typedef kdtree<int, 2> tree2d; point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } }; tree2d tree(std::begin(points), std::end(points)); point2d n = tree.nearest({ 9, 2 }); std::cout << "Wikipedia example data:\n"; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } typedef point<double, 3> point3d; typedef kdtree<double, 3> tree3d; struct random_point_generator { random_point_generator(double min, double max) : engine_(std::random_device()()), distribution_(min, max) {} point3d operator()() { double x = distribution_(engine_); double y = distribution_(engine_); double z = distribution_(engine_); return point3d({x, y, z}); } std::mt19937 engine_; std::uniform_real_distribution<double> distribution_; }; void test_random(size_t count) { random_point_generator rpg(0, 1); tree3d tree(rpg, count); point3d pt(rpg()); point3d n = tree.nearest(pt); std::cout << "Random data (" << count << " points):\n"; std::cout << "point: " << pt << '\n'; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } int main() { try { test_wikipedia(); std::cout << '\n'; test_random(1000); std::cout << '\n'; test_random(1000000); } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
Rewrite the snippet below in C so it works the same as the original C++ code.
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { size_t n = std::min(dimensions, list.size()); std::copy_n(list.begin(), n, coords_.begin()); } coordinate_type get(size_t index) const { return coords_[index]; } double distance(const point& pt) const { double dist = 0; for (size_t i = 0; i < dimensions; ++i) { double d = get(i) - pt.get(i); dist += d * d; } return dist; } private: std::array<coordinate_type, dimensions> coords_; }; template<typename coordinate_type, size_t dimensions> std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) { out << '('; for (size_t i = 0; i < dimensions; ++i) { if (i > 0) out << ", "; out << pt.get(i); } out << ')'; return out; } template<typename coordinate_type, size_t dimensions> class kdtree { public: typedef point<coordinate_type, dimensions> point_type; private: struct node { node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {} coordinate_type get(size_t index) const { return point_.get(index); } double distance(const point_type& pt) const { return point_.distance(pt); } point_type point_; node* left_; node* right_; }; node* root_ = nullptr; node* best_ = nullptr; double best_dist_ = 0; size_t visited_ = 0; std::vector<node> nodes_; struct node_cmp { node_cmp(size_t index) : index_(index) {} bool operator()(const node& n1, const node& n2) const { return n1.point_.get(index_) < n2.point_.get(index_); } size_t index_; }; node* make_tree(size_t begin, size_t end, size_t index) { if (end <= begin) return nullptr; size_t n = begin + (end - begin)/2; auto i = nodes_.begin(); std::nth_element(i + begin, i + n, i + end, node_cmp(index)); index = (index + 1) % dimensions; nodes_[n].left_ = make_tree(begin, n, index); nodes_[n].right_ = make_tree(n + 1, end, index); return &nodes_[n]; } void nearest(node* root, const point_type& point, size_t index) { if (root == nullptr) return; ++visited_; double d = root->distance(point); if (best_ == nullptr || d < best_dist_) { best_dist_ = d; best_ = root; } if (best_dist_ == 0) return; double dx = root->get(index) - point.get(index); index = (index + 1) % dimensions; nearest(dx > 0 ? root->left_ : root->right_, point, index); if (dx * dx >= best_dist_) return; nearest(dx > 0 ? root->right_ : root->left_, point, index); } public: kdtree(const kdtree&) = delete; kdtree& operator=(const kdtree&) = delete; template<typename iterator> kdtree(iterator begin, iterator end) : nodes_(begin, end) { root_ = make_tree(0, nodes_.size(), 0); } template<typename func> kdtree(func&& f, size_t n) { nodes_.reserve(n); for (size_t i = 0; i < n; ++i) nodes_.push_back(f()); root_ = make_tree(0, nodes_.size(), 0); } bool empty() const { return nodes_.empty(); } size_t visited() const { return visited_; } double distance() const { return std::sqrt(best_dist_); } const point_type& nearest(const point_type& pt) { if (root_ == nullptr) throw std::logic_error("tree is empty"); best_ = nullptr; visited_ = 0; best_dist_ = 0; nearest(root_, pt, 0); return best_->point_; } }; void test_wikipedia() { typedef point<int, 2> point2d; typedef kdtree<int, 2> tree2d; point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } }; tree2d tree(std::begin(points), std::end(points)); point2d n = tree.nearest({ 9, 2 }); std::cout << "Wikipedia example data:\n"; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } typedef point<double, 3> point3d; typedef kdtree<double, 3> tree3d; struct random_point_generator { random_point_generator(double min, double max) : engine_(std::random_device()()), distribution_(min, max) {} point3d operator()() { double x = distribution_(engine_); double y = distribution_(engine_); double z = distribution_(engine_); return point3d({x, y, z}); } std::mt19937 engine_; std::uniform_real_distribution<double> distribution_; }; void test_random(size_t count) { random_point_generator rpg(0, 1); tree3d tree(rpg, count); point3d pt(rpg()); point3d n = tree.nearest(pt); std::cout << "Random data (" << count << " points):\n"; std::cout << "point: " << pt << '\n'; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } int main() { try { test_wikipedia(); std::cout << '\n'; test_random(1000); std::cout << '\n'; test_random(1000000); } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
Change the programming language of this snippet from C++ to C without modifying what it does.
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { size_t n = std::min(dimensions, list.size()); std::copy_n(list.begin(), n, coords_.begin()); } coordinate_type get(size_t index) const { return coords_[index]; } double distance(const point& pt) const { double dist = 0; for (size_t i = 0; i < dimensions; ++i) { double d = get(i) - pt.get(i); dist += d * d; } return dist; } private: std::array<coordinate_type, dimensions> coords_; }; template<typename coordinate_type, size_t dimensions> std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) { out << '('; for (size_t i = 0; i < dimensions; ++i) { if (i > 0) out << ", "; out << pt.get(i); } out << ')'; return out; } template<typename coordinate_type, size_t dimensions> class kdtree { public: typedef point<coordinate_type, dimensions> point_type; private: struct node { node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {} coordinate_type get(size_t index) const { return point_.get(index); } double distance(const point_type& pt) const { return point_.distance(pt); } point_type point_; node* left_; node* right_; }; node* root_ = nullptr; node* best_ = nullptr; double best_dist_ = 0; size_t visited_ = 0; std::vector<node> nodes_; struct node_cmp { node_cmp(size_t index) : index_(index) {} bool operator()(const node& n1, const node& n2) const { return n1.point_.get(index_) < n2.point_.get(index_); } size_t index_; }; node* make_tree(size_t begin, size_t end, size_t index) { if (end <= begin) return nullptr; size_t n = begin + (end - begin)/2; auto i = nodes_.begin(); std::nth_element(i + begin, i + n, i + end, node_cmp(index)); index = (index + 1) % dimensions; nodes_[n].left_ = make_tree(begin, n, index); nodes_[n].right_ = make_tree(n + 1, end, index); return &nodes_[n]; } void nearest(node* root, const point_type& point, size_t index) { if (root == nullptr) return; ++visited_; double d = root->distance(point); if (best_ == nullptr || d < best_dist_) { best_dist_ = d; best_ = root; } if (best_dist_ == 0) return; double dx = root->get(index) - point.get(index); index = (index + 1) % dimensions; nearest(dx > 0 ? root->left_ : root->right_, point, index); if (dx * dx >= best_dist_) return; nearest(dx > 0 ? root->right_ : root->left_, point, index); } public: kdtree(const kdtree&) = delete; kdtree& operator=(const kdtree&) = delete; template<typename iterator> kdtree(iterator begin, iterator end) : nodes_(begin, end) { root_ = make_tree(0, nodes_.size(), 0); } template<typename func> kdtree(func&& f, size_t n) { nodes_.reserve(n); for (size_t i = 0; i < n; ++i) nodes_.push_back(f()); root_ = make_tree(0, nodes_.size(), 0); } bool empty() const { return nodes_.empty(); } size_t visited() const { return visited_; } double distance() const { return std::sqrt(best_dist_); } const point_type& nearest(const point_type& pt) { if (root_ == nullptr) throw std::logic_error("tree is empty"); best_ = nullptr; visited_ = 0; best_dist_ = 0; nearest(root_, pt, 0); return best_->point_; } }; void test_wikipedia() { typedef point<int, 2> point2d; typedef kdtree<int, 2> tree2d; point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } }; tree2d tree(std::begin(points), std::end(points)); point2d n = tree.nearest({ 9, 2 }); std::cout << "Wikipedia example data:\n"; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } typedef point<double, 3> point3d; typedef kdtree<double, 3> tree3d; struct random_point_generator { random_point_generator(double min, double max) : engine_(std::random_device()()), distribution_(min, max) {} point3d operator()() { double x = distribution_(engine_); double y = distribution_(engine_); double z = distribution_(engine_); return point3d({x, y, z}); } std::mt19937 engine_; std::uniform_real_distribution<double> distribution_; }; void test_random(size_t count) { random_point_generator rpg(0, 1); tree3d tree(rpg, count); point3d pt(rpg()); point3d n = tree.nearest(pt); std::cout << "Random data (" << count << " points):\n"; std::cout << "point: " << pt << '\n'; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } int main() { try { test_wikipedia(); std::cout << '\n'; test_random(1000); std::cout << '\n'; test_random(1000000); } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); return 0; }
Write a version of this C++ function in C with identical behavior.
#include <iostream> #include <algorithm> void print_square(int i) { std::cout << i*i << " "; } int main() { int ary[]={1,2,3,4,5}; std::for_each(ary,ary+5,print_square); return 0; }
#ifndef CALLBACK_H #define CALLBACK_H void map(int* array, int len, void(*callback)(int,int)); #endif
Generate a C translation of this C++ snippet without changing its computational steps.
#include <stdexcept> template <typename Self> class singleton { protected: static Self* sentry; public: static Self& instance() { return *sentry; } singleton() { if(sentry) throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!"); sentry = (Self*)this; } virtual ~singleton() { if(sentry == this) sentry = 0; } }; template <typename Self> Self* singleton<Self>::sentry = 0; #include <iostream> #include <string> using namespace std; class controller : public singleton<controller> { public: controller(string const& name) : name(name) { trace("begin"); } ~controller() { trace("end"); } void work() { trace("doing stuff"); } void trace(string const& message) { cout << name << ": " << message << endl; } string name; }; int main() { controller* first = new controller("first"); controller::instance().work(); delete first; controller second("second"); controller::instance().work(); try { controller goner("goner"); controller::instance().work(); } catch(exception const& error) { cout << error.what() << endl; } controller::instance().work(); controller goner("goner"); controller::instance().work(); }
#ifndef SILLY_H #define SILLY_H extern void JumpOverTheDog( int numberOfTimes); extern int PlayFetchWithDog( float weightOfStick); #endif
Generate a C translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <tuple> union conv { int i; float f; }; float nextUp(float d) { if (isnan(d) || d == -INFINITY || d == INFINITY) return d; if (d == 0.0) return FLT_EPSILON; conv c; c.f = d; c.i++; return c.f; } float nextDown(float d) { if (isnan(d) || d == -INFINITY || d == INFINITY) return d; if (d == 0.0) return -FLT_EPSILON; conv c; c.f = d; c.i--; return c.f; } auto safeAdd(float a, float b) { return std::make_tuple(nextDown(a + b), nextUp(a + b)); } int main() { float a = 1.20f; float b = 0.03f; auto result = safeAdd(a, b); printf("(%f + %f) is in the range (%0.16f, %0.16f)\n", a, b, std::get<0>(result), std::get<1>(result)); return 0; }
#include <fenv.h> #include <stdio.h> void safe_add(volatile double interval[2], volatile double a, volatile double b) { #pragma STDC FENV_ACCESS ON unsigned int orig; orig = fegetround(); fesetround(FE_DOWNWARD); interval[0] = a + b; fesetround(FE_UPWARD); interval[1] = a + b; fesetround(orig); } int main() { const double nums[][2] = { {1, 2}, {0.1, 0.2}, {1e100, 1e-100}, {1e308, 1e308}, }; double ival[2]; int i; for (i = 0; i < sizeof(nums) / sizeof(nums[0]); i++) { safe_add(ival, nums[i][0], nums[i][1]); printf("%.17g + %.17g =\n", nums[i][0], nums[i][1]); printf(" [%.17g, %.17g]\n", ival[0], ival[1]); printf(" size %.17g\n\n", ival[1] - ival[0]); } return 0; }
Change the following C++ code into C without altering its purpose.
#include <iostream> #include <string> using namespace std; int main() { string dog = "Benjamin", Dog = "Samba", DOG = "Bernie"; cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl; }
#include <stdio.h> static const char *dog = "Benjamin"; static const char *Dog = "Samba"; static const char *DOG = "Bernie"; int main() { printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG); return 0; }
Can you help me rewrite this code in C instead of C++, keeping it the same logically?
for(int i = 10; i >= 0; --i) std::cout << i << "\n";
int i; for(i = 10; i >= 0; --i) printf("%d\n",i);
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <fstream> using namespace std; int main() { ofstream file("new.txt"); file << "this is a string"; file.close(); return 0; }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main(void) { return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.", freopen("sample.txt","wb",stdout)); }
Rewrite this program in C while keeping its functionality equivalent to the C++ version.
for(int i = 0; i < 5; ++i) { for(int j = 0; j < i; ++j) std::cout.put('*'); std::cout.put('\n'); }
int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) putchar('*'); puts(""); }
Generate an equivalent C version of this C++ code.
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1), digit_(digit), even_(false) {} integer next_palindrome() { ++next_; if (next_ == power_ * (digit_ + 1)) { if (even_) power_ *= 10; next_ = digit_ * power_; even_ = !even_; } return next_ * (even_ ? 10 * power_ : power_) + reverse(even_ ? next_ : next_/10); } private: integer power_; integer next_; int digit_; bool even_; }; bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } template<size_t len> void print(integer (&array)[9][len]) { for (int digit = 1; digit < 10; ++digit) { std::cout << digit << ":"; for (int i = 0; i < len; ++i) std::cout << ' ' << array[digit - 1][i]; std::cout << '\n'; } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palindrome_generator pgen(digit); for (int i = 0; i < m2; ) { integer n = pgen.next_palindrome(); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n"; print(pg1); std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n"; print(pg2); std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n"; print(pg3); return 0; }
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
Generate a C translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1), digit_(digit), even_(false) {} integer next_palindrome() { ++next_; if (next_ == power_ * (digit_ + 1)) { if (even_) power_ *= 10; next_ = digit_ * power_; even_ = !even_; } return next_ * (even_ ? 10 * power_ : power_) + reverse(even_ ? next_ : next_/10); } private: integer power_; integer next_; int digit_; bool even_; }; bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } template<size_t len> void print(integer (&array)[9][len]) { for (int digit = 1; digit < 10; ++digit) { std::cout << digit << ":"; for (int i = 0; i < len; ++i) std::cout << ' ' << array[digit - 1][i]; std::cout << '\n'; } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palindrome_generator pgen(digit); for (int i = 0; i < m2; ) { integer n = pgen.next_palindrome(); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n"; print(pg1); std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n"; print(pg2); std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n"; print(pg3); return 0; }
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
Write the same code in C as shown below in C++.
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1), digit_(digit), even_(false) {} integer next_palindrome() { ++next_; if (next_ == power_ * (digit_ + 1)) { if (even_) power_ *= 10; next_ = digit_ * power_; even_ = !even_; } return next_ * (even_ ? 10 * power_ : power_) + reverse(even_ ? next_ : next_/10); } private: integer power_; integer next_; int digit_; bool even_; }; bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } template<size_t len> void print(integer (&array)[9][len]) { for (int digit = 1; digit < 10; ++digit) { std::cout << digit << ":"; for (int i = 0; i < len; ++i) std::cout << ' ' << array[digit - 1][i]; std::cout << '\n'; } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palindrome_generator pgen(digit); for (int i = 0; i < m2; ) { integer n = pgen.next_palindrome(); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n"; print(pg1); std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n"; print(pg2); std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n"; print(pg3); return 0; }
#include <stdbool.h> #include <stdio.h> #include <stdint.h> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2); printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3); return 0; }
Convert this C++ block to C, preserving its control flow and logic.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); sierp(size, depth + 2); return 0; }
Write the same algorithm in C as shown in this C++ implementation.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); sierp(size, depth + 2); return 0; }
Please provide an equivalent version of this C++ code in C.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); sierp(size, depth + 2); return 0; }
Change the programming language of this snippet from C++ to C without modifying what it does.
#include <iostream> bool is_prime(int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } int i = 5; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; for (int p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; int p; for (p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
Write a version of this C++ function in C with identical behavior.
#include <iostream> bool is_prime(int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } int i = 5; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; for (int p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; int p; for (p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
Port the provided C++ code into C while preserving the original functionality.
#include <iostream> bool is_prime(int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } int i = 5; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; for (int p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
#include <stdbool.h> #include <stdio.h> bool is_prime(int n) { int i = 5; if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; int p; for (p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
Keep all operations the same but rewrite the snippet in C.
#include <iostream> #include <vector> #include <set> #include <algorithm> template<typename T> std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) { std::set<T> resultset; std::vector<T> result; for (auto& list : ll) for (auto& item : list) resultset.insert(item); for (auto& item : resultset) result.push_back(item); std::sort(result.begin(), result.end()); return result; } int main() { std::vector<int> a = {5,1,3,8,9,4,8,7}; std::vector<int> b = {3,5,9,8,4}; std::vector<int> c = {1,3,7,9}; std::vector<std::vector<int>> nums = {a, b, c}; auto csl = common_sorted_list(nums); for (auto n : csl) std::cout << n << " "; std::cout << std::endl; return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define COUNTOF(a) (sizeof(a)/sizeof(a[0])) 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; } int icompare(const void* p1, const void* p2) { const int* ip1 = p1; const int* ip2 = p2; return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0); } size_t unique(int* array, size_t len) { size_t out_index = 0; int prev; for (size_t i = 0; i < len; ++i) { if (i == 0 || prev != array[i]) array[out_index++] = array[i]; prev = array[i]; } return out_index; } int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) { size_t len = 0; for (size_t i = 0; i < count; ++i) len += lengths[i]; int* array = xmalloc(len * sizeof(int)); for (size_t i = 0, offset = 0; i < count; ++i) { memcpy(array + offset, arrays[i], lengths[i] * sizeof(int)); offset += lengths[i]; } qsort(array, len, sizeof(int), icompare); *size = unique(array, len); return array; } void print(const int* array, size_t len) { printf("["); for (size_t i = 0; i < len; ++i) { if (i > 0) printf(", "); printf("%d", array[i]); } printf("]\n"); } int main() { const int a[] = {5, 1, 3, 8, 9, 4, 8, 7}; const int b[] = {3, 5, 9, 8, 4}; const int c[] = {1, 3, 7, 9}; size_t len = 0; const int* arrays[] = {a, b, c}; size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)}; int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len); print(sorted, len); free(sorted); return 0; }
Convert this C++ snippet to C and keep its semantics consistent.
#include <iostream> #include <vector> #include <set> #include <algorithm> template<typename T> std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) { std::set<T> resultset; std::vector<T> result; for (auto& list : ll) for (auto& item : list) resultset.insert(item); for (auto& item : resultset) result.push_back(item); std::sort(result.begin(), result.end()); return result; } int main() { std::vector<int> a = {5,1,3,8,9,4,8,7}; std::vector<int> b = {3,5,9,8,4}; std::vector<int> c = {1,3,7,9}; std::vector<std::vector<int>> nums = {a, b, c}; auto csl = common_sorted_list(nums); for (auto n : csl) std::cout << n << " "; std::cout << std::endl; return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define COUNTOF(a) (sizeof(a)/sizeof(a[0])) 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; } int icompare(const void* p1, const void* p2) { const int* ip1 = p1; const int* ip2 = p2; return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0); } size_t unique(int* array, size_t len) { size_t out_index = 0; int prev; for (size_t i = 0; i < len; ++i) { if (i == 0 || prev != array[i]) array[out_index++] = array[i]; prev = array[i]; } return out_index; } int* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) { size_t len = 0; for (size_t i = 0; i < count; ++i) len += lengths[i]; int* array = xmalloc(len * sizeof(int)); for (size_t i = 0, offset = 0; i < count; ++i) { memcpy(array + offset, arrays[i], lengths[i] * sizeof(int)); offset += lengths[i]; } qsort(array, len, sizeof(int), icompare); *size = unique(array, len); return array; } void print(const int* array, size_t len) { printf("["); for (size_t i = 0; i < len; ++i) { if (i > 0) printf(", "); printf("%d", array[i]); } printf("]\n"); } int main() { const int a[] = {5, 1, 3, 8, 9, 4, 8, 7}; const int b[] = {3, 5, 9, 8, 4}; const int c[] = {1, 3, 7, 9}; size_t len = 0; const int* arrays[] = {a, b, c}; size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)}; int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len); print(sorted, len); free(sorted); return 0; }
Write a version of this C++ function in C with identical behavior.
class N{ uint n,i,g,e,l; public: N(uint n): n(n-1),i{},g{},e(1),l(n-1){} bool hasNext(){ g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i; if (l==2) {l=--n; e=1; return true;} if (e<((1<<(l-1))-1)) {++e; return true;} e=1; --l; return (l>0); } uint next() {return g;} };
#include <assert.h> #include <stdio.h> int main(int c, char **v) { unsigned int n = 1 << (c - 1), i = n, j, k; assert(n); while (i--) { if (!(i & (i + (i & -(int)i)))) continue; for (j = n, k = 1; j >>= 1; k++) if (i & j) printf("%s ", v[k]); putchar('\n'); } return 0; }
Transform the following C++ implementation into C, maintaining the same output and logic.
#include <windows.h> #include <string> using namespace std; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; clear(); return true; } void clear() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); } void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD* dwpBits; DWORD wb; HANDLE file; GetObject( bmp, sizeof( bitmap ), &bitmap ); dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() { return hdc; } int getWidth() { return width; } int getHeight() { return height; } private: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; class fiboFractal { public: fiboFractal( int l ) { bmp.create( 600, 440 ); bmp.setPenColor( 0x00ff00 ); createWord( l ); createFractal(); bmp.saveBitmap( "path_to_save_bitmap" ); } private: void createWord( int l ) { string a = "1", b = "0", c; l -= 2; while( l-- ) { c = b + a; a = b; b = c; } fWord = c; } void createFractal() { int n = 1, px = 10, dir, py = 420, len = 1, x = 0, y = -len, goingTo = 0; HDC dc = bmp.getDC(); MoveToEx( dc, px, py, NULL ); for( string::iterator si = fWord.begin(); si != fWord.end(); si++ ) { px += x; py += y; LineTo( dc, px, py ); if( !( *si - 48 ) ) { if( n & 1 ) dir = 1; else dir = 0; switch( goingTo ) { case 0: y = 0; if( dir ){ x = len; goingTo = 1; } else { x = -len; goingTo = 3; } break; case 1: x = 0; if( dir ) { y = len; goingTo = 2; } else { y = -len; goingTo = 0; } break; case 2: y = 0; if( dir ) { x = -len; goingTo = 3; } else { x = len; goingTo = 1; } break; case 3: x = 0; if( dir ) { y = -len; goingTo = 0; } else { y = len; goingTo = 2; } } } n++; } } string fWord; myBitmap bmp; }; int main( int argc, char* argv[] ) { fiboFractal ff( 23 ); return system( "pause" ); }
#include <stdio.h> int main(void) { puts( "%!PS-Adobe-3.0 EPSF\n" "%%BoundingBox: -10 -10 400 565\n" "/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n" "/b{a 90 rotate}def"); char i; for (i = 'c'; i <= 'z'; i++) printf("/%c{%c %c}def\n", i, i-1, i-2); puts("0 setlinewidth z showpage\n%%EOF"); return 0; }
Translate this program into C but keep the logic exactly as in C++.
#include <cstdint> #include <iostream> #include <string> #include <primesieve.hpp> void print_twin_prime_count(long long limit) { std::cout << "Number of twin prime pairs less than " << limit << " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n'; } int main(int argc, char** argv) { std::cout.imbue(std::locale("")); if (argc > 1) { for (int i = 1; i < argc; ++i) { try { print_twin_prime_count(std::stoll(argv[i])); } catch (const std::exception& ex) { std::cerr << "Cannot parse limit from '" << argv[i] << "'\n"; } } } else { uint64_t limit = 10; for (int power = 1; power < 12; ++power, limit *= 10) print_twin_prime_count(limit); } return 0; }
#include <stdbool.h> #include <stdint.h> #include <stdio.h> bool isPrime(int64_t n) { int64_t i; if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; if (n % 7 == 0) return n == 7; if (n % 11 == 0) return n == 11; if (n % 13 == 0) return n == 13; if (n % 17 == 0) return n == 17; if (n % 19 == 0) return n == 19; for (i = 23; i * i <= n; i += 2) { if (n % i == 0) return false; } return true; } int countTwinPrimes(int limit) { int count = 0; int64_t p3 = true, p2 = true, p1 = false; int64_t i; for (i = 5; i <= limit; i++) { p3 = p2; p2 = p1; p1 = isPrime(i); if (p3 && p1) { count++; } } return count; } void test(int limit) { int count = countTwinPrimes(limit); printf("Number of twin prime pairs less than %d is %d\n", limit, count); } int main() { test(10); test(100); test(1000); test(10000); test(100000); test(1000000); test(10000000); test(100000000); return 0; }
Produce a functionally identical C code for the snippet given in C++.
class fifteenSolver{ const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2}; int n{},_n{}, N0[100]{},N3[100]{},N4[100]{}; unsigned long N2[100]{}; const bool fY(){ if (N4[n]<_n) return fN(); if (N2[n]==0x123456789abcdef0) {std::cout<<"Solution found in "<<n<<" moves :"; for (int g{1};g<=n;++g) std::cout<<(char)N3[g]; std::cout<<std::endl; return true;}; if (N4[n]==_n) return fN(); else return false; } const bool fN(){ if (N3[n]!='u' && N0[n]/4<3){fI(); ++n; if (fY()) return true; --n;} if (N3[n]!='d' && N0[n]/4>0){fG(); ++n; if (fY()) return true; --n;} if (N3[n]!='l' && N0[n]%4<3){fE(); ++n; if (fY()) return true; --n;} if (N3[n]!='r' && N0[n]%4>0){fL(); ++n; if (fY()) return true; --n;} return false; } void fI(){ const int g = (11-N0[n])*4; const unsigned long a = N2[n]&((unsigned long)15<<g); N0[n+1]=N0[n]+4; N2[n+1]=N2[n]-a+(a<<16); N3[n+1]='d'; N4[n+1]=N4[n]+(Nr[a>>g]<=N0[n]/4?0:1); } void fG(){ const int g = (19-N0[n])*4; const unsigned long a = N2[n]&((unsigned long)15<<g); N0[n+1]=N0[n]-4; N2[n+1]=N2[n]-a+(a>>16); N3[n+1]='u'; N4[n+1]=N4[n]+(Nr[a>>g]>=N0[n]/4?0:1); } void fE(){ const int g = (14-N0[n])*4; const unsigned long a = N2[n]&((unsigned long)15<<g); N0[n+1]=N0[n]+1; N2[n+1]=N2[n]-a+(a<<4); N3[n+1]='r'; N4[n+1]=N4[n]+(Nc[a>>g]<=N0[n]%4?0:1); } void fL(){ const int g = (16-N0[n])*4; const unsigned long a = N2[n]&((unsigned long)15<<g); N0[n+1]=N0[n]-1; N2[n+1]=N2[n]-a+(a>>4); N3[n+1]='l'; N4[n+1]=N4[n]+(Nc[a>>g]>=N0[n]%4?0:1); } public: fifteenSolver(int n, unsigned long g){N0[0]=n; N2[0]=g;} void Solve(){for(;not fY();++_n);} };
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> typedef unsigned char u8t; typedef unsigned short u16t; enum { NR=4, NC=4, NCELLS = NR*NC }; enum { UP, DOWN, LEFT, RIGHT, NDIRS }; enum { OK = 1<<8, XX = 1<<9, FOUND = 1<<10, zz=0x80 }; enum { MAX_INT=0x7E, MAX_NODES=(16*65536)*90}; enum { BIT_HDR=1<<0, BIT_GRID=1<<1, BIT_OTHER=1<<2 }; enum { PHASE1,PHASE2 }; typedef struct { u16t dn; u16t hn; }HSORT_T; typedef struct { u8t data[NCELLS]; unsigned id; unsigned src; u8t h; u8t g; u8t udlr; }NODE_T; NODE_T goal44={ {1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,0},0,0,0,0,0}; NODE_T work; NODE_T G34={ {13,9,5,4, 15,6,1,8, 0,10,2,11, 14,3,7,12},0,0,0,0,0}; NODE_T G52={ {15,13,9,5, 14,6,1,4, 10,12,0,8, 3,7,11,2},0,0,0,0,0}; NODE_T G99={ {15,14,1,6, 9,11,4,12, 0,10,7,3, 13,8,5,2},0,0,0,0,0}; struct { unsigned nodes; unsigned gfound; unsigned root_visits; unsigned verbose; unsigned locks; unsigned phase; }my; u16t HybridIDA_star(NODE_T *pNode); u16t make_node(NODE_T *pNode, NODE_T *pNew, u8t udlr ); u16t search(NODE_T *pNode, u16t bound); u16t taxi_dist( NODE_T *pNode); u16t tile_home( NODE_T *p44); void print_node( NODE_T *pN, const char *pMsg, short force ); u16t goal_found(NODE_T *pNode); char udlr_to_char( char udlr ); void idx_to_rc( u16t idx, u16t *row, u16t *col ); void sort_nodes(HSORT_T *p); int main( ) { my.verbose = 0; memcpy(&work, &G99, sizeof(NODE_T)); if(1){ printf("Phase1: IDA* search for 1234 permutation..\n"); my.phase = PHASE1; (void) HybridIDA_star(&work); } printf("Phase2: IDA* search phase1 seed..\n"); my.phase = PHASE2; (void)HybridIDA_star(&work); return 0; } u16t HybridIDA_star(NODE_T *pN){ my.nodes = 1; my.gfound = 0; my.root_visits = 0; pN->udlr = NDIRS; pN->g = 0; pN->h = taxi_dist(pN); pN->id = my.nodes; pN->src = 0; const char *pr = {"Start"}; print_node( pN,pr,1 ); u16t depth = pN->h; while(1){ depth = search(pN,depth); if( depth & FOUND){ return FOUND; } if( depth & 0xFF00 ){ printf("..error %x\n",depth); return XX; } my.root_visits++; printf("[root visits: %u, depth %u]\n",my.root_visits,depth); } return 0; } u16t search(NODE_T *pN, u16t bound){ if(bound & 0xff00){ return bound; } u16t f = pN->g + pN->h; if( f > bound){ return f; } if(goal_found(pN)){ my.gfound = pN->g; memcpy(&work,pN,sizeof(NODE_T)); printf("total nodes=%d, g=%u \n", my.nodes, my.gfound); const char *pr = {"Found.."}; print_node( &work,pr,1 ); return FOUND; } NODE_T news; HSORT_T hlist[NDIRS]; for( short i=0; i<NDIRS; i++ ){ u16t rv = make_node(pN,&news, i ); hlist[i].dn = i; if( rv & OK ){ hlist[i].hn = news.h; continue; } hlist[i].hn = XX; } sort_nodes(&hlist[0]); u16t temp, min = MAX_INT; for( short i=0; i<NDIRS; i++ ){ if( hlist[i].hn > 0xff ) continue; temp = make_node(pN,&news, hlist[i].dn ); if( temp & XX ) return XX; if( temp & OK ){ news.id = my.nodes++; print_node(&news," succ",0 ); temp = search(&news, bound); if(temp & 0xff00){ return temp;} if(temp < min){ min = temp; } } } return min; } void sort_nodes(HSORT_T *p){ for( short s=0; s<NDIRS-1; s++ ){ HSORT_T tmp = p[0]; if( p[1].hn < p[0].hn ){tmp=p[0]; p[0]=p[1]; p[1]=tmp; } if( p[2].hn < p[1].hn ){tmp=p[1]; p[1]=p[2]; p[2]=tmp; } if( p[3].hn < p[2].hn ){tmp=p[2]; p[2]=p[3]; p[3]=tmp; } } } u16t tile_home(NODE_T *pN ){ for( short i=0; i<NCELLS; i++ ){ if( pN->data[i] == 0 ) return i; } return XX; } void print_node( NODE_T *pN, const char *pMsg, short force ){ const int tp1 = 0; if( my.verbose & BIT_HDR || force || tp1){ char ch = udlr_to_char(pN->udlr); printf("id:%u src:%u; h=%d, g=%u, udlr=%c, %s\n", pN->id, pN->src, pN->h, pN->g, ch, pMsg); } if(my.verbose & BIT_GRID || force || tp1){ for(u16t i=0; i<NR; i++ ){ for( u16t j=0; j<NC; j++ ){ printf("%3d",pN->data[i*NR+j]); } printf("\n"); } printf("\n"); } } u16t goal_found(NODE_T *pN) { if(my.phase==PHASE1){ short tags = 0; for( short i=0; i<(NC); i++ ){ if( pN->data[i] == i+1 ) tags++; } if( tags==4 ) return 1; } for( short i=0; i<(NR*NC); i++ ){ if( pN->data[i] != goal44.data[i] ) return 0; } return 1; } char udlr_to_char( char udlr ){ char ch = '?'; switch(udlr){ case UP: ch = 'U'; break; case DOWN: ch = 'D'; break; case LEFT: ch = 'L'; break; case RIGHT: ch = 'R'; break; default: break; } return ch; } void idx_to_rc( u16t idx, u16t *row, u16t *col ){ *row = idx/NR; *col = abs( idx - (*row * NR)); } u16t make_node(NODE_T *pSrc, NODE_T *pNew, u8t udlr ){ u16t row,col,home_idx,idx2; if(udlr>=NDIRS||udlr<0 ){ printf("invalid udlr %u\n",udlr); return XX; } if(my.nodes > MAX_NODES ){ printf("excessive nodes %u\n",my.nodes); return XX; } memcpy(pNew,pSrc,sizeof(NODE_T)); home_idx = tile_home(pNew); idx_to_rc(home_idx, &row, &col ); if( udlr == LEFT) { if( col < 1 ) return 0; col--; } if( udlr == RIGHT ){ if( col >= (NC-1) ) return 0; col++; } if( udlr == DOWN ) { if(row >= (NR-1)) return 0; row++; } if( udlr == UP ){ if(row < 1) return 0; row--; } idx2 = row * NR + col; if( idx2 < NCELLS ){ u8t *p = &pNew->data[0]; p[home_idx] = p[idx2]; p[idx2] = 0; pNew->src = pSrc->id; pNew->g = pSrc->g + 1; pNew->h = taxi_dist(pNew); pNew->udlr = udlr; return OK; } return 0; } u16t taxi_dist( NODE_T *pN){ u16t tile,sum = 0, r1,c1,r2,c2; u8t *p44 = &pN->data[0]; for( short i=0; i<(NR*NC); i++ ){ tile = p44[i]; if( tile==0 ) continue; idx_to_rc(i, &r2, &c2 ); idx_to_rc(tile-1, &r1, &c1 ); sum += abs(r1-r2) + abs(c1-c2); } } return sum; }
Keep all operations the same but rewrite the snippet in C.
#include <complex> #include <cmath> #include <iostream> double const pi = 4 * std::atan(1); int main() { for (int n = 2; n <= 10; ++n) { std::cout << n << ": "; for (int k = 0; k < n; ++k) std::cout << std::polar(1, 2*pi*k/n) << " "; std::cout << std::endl; } }
#include <stdio.h> #include <math.h> int main() { double a, c, s, PI2 = atan2(1, 1) * 8; int n, i; for (n = 1; n < 10; n++) for (i = 0; i < n; i++) { c = s = 0; if (!i ) c = 1; else if(n == 4 * i) s = 1; else if(n == 2 * i) c = -1; else if(3 * n == 4 * i) s = -1; else a = i * PI2 / n, c = cos(a), s = sin(a); if (c) printf("%.2g", c); printf(s == 1 ? "i" : s == -1 ? "-i" : s ? "%+.2gi" : "", s); printf(i == n - 1 ?"\n":", "); } return 0; }
Ensure the translated C code behaves exactly like the original C++ snippet.
#include <iostream> #include <sstream> typedef long long bigInt; using namespace std; class number { public: number() { s = "0"; neg = false; } number( bigInt a ) { set( a ); } number( string a ) { set( a ); } void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); } void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); } number operator * ( const number& b ) { return this->mul( b ); } number& operator *= ( const number& b ) { *this = *this * b; return *this; } number& operator = ( const number& b ) { s = b.s; return *this; } friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; } friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; } private: number mul( const number& b ) { number a; bool neg = false; string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' ); int xx, ss, rr, t, c, stp = 0; string::reverse_iterator xi = bs.rbegin(), si, ri; for( ; xi != bs.rend(); xi++ ) { c = 0; ri = r.rbegin() + stp; for( si = s.rbegin(); si != s.rend(); si++ ) { xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48; ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10; ( *ri++ ) = t + 48; } if( c > 0 ) ( *ri ) = c + 48; stp++; } trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0; if( t & 1 ) a.s = "-" + r; else a.s = r; return a; } void trimLeft( string& r ) { if( r.length() < 2 ) return; for( string::iterator x = r.begin(); x != ( r.end() - 1 ); ) { if( ( *x ) != '0' ) return; x = r.erase( x ); } } void clearStr() { for( string::iterator x = s.begin(); x != s.end(); ) { if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x ); else x++; } } string s; bool neg; }; int main( int argc, char* argv[] ) { number a, b; a.set( "18446744073709551616" ); b.set( "18446744073709551616" ); cout << a * b << endl << endl; cout << "Factor 1 = "; cin >> a; cout << "Factor 2 = "; cin >> b; cout << "Product: = " << a * b << endl << endl; return system( "pause" ); }
#include <stdio.h> #include <string.h> void longmulti(const char *a, const char *b, char *c) { int i = 0, j = 0, k = 0, n, carry; int la, lb; if (!strcmp(a, "0") || !strcmp(b, "0")) { c[0] = '0', c[1] = '\0'; return; } if (a[0] == '-') { i = 1; k = !k; } if (b[0] == '-') { j = 1; k = !k; } if (i || j) { if (k) c[0] = '-'; longmulti(a + i, b + j, c + k); return; } la = strlen(a); lb = strlen(b); memset(c, '0', la + lb); c[la + lb] = '\0'; # define I(a) (a - '0') for (i = la - 1; i >= 0; i--) { for (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) { n = I(a[i]) * I(b[j]) + I(c[k]) + carry; carry = n / 10; c[k] = (n % 10) + '0'; } c[k] += carry; } # undef I if (c[0] == '0') memmove(c, c + 1, la + lb); return; } int main() { char c[1024]; longmulti("-18446744073709551616", "-18446744073709551616", c); printf("%s\n", c); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
#include <iomanip> #include <iostream> #include <tuple> std::tuple<uint64_t, uint64_t> solvePell(int n) { int x = (int)sqrt(n); if (x * x == n) { return std::make_pair(1, 0); } int y = x; int z = 1; int r = 2 * x; std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0); std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e)); f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f)); a = std::get<1>(e) + x * std::get<1>(f); b = std::get<1>(f); if (a * a - n * b * b == 1) { break; } } return std::make_pair(a, b); } void test(int n) { auto r = solvePell(n); std::cout << "x^2 - " << std::setw(3) << n << " * y^2 = 1 for x = " << std::setw(21) << std::get<0>(r) << " and y = " << std::setw(21) << std::get<1>(r) << '\n'; } int main() { test(61); test(109); test(181); test(277); return 0; }
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct Pair { uint64_t v1, v2; }; struct Pair makePair(uint64_t a, uint64_t b) { struct Pair r; r.v1 = a; r.v2 = b; return r; } struct Pair solvePell(int n) { int x = (int) sqrt(n); if (x * x == n) { return makePair(1, 0); } else { int y = x; int z = 1; int r = 2 * x; struct Pair e = makePair(1, 0); struct Pair f = makePair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = makePair(e.v2, r * e.v2 + e.v1); f = makePair(f.v2, r * f.v2 + f.v1); a = e.v2 + x * f.v2; b = f.v2; if (a * a - n * b * b == 1) { break; } } return makePair(a, b); } } void test(int n) { struct Pair r = solvePell(n); printf("x^2 - %3d * y^2 = 1 for x = %21llu and y = %21llu\n", n, r.v1, r.v2); } int main() { test(61); test(109); test(181); test(277); return 0; }
Convert this C++ block to C, preserving its control flow and logic.
#include <iostream> #include <string> #include <algorithm> #include <cstdlib> bool contains_duplicates(std::string s) { std::sort(s.begin(), s.end()); return std::adjacent_find(s.begin(), s.end()) != s.end(); } void game() { typedef std::string::size_type index; std::string symbols = "0123456789"; unsigned int const selection_length = 4; std::random_shuffle(symbols.begin(), symbols.end()); std::string selection = symbols.substr(0, selection_length); std::string guess; while (std::cout << "Your guess? ", std::getline(std::cin, guess)) { if (guess.length() != selection_length || guess.find_first_not_of(symbols) != std::string::npos || contains_duplicates(guess)) { std::cout << guess << " is not a valid guess!"; continue; } unsigned int bulls = 0; unsigned int cows = 0; for (index i = 0; i != selection_length; ++i) { index pos = selection.find(guess[i]); if (pos == i) ++bulls; else if (pos != std::string::npos) ++cows; } std::cout << bulls << " bulls, " << cows << " cows.\n"; if (bulls == selection_length) { std::cout << "Congratulations! You have won!\n"; return; } } std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n"; std::exit(EXIT_FAILURE); } int main() { std::cout << "Welcome to bulls and cows!\nDo you want to play? "; std::string answer; while (true) { while (true) { if (!std::getline(std::cin, answer)) { std::cout << "I can't get an answer. Exiting.\n"; return EXIT_FAILURE; } if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y") break; if (answer == "no" || answer == "No" || answer == "n" || answer == "N") { std::cout << "Ok. Goodbye.\n"; return EXIT_SUCCESS; } std::cout << "Please answer yes or no: "; } game(); std::cout << "Another game? "; } }
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <stdbool.h> #include <curses.h> #include <string.h> #define MAX_NUM_TRIES 72 #define LINE_BEGIN 7 #define LAST_LINE 18 int yp=LINE_BEGIN, xp=0; char number[5]; char guess[5]; #define MAX_STR 256 void mvaddstrf(int y, int x, const char *fmt, ...) { va_list args; char buf[MAX_STR]; va_start(args, fmt); vsprintf(buf, fmt, args); move(y, x); clrtoeol(); addstr(buf); va_end(args); } void ask_for_a_number() { int i=0; char symbols[] = "123456789"; move(5,0); clrtoeol(); addstr("Enter four digits: "); while(i<4) { int c = getch(); if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) { addch(c); symbols[c-'1'] = 0; guess[i++] = c; } } } void choose_the_number() { int i=0, j; char symbols[] = "123456789"; while(i<4) { j = rand() % 9; if ( symbols[j] != 0 ) { number[i++] = symbols[j]; symbols[j] = 0; } } }
Change the programming language of this snippet from C++ to C without modifying what it does.
#include <algorithm> #include <iostream> #include <iterator> template <typename RandomAccessIterator> void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) { bool swapped = true; while (begin != end-- && swapped) { swapped = false; for (auto i = begin; i != end; ++i) { if (*(i + 1) < *i) { std::iter_swap(i, i + 1); swapped = true; } } } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bubble_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
#include <stdio.h> void bubble_sort (int *a, int n) { int i, t, j = n, s = 1; while (s) { s = 0; for (i = 1; i < j; i++) { if (a[i] < a[i - 1]) { t = a[i]; a[i] = a[i - 1]; a[i - 1] = t; s = 1; } } j--; } } 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" : " "); bubble_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
Can you help me rewrite this code in C instead of C++, keeping it the same logically?
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } unsigned int divisor_product(unsigned int n) { return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0)); } int main() { const unsigned int limit = 50; std::cout << "Product of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(11) << divisor_product(n); if (n % 5 == 0) std::cout << '\n'; } }
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } unsigned int divisor_product(unsigned int n) { return pow(n, divisor_count(n) / 2.0); } int main() { const unsigned int limit = 50; unsigned int n; printf("Product of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%11d", divisor_product(n)); if (n % 5 == 0) { printf("\n"); } } return 0; }
Produce a functionally identical C code for the snippet given in C++.
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } unsigned int divisor_product(unsigned int n) { return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0)); } int main() { const unsigned int limit = 50; std::cout << "Product of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(11) << divisor_product(n); if (n % 5 == 0) std::cout << '\n'; } }
#include <math.h> #include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } unsigned int divisor_product(unsigned int n) { return pow(n, divisor_count(n) / 2.0); } int main() { const unsigned int limit = 50; unsigned int n; printf("Product of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%11d", divisor_product(n)); if (n % 5 == 0) { printf("\n"); } } return 0; }
Preserve the algorithm and functionality while converting the code from C++ to C.
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream input ( "input.txt" ); ofstream output ("output.txt"); if (output.is_open()) { if (input.is_open()){ while (getline (input,line)) { output << line << endl; } input.close(); } else { cout << "input.txt cannot be opened!\n"; } output.close(); } else { cout << "output.txt cannot be written to!\n"; } return 0; }
#include <stdio.h> int main(int argc, char **argv) { FILE *in, *out; int c; in = fopen("input.txt", "r"); if (!in) { fprintf(stderr, "Error opening input.txt for reading.\n"); return 1; } out = fopen("output.txt", "w"); if (!out) { fprintf(stderr, "Error opening output.txt for writing.\n"); fclose(in); return 1; } while ((c = fgetc(in)) != EOF) { fputc(c, out); } fclose(out); fclose(in); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the C++ version.
#include <iostream> int main() { int a, b; std::cin >> a >> b; std::cout << "a+b = " << a+b << "\n"; std::cout << "a-b = " << a-b << "\n"; std::cout << "a*b = " << a*b << "\n"; std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n"; return 0; }
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int a, b; if (argc < 3) exit(1); b = atoi(argv[--argc]); if (b == 0) exit(2); a = atoi(argv[--argc]); printf("a+b = %d\n", a+b); printf("a-b = %d\n", a-b); printf("a*b = %d\n", a*b); printf("a/b = %d\n", a/b); printf("a%%b = %d\n", a%b); return 0; }
Rewrite the snippet below in C so it works the same as the original C++ code.
#include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> int main() { using namespace boost::numeric::ublas; matrix<double> m(3,3); for(int i=0; i!=m.size1(); ++i) for(int j=0; j!=m.size2(); ++j) m(i,j)=3*i+j; std::cout << trans(m) << std::endl; }
#include <stdio.h> void transpose(void *dest, void *src, int src_h, int src_w) { int i, j; double (*d)[src_h] = dest, (*s)[src_w] = src; for (i = 0; i < src_h; i++) for (j = 0; j < src_w; j++) d[j][i] = s[i][j]; } int main() { int i, j; double a[3][5] = {{ 0, 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 }, { 1, 0, 0, 0, 42}}; double b[5][3]; transpose(b, a, 3, 5); for (i = 0; i < 5; i++) for (j = 0; j < 3; j++) printf("%g%c", b[i][j], j == 2 ? '\n' : ' '); return 0; }
Produce a functionally identical C code for the snippet given in C++.
#include <iostream> #include <tr1/memory> using std::tr1::shared_ptr; using std::tr1::enable_shared_from_this; struct Arg { virtual int run() = 0; virtual ~Arg() { }; }; int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>); class B : public Arg, public enable_shared_from_this<B> { private: int k; const shared_ptr<Arg> x1, x2, x3, x4; public: B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3, shared_ptr<Arg> _x4) : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { } int run() { return A(--k, shared_from_this(), x1, x2, x3, x4); } }; class Const : public Arg { private: const int x; public: Const(int _x) : x(_x) { } int run () { return x; } }; int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3, shared_ptr<Arg> x4, shared_ptr<Arg> x5) { if (k <= 0) return x4->run() + x5->run(); else { shared_ptr<Arg> b(new B(k, x1, x2, x3, x4)); return b->run(); } } int main() { std::cout << A(10, shared_ptr<Arg>(new Const(1)), shared_ptr<Arg>(new Const(-1)), shared_ptr<Arg>(new Const(-1)), shared_ptr<Arg>(new Const(1)), shared_ptr<Arg>(new Const(0))) << std::endl; return 0; }
#include <stdio.h> #include <stdlib.h> typedef struct arg { int (*fn)(struct arg*); int *k; struct arg *x1, *x2, *x3, *x4, *x5; } ARG; int f_1 (ARG* _) { return -1; } int f0 (ARG* _) { return 0; } int f1 (ARG* _) { return 1; } int eval(ARG* a) { return a->fn(a); } #define MAKE_ARG(...) (&(ARG){__VA_ARGS__}) #define FUN(...) MAKE_ARG(B, &k, __VA_ARGS__) int A(ARG*); int B(ARG* a) { int k = *a->k -= 1; return A(FUN(a, a->x1, a->x2, a->x3, a->x4)); } int A(ARG* a) { return *a->k <= 0 ? eval(a->x4) + eval(a->x5) : B(a); } int main(int argc, char **argv) { int k = argc == 2 ? strtol(argv[1], 0, 0) : 10; printf("%d\n", A(FUN(MAKE_ARG(f1), MAKE_ARG(f_1), MAKE_ARG(f_1), MAKE_ARG(f1), MAKE_ARG(f0)))); return 0; }
Ensure the translated C code behaves exactly like the original C++ snippet.
#include <iostream> bool a(bool in) { std::cout << "a" << std::endl; return in; } bool b(bool in) { std::cout << "b" << std::endl; return in; } void test(bool i, bool j) { std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl; std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl; } int main() { test(false, false); test(false, true); test(true, false); test(true, true); return 0; }
#include <stdio.h> #include <stdbool.h> bool a(bool in) { printf("I am a\n"); return in; } bool b(bool in) { printf("I am b\n"); return in; } #define TEST(X,Y,O) \ do { \ x = a(X) O b(Y); \ printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \ } while(false); int main() { bool x; TEST(false, true, &&); TEST(true, false, ||); TEST(true, false, &&); TEST(false, false, ||); return 0; }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
Change the following C++ code into C without altering its purpose.
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
Convert this C++ block to C, preserving its control flow and logic.
#include <iomanip> #include <iostream> int mod(int n, int d) { return (d + n % d) % d; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } void print_carmichael_numbers(int prime1) { for (int h3 = 1; h3 < prime1; ++h3) { for (int d = 1; d < h3 + prime1; ++d) { if (mod((h3 + prime1) * (prime1 - 1), d) != 0 || mod(-prime1 * prime1, h3) != mod(d, h3)) continue; int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d; if (!is_prime(prime2)) continue; int prime3 = 1 + prime1 * prime2/h3; if (!is_prime(prime3)) continue; if (mod(prime2 * prime3, prime1 - 1) != 1) continue; unsigned int c = prime1 * prime2 * prime3; std::cout << std::setw(2) << prime1 << " x " << std::setw(4) << prime2 << " x " << std::setw(5) << prime3 << " = " << std::setw(10) << c << '\n'; } } } int main() { for (int p = 2; p <= 61; ++p) { if (is_prime(p)) print_carmichael_numbers(p); } return 0; }
#include <stdio.h> #define mod(n,m) ((((n) % (m)) + (m)) % (m)) int is_prime(unsigned int n) { if (n <= 3) { return n > 1; } else if (!(n % 2) || !(n % 3)) { return 0; } else { unsigned int i; for (i = 5; i*i <= n; i += 6) if (!(n % i) || !(n % (i + 2))) return 0; return 1; } } void carmichael3(int p1) { if (!is_prime(p1)) return; int h3, d, p2, p3; for (h3 = 1; h3 < p1; ++h3) { for (d = 1; d < h3 + p1; ++d) { if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) { p2 = 1 + ((p1 - 1) * (h3 + p1)/d); if (!is_prime(p2)) continue; p3 = 1 + (p1 * p2 / h3); if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue; printf("%d %d %d\n", p1, p2, p3); } } } } int main(void) { int p1; for (p1 = 2; p1 < 62; ++p1) carmichael3(p1); return 0; }
Preserve the algorithm and functionality while converting the code from C++ to C.
#include <cstdio> void divisor_count_and_sum(unsigned int n, unsigned int& divisor_count, unsigned int& divisor_sum) { divisor_count = 0; divisor_sum = 0; for (unsigned int i = 1;; i++) { unsigned int j = n / i; if (j < i) break; if (i * j != n) continue; divisor_sum += i; divisor_count += 1; if (i != j) { divisor_sum += j; divisor_count += 1; } } } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; n++) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, divisor_count, divisor_sum); unsigned int mean = divisor_sum / divisor_count; if (mean * divisor_count != divisor_sum) continue; arithmetic_count++; if (divisor_count > 2) composite_count++; if (arithmetic_count <= 100) { std::printf("%3u ", n); if (arithmetic_count % 10 == 0) std::printf("\n"); } if ((arithmetic_count == 1000) || (arithmetic_count == 10000) || (arithmetic_count == 100000) || (arithmetic_count == 1000000)) { std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
#include <stdio.h> void divisor_count_and_sum(unsigned int n, unsigned int* pcount, unsigned int* psum) { unsigned int divisor_count = 1; unsigned int divisor_sum = 1; unsigned int power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) { ++divisor_count; divisor_sum += power; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1, sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { ++count; sum += power; } divisor_count *= count; divisor_sum *= sum; } if (n > 1) { divisor_count *= 2; divisor_sum *= n + 1; } *pcount = divisor_count; *psum = divisor_sum; } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, &divisor_count, &divisor_sum); if (divisor_sum % divisor_count != 0) continue; ++arithmetic_count; if (divisor_count > 2) ++composite_count; if (arithmetic_count <= 100) { printf("%3u ", n); if (arithmetic_count % 10 == 0) printf("\n"); } if (arithmetic_count == 1000 || arithmetic_count == 10000 || arithmetic_count == 100000 || arithmetic_count == 1000000) { printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
Change the following C++ code into C without altering its purpose.
#include <cstdio> void divisor_count_and_sum(unsigned int n, unsigned int& divisor_count, unsigned int& divisor_sum) { divisor_count = 0; divisor_sum = 0; for (unsigned int i = 1;; i++) { unsigned int j = n / i; if (j < i) break; if (i * j != n) continue; divisor_sum += i; divisor_count += 1; if (i != j) { divisor_sum += j; divisor_count += 1; } } } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; n++) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, divisor_count, divisor_sum); unsigned int mean = divisor_sum / divisor_count; if (mean * divisor_count != divisor_sum) continue; arithmetic_count++; if (divisor_count > 2) composite_count++; if (arithmetic_count <= 100) { std::printf("%3u ", n); if (arithmetic_count % 10 == 0) std::printf("\n"); } if ((arithmetic_count == 1000) || (arithmetic_count == 10000) || (arithmetic_count == 100000) || (arithmetic_count == 1000000)) { std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
#include <stdio.h> void divisor_count_and_sum(unsigned int n, unsigned int* pcount, unsigned int* psum) { unsigned int divisor_count = 1; unsigned int divisor_sum = 1; unsigned int power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) { ++divisor_count; divisor_sum += power; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1, sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { ++count; sum += power; } divisor_count *= count; divisor_sum *= sum; } if (n > 1) { divisor_count *= 2; divisor_sum *= n + 1; } *pcount = divisor_count; *psum = divisor_sum; } int main() { unsigned int arithmetic_count = 0; unsigned int composite_count = 0; for (unsigned int n = 1; arithmetic_count <= 1000000; ++n) { unsigned int divisor_count; unsigned int divisor_sum; divisor_count_and_sum(n, &divisor_count, &divisor_sum); if (divisor_sum % divisor_count != 0) continue; ++arithmetic_count; if (divisor_count > 2) ++composite_count; if (arithmetic_count <= 100) { printf("%3u ", n); if (arithmetic_count % 10 == 0) printf("\n"); } if (arithmetic_count == 1000 || arithmetic_count == 10000 || arithmetic_count == 100000 || arithmetic_count == 1000000) { printf("\n%uth arithmetic number is %u\n", arithmetic_count, n); printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count); } } return 0; }
Produce a functionally identical C code for the snippet given in C++.
#include <windows.h> #include <sstream> #include <tchar.h> using namespace std; const unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } void* getBits( void ) const { return pBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void* pBits; int width, height, wid; DWORD clr; }; class bmpNoise { public: bmpNoise() { QueryPerformanceFrequency( &_frequency ); _bmp.create( BMP_WID, BMP_HEI ); _frameTime = _fps = 0; _start = getTime(); _frames = 0; } void mainLoop() { float now = getTime(); if( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; } HDC wdc, dc = _bmp.getDC(); unsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() ); for( int y = 0; y < BMP_HEI; y++ ) { for( int x = 0; x < BMP_WID; x++ ) { if( rand() % 10 < 5 ) memset( bits, 255, 3 ); else memset( bits, 0, 3 ); bits++; } } ostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() ); wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); _frames++; _frameTime = getTime() - now; if( _frameTime > 1.0f ) _frameTime = 1.0f; } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: float getTime() { LARGE_INTEGER liTime; QueryPerformanceCounter( &liTime ); return liTime.QuadPart / ( float )_frequency.QuadPart; } myBitmap _bmp; HWND _hwnd; float _start, _fps, _frameTime; unsigned int _frames; LARGE_INTEGER _frequency; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _noise.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { _noise.mainLoop(); } } return UnregisterClass( "_MY_NOISE_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_NOISE_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_WID, BMP_HEI }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_NOISE_", ".: Noise image -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; bmpNoise _noise; }; wnd* wnd::_inst = 0; int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
#include <stdlib.h> #include <stdio.h> #include <time.h> #include <SDL/SDL.h> unsigned int frames = 0; unsigned int t_acc = 0; void print_fps () { static Uint32 last_t = 0; Uint32 t = SDL_GetTicks(); Uint32 dt = t - last_t; t_acc += dt; if (t_acc > 1000) { unsigned int el_time = t_acc / 1000; printf("- fps: %g\n", (float) frames / (float) el_time); t_acc = 0; frames = 0; } last_t = t; } void blit_noise(SDL_Surface *surf) { unsigned int i; long dim = surf->w * surf->h; while (1) { SDL_LockSurface(surf); for (i=0; i < dim; ++i) { ((unsigned char *)surf->pixels)[i] = ((rand() & 1) ? 255 : 0); } SDL_UnlockSurface(surf); SDL_Flip(surf); ++frames; print_fps(); } } int main(void) { SDL_Surface *surf = NULL; srand((unsigned int)time(NULL)); SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO); surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE); blit_noise(surf); }
Port the following code from C++ to C with equivalent syntax and logic.
#include <conio.h> #include <iostream> using namespace std; int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N'); if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }
#include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> void set_mode(int want_key) { static struct termios old, new; if (!want_key) { tcsetattr(STDIN_FILENO, TCSANOW, &old); return; } tcgetattr(STDIN_FILENO, &old); new = old; new.c_lflag &= ~(ICANON); tcsetattr(STDIN_FILENO, TCSANOW, &new); } int get_key(int no_timeout) { int c = 0; struct timeval tv; fd_set fs; tv.tv_usec = tv.tv_sec = 0; FD_ZERO(&fs); FD_SET(STDIN_FILENO, &fs); select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv); if (FD_ISSET(STDIN_FILENO, &fs)) { c = getchar(); set_mode(0); } return c; } int main() { int c; while(1) { set_mode(1); while (get_key(0)); printf("Prompt again [Y/N]? "); fflush(stdout); c = get_key(1); if (c == 'Y' || c == 'y') { printf("\n"); continue; } if (c == 'N' || c == 'n') { printf("\nDone\n"); break; } printf("\nYes or no?\n"); } return 0; }