Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Can you help me rewrite this code in C instead of C++, keeping it the same logically?
#include <array> #include <iostream> #include <vector> constexpr int MAX = 12; static std::vector<char> sp; static std::array<int, MAX> count; static int pos = 0; int factSum(int n) { int s = 0; int x = 0; int f = 1; while (x < n) { f *= ++x; s += f; } return s; } bool r(int n) { if (n == 0) { return false; } char c = sp[pos - n]; if (--count[n] == 0) { count[n] = n; if (!r(n - 1)) { return false; } } sp[pos++] = c; return true; } void superPerm(int n) { pos = n; int len = factSum(n); if (len > 0) { sp.resize(len); } for (size_t i = 0; i <= n; i++) { count[i] = i; } for (size_t i = 1; i <= n; i++) { sp[i - 1] = '0' + i; } while (r(n)) {} } int main() { for (size_t n = 0; n < MAX; n++) { superPerm(n); std::cout << "superPerm(" << n << ") len = " << sp.size() << '\n'; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 12 char *super = 0; int pos, cnt[MAX]; int fact_sum(int n) { int s, x, f; for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f); return s; } int r(int n) { if (!n) return 0; char c = super[pos - n]; if (!--cnt[n]) { cnt[n] = n; if (!r(n-1)) return 0; } super[pos++] = c; return 1; } void superperm(int n) { int i, len; pos = n; len = fact_sum(n); super = realloc(super, len + 1); super[len] = '\0'; for (i = 0; i <= n; i++) cnt[i] = i; for (i = 1; i <= n; i++) super[i - 1] = i + '0'; while (r(n)); } int main(void) { int n; for (n = 0; n < MAX; n++) { printf("superperm(%2d) ", n); superperm(n); printf("len = %d", (int)strlen(super)); putchar('\n'); } return 0; }
Convert this C++ block to C, preserving its control flow and logic.
#include <random> #include <iostream> #include <iterator> #include <algorithm> using namespace std; mt19937 engine; unsigned int one_of_n(unsigned int n) { unsigned int choice; for(unsigned int i = 0; i < n; ++i) { uniform_int_distribution<unsigned int> distribution(0, i); if(!distribution(engine)) choice = i; } return choice; } int main() { engine = mt19937(random_device()()); unsigned int results[10] = {0}; for(unsigned int i = 0; i < 1000000; ++i) results[one_of_n(10)]++; ostream_iterator<unsigned int> out_it(cout, " "); copy(results, results+10, out_it); cout << '\n'; }
#include <stdio.h> #include <stdlib.h> inline int irand(int n) { int r, randmax = RAND_MAX/n * n; while ((r = rand()) >= randmax); return r / (randmax / n); } inline int one_of_n(int n) { int i, r = 0; for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; return r; } int main(void) { int i, r[10] = {0}; for (i = 0; i < 1000000; i++, r[one_of_n(10)]++); for (i = 0; i < 10; i++) printf("%d%c", r[i], i == 9 ? '\n':' '); return 0; }
Keep all operations the same but rewrite the snippet in C.
#include <random> #include <iostream> #include <iterator> #include <algorithm> using namespace std; mt19937 engine; unsigned int one_of_n(unsigned int n) { unsigned int choice; for(unsigned int i = 0; i < n; ++i) { uniform_int_distribution<unsigned int> distribution(0, i); if(!distribution(engine)) choice = i; } return choice; } int main() { engine = mt19937(random_device()()); unsigned int results[10] = {0}; for(unsigned int i = 0; i < 1000000; ++i) results[one_of_n(10)]++; ostream_iterator<unsigned int> out_it(cout, " "); copy(results, results+10, out_it); cout << '\n'; }
#include <stdio.h> #include <stdlib.h> inline int irand(int n) { int r, randmax = RAND_MAX/n * n; while ((r = rand()) >= randmax); return r / (randmax / n); } inline int one_of_n(int n) { int i, r = 0; for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; return r; } int main(void) { int i, r[10] = {0}; for (i = 0; i < 1000000; i++, r[one_of_n(10)]++); for (i = 0; i < 10; i++) printf("%d%c", r[i], i == 9 ? '\n':' '); return 0; }
Write a version of this C++ function in C with identical behavior.
#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> std::map<char, int> _map; std::vector<std::string> _result; size_t longest = 0; void make_sequence( std::string n ) { _map.clear(); for( std::string::iterator i = n.begin(); i != n.end(); i++ ) _map.insert( std::make_pair( *i, _map[*i]++ ) ); std::string z; for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) { char c = ( *i ).second + 48; z.append( 1, c ); z.append( 1, i->first ); } if( longest <= z.length() ) { longest = z.length(); if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) { _result.push_back( z ); make_sequence( z ); } } } int main( int argc, char* argv[] ) { std::vector<std::string> tests; tests.push_back( "9900" ); tests.push_back( "9090" ); tests.push_back( "9009" ); for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) { make_sequence( *i ); std::cout << "[" << *i << "] Iterations: " << _result.size() + 1 << "\n"; for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) { std::cout << *j << "\n"; } std::cout << "\n\n"; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct rec_t rec_t; struct rec_t { int depth; rec_t * p[10]; }; rec_t root = {0, {0}}; #define USE_POOL_ALLOC #ifdef USE_POOL_ALLOC rec_t *tail = 0, *head = 0; #define POOL_SIZE (1 << 20) inline rec_t *new_rec() { if (head == tail) { head = calloc(sizeof(rec_t), POOL_SIZE); tail = head + POOL_SIZE; } return head++; } #else #define new_rec() calloc(sizeof(rec_t), 1) #endif rec_t *find_rec(char *s) { int i; rec_t *r = &root; while (*s) { i = *s++ - '0'; if (!r->p[i]) r->p[i] = new_rec(); r = r->p[i]; } return r; } char number[100][4]; void init() { int i; for (i = 0; i < 100; i++) sprintf(number[i], "%d", i); } void count(char *buf) { int i, c[10] = {0}; char *s; for (s = buf; *s; c[*s++ - '0']++); for (i = 9; i >= 0; i--) { if (!c[i]) continue; s = number[c[i]]; *buf++ = s[0]; if ((*buf = s[1])) buf++; *buf++ = i + '0'; } *buf = '\0'; } int depth(char *in, int d) { rec_t *r = find_rec(in); if (r->depth > 0) return r->depth; d++; if (!r->depth) r->depth = -d; else r->depth += d; count(in); d = depth(in, d); if (r->depth <= 0) r->depth = d + 1; return r->depth; } int main(void) { char a[100]; int i, d, best_len = 0, n_best = 0; int best_ints[32]; rec_t *r; init(); for (i = 0; i < 1000000; i++) { sprintf(a, "%d", i); d = depth(a, 0); if (d < best_len) continue; if (d > best_len) { n_best = 0; best_len = d; } if (d == best_len) best_ints[n_best++] = i; } printf("longest length: %d\n", best_len); for (i = 0; i < n_best; i++) { printf("%d\n", best_ints[i]); sprintf(a, "%d", best_ints[i]); for (d = 0; d <= best_len; d++) { r = find_rec(a); printf("%3d: %s\n", r->depth, a); count(a); } putchar('\n'); } return 0; }
Can you help me rewrite this code in C instead of C++, keeping it the same logically?
#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> std::map<char, int> _map; std::vector<std::string> _result; size_t longest = 0; void make_sequence( std::string n ) { _map.clear(); for( std::string::iterator i = n.begin(); i != n.end(); i++ ) _map.insert( std::make_pair( *i, _map[*i]++ ) ); std::string z; for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) { char c = ( *i ).second + 48; z.append( 1, c ); z.append( 1, i->first ); } if( longest <= z.length() ) { longest = z.length(); if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) { _result.push_back( z ); make_sequence( z ); } } } int main( int argc, char* argv[] ) { std::vector<std::string> tests; tests.push_back( "9900" ); tests.push_back( "9090" ); tests.push_back( "9009" ); for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) { make_sequence( *i ); std::cout << "[" << *i << "] Iterations: " << _result.size() + 1 << "\n"; for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) { std::cout << *j << "\n"; } std::cout << "\n\n"; } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct rec_t rec_t; struct rec_t { int depth; rec_t * p[10]; }; rec_t root = {0, {0}}; #define USE_POOL_ALLOC #ifdef USE_POOL_ALLOC rec_t *tail = 0, *head = 0; #define POOL_SIZE (1 << 20) inline rec_t *new_rec() { if (head == tail) { head = calloc(sizeof(rec_t), POOL_SIZE); tail = head + POOL_SIZE; } return head++; } #else #define new_rec() calloc(sizeof(rec_t), 1) #endif rec_t *find_rec(char *s) { int i; rec_t *r = &root; while (*s) { i = *s++ - '0'; if (!r->p[i]) r->p[i] = new_rec(); r = r->p[i]; } return r; } char number[100][4]; void init() { int i; for (i = 0; i < 100; i++) sprintf(number[i], "%d", i); } void count(char *buf) { int i, c[10] = {0}; char *s; for (s = buf; *s; c[*s++ - '0']++); for (i = 9; i >= 0; i--) { if (!c[i]) continue; s = number[c[i]]; *buf++ = s[0]; if ((*buf = s[1])) buf++; *buf++ = i + '0'; } *buf = '\0'; } int depth(char *in, int d) { rec_t *r = find_rec(in); if (r->depth > 0) return r->depth; d++; if (!r->depth) r->depth = -d; else r->depth += d; count(in); d = depth(in, d); if (r->depth <= 0) r->depth = d + 1; return r->depth; } int main(void) { char a[100]; int i, d, best_len = 0, n_best = 0; int best_ints[32]; rec_t *r; init(); for (i = 0; i < 1000000; i++) { sprintf(a, "%d", i); d = depth(a, 0); if (d < best_len) continue; if (d > best_len) { n_best = 0; best_len = d; } if (d == best_len) best_ints[n_best++] = i; } printf("longest length: %d\n", best_len); for (i = 0; i < n_best; i++) { printf("%d\n", best_ints[i]); sprintf(a, "%d", best_ints[i]); for (d = 0; d <= best_len; d++) { r = find_rec(a); printf("%3d: %s\n", r->depth, a); count(a); } putchar('\n'); } return 0; }
Change the following C++ code into C without altering its purpose.
#include <iostream> #include <string> #include <cstdint> typedef std::uint64_t integer; struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; struct named_number { const char* cardinal; const char* ordinal; integer number; }; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_name(const number_names& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const char* get_name(const named_number& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const named_number& get_named_number(integer n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return named_numbers[i]; } return named_numbers[names_len - 1]; } std::string number_name(integer n, bool ordinal) { std::string result; if (n < 20) result = get_name(small[n], ordinal); else if (n < 100) { if (n % 10 == 0) { result = get_name(tens[n/10 - 2], ordinal); } else { result = get_name(tens[n/10 - 2], false); result += "-"; result += get_name(small[n % 10], ordinal); } } else { const named_number& num = get_named_number(n); integer p = num.number; result = number_name(n/p, false); result += " "; if (n % p == 0) { result += get_name(num, ordinal); } else { result += get_name(num, false); result += " "; result += number_name(n % p, ordinal); } } return result; } void test_ordinal(integer n) { std::cout << n << ": " << number_name(n, true) << '\n'; } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
#include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <glib.h> typedef uint64_t integer; typedef struct number_names_tag { const char* cardinal; const char* ordinal; } number_names; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } void append_number_name(GString* gstr, integer n, bool ordinal) { if (n < 20) g_string_append(gstr, get_small_name(&small[n], ordinal)); else if (n < 100) { if (n % 10 == 0) { g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal)); } else { g_string_append(gstr, get_small_name(&tens[n/10 - 2], false)); g_string_append_c(gstr, '-'); g_string_append(gstr, get_small_name(&small[n % 10], ordinal)); } } else { const named_number* num = get_named_number(n); integer p = num->number; append_number_name(gstr, n/p, false); g_string_append_c(gstr, ' '); if (n % p == 0) { g_string_append(gstr, get_big_name(num, ordinal)); } else { g_string_append(gstr, get_big_name(num, false)); g_string_append_c(gstr, ' '); append_number_name(gstr, n % p, ordinal); } } } GString* number_name(integer n, bool ordinal) { GString* result = g_string_sized_new(8); append_number_name(result, n, ordinal); return result; } void test_ordinal(integer n) { GString* name = number_name(n, true); printf("%llu: %s\n", n, name->str); g_string_free(name, TRUE); } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
Write the same code in C as shown below in C++.
#include <iostream> typedef unsigned long long bigint; using namespace std; class sdn { public: bool check( bigint n ) { int cc = digitsCount( n ); return compare( n, cc ); } void displayAll( bigint s ) { for( bigint y = 1; y < s; y++ ) if( check( y ) ) cout << y << " is a Self-Describing Number." << endl; } private: bool compare( bigint n, int cc ) { bigint a; while( cc ) { cc--; a = n % 10; if( dig[cc] != a ) return false; n -= a; n /= 10; } return true; } int digitsCount( bigint n ) { int cc = 0; bigint a; memset( dig, 0, sizeof( dig ) ); while( n ) { a = n % 10; dig[a]++; cc++ ; n -= a; n /= 10; } return cc; } int dig[10]; }; int main( int argc, char* argv[] ) { sdn s; s. displayAll( 1000000000000 ); cout << endl << endl; system( "pause" ); bigint n; while( true ) { system( "cls" ); cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n; if( !n ) return 0; if( s.check( n ) ) cout << n << " is"; else cout << n << " is NOT"; cout << " a Self-Describing Number!" << endl << endl; system( "pause" ); } return 0; }
#include <stdio.h> inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0}; for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++; for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++; while(d-- && dig[x++] == cnt[d]); return d == -1; } int main() { int i; for (i = 1; i < 100000000; i++) if (self_desc(i)) printf("%d\n", i); return 0; }
Preserve the algorithm and functionality while converting the code from C++ to C.
#include <iostream> typedef unsigned long long bigint; using namespace std; class sdn { public: bool check( bigint n ) { int cc = digitsCount( n ); return compare( n, cc ); } void displayAll( bigint s ) { for( bigint y = 1; y < s; y++ ) if( check( y ) ) cout << y << " is a Self-Describing Number." << endl; } private: bool compare( bigint n, int cc ) { bigint a; while( cc ) { cc--; a = n % 10; if( dig[cc] != a ) return false; n -= a; n /= 10; } return true; } int digitsCount( bigint n ) { int cc = 0; bigint a; memset( dig, 0, sizeof( dig ) ); while( n ) { a = n % 10; dig[a]++; cc++ ; n -= a; n /= 10; } return cc; } int dig[10]; }; int main( int argc, char* argv[] ) { sdn s; s. displayAll( 1000000000000 ); cout << endl << endl; system( "pause" ); bigint n; while( true ) { system( "cls" ); cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n; if( !n ) return 0; if( s.check( n ) ) cout << n << " is"; else cout << n << " is NOT"; cout << " a Self-Describing Number!" << endl << endl; system( "pause" ); } return 0; }
#include <stdio.h> inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0}; for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++; for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++; while(d-- && dig[x++] == cnt[d]); return d == -1; } int main() { int i; for (i = 1; i < 100000000; i++) if (self_desc(i)) printf("%d\n", i); return 0; }
Port the following code from C++ to C with equivalent syntax and logic.
#include <iostream> #include <tuple> #include <vector> std::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int); std::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) { if (pos > minLen || seq[0] > n) return { minLen, 0 }; else if (seq[0] == n) return { pos, 1 }; else if (pos < minLen) return tryPerm(0, pos, seq, n, minLen); else return { minLen, 0 }; } std::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) { if (i > pos) return { minLen, 0 }; std::vector<int> seq2{ seq[0] + seq[i] }; seq2.insert(seq2.end(), seq.cbegin(), seq.cend()); auto res1 = checkSeq(pos + 1, seq2, n, minLen); auto res2 = tryPerm(i + 1, pos, seq, n, res1.first); if (res2.first < res1.first) return res2; else if (res2.first == res1.first) return { res2.first, res1.second + res2.second }; else throw std::runtime_error("tryPerm exception"); } std::pair<int, int> initTryPerm(int x) { return tryPerm(0, 0, { 1 }, x, 12); } void findBrauer(int num) { auto res = initTryPerm(num); std::cout << '\n'; std::cout << "N = " << num << '\n'; std::cout << "Minimum length of chains: L(n)= " << res.first << '\n'; std::cout << "Number of minimum length Brauer chains: " << res.second << '\n'; } int main() { std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 }; for (int i : nums) { findBrauer(i); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 typedef int bool; typedef struct { int x, y; } pair; int* example = NULL; int exampleLen = 0; void reverse(int s[], int len) { int i, j, t; for (i = 0, j = len - 1; i < j; ++i, --j) { t = s[i]; s[i] = s[j]; s[j] = t; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen); pair checkSeq(int pos, int seq[], int n, int len, int minLen) { pair p; if (pos > minLen || seq[0] > n) { p.x = minLen; p.y = 0; return p; } else if (seq[0] == n) { example = malloc(len * sizeof(int)); memcpy(example, seq, len * sizeof(int)); exampleLen = len; p.x = pos; p.y = 1; return p; } else if (pos < minLen) { return tryPerm(0, pos, seq, n, len, minLen); } else { p.x = minLen; p.y = 0; return p; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) { int *seq2; pair p, res1, res2; size_t size = sizeof(int); if (i > pos) { p.x = minLen; p.y = 0; return p; } seq2 = malloc((len + 1) * size); memcpy(seq2 + 1, seq, len * size); seq2[0] = seq[0] + seq[i]; res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen); res2 = tryPerm(i + 1, pos, seq, n, len, res1.x); free(seq2); if (res2.x < res1.x) return res2; else if (res2.x == res1.x) { p.x = res2.x; p.y = res1.y + res2.y; return p; } else { printf("Error in tryPerm\n"); p.x = 0; p.y = 0; return p; } } pair initTryPerm(int x, int minLen) { int seq[1] = {1}; return tryPerm(0, 0, seq, x, 1, minLen); } void printArray(int a[], int len) { int i; printf("["); for (i = 0; i < len; ++i) printf("%d ", a[i]); printf("\b]\n"); } bool isBrauer(int a[], int len) { int i, j; bool ok; for (i = 2; i < len; ++i) { ok = FALSE; for (j = i - 1; j >= 0; j--) { if (a[i-1] + a[j] == a[i]) { ok = TRUE; break; } } if (!ok) return FALSE; } return TRUE; } bool isAdditionChain(int a[], int len) { int i, j, k; bool ok, exit; for (i = 2; i < len; ++i) { if (a[i] > a[i - 1] * 2) return FALSE; ok = FALSE; exit = FALSE; for (j = i - 1; j >= 0; --j) { for (k = j; k >= 0; --k) { if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; } } if (exit) break; } if (!ok) return FALSE; } if (example == NULL && !isBrauer(a, len)) { example = malloc(len * sizeof(int)); memcpy(example, a, len * sizeof(int)); exampleLen = len; } return TRUE; } void nextChains(int index, int len, int seq[], int *pcount) { for (;;) { int i; if (index < len - 1) { nextChains(index + 1, len, seq, pcount); } if (seq[index] + len - 1 - index >= seq[len - 1]) return; seq[index]++; for (i = index + 1; i < len - 1; ++i) { seq[i] = seq[i-1] + 1; } if (isAdditionChain(seq, len)) (*pcount)++; } } int findNonBrauer(int num, int len, int brauer) { int i, count = 0; int *seq = malloc(len * sizeof(int)); seq[0] = 1; seq[len - 1] = num; for (i = 1; i < len - 1; ++i) { seq[i] = seq[i - 1] + 1; } if (isAdditionChain(seq, len)) count = 1; nextChains(2, len, seq, &count); free(seq); return count - brauer; } void findBrauer(int num, int minLen, int nbLimit) { pair p = initTryPerm(num, minLen); int actualMin = p.x, brauer = p.y, nonBrauer; printf("\nN = %d\n", num); printf("Minimum length of chains : L(%d) = %d\n", num, actualMin); printf("Number of minimum length Brauer chains : %d\n", brauer); if (brauer > 0) { printf("Brauer example : "); reverse(example, exampleLen); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } if (num <= nbLimit) { nonBrauer = findNonBrauer(num, actualMin + 1, brauer); printf("Number of minimum length non-Brauer chains : %d\n", nonBrauer); if (nonBrauer > 0) { printf("Non-Brauer example : "); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } } else { printf("Non-Brauer analysis suppressed\n"); } } int main() { int i; int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; printf("Searching for Brauer chains up to a minimum length of 12:\n"); for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79); return 0; }
Write a version of this C++ function in C with identical behavior.
#include <iostream> using namespace std; int main() { long long int a = 30'00'000; std::cout <<"And with the ' in C++ 14 : "<< a << endl; return 0; }
#include <locale.h> #include <stdio.h> int main() { unsigned long long int trillion = 1000000000000; setlocale(LC_NUMERIC,""); printf("Locale : %s, One Trillion : %'llu\n", setlocale(LC_CTYPE,NULL),trillion); return 0; }
Rewrite the snippet below in C so it works the same as the original C++ code.
template <typename Function> void repeat(Function f, unsigned int n) { for(unsigned int i=n; 0<i; i--) f(); }
#include <stdio.h> void repeat(void (*f)(void), unsigned int n) { while (n-->0) (*f)(); } void example() { printf("Example\n"); } int main(int argc, char *argv[]) { repeat(example, 4); return 0; }
Translate the given C++ code snippet into C without altering its behavior.
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <algorithm> #include <locale> class Sparkline { public: Sparkline(std::wstring &cs) : charset( cs ){ } virtual ~Sparkline(){ } void print(std::string spark){ const char *delim = ", "; std::vector<float> data; std::string::size_type last = spark.find_first_not_of(delim, 0); std::string::size_type pos = spark.find_first_of(delim, last); while( pos != std::string::npos || last != std::string::npos ){ std::string tok = spark.substr(last, pos-last); std::stringstream ss(tok); float entry; ss >> entry; data.push_back( entry ); last = spark.find_first_not_of(delim, pos); pos = spark.find_first_of(delim, last); } float min = *std::min_element( data.begin(), data.end() ); float max = *std::max_element( data.begin(), data.end() ); float skip = (charset.length()-1) / (max - min); std::wcout<<L"Min: "<<min<<L"; Max: "<<max<<L"; Range: "<<(max-min)<<std::endl; std::vector<float>::const_iterator it; for(it = data.begin(); it != data.end(); it++){ float v = ( (*it) - min ) * skip; std::wcout<<charset[ (int)floor( v ) ]; } std::wcout<<std::endl; } private: std::wstring &charset; }; int main( int argc, char **argv ){ std::wstring charset = L"\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588"; std::locale::global(std::locale("en_US.utf8")); Sparkline sl(charset); sl.print("1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"); sl.print("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"); return 0; }
#include<string.h> #include<stdlib.h> #include<locale.h> #include<stdio.h> #include<wchar.h> #include<math.h> int main(int argC,char* argV[]) { double* arr,min,max; char* str; int i,len; if(argC == 1) printf("Usage : %s <data points separated by spaces or commas>",argV[0]); else{ arr = (double*)malloc((argC-1)*sizeof(double)); for(i=1;i<argC;i++){ len = strlen(argV[i]); if(argV[i][len-1]==','){ str = (char*)malloc(len*sizeof(char)); strncpy(str,argV[i],len-1); arr[i-1] = atof(str); free(str); } else arr[i-1] = atof(argV[i]); if(i==1){ min = arr[i-1]; max = arr[i-1]; } else{ min=(min<arr[i-1]?min:arr[i-1]); max=(max>arr[i-1]?max:arr[i-1]); } } printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min); setlocale(LC_ALL, ""); for(i=1;i<argC;i++){ printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7))); } } return 0; }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <iostream> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { std::cout << mul_inv(42, 2017) << std::endl; return 0; }
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { printf("%d\n", mul_inv(42, 2017)); return 0; }
Generate an equivalent C version of this C++ code.
#include <cmath> #include <fstream> #include <iostream> bool sunflower(const char* filename) { std::ofstream out(filename); if (!out) return false; constexpr int size = 600; constexpr int seeds = 5 * size; constexpr double pi = 3.14159265359; constexpr double phi = 1.61803398875; out << "<svg xmlns='http: out << "' height='" << size << "' style='stroke:gold'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << std::setprecision(2) << std::fixed; for (int i = 1; i <= seeds; ++i) { double r = 2 * std::pow(i, phi)/seeds; double theta = 2 * pi * phi * i; double x = r * std::sin(theta) + size/2; double y = r * std::cos(theta) + size/2; double radius = std::sqrt(i)/13; out << "<circle cx='" << x << "' cy='" << y << "' r='" << radius << "'/>\n"; } out << "</svg>\n"; return true; } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " filename\n"; return EXIT_FAILURE; } if (!sunflower(argv[1])) { std::cerr << "image generation failed\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
#include<graphics.h> #include<math.h> #define pi M_PI void sunflower(int winWidth, int winHeight, double diskRatio, int iter){ double factor = .5 + sqrt(1.25),r,theta; double x = winWidth/2.0, y = winHeight/2.0; double maxRad = pow(iter,factor)/iter; int i; setbkcolor(LIGHTBLUE); for(i=0;i<=iter;i++){ r = pow(i,factor)/iter; r/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW); theta = 2*pi*factor*i; circle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter)); } } int main() { initwindow(1000,1000,"Sunflower..."); sunflower(1000,1000,0.5,3000); getch(); closegraph(); return 0; }
Translate the given C++ code snippet into C without altering its behavior.
#include <iostream> #include <numeric> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } std::vector<int> demand = { 30, 20, 70, 30, 60 }; std::vector<int> supply = { 50, 60, 50, 50 }; std::vector<std::vector<int>> costs = { {16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11} }; int nRows = supply.size(); int nCols = demand.size(); std::vector<bool> rowDone(nRows, false); std::vector<bool> colDone(nCols, false); std::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0)); std::vector<int> diff(int j, int len, bool isRow) { int min1 = INT_MAX; int min2 = INT_MAX; int minP = -1; for (int i = 0; i < len; i++) { if (isRow ? colDone[i] : rowDone[i]) { continue; } int c = isRow ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; minP = i; } else if (c < min2) { min2 = c; } } return { min2 - min1, min1, minP }; } std::vector<int> maxPenalty(int len1, int len2, bool isRow) { int md = INT_MIN; int pc = -1; int pm = -1; int mc = -1; for (int i = 0; i < len1; i++) { if (isRow ? rowDone[i] : colDone[i]) { continue; } std::vector<int> res = diff(i, len2, isRow); if (res[0] > md) { md = res[0]; pm = i; mc = res[1]; pc = res[2]; } } return isRow ? std::vector<int> { pm, pc, mc, md } : std::vector<int>{ pc, pm, mc, md }; } std::vector<int> nextCell() { auto res1 = maxPenalty(nRows, nCols, true); auto res2 = maxPenalty(nCols, nRows, false); if (res1[3] == res2[3]) { return res1[2] < res2[2] ? res1 : res2; } return res1[3] > res2[3] ? res2 : res1; } int main() { int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; }); int totalCost = 0; while (supplyLeft > 0) { auto cell = nextCell(); int r = cell[0]; int c = cell[1]; int quantity = std::min(demand[c], supply[r]); demand[c] -= quantity; if (demand[c] == 0) { colDone[c] = true; } supply[r] -= quantity; if (supply[r] == 0) { rowDone[r] = true; } result[r][c] = quantity; supplyLeft -= quantity; totalCost += quantity * costs[r][c]; } for (auto &a : result) { std::cout << a << '\n'; } std::cout << "Total cost: " << totalCost; return 0; }
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 4 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 50, 60, 50, 50 }; int demand[N_COLS] = { 30, 20, 70, 30, 60 }; int costs[N_ROWS][N_COLS] = { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 }, { 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } }; bool row_done[N_ROWS] = { FALSE }; bool col_done[N_COLS] = { FALSE }; void diff(int j, int len, bool is_row, int res[3]) { int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; for (i = 0; i < len; ++i) { if((is_row) ? col_done[i] : row_done[i]) continue; c = (is_row) ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; min_p = i; } else if (c < min2) min2 = c; } res[0] = min2 - min1; res[1] = min1; res[2] = min_p; } void max_penalty(int len1, int len2, bool is_row, int res[4]) { int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; int res2[3]; for (i = 0; i < len1; ++i) { if((is_row) ? row_done[i] : col_done[i]) continue; diff(i, len2, is_row, res2); if (res2[0] > md) { md = res2[0]; pm = i; mc = res2[1]; pc = res2[2]; } } if (is_row) { res[0] = pm; res[1] = pc; } else { res[0] = pc; res[1] = pm; } res[2] = mc; res[3] = md; } void next_cell(int res[4]) { int i, res1[4], res2[4]; max_penalty(N_ROWS, N_COLS, TRUE, res1); max_penalty(N_COLS, N_ROWS, FALSE, res2); if (res1[3] == res2[3]) { if (res1[2] < res2[2]) for (i = 0; i < 4; ++i) res[i] = res1[i]; else for (i = 0; i < 4; ++i) res[i] = res2[i]; return; } if (res1[3] > res2[3]) for (i = 0; i < 4; ++i) res[i] = res2[i]; else for (i = 0; i < 4; ++i) res[i] = res1[i]; } int main() { int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; int results[N_ROWS][N_COLS] = { 0 }; for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; while (supply_left > 0) { next_cell(cell); r = cell[0]; c = cell[1]; q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; demand[c] -= q; if (!demand[c]) col_done[c] = TRUE; supply[r] -= q; if (!supply[r]) row_done[r] = TRUE; results[r][c] = q; supply_left -= q; total_cost += q * costs[r][c]; } printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'W' + i); for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
Change the following C++ code into C without altering its purpose.
#include <iostream> #include <numeric> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } std::vector<int> demand = { 30, 20, 70, 30, 60 }; std::vector<int> supply = { 50, 60, 50, 50 }; std::vector<std::vector<int>> costs = { {16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11} }; int nRows = supply.size(); int nCols = demand.size(); std::vector<bool> rowDone(nRows, false); std::vector<bool> colDone(nCols, false); std::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0)); std::vector<int> diff(int j, int len, bool isRow) { int min1 = INT_MAX; int min2 = INT_MAX; int minP = -1; for (int i = 0; i < len; i++) { if (isRow ? colDone[i] : rowDone[i]) { continue; } int c = isRow ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; minP = i; } else if (c < min2) { min2 = c; } } return { min2 - min1, min1, minP }; } std::vector<int> maxPenalty(int len1, int len2, bool isRow) { int md = INT_MIN; int pc = -1; int pm = -1; int mc = -1; for (int i = 0; i < len1; i++) { if (isRow ? rowDone[i] : colDone[i]) { continue; } std::vector<int> res = diff(i, len2, isRow); if (res[0] > md) { md = res[0]; pm = i; mc = res[1]; pc = res[2]; } } return isRow ? std::vector<int> { pm, pc, mc, md } : std::vector<int>{ pc, pm, mc, md }; } std::vector<int> nextCell() { auto res1 = maxPenalty(nRows, nCols, true); auto res2 = maxPenalty(nCols, nRows, false); if (res1[3] == res2[3]) { return res1[2] < res2[2] ? res1 : res2; } return res1[3] > res2[3] ? res2 : res1; } int main() { int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; }); int totalCost = 0; while (supplyLeft > 0) { auto cell = nextCell(); int r = cell[0]; int c = cell[1]; int quantity = std::min(demand[c], supply[r]); demand[c] -= quantity; if (demand[c] == 0) { colDone[c] = true; } supply[r] -= quantity; if (supply[r] == 0) { rowDone[r] = true; } result[r][c] = quantity; supplyLeft -= quantity; totalCost += quantity * costs[r][c]; } for (auto &a : result) { std::cout << a << '\n'; } std::cout << "Total cost: " << totalCost; return 0; }
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 4 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 50, 60, 50, 50 }; int demand[N_COLS] = { 30, 20, 70, 30, 60 }; int costs[N_ROWS][N_COLS] = { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 }, { 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } }; bool row_done[N_ROWS] = { FALSE }; bool col_done[N_COLS] = { FALSE }; void diff(int j, int len, bool is_row, int res[3]) { int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; for (i = 0; i < len; ++i) { if((is_row) ? col_done[i] : row_done[i]) continue; c = (is_row) ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; min_p = i; } else if (c < min2) min2 = c; } res[0] = min2 - min1; res[1] = min1; res[2] = min_p; } void max_penalty(int len1, int len2, bool is_row, int res[4]) { int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; int res2[3]; for (i = 0; i < len1; ++i) { if((is_row) ? row_done[i] : col_done[i]) continue; diff(i, len2, is_row, res2); if (res2[0] > md) { md = res2[0]; pm = i; mc = res2[1]; pc = res2[2]; } } if (is_row) { res[0] = pm; res[1] = pc; } else { res[0] = pc; res[1] = pm; } res[2] = mc; res[3] = md; } void next_cell(int res[4]) { int i, res1[4], res2[4]; max_penalty(N_ROWS, N_COLS, TRUE, res1); max_penalty(N_COLS, N_ROWS, FALSE, res2); if (res1[3] == res2[3]) { if (res1[2] < res2[2]) for (i = 0; i < 4; ++i) res[i] = res1[i]; else for (i = 0; i < 4; ++i) res[i] = res2[i]; return; } if (res1[3] > res2[3]) for (i = 0; i < 4; ++i) res[i] = res2[i]; else for (i = 0; i < 4; ++i) res[i] = res1[i]; } int main() { int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; int results[N_ROWS][N_COLS] = { 0 }; for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; while (supply_left > 0) { next_cell(cell); r = cell[0]; c = cell[1]; q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; demand[c] -= q; if (!demand[c]) col_done[c] = TRUE; supply[r] -= q; if (!supply[r]) row_done[r] = TRUE; results[r][c] = q; supply_left -= q; total_cost += q * costs[r][c]; } printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'W' + i); for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
Generate an equivalent C version of this C++ code.
#include <iostream> #include <vector> using namespace std; vector<int> UpTo(int n, int offset = 0) { vector<int> retval(n); for (int ii = 0; ii < n; ++ii) retval[ii] = ii + offset; return retval; } struct JohnsonTrotterState_ { vector<int> values_; vector<int> positions_; vector<bool> directions_; int sign_; JohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {} int LargestMobile() const { for (int r = values_.size(); r > 0; --r) { const int loc = positions_[r] + (directions_[r] ? 1 : -1); if (loc >= 0 && loc < values_.size() && values_[loc] < r) return r; } return 0; } bool IsComplete() const { return LargestMobile() == 0; } void operator++() { const int r = LargestMobile(); const int rLoc = positions_[r]; const int lLoc = rLoc + (directions_[r] ? 1 : -1); const int l = values_[lLoc]; swap(values_[lLoc], values_[rLoc]); swap(positions_[l], positions_[r]); sign_ = -sign_; for (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd) *pd = !*pd; } }; int main(void) { JohnsonTrotterState_ state(4); do { for (auto v : state.values_) cout << v << " "; cout << "\n"; ++state; } while (!state.IsComplete()); }
#include<stdlib.h> #include<string.h> #include<stdio.h> int flag = 1; void heapPermute(int n, int arr[],int arrLen){ int temp; int i; if(n==1){ printf("\n["); for(i=0;i<arrLen;i++) printf("%d,",arr[i]); printf("\b] Sign : %d",flag); flag*=-1; } else{ for(i=0;i<n-1;i++){ heapPermute(n-1,arr,arrLen); if(n%2==0){ temp = arr[i]; arr[i] = arr[n-1]; arr[n-1] = temp; } else{ temp = arr[0]; arr[0] = arr[n-1]; arr[n-1] = temp; } } heapPermute(n-1,arr,arrLen); } } int main(int argC,char* argV[0]) { int *arr, i=0, count = 1; char* token; if(argC==1) printf("Usage : %s <comma separated list of integers>",argV[0]); else{ while(argV[1][i]!=00){ if(argV[1][i++]==',') count++; } arr = (int*)malloc(count*sizeof(int)); i = 0; token = strtok(argV[1],","); while(token!=NULL){ arr[i++] = atoi(token); token = strtok(NULL,","); } heapPermute(i,arr,count); } return 0; }
Produce a language-to-language conversion: from C++ to C, same semantics.
#include <iomanip> #include <iostream> int digit_sum(int n) { int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int main() { for (int n = 1; n <= 70; ++n) { for (int m = 1;; ++m) { if (digit_sum(m * n) == n) { std::cout << std::setw(8) << m << (n % 10 == 0 ? '\n' : ' '); break; } } } }
#include <stdio.h> unsigned digit_sum(unsigned n) { unsigned sum = 0; do { sum += n % 10; } while(n /= 10); return sum; } unsigned a131382(unsigned n) { unsigned m; for (m = 1; n != digit_sum(m*n); m++); return m; } int main() { unsigned n; for (n = 1; n <= 70; n++) { printf("%9u", a131382(n)); if (n % 10 == 0) printf("\n"); } return 0; }
Can you help me rewrite this code in C instead of C++, keeping it the same logically?
#include <iostream> #include <vector> constexpr int N = 2200; constexpr int N2 = 2 * N * N; int main() { using namespace std; vector<bool> found(N + 1); vector<bool> aabb(N2 + 1); int s = 3; for (int a = 1; a < N; ++a) { int aa = a * a; for (int b = 1; b < N; ++b) { aabb[aa + b * b] = true; } } for (int c = 1; c <= N; ++c) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= N; ++d) { if (aabb[s1]) { found[d] = true; } s1 += s2; s2 += 2; } } cout << "The values of d <= " << N << " which can't be represented:" << endl; for (int d = 1; d <= N; ++d) { if (!found[d]) { cout << d << " "; } } cout << endl; return 0; }
#include <stdio.h> #include <math.h> #include <string.h> #define N 2200 int main(int argc, char **argv){ int a,b,c,d; int r[N+1]; memset(r,0,sizeof(r)); for(a=1; a<=N; a++){ for(b=a; b<=N; b++){ int aabb; if(a&1 && b&1) continue; aabb=a*a + b*b; for(c=b; c<=N; c++){ int aabbcc=aabb + c*c; d=(int)sqrt((float)aabbcc); if(aabbcc == d*d && d<=N) r[d]=1; } } } for(a=1; a<=N; a++) if(!r[a]) printf("%d ",a); printf("\n"); }
Please provide an equivalent version of this C++ code in C.
#include <iostream> using namespace std; bool steady(int n) { int mask = 1; for (int d = n; d != 0; d /= 10) mask *= 10; return (n * n) % mask == n; } int main() { for (int i = 1; i < 10000; i++) if (steady(i)) printf("%4d^2 = %8d\n", i, i * i); }
#include <stdio.h> #include <stdbool.h> bool steady(int n) { int mask = 1; for (int d = n; d != 0; d /= 10) mask *= 10; return (n * n) % mask == n; } int main() { for (int i = 1; i < 10000; i++) if (steady(i)) printf("%4d^2 = %8d\n", i, i * i); return 0; }
Preserve the algorithm and functionality while converting the code from C++ to C.
#include <exception> #include <iostream> using ulong = unsigned long; class MiddleSquare { private: ulong state; ulong div, mod; public: MiddleSquare() = delete; MiddleSquare(ulong start, ulong length) { if (length % 2) throw std::invalid_argument("length must be even"); div = mod = 1; for (ulong i=0; i<length/2; i++) div *= 10; for (ulong i=0; i<length; i++) mod *= 10; state = start % mod; } ulong next() { return state = state * state / div % mod; } }; int main() { MiddleSquare msq(675248, 6); for (int i=0; i<5; i++) std::cout << msq.next() << std::endl; return 0; }
#include<stdio.h> long long seed; long long random(){ seed = seed * seed / 1000 % 1000000; return seed; } int main(){ seed = 675248; for(int i=1;i<=5;i++) printf("%lld\n",random()); return 0; }
Keep all operations the same but rewrite the snippet in C.
#include <exception> #include <iostream> using ulong = unsigned long; class MiddleSquare { private: ulong state; ulong div, mod; public: MiddleSquare() = delete; MiddleSquare(ulong start, ulong length) { if (length % 2) throw std::invalid_argument("length must be even"); div = mod = 1; for (ulong i=0; i<length/2; i++) div *= 10; for (ulong i=0; i<length; i++) mod *= 10; state = start % mod; } ulong next() { return state = state * state / div % mod; } }; int main() { MiddleSquare msq(675248, 6); for (int i=0; i<5; i++) std::cout << msq.next() << std::endl; return 0; }
#include<stdio.h> long long seed; long long random(){ seed = seed * seed / 1000 % 1000000; return seed; } int main(){ seed = 675248; for(int i=1;i<=5;i++) printf("%lld\n",random()); return 0; }
Generate an equivalent C version of this C++ code.
#include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <map> std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) { std::map<uint32_t, uint32_t> result; for (uint32_t i = 1; i <= faces; ++i) result.emplace(i, 1); for (uint32_t d = 2; d <= dice; ++d) { std::map<uint32_t, uint32_t> tmp; for (const auto& p : result) { for (uint32_t i = 1; i <= faces; ++i) tmp[p.first + i] += p.second; } tmp.swap(result); } return result; } double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) { auto totals1 = get_totals(dice1, faces1); auto totals2 = get_totals(dice2, faces2); double wins = 0; for (const auto& p1 : totals1) { for (const auto& p2 : totals2) { if (p2.first >= p1.first) break; wins += p1.second * p2.second; } } double total = std::pow(faces1, dice1) * std::pow(faces2, dice2); return wins/total; } int main() { std::cout << std::setprecision(10); std::cout << probability(9, 4, 6, 6) << '\n'; std::cout << probability(5, 10, 6, 7) << '\n'; return 0; }
#include <stdio.h> #include <stdint.h> typedef uint32_t uint; typedef uint64_t ulong; ulong ipow(const uint x, const uint y) { ulong result = 1; for (uint i = 1; i <= y; i++) result *= x; return result; } uint min(const uint x, const uint y) { return (x < y) ? x : y; } void throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) { if (n_dice == 0) { counts[s]++; return; } for (uint i = 1; i < n_sides + 1; i++) throw_die(n_sides, n_dice - 1, s + i, counts); } double beating_probability(const uint n_sides1, const uint n_dice1, const uint n_sides2, const uint n_dice2) { const uint len1 = (n_sides1 + 1) * n_dice1; uint C1[len1]; for (uint i = 0; i < len1; i++) C1[i] = 0; throw_die(n_sides1, n_dice1, 0, C1); const uint len2 = (n_sides2 + 1) * n_dice2; uint C2[len2]; for (uint j = 0; j < len2; j++) C2[j] = 0; throw_die(n_sides2, n_dice2, 0, C2); const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2)); double tot = 0; for (uint i = 0; i < len1; i++) for (uint j = 0; j < min(i, len2); j++) tot += (double)C1[i] * C2[j] / p12; return tot; } int main() { printf("%1.16f\n", beating_probability(4, 9, 6, 6)); printf("%1.16f\n", beating_probability(10, 5, 7, 6)); return 0; }
Convert the following code from C++ to C, ensuring the logic remains intact.
#include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <map> std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) { std::map<uint32_t, uint32_t> result; for (uint32_t i = 1; i <= faces; ++i) result.emplace(i, 1); for (uint32_t d = 2; d <= dice; ++d) { std::map<uint32_t, uint32_t> tmp; for (const auto& p : result) { for (uint32_t i = 1; i <= faces; ++i) tmp[p.first + i] += p.second; } tmp.swap(result); } return result; } double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) { auto totals1 = get_totals(dice1, faces1); auto totals2 = get_totals(dice2, faces2); double wins = 0; for (const auto& p1 : totals1) { for (const auto& p2 : totals2) { if (p2.first >= p1.first) break; wins += p1.second * p2.second; } } double total = std::pow(faces1, dice1) * std::pow(faces2, dice2); return wins/total; } int main() { std::cout << std::setprecision(10); std::cout << probability(9, 4, 6, 6) << '\n'; std::cout << probability(5, 10, 6, 7) << '\n'; return 0; }
#include <stdio.h> #include <stdint.h> typedef uint32_t uint; typedef uint64_t ulong; ulong ipow(const uint x, const uint y) { ulong result = 1; for (uint i = 1; i <= y; i++) result *= x; return result; } uint min(const uint x, const uint y) { return (x < y) ? x : y; } void throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) { if (n_dice == 0) { counts[s]++; return; } for (uint i = 1; i < n_sides + 1; i++) throw_die(n_sides, n_dice - 1, s + i, counts); } double beating_probability(const uint n_sides1, const uint n_dice1, const uint n_sides2, const uint n_dice2) { const uint len1 = (n_sides1 + 1) * n_dice1; uint C1[len1]; for (uint i = 0; i < len1; i++) C1[i] = 0; throw_die(n_sides1, n_dice1, 0, C1); const uint len2 = (n_sides2 + 1) * n_dice2; uint C2[len2]; for (uint j = 0; j < len2; j++) C2[j] = 0; throw_die(n_sides2, n_dice2, 0, C2); const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2)); double tot = 0; for (uint i = 0; i < len1; i++) for (uint j = 0; j < min(i, len2); j++) tot += (double)C1[i] * C2[j] / p12; return tot; } int main() { printf("%1.16f\n", beating_probability(4, 9, 6, 6)); printf("%1.16f\n", beating_probability(10, 5, 7, 6)); return 0; }
Write the same code in C as shown below in C++.
#include <stdexcept> int main() { throw std::runtime_error("boom"); }
int main(){int a=0, b=0, c=a/b;}
Rewrite the snippet below in C so it works the same as the original C++ code.
#include <windows.h> #include <math.h> #include <string> const int BMP_SIZE = 240, MY_TIMER = 987654; 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; } DWORD* bits() { return ( DWORD* )pBits; } 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 plasma { public: plasma() { currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1; _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear(); plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4]; plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4]; int i, j, dst = 0; double temp; for( j = 0; j < BMP_SIZE * 2; j++ ) { for( i = 0; i < BMP_SIZE * 2; i++ ) { plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) ); plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 ); dst++; } } } void update() { DWORD dst; BYTE a, c1,c2, c3; currentTime += ( double )( rand() % 2 + 1 ); int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ), x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ), x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ), y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ), y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ), y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) ); int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3; DWORD* bits = _bmp.bits(); for( int j = 0; j < BMP_SIZE; j++ ) { dst = j * BMP_SIZE; for( int i= 0; i < BMP_SIZE; i++ ) { a = plasma2[src1] + plasma1[src2] + plasma2[src3]; c1 = a << 1; c2 = a << 2; c3 = a << 3; bits[dst + i] = RGB( c1, c2, c3 ); src1++; src2++; src3++; } src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE; } draw(); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: void draw() { HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); } myBitmap _bmp; HWND _hwnd; float _ang; BYTE *plasma1, *plasma2; double currentTime; int _WD, _WV; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); SetTimer( _hwnd, MY_TIMER, 15, NULL ); _plasma.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 ); } } return UnregisterClass( "_MY_PLASMA_", _hInst ); } private: void wnd::doPaint( HDC dc ) { _plasma.update(); } void wnd::doTimer() { _plasma.update(); } static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_PAINT: { PAINTSTRUCT ps; _inst->doPaint( BeginPaint( hWnd, &ps ) ); EndPaint( hWnd, &ps ); return 0; } case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_TIMER: _inst->doTimer(); 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_PLASMA_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma; }; wnd* wnd::_inst = 0; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { wnd myWnd; return myWnd.Run( hInstance ); }
#include<windows.h> #include<stdlib.h> #include<stdio.h> #include<time.h> #include<math.h> #define pi M_PI int main() { CONSOLE_SCREEN_BUFFER_INFO info; int cols, rows; time_t t; int i,j; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info); cols = info.srWindow.Right - info.srWindow.Left + 1; rows = info.srWindow.Bottom - info.srWindow.Top + 1; HANDLE console; console = GetStdHandle(STD_OUTPUT_HANDLE); system("@clear||cls"); srand((unsigned)time(&t)); for(i=0;i<rows;i++) for(j=0;j<cols;j++){ SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254); printf("%c",219); } getchar(); return 0; }
Write the same code in C as shown below in C++.
#include <windows.h> #include <math.h> #include <string> const int BMP_SIZE = 240, MY_TIMER = 987654; 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; } DWORD* bits() { return ( DWORD* )pBits; } 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 plasma { public: plasma() { currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1; _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear(); plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4]; plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4]; int i, j, dst = 0; double temp; for( j = 0; j < BMP_SIZE * 2; j++ ) { for( i = 0; i < BMP_SIZE * 2; i++ ) { plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) ); plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) + ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 ); dst++; } } } void update() { DWORD dst; BYTE a, c1,c2, c3; currentTime += ( double )( rand() % 2 + 1 ); int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime / 137 ) ), x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 75 ) ), x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ), y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime / 123 ) ), y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 85 ) ), y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) ); int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3; DWORD* bits = _bmp.bits(); for( int j = 0; j < BMP_SIZE; j++ ) { dst = j * BMP_SIZE; for( int i= 0; i < BMP_SIZE; i++ ) { a = plasma2[src1] + plasma1[src2] + plasma2[src3]; c1 = a << 1; c2 = a << 2; c3 = a << 3; bits[dst + i] = RGB( c1, c2, c3 ); src1++; src2++; src3++; } src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE; } draw(); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: void draw() { HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); } myBitmap _bmp; HWND _hwnd; float _ang; BYTE *plasma1, *plasma2; double currentTime; int _WD, _WV; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); SetTimer( _hwnd, MY_TIMER, 15, NULL ); _plasma.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 ); } } return UnregisterClass( "_MY_PLASMA_", _hInst ); } private: void wnd::doPaint( HDC dc ) { _plasma.update(); } void wnd::doTimer() { _plasma.update(); } static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_PAINT: { PAINTSTRUCT ps; _inst->doPaint( BeginPaint( hWnd, &ps ) ); EndPaint( hWnd, &ps ); return 0; } case WM_DESTROY: PostQuitMessage( 0 ); break; case WM_TIMER: _inst->doTimer(); 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_PLASMA_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma; }; wnd* wnd::_inst = 0; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { wnd myWnd; return myWnd.Run( hInstance ); }
#include<windows.h> #include<stdlib.h> #include<stdio.h> #include<time.h> #include<math.h> #define pi M_PI int main() { CONSOLE_SCREEN_BUFFER_INFO info; int cols, rows; time_t t; int i,j; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info); cols = info.srWindow.Right - info.srWindow.Left + 1; rows = info.srWindow.Bottom - info.srWindow.Top + 1; HANDLE console; console = GetStdHandle(STD_OUTPUT_HANDLE); system("@clear||cls"); srand((unsigned)time(&t)); for(i=0;i<rows;i++) for(j=0;j<cols;j++){ SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254); printf("%c",219); } getchar(); return 0; }
Write the same algorithm in PHP as shown in this C implementation.
#include <stdlib.h> #include <string.h> #include <stdio.h> double* fwd_diff(double* x, unsigned int len, unsigned int order) { unsigned int i, j; double* y; if (order >= len) return 0; y = malloc(sizeof(double) * len); if (!order) { memcpy(y, x, sizeof(double) * len); return y; } for (j = 0; j < order; j++, x = y) for (i = 0, len--; i < len; i++) y[i] = x[i + 1] - x[i]; y = realloc(y, sizeof(double) * len); return y; } int main(void) { double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; int i, len = sizeof(x) / sizeof(x[0]); y = fwd_diff(x, len, 1); for (i = 0; i < len - 1; i++) printf("%g ", y[i]); putchar('\n'); return 0; }
<?php function forwardDiff($anArray, $times = 1) { if ($times <= 0) { return $anArray; } for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { $accumilation[] = $anArray[$i] - $anArray[$i - 1]; } if ($times === 1) { return $accumilation; } return forwardDiff($accumilation, $times - 1); } class ForwardDiffExample extends PweExample { function _should_run_empty_array_for_single_elem() { $expected = array($this->rand()->int()); $this->spec(forwardDiff($expected))->shouldEqual(array()); } function _should_give_diff_of_two_elem_as_single_elem() { $twoNums = array($this->rand()->int(), $this->rand()->int()); $expected = array($twoNums[1] - $twoNums[0]); $this->spec(forwardDiff($twoNums))->shouldEqual($expected); } function _should_compute_correct_forward_diff_for_longer_arrays() { $diffInput = array(10, 2, 9, 6, 5); $expected = array(-8, 7, -3, -1); $this->spec(forwardDiff($diffInput))->shouldEqual($expected); } function _should_apply_more_than_once_if_specified() { $diffInput = array(4, 6, 9, 3, 4); $expectedAfter1 = array(2, 3, -6, 1); $expectedAfter2 = array(1, -9, 7); $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1); $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2); } function _should_return_array_unaltered_if_no_times() { $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected); } }
Can you help me rewrite this code in PHP instead of C, keeping it the same logically?
int is_prime(unsigned int n) { unsigned int p; if (!(n & 1) || n < 2 ) return n == 2; for (p = 3; p <= n/p; p += 2) if (!(n % p)) return 0; return 1; }
<?php function prime($a) { if (($a % 2 == 0 && $a != 2) || $a < 2) return false; $limit = sqrt($a); for ($i = 2; $i <= $limit; $i++) if ($a % $i == 0) return false; return true; } foreach (range(1, 100) as $x) if (prime($x)) echo "$x\n"; ?>
Please provide an equivalent version of this C code in PHP.
#include <stdio.h> #include <limits.h> static unsigned long gcd_ui(unsigned long x, unsigned long y) { unsigned long t; if (y < x) { t = x; x = y; y = t; } while (y > 0) { t = y; y = x % y; x = t; } return x; } unsigned long binomial(unsigned long n, unsigned long k) { unsigned long d, g, r = 1; if (k == 0) return 1; if (k == 1) return n; if (k >= n) return (k == n); if (k > n/2) k = n-k; for (d = 1; d <= k; d++) { if (r >= ULONG_MAX/n) { unsigned long nr, dr; g = gcd_ui(n, d); nr = n/g; dr = d/g; g = gcd_ui(r, dr); r = r/g; dr = dr/g; if (r >= ULONG_MAX/nr) return 0; r *= nr; r /= dr; n--; } else { r *= n--; r /= d; } } return r; } int main() { printf("%lu\n", binomial(5, 3)); printf("%lu\n", binomial(40, 19)); printf("%lu\n", binomial(67, 31)); return 0; }
<?php $n=5; $k=3; function factorial($val){ for($f=2;$val-1>1;$f*=$val--); return $f; } $binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k)); echo $binomial_coefficient; ?>
Produce a functionally identical PHP code for the snippet given in C.
#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) int ar[10]; ar[0] = 1; ar[1] = 2; int* p; for (p=ar; p<(ar+cSize(ar)); p++) { printf("%d\n",*p); }
<?php $a = array(); # add elements "at the end" array_push($a, 55, 10, 20); print_r($a); # using an explicit key $a['one'] = 1; $a['two'] = 2; print_r($a); ?>
Keep all operations the same but rewrite the snippet in PHP.
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){ if (is_null($w)) $w = $this->w; if (is_null($h)) $h = $this->h; $w += $x; $h += $y; for ($i = $y; $i < $h; $i++){ for ($j = $x; $j < $w; $j++){ $this->setPixel($j, $i, $color); } } } public function setPixel($x, $y, $color = array(0,0,0)){ if ($x >= $this->w) return false; if ($x < 0) return false; if ($y >= $this->h) return false; if ($y < 0) return false; $this->data[$y][$x] = $color; } public function getPixel($x, $y){ return $this->data[$y][$x]; } public function writeP6($filename){ $fh = fopen($filename, 'w'); if (!$fh) return false; fputs($fh, "P6 {$this->w} {$this->h} 255\n"); foreach ($this->data as $row){ foreach($row as $pixel){ fputs($fh, pack('C', $pixel[0])); fputs($fh, pack('C', $pixel[1])); fputs($fh, pack('C', $pixel[2])); } } fclose($fh); } } $b = new Bitmap(16,16); $b->fill(); $b->fill(2, 2, 18, 18, array(240,240,240)); $b->setPixel(0, 15, array(255,0,0)); $b->writeP6('p6.ppm');
Can you help me rewrite this code in PHP instead of C, keeping it the same logically?
#include <stdio.h> int main() { remove("input.txt"); remove("/input.txt"); remove("docs"); remove("/docs"); return 0; }
<?php unlink('input.txt'); unlink('/input.txt'); rmdir('docs'); rmdir('/docs'); ?>
Translate the given C code snippet into PHP without altering its behavior.
#include <stdlib.h> #include <stdio.h> #include <time.h> #define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\ (x) == 2 ? "Boomtime" :\ (x) == 3 ? "Pungenday" :\ (x) == 4 ? "Prickle-Prickle" :\ "Setting Orange") #define season( x ) ((x) == 0 ? "Chaos" :\ (x) == 1 ? "Discord" :\ (x) == 2 ? "Confusion" :\ (x) == 3 ? "Bureaucracy" :\ "The Aftermath") #define date( x ) ((x)%73 == 0 ? 73 : (x)%73) #define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100)) char * ddate( int y, int d ){ int dyear = 1166 + y; char * result = malloc( 100 * sizeof( char ) ); if( leap_year( y ) ){ if( d == 60 ){ sprintf( result, "St. Tib's Day, YOLD %d", dyear ); return result; } else if( d >= 60 ){ -- d; } } sprintf( result, "%s, %s %d, YOLD %d", day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear ); return result; } int day_of_year( int y, int m, int d ){ int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; for( ; m > 1; m -- ){ d += month_lengths[ m - 2 ]; if( m == 3 && leap_year( y ) ){ ++ d; } } return d; } int main( int argc, char * argv[] ){ time_t now; struct tm * now_time; int year, doy; if( argc == 1 ){ now = time( NULL ); now_time = localtime( &now ); year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1; } else if( argc == 4 ){ year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) ); } char * result = ddate( year, doy ); puts( result ); free( result ); return 0; }
<?php $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31); $MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath"); $DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle"); $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th'); $Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay"); $Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux"); $edate = explode(" ",date('Y m j L')); $usery = $edate[0]; $userm = $edate[1]; $userd = $edate[2]; $IsLeap = $edate[3]; if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { $usery = $_GET['y']; $userm = $_GET['m']; $userd = $_GET['d']; $IsLeap = 0; if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; if ($usery%400 == 0) $IsLeap = 1; } $userdays = 0; $i = 0; while ($i < ($userm-1)) { $userdays = $userdays + $Anerisia[$i]; $i = $i +1; } $userdays = $userdays + $userd; $IsHolyday = 0; $dyear = $usery + 1166; $dmonth = $MONTHS[$userdays/73.2]; $dday = $userdays%73; if (0 == $dday) $dday = 73; $Dname = $DAYS[$userdays%5]; $Holyday = "St. Tibs Day"; if ($dday == 5) { $Holyday = $Holy5[$userdays/73.2]; $IsHolyday =1; } if ($dday == 50) { $Holyday = $Holy50[$userdays/73.2]; $IsHolyday =1; } if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2; $suff = $Dsuff[$dday%10] ; if ((11 <= $dday) && (19 >= $dday)) $suff='th'; if ($IsHolyday ==2) echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear; if ($IsHolyday ==1) echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday; if ($IsHolyday == 0) echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear; ?>
Ensure the translated PHP code behaves exactly like the original C snippet.
#include <stdio.h> int main() { const char *extra = "little"; printf("Mary had a %s lamb.\n", extra); return 0; }
<?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?>
Change the following C code into PHP without altering its purpose.
#include<stdlib.h> #include<stdio.h> int* patienceSort(int* arr,int size){ int decks[size][size],i,j,min,pickedRow; int *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int)); for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){ decks[j][count[j]] = arr[i]; count[j]++; break; } } } min = decks[0][count[0]-1]; pickedRow = 0; for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(count[j]>0 && decks[j][count[j]-1]<min){ min = decks[j][count[j]-1]; pickedRow = j; } } sortedArr[i] = min; count[pickedRow]--; for(j=0;j<size;j++) if(count[j]>0){ min = decks[j][count[j]-1]; pickedRow = j; break; } } free(count); free(decks); return sortedArr; } int main(int argC,char* argV[]) { int *arr, *sortedArr, i; if(argC==0) printf("Usage : %s <integers to be sorted separated by space>"); else{ arr = (int*)malloc((argC-1)*sizeof(int)); for(i=1;i<=argC;i++) arr[i-1] = atoi(argV[i]); sortedArr = patienceSort(arr,argC-1); for(i=0;i<argC-1;i++) printf("%d ",sortedArr[i]); } return 0; }
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } } function patience_sort(&$n) { $piles = array(); foreach ($n as $x) { $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); } $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); } $a = array(4, 65, 2, -31, 0, 99, 83, 782, 1); patience_sort($a); print_r($a); ?>
Write the same code in PHP as shown below in C.
#define ANIMATE_VT100_POSIX #include <stdio.h> #include <string.h> #ifdef ANIMATE_VT100_POSIX #include <time.h> #endif char world_7x14[2][512] = { { "+-----------+\n" "|tH.........|\n" "|. . |\n" "| ... |\n" "|. . |\n" "|Ht.. ......|\n" "+-----------+\n" } }; void next_world(const char *in, char *out, int w, int h) { int i; for (i = 0; i < w*h; i++) { switch (in[i]) { case ' ': out[i] = ' '; break; case 't': out[i] = '.'; break; case 'H': out[i] = 't'; break; case '.': { int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') + (in[i-1] == 'H') + (in[i+1] == 'H') + (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H'); out[i] = (hc == 1 || hc == 2) ? 'H' : '.'; break; } default: out[i] = in[i]; } } out[i] = in[i]; } int main() { int f; for (f = 0; ; f = 1 - f) { puts(world_7x14[f]); next_world(world_7x14[f], world_7x14[1-f], 14, 7); #ifdef ANIMATE_VT100_POSIX printf("\x1b[%dA", 8); printf("\x1b[%dD", 14); { static const struct timespec ts = { 0, 100000000 }; nanosleep(&ts, 0); } #endif } return 0; }
$desc = 'tH......... . . ........ . . Ht.. ...... .. tH.... ....... .. .. tH..... ...... ..'; $steps = 30; $world = array(array()); $row = 0; $col = 0; foreach(str_split($desc) as $i){ switch($i){ case "\n": $row++; $col = 0; $world[] = array(); break; case '.': $world[$row][$col] = 1;//conductor $col++; break; case 'H': $world[$row][$col] = 2;//head $col++; break; case 't': $world[$row][$col] = 3;//tail $col++; break; default: $world[$row][$col] = 0;//insulator/air $col++; break; }; }; function draw_world($world){ foreach($world as $rowc){ foreach($rowc as $cell){ switch($cell){ case 0: echo ' '; break; case 1: echo '.'; break; case 2: echo 'H'; break; case 3: echo 't'; }; }; echo "\n"; }; }; echo "Original world:\n"; draw_world($world); for($i = 0; $i < $steps; $i++){ $old_world = $world; //backup to look up where was an electron head foreach($world as $row => &$rowc){ foreach($rowc as $col => &$cell){ switch($cell){ case 2: $cell = 3; break; case 3: $cell = 1; break; case 1: $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col] == 2; if($neigh_heads == 1 || $neigh_heads == 2){ $cell = 2; }; }; }; unset($cell); //just to be safe }; unset($rowc); //just to be safe echo "\nStep " . ($i + 1) . ":\n"; draw_world($world); };
Keep all operations the same but rewrite the snippet in PHP.
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { double x, y; } vec; typedef struct { int n; vec* v; } polygon_t, *polygon; #define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;} #define BIN_S(op, r) double v##op(vec a, vec b){ return r; } BIN_V(sub, a.x - b.x, a.y - b.y); BIN_V(add, a.x + b.x, a.y + b.y); BIN_S(dot, a.x * b.x + a.y * b.y); BIN_S(cross, a.x * b.y - a.y * b.x); vec vmadd(vec a, double s, vec b) { vec c; c.x = a.x + s * b.x; c.y = a.y + s * b.y; return c; } int intersect(vec x0, vec x1, vec y0, vec y1, double tol, vec *sect) { vec dx = vsub(x1, x0), dy = vsub(y1, y0); double d = vcross(dy, dx), a; if (!d) return 0; a = (vcross(x0, dx) - vcross(y0, dx)) / d; if (sect) *sect = vmadd(y0, a, dy); if (a < -tol || a > 1 + tol) return -1; if (a < tol || a > 1 - tol) return 0; a = (vcross(x0, dy) - vcross(y0, dy)) / d; if (a < 0 || a > 1) return -1; return 1; } double dist(vec x, vec y0, vec y1, double tol) { vec dy = vsub(y1, y0); vec x1, s; int r; x1.x = x.x + dy.y; x1.y = x.y - dy.x; r = intersect(x, x1, y0, y1, tol, &s); if (r == -1) return HUGE_VAL; s = vsub(s, x); return sqrt(vdot(s, s)); } #define for_v(i, z, p) for(i = 0, z = p->v; i < p->n; i++, z++) int inside(vec v, polygon p, double tol) { int i, k, crosses, intersectResult; vec *pv; double min_x, max_x, min_y, max_y; for (i = 0; i < p->n; i++) { k = (i + 1) % p->n; min_x = dist(v, p->v[i], p->v[k], tol); if (min_x < tol) return 0; } min_x = max_x = p->v[0].x; min_y = max_y = p->v[1].y; for_v(i, pv, p) { if (pv->x > max_x) max_x = pv->x; if (pv->x < min_x) min_x = pv->x; if (pv->y > max_y) max_y = pv->y; if (pv->y < min_y) min_y = pv->y; } if (v.x < min_x || v.x > max_x || v.y < min_y || v.y > max_y) return -1; max_x -= min_x; max_x *= 2; max_y -= min_y; max_y *= 2; max_x += max_y; vec e; while (1) { crosses = 0; e.x = v.x + (1 + rand() / (RAND_MAX + 1.)) * max_x; e.y = v.y + (1 + rand() / (RAND_MAX + 1.)) * max_x; for (i = 0; i < p->n; i++) { k = (i + 1) % p->n; intersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0); if (!intersectResult) break; if (intersectResult == 1) crosses++; } if (i == p->n) break; } return (crosses & 1) ? 1 : -1; } int main() { vec vsq[] = { {0,0}, {10,0}, {10,10}, {0,10}, {2.5,2.5}, {7.5,0.1}, {7.5,7.5}, {2.5,7.5}}; polygon_t sq = { 4, vsq }, sq_hole = { 8, vsq }; vec c = { 10, 5 }; vec d = { 5, 5 }; printf("%d\n", inside(c, &sq, 1e-10)); printf("%d\n", inside(c, &sq_hole, 1e-10)); printf("%d\n", inside(d, &sq, 1e-10)); printf("%d\n", inside(d, &sq_hole, 1e-10)); return 0; }
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
Write the same code in PHP as shown below in C.
#include <stdio.h> #include <string.h> int match(const char *s, const char *p, int overlap) { int c = 0, l = strlen(p); while (*s != '\0') { if (strncmp(s++, p, l)) continue; if (!overlap) s += l - 1; c++; } return c; } int main() { printf("%d\n", match("the three truths", "th", 0)); printf("overlap:%d\n", match("abababababa", "aba", 1)); printf("not: %d\n", match("abababababa", "aba", 0)); return 0; }
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
Port the following code from C to PHP with equivalent syntax and logic.
#include <stdio.h> #include <time.h> #define note_file "NOTES.TXT" int main(int argc, char**argv) { FILE *note = 0; time_t tm; int i; char *p; if (argc < 2) { if ((note = fopen(note_file, "r"))) while ((i = fgetc(note)) != EOF) putchar(i); } else if ((note = fopen(note_file, "a"))) { tm = time(0); p = ctime(&tm); while (*p) fputc(*p != '\n'?*p:'\t', note), p++; for (i = 1; i < argc; i++) fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n'); } if (note) fclose(note); return 0; }
#!/usr/bin/php <?php if ($argc > 1) file_put_contents( 'notes.txt', date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", FILE_APPEND ); else @readfile('notes.txt');
Translate the given C code snippet into PHP without altering its behavior.
#include <stdio.h> int common_len(const char *const *names, int n, char sep) { int i, pos; for (pos = 0; ; pos++) { for (i = 0; i < n; i++) { if (names[i][pos] != '\0' && names[i][pos] == names[0][pos]) continue; while (pos > 0 && names[0][--pos] != sep); return pos; } } return 0; } int main() { const char *names[] = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", }; int len = common_len(names, sizeof(names) / sizeof(const char*), '/'); if (!len) printf("No common path\n"); else printf("Common path: %.*s\n", len, names[0]); return 0; }
<?php function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]); $arr[$i] = count($dirList[$i]); } $min = min($arr); for($i = 0; $i < count($dirList); $i++) { while(count($dirList[$i]) > $min) { array_pop($dirList[$i]); } $dirList[$i] = '/' . implode('/' , $dirList[$i]); } $dirList = array_unique($dirList); while(count($dirList) !== 1) { $dirList = array_map('dirname', $dirList); $dirList = array_unique($dirList); } reset($dirList); return current($dirList); } $dirs = array( '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members', ); if('/home/user1/tmp' !== common_path($dirs)) { echo 'test fail'; } else { echo 'test success'; } ?>
Write the same code in PHP as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
Write the same code in PHP as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf("The first 15 terms of the Recaman's sequence are: "); printf("["); for (i = 0; i < 15; ++i) printf("%d ", a[i]); printf("\b]\n"); } if (!foundDup && alreadyUsed) { printf("The first duplicated term is a[%d] = %d\n", n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
Keep all operations the same but rewrite the snippet in PHP.
#include <stdio.h> #include <stdlib.h> int b[3][3]; int check_winner() { int i; for (i = 0; i < 3; i++) { if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0]; if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i]) return b[0][i]; } if (!b[1][1]) return 0; if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0]; if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1]; return 0; } void showboard() { const char *t = "X O"; int i, j; for (i = 0; i < 3; i++, putchar('\n')) for (j = 0; j < 3; j++) printf("%c ", t[ b[i][j] + 1 ]); printf("-----\n"); } #define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) int best_i, best_j; int test_move(int val, int depth) { int i, j, score; int best = -1, changed = 0; if ((score = check_winner())) return (score == val) ? 1 : -1; for_ij { if (b[i][j]) continue; changed = b[i][j] = val; score = -test_move(-val, depth + 1); b[i][j] = 0; if (score <= best) continue; if (!depth) { best_i = i; best_j = j; } best = score; } return changed ? best : 0; } const char* game(int user) { int i, j, k, move, win = 0; for_ij b[i][j] = 0; printf("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n"); printf("You have O, I have X.\n\n"); for (k = 0; k < 9; k++, user = !user) { while(user) { printf("your move: "); if (!scanf("%d", &move)) { scanf("%*s"); continue; } if (--move < 0 || move >= 9) continue; if (b[i = move / 3][j = move % 3]) continue; b[i][j] = 1; break; } if (!user) { if (!k) { best_i = rand() % 3; best_j = rand() % 3; } else test_move(-1, 0); b[best_i][best_j] = -1; printf("My move: %d\n", best_i * 3 + best_j + 1); } showboard(); if ((win = check_winner())) return win == 1 ? "You win.\n\n": "I win.\n\n"; } return "A draw.\n\n"; } int main() { int first = 0; while (1) printf("%s", game(first = !first)); return 0; }
<?php const BOARD_NUM = 9; const ROW_NUM = 3; $EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM); function isGameOver($board, $pin) { $pat = '/X{3}|' . //Horz 'X..X..X..|' . //Vert Left '.X..X..X.|' . //Vert Middle '..X..X..X|' . //Vert Right '..X.X.X..|' . //Diag TL->BR 'X...X...X|' . //Diag TR->BL '[^\.]{9}/i'; //Cat's game if ($pin == 'O') $pat = str_replace('X', 'O', $pat); return preg_match($pat, $board); } $boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR; $turn = substr_count($boardStr, '.')%2==0? 'O' : 'X'; $oppTurn = $turn == 'X'? 'O' : 'X'; $gameOver = isGameOver($boardStr, $oppTurn); echo '<style>'; echo 'td {width: 200px; height: 200px; text-align: center; }'; echo '.pin {font-size:72pt; text-decoration:none; color: black}'; echo '.pin.X {color:red}'; echo '.pin.O {color:blue}'; echo '</style>'; echo '<table border="1">'; $p = 0; for ($r = 0; $r < ROW_NUM; $r++) { echo '<tr>'; for ($c = 0; $c < ROW_NUM; $c++) { $pin = $boardStr[$p]; echo '<td>'; if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied else { //Available $boardDelta = $boardStr; $boardDelta[$p] = $turn; echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">'; echo $boardStr[$p]; echo '</a>'; } echo '</td>'; $p++; } echo '</tr>'; echo '<input type="hidden" name="b" value="', $boardStr, '"/>'; } echo '</table>'; echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>'; if ($gameOver) echo '<h1>Game Over!</h1>';
Produce a language-to-language conversion: from C to PHP, same semantics.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 961 int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ char S[MAXLEN]; int len,*hist,histlen; double H; FILE *f; f=fopen("entropy.c","r"); for(len=0;!feof(f);len++)S[len]=fgetc(f); S[--len]='\0'; hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
Transform the following C implementation into PHP, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 961 int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ char S[MAXLEN]; int len,*hist,histlen; double H; FILE *f; f=fopen("entropy.c","r"); for(len=0;!feof(f);len++)S[len]=fgetc(f); S[--len]='\0'; hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
Convert the following code from C to PHP, ensuring the logic remains intact.
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
<?php $ipv4_record = dns_get_record("www.kame.net",DNS_A); $ipv6_record = dns_get_record("www.kame.net",DNS_AAAA); print "ipv4: " . $ipv4_record[0]["ip"] . "\n"; print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n"; ?>
Produce a language-to-language conversion: from C to PHP, same semantics.
#include <stdio.h> #include <stdlib.h> #define LEN 3 int rand_idx(double *p, int n) { double s = rand() / (RAND_MAX + 1.0); int i; for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++); return i; } int main() { int user_action, my_action; int user_rec[] = {0, 0, 0}; const char *names[] = { "Rock", "Paper", "Scissors" }; char str[2]; const char *winner[] = { "We tied.", "Meself winned.", "You win." }; double p[LEN] = { 1./3, 1./3, 1./3 }; while (1) { my_action = rand_idx(p,LEN); printf("\nYour choice [1-3]:\n" " 1. Rock\n 2. Paper\n 3. Scissors\n> "); if (!scanf("%d", &user_action)) { scanf("%1s", str); if (*str == 'q') { printf("Your choices [rock : %d , paper : %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]); return 0; } continue; } user_action --; if (user_action > 2 || user_action < 0) { printf("invalid choice; again\n"); continue; } printf("You chose %s; I chose %s. %s\n", names[user_action], names[my_action], winner[(my_action - user_action + 3) % 3]); user_rec[user_action]++; } }
<?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo ""; $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>"; echo "<br>"; echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>"; $results = ""; if ($player == $a_i){ $results = "Draw"; } else if($wins[$a_i] == $player ){ $results = "A.I wins"; } else { $results = "Player wins"; } echo "<br>" . $results; ?>
Rewrite the snippet below in PHP so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> typedef struct func_t *func; typedef struct func_t { func (*fn) (func, func); func _; int num; } func_t; func new(func(*f)(func, func), func _) { func x = malloc(sizeof(func_t)); x->fn = f; x->_ = _; x->num = 0; return x; } func call(func f, func n) { return f->fn(f, n); } func Y(func(*f)(func, func)) { func g = new(f, 0); g->_ = g; return g; } func num(int n) { func x = new(0, 0); x->num = n; return x; } func fac(func self, func n) { int nn = n->num; return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num) : num(1); } func fib(func self, func n) { int nn = n->num; return nn > 1 ? num( call(self->_, num(nn - 1))->num + call(self->_, num(nn - 2))->num ) : num(1); } void show(func n) { printf(" %d", n->num); } int main() { int i; func f = Y(fac); printf("fac: "); for (i = 1; i < 10; i++) show( call(f, num(i)) ); printf("\n"); f = Y(fib); printf("fib: "); for (i = 1; i < 10; i++) show( call(f, num(i)) ); printf("\n"); return 0; }
<?php function Y($f) { $g = function($w) use($f) { return $f(function() use($w) { return call_user_func_array($w($w), func_get_args()); }); }; return $g($g); } $fibonacci = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); }; }); echo $fibonacci(10), "\n"; $factorial = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); }; }); echo $factorial(10), "\n"; ?>
Change the following C code into PHP without altering its purpose.
#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; }
function addsub($x, $y) { return array($x + $y, $x - $y); }
Produce a language-to-language conversion: from C to PHP, same semantics.
#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; }
$server = "speedtest.tele2.net"; $user = "anonymous"; $pass = "ftptest@example.com"; $conn = ftp_connect($server); if (!$conn) { die('unable to connect to: '. $server); } $login = ftp_login($conn, $user, $pass); if (!$login) { echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass; } else{ echo 'connected successfully'.PHP_EOL; $directory = ftp_nlist($conn,''); print_r($directory); } if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) { echo "Successfully downloaded file".PHP_EOL; } else { echo "failed to download file"; }
Write the same algorithm in PHP as shown in this C implementation.
#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; }
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
Port the provided C code into PHP while preserving the original functionality.
#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; }
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
Convert this C block to PHP, preserving its control flow and logic.
for(int i = 1;i <= 10; i++){ printf("%d", i); if(i % 5 == 0){ printf("\n"); continue; } printf(", "); }
for ($i = 1; $i <= 10; $i++) { echo $i; if ($i % 5 == 0) { echo "\n"; continue; } echo ', '; }
Rewrite the snippet below in PHP so it works the same as the original C code.
#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; }
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480); $image = imagecreate(BARWIDTH * count($colors), HEIGHT); foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); } header('Content-type:image/png'); imagepng($image); imagedestroy($image);
Ensure the translated PHP code behaves exactly like the original C snippet.
#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; }
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480); $image = imagecreate(BARWIDTH * count($colors), HEIGHT); foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); } header('Content-type:image/png'); imagepng($image); imagedestroy($image);
Translate this program into PHP but keep the logic exactly as in C.
#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; }
<?php $max = 20; $factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz'); for ($i = 1 ; $i <= $max ; $i++) { $matched = false; foreach ($factor AS $number => $word) { if ($i % $number == 0) { echo $word; $matched = true; } } echo ($matched ? '' : $i), PHP_EOL; } ?>
Write a version of this C function in PHP with identical behavior.
#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; }
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
Generate an equivalent PHP version of this C code.
#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; }
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
Port the provided C code into PHP while preserving the original functionality.
#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; }
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf("%20s : %s \n", $test[0],$result); }
Can you help me rewrite this code in PHP instead of C, keeping it the same logically?
#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; }
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf("%20s : %s \n", $test[0],$result); }
Convert the following code from C to PHP, ensuring the logic remains intact.
#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; }
$str = "alphaBETA"; echo strtoupper($str), "\n"; // ALPHABETA echo strtolower($str), "\n"; // alphabeta echo ucfirst($str), "\n"; // AlphaBETA echo lcfirst("FOObar"), "\n"; // fOObar echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
Can you help me rewrite this code in PHP instead of C, keeping it the same logically?
#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; }
$string = "The quick brown fox jumped over the lazy dog's back"; echo md5( $string );
Write the same code in PHP as shown below in C.
#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; }
<?php $time = new DateTime('March 7 2009 7:30pm EST'); $time->modify('+12 hours'); echo $time->format('c'); ?>
Rewrite the snippet below in PHP so it works the same as the original C code.
>>>>>,----------[++++++++ ++[->+>+<<]>+>[-<<+>>]+++ +++++[-<------>]>>+>,---- ------<<+[->>>>>+<<<<<]>> ]>>>[<<<<[<<<[->>+<<[->+> [-]<<]]>[-<+>]>[-<<<.>>>> ->>>>>[>>>>>]<-<<<<[<<<<< ]+<]<<<<]>>>>>[>>>>>]<]
<?php $buffer = 1; $pids = []; for ($i = 1; $i < $argc; $i++) { $pid = pcntl_fork(); if ($pid < 0) { die("failed to start child process"); } if ($pid === 0) { sleep($argv[$i] + $buffer); echo $argv[$i] . "\n"; exit(); } $pids[] = $pid; } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); }
Generate a PHP translation of this C snippet without changing its computational steps.
#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; }
<?php for ($i = 0; $i < 10; $i++) for ($j = 0; $j < 10; $j++) $a[$i][$j] = rand(1, 20); foreach ($a as $row) { foreach ($row as $element) { echo " $element"; if ($element == 20) break 2; // 2 is the number of loops we want to break out of } echo "\n"; } echo "\n"; ?>
Can you help me rewrite this code in PHP instead of C, keeping it the same logically?
#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; }
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
Convert this C block to PHP, preserving its control flow and logic.
#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; }
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
Convert this C block to PHP, preserving its control flow and logic.
#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;}
$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'); $unique_list = array_unique($list);
Change the programming language of this snippet from C to PHP without modifying what it does.
#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; }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Produce a functionally identical PHP code for the snippet given in C.
#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; }
$stack = array(); empty( $stack ); // true array_push( $stack, 1 ); // or $stack[] = 1; array_push( $stack, 2 ); // or $stack[] = 2; empty( $stack ); // false echo array_pop( $stack ); // outputs "2" echo array_pop( $stack ); // outputs "1"
Transform the following C implementation into PHP, maintaining the same output and logic.
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"); }
<?php $foo = 3; if ($foo == 2) if ($foo == 3) else if ($foo != 0) { } else { } ?>
Port the provided C code into PHP while preserving the original functionality.
#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; }
function stoogeSort(&$arr, $i, $j) { if($arr[$j] < $arr[$i]) { list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); } if(($j - $i) > 1) { $t = ($j - $i + 1) / 3; stoogesort($arr, $i, $j - $t); stoogesort($arr, $i + $t, $j); stoogesort($arr, $i, $j - $t); } }
Produce a functionally identical PHP code for the snippet given in C.
#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; }
<?php $conf = file_get_contents('parse-conf-file.txt'); $conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf); $conf = preg_replace_callback( '/^([a-z]+)\s*=((?=.*\,.*).*)$/mi', function ($matches) { $r = ''; foreach (explode(',', $matches[2]) AS $val) { $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL; } return $r; }, $conf ); $conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf); $ini = parse_ini_string($conf); echo 'Full name = ', $ini['FULLNAME'], PHP_EOL; echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL; echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL; echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL; echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
Write a version of this C function in PHP with identical behavior.
#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; }
<?php function mycmp($s1, $s2) { if ($d = strlen($s2) - strlen($s1)) return $d; return strcasecmp($s1, $s2); } $strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted"); usort($strings, "mycmp"); ?>
Convert the following code from C to PHP, ensuring the logic remains intact.
#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; }
function selection_sort(&$arr) { $n = count($arr); for($i = 0; $i < count($arr); $i++) { $min = $i; for($j = $i + 1; $j < $n; $j++){ if($arr[$j] < $arr[$min]){ $min = $j; } } list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]); } }
Generate a PHP translation of this C snippet without changing its computational steps.
#ifndef CALLBACK_H #define CALLBACK_H void map(int* array, int len, void(*callback)(int,int)); #endif
function cube($n) { return($n * $n * $n); } $a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b);
Preserve the algorithm and functionality while converting the code from C to PHP.
#ifndef SILLY_H #define SILLY_H extern void JumpOverTheDog( int numberOfTimes); extern int PlayFetchWithDog( float weightOfStick); #endif
class Singleton { protected static $instance = null; public $test_var; private function __construct(){ } public static function getInstance(){ if (is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } } $foo = Singleton::getInstance(); $foo->test_var = 'One'; $bar = Singleton::getInstance(); echo $bar->test_var; //Prints 'One' $fail = new Singleton(); //Fatal error
Ensure the translated PHP code behaves exactly like the original C snippet.
#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; }
<?php $dog = 'Benjamin'; $Dog = 'Samba'; $DOG = 'Bernie'; echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n"; function DOG() { return 'Bernie'; } echo 'There is only 1 dog named ' . dog() . "\n";
Change the following C code into PHP without altering its purpose.
int i; for(i = 10; i >= 0; --i) printf("%d\n",i);
for ($i = 10; $i >= 0; $i--) echo "$i\n";
Maintain the same structure and functionality when rewriting this code in PHP.
#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)); }
file_put_contents($filename, $data)
Generate a PHP translation of this C snippet without changing its computational steps.
int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) putchar('*'); puts(""); }
for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo '*'; } echo "\n"; }
Produce a functionally identical PHP code for the snippet given in C.
#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; }
<?php function longMult($a, $b) { $as = (string) $a; $bs = (string) $b; for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--) { for($p = 0; $p < $pi; $p++) { $regi[$ai][] = 0; } for($bi = strlen($bs) - 1; $bi >= 0; $bi--) { $regi[$ai][] = $as[$ai] * $bs[$bi]; } } return $regi; } function longAdd($arr) { $outer = count($arr); $inner = count($arr[$outer-1]) + $outer; for($i = 0; $i <= $inner; $i++) { for($o = 0; $o < $outer; $o++) { $val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0; @$sum[$i] += $val; } } return $sum; } function carry($arr) { for($i = 0; $i < count($arr); $i++) { $s = (string) $arr[$i]; switch(strlen($s)) { case 2: $arr[$i] = $s{1}; @$arr[$i+1] += $s{0}; break; case 3: $arr[$i] = $s{2}; @$arr[$i+1] += $s{0}.$s{1}; break; } } return ltrim(implode('',array_reverse($arr)),'0'); } function lm($a,$b) { return carry(longAdd(longMult($a,$b))); } if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456') { echo 'pass!'; }; // 2^64 * 2^64
Transform the following C implementation into PHP, maintaining the same output and logic.
#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; } } }
<?php $size = 4; $chosen = implode(array_rand(array_flip(range(1,9)), $size)); echo "I've chosen a number from $size unique digits from 1 to 9; you need to input $size unique digits to guess my number\n"; for ($guesses = 1; ; $guesses++) { while (true) { echo "\nNext guess [$guesses]: "; $guess = rtrim(fgets(STDIN)); if (!checkguess($guess)) echo "$size digits, no repetition, no 0... retry\n"; else break; } if ($guess == $chosen) { echo "You did it in $guesses attempts!\n"; break; } else { $bulls = 0; $cows = 0; foreach (range(0, $size-1) as $i) { if ($guess[$i] == $chosen[$i]) $bulls++; else if (strpos($chosen, $guess[$i]) !== FALSE) $cows++; } echo "$cows cows, $bulls bulls\n"; } } function checkguess($g) { global $size; return count(array_unique(str_split($g))) == $size && preg_match("/^[1-9]{{$size}}$/", $g); } ?>
Convert this C snippet to PHP and keep its semantics consistent.
#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; }
function bubbleSort(array $array){ foreach($array as $i => &$val){ foreach($array as $k => &$val2){ if($k <= $i) continue; if($val > $val2) { list($val, $val2) = [$val2, $val]; break; } } } return $array; }
Rewrite this program in PHP while keeping its functionality equivalent to the C version.
#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; }
<?php if (!$in = fopen('input.txt', 'r')) { die('Could not open input file.'); } if (!$out = fopen('output.txt', 'w')) { die('Could not open output file.'); } while (!feof($in)) { $data = fread($in, 512); fwrite($out, $data); } fclose($out); fclose($in); ?>
Convert this C snippet to PHP and keep its semantics consistent.
#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; }
<?php $a = fgets(STDIN); $b = fgets(STDIN); echo "sum: ", $a + $b, "\n", "difference: ", $a - $b, "\n", "product: ", $a * $b, "\n", "truncating quotient: ", (int)($a / $b), "\n", "flooring quotient: ", floor($a / $b), "\n", "remainder: ", $a % $b, "\n", "power: ", $a ** $b, "\n"; // PHP 5.6+ only ?>
Change the following C code into PHP without altering its purpose.
#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; }
function transpose($m) { if (count($m) == 0) // special case: empty matrix return array(); else if (count($m) == 1) // special case: row matrix return array_chunk($m[0], 1); array_unshift($m, NULL); // the original matrix is not modified because it was passed by value return call_user_func_array('array_map', $m); }
Translate the given C code snippet into PHP without altering its behavior.
#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; }
<?php function A($k,$x1,$x2,$x3,$x4,$x5) { $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) { return A(--$k,$b,$x1,$x2,$x3,$x4); }; return $k <= 0 ? $x4() + $x5() : $b(); } echo A(10, function () { return 1; }, function () { return -1; }, function () { return -1; }, function () { return 1; }, function () { return 0; }) . "\n"; ?>
Generate a PHP translation of this C snippet without changing its computational steps.
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
Maintain the same structure and functionality when rewriting this code in PHP.
#include <stdio.h> void recurse(unsigned int i) { printf("%d\n", i); recurse(i+1); } int main() { recurse(0); return 0; }
<?php function a() { static $i = 0; print ++$i . "\n"; a(); } a();
Change the following C code into PHP without altering its purpose.
#include "stdio.h" #include "math.h" int perfect(int n) { int max = (int)sqrt((double)n) + 1; int tot = 1; int i; for (i = 2; i < max; i++) if ( (n % i) == 0 ) { tot += i; int q = n / i; if (q > i) tot += q; } return tot == n; } int main() { int n; for (n = 2; n < 33550337; n++) if (perfect(n)) printf("%d\n", n); return 0; }
function is_perfect($number) { $sum = 0; for($i = 1; $i < $number; $i++) { if($number % $i == 0) $sum += $i; } return $sum == $number; } echo "Perfect numbers from 1 to 33550337:" . PHP_EOL; for($num = 1; $num < 33550337; $num++) { if(is_perfect($num)) echo $num . PHP_EOL; }
Preserve the algorithm and functionality while converting the code from C to PHP.
#include <stdio.h> #include <stdlib.h> void bead_sort(int *a, int len) { int i, j, max, sum; unsigned char *beads; # define BEAD(i, j) beads[i * max + j] for (i = 1, max = a[0]; i < len; i++) if (a[i] > max) max = a[i]; beads = calloc(1, max * len); for (i = 0; i < len; i++) for (j = 0; j < a[i]; j++) BEAD(i, j) = 1; for (j = 0; j < max; j++) { for (sum = i = 0; i < len; i++) { sum += BEAD(i, j); BEAD(i, j) = 0; } for (i = len - sum; i < len; i++) BEAD(i, j) = 1; } for (i = 0; i < len; i++) { for (j = 0; j < max && BEAD(i, j); j++); a[i] = j; } free(beads); } int main() { int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(x)/sizeof(x[0]); bead_sort(x, len); for (i = 0; i < len; i++) printf("%d\n", x[i]); return 0; }
<?php function columns($arr) { if (count($arr) == 0) return array(); else if (count($arr) == 1) return array_chunk($arr[0], 1); array_unshift($arr, NULL); $transpose = call_user_func_array('array_map', $arr); return array_map('array_filter', $transpose); } function beadsort($arr) { foreach ($arr as $e) $poles []= array_fill(0, $e, 1); return array_map('count', columns(columns($poles))); } print_r(beadsort(array(5,3,1,7,4,1,1))); ?>
Transform the following C implementation into PHP, maintaining the same output and logic.
#include <gmp.h> #include <stdio.h> #include <string.h> int main() { mpz_t a; mpz_init_set_ui(a, 5); mpz_pow_ui(a, a, 1 << 18); int len = mpz_sizeinbase(a, 10); printf("GMP says size is: %d\n", len); char *s = mpz_get_str(0, 10, a); printf("size really is %d\n", len = strlen(s)); printf("Digits: %.20s...%s\n", s, s + len - 20); return 0; }
<?php $y = bcpow('5', bcpow('4', bcpow('3', '2'))); printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y)); ?>
Port the following code from C to PHP with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> char chr_legal[] = "abcdefghijklmnopqrstuvwxyz0123456789_-./"; int chr_idx[256] = {0}; char idx_chr[256] = {0}; #define FNAME 0 typedef struct trie_t *trie, trie_t; struct trie_t { trie next[sizeof(chr_legal)]; int eow; }; trie trie_new() { return calloc(sizeof(trie_t), 1); } #define find_word(r, w) trie_trav(r, w, 1) trie trie_trav(trie root, const char * str, int no_create) { int c; while (root) { if ((c = str[0]) == '\0') { if (!root->eow && no_create) return 0; break; } if (! (c = chr_idx[c]) ) { str++; continue; } if (!root->next[c]) { if (no_create) return 0; root->next[c] = trie_new(); } root = root->next[c]; str++; } return root; } int trie_all(trie root, char path[], int depth, int (*callback)(char *)) { int i; if (root->eow && !callback(path)) return 0; for (i = 1; i < sizeof(chr_legal); i++) { if (!root->next[i]) continue; path[depth] = idx_chr[i]; path[depth + 1] = '\0'; if (!trie_all(root->next[i], path, depth + 1, callback)) return 0; } return 1; } void add_index(trie root, const char *word, const char *fname) { trie x = trie_trav(root, word, 0); x->eow = 1; if (!x->next[FNAME]) x->next[FNAME] = trie_new(); x = trie_trav(x->next[FNAME], fname, 0); x->eow = 1; } int print_path(char *path) { printf(" %s", path); return 1; } const char *files[] = { "f1.txt", "source/f2.txt", "other_file" }; const char *text[][5] ={{ "it", "is", "what", "it", "is" }, { "what", "is", "it", 0 }, { "it", "is", "a", "banana", 0 }}; trie init_tables() { int i, j; trie root = trie_new(); for (i = 0; i < sizeof(chr_legal); i++) { chr_idx[(int)chr_legal[i]] = i + 1; idx_chr[i + 1] = chr_legal[i]; } #define USE_ADVANCED_FILE_HANDLING 0 #if USE_ADVANCED_FILE_HANDLING void read_file(const char * fname) { char cmd[1024]; char word[1024]; sprintf(cmd, "perl -p -e 'while(/(\\w+)/g) {print lc($1),\"\\n\"}' %s", fname); FILE *in = popen(cmd, "r"); while (!feof(in)) { fscanf(in, "%1000s", word); add_index(root, word, fname); } pclose(in); }; read_file("f1.txt"); read_file("source/f2.txt"); read_file("other_file"); #else for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) { if (!text[i][j]) break; add_index(root, text[i][j], files[i]); } } #endif return root; } void search_index(trie root, const char *word) { char path[1024]; printf("Search for \"%s\": ", word); trie found = find_word(root, word); if (!found) printf("not found\n"); else { trie_all(found->next[FNAME], path, 0, print_path); printf("\n"); } } int main() { trie root = init_tables(); search_index(root, "what"); search_index(root, "is"); search_index(root, "banana"); search_index(root, "boo"); return 0; }
<?php function buildInvertedIndex($filenames) { $invertedIndex = []; foreach($filenames as $filename) { $data = file_get_contents($filename); if($data === false) die('Unable to read file: ' . $filename); preg_match_all('/(\w+)/', $data, $matches, PREG_SET_ORDER); foreach($matches as $match) { $word = strtolower($match[0]); if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = []; if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename; } } return $invertedIndex; } function lookupWord($invertedIndex, $word) { return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false; } $invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']); foreach(['cat', 'is', 'banana', 'it'] as $word) { $matches = lookupWord($invertedIndex, $word); if($matches !== false) { echo "Found the word \"$word\" in the following files: " . implode(', ', $matches) . "\n"; } else { echo "Unable to find the word \"$word\" in the index\n"; } }
Keep all operations the same but rewrite the snippet in PHP.
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
Write the same algorithm in PHP as shown in this C implementation.
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
echo lcm(12, 18) == 36; function lcm($m, $n) { if ($m == 0 || $n == 0) return 0; $r = ($m * $n) / gcd($m, $n); return abs($r); } function gcd($a, $b) { while ($b != 0) { $t = $b; $b = $a % $b; $a = $t; } return $a; }
Port the following code from C to PHP with equivalent syntax and logic.
int main(){ time_t t; int a, b; srand((unsigned)time(&t)); for(;;){ a = rand() % 20; printf("%d\n", a); if(a == 10) break; b = rand() % 20; printf("%d\n", b); } return 0; }
while (true) { $a = rand(0,19); echo "$a\n"; if ($a == 10) break; $b = rand(0,19); echo "$b\n"; }
Convert this C block to PHP, preserving its control flow and logic.
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
<?php file_put_contents('/dev/lp0', 'Hello world!'); ?>
Produce a functionally identical PHP code for the snippet given in C.
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
<?php file_put_contents('/dev/lp0', 'Hello world!'); ?>