Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite the snippet below in C so it works the same as the original Python code.
def compress(uncompressed): dict_size = 256 dictionary = dict((chr(i), i) for i in range(dict_size)) w = "" result = [] for c in uncompressed: wc = w + c if wc in dictionary: w = wc else: result.append(dictionary[w]) dictionary[wc] = dict_size dict_size += 1 w = c if w: result.append(dictionary[w]) return result def decompress(compressed): from io import StringIO dict_size = 256 dictionary = dict((i, chr(i)) for i in range(dict_size)) result = StringIO() w = chr(compressed.pop(0)) result.write(w) for k in compressed: if k in dictionary: entry = dictionary[k] elif k == dict_size: entry = w + w[0] else: raise ValueError('Bad compressed k: %s' % k) result.write(entry) dictionary[dict_size] = w + entry[0] dict_size += 1 w = entry return result.getvalue() compressed = compress('TOBEORNOTTOBEORTOBEORNOT') print (compressed) decompressed = decompress(compressed) print (decompressed)
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> void* mem_alloc(size_t item_size, size_t n_item) { size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size); x[0] = item_size; x[1] = n_item; return x + 2; } void* mem_extend(void *m, size_t new_n) { size_t *x = (size_t*)m - 2; x = realloc(x, sizeof(size_t) * 2 + *x * new_n); if (new_n > x[1]) memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1])); x[1] = new_n; return x + 2; } inline void _clear(void *m) { size_t *x = (size_t*)m - 2; memset(m, 0, x[0] * x[1]); } #define _new(type, n) mem_alloc(sizeof(type), n) #define _del(m) { free((size_t*)(m) - 2); m = 0; } #define _len(m) *((size_t*)m - 1) #define _setsize(m, n) m = mem_extend(m, n) #define _extend(m) m = mem_extend(m, _len(m) * 2) typedef uint8_t byte; typedef uint16_t ushort; #define M_CLR 256 #define M_EOD 257 #define M_NEW 258 typedef struct { ushort next[256]; } lzw_enc_t; typedef struct { ushort prev, back; byte c; } lzw_dec_t; byte* lzw_encode(byte *in, int max_bits) { int len = _len(in), bits = 9, next_shift = 512; ushort code, c, nc, next_code = M_NEW; lzw_enc_t *d = _new(lzw_enc_t, 512); if (max_bits > 15) max_bits = 15; if (max_bits < 9 ) max_bits = 12; byte *out = _new(ushort, 4); int out_len = 0, o_bits = 0; uint32_t tmp = 0; inline void write_bits(ushort x) { tmp = (tmp << bits) | x; o_bits += bits; if (_len(out) <= out_len) _extend(out); while (o_bits >= 8) { o_bits -= 8; out[out_len++] = tmp >> o_bits; tmp &= (1 << o_bits) - 1; } } for (code = *(in++); --len; ) { c = *(in++); if ((nc = d[code].next[c])) code = nc; else { write_bits(code); nc = d[code].next[c] = next_code++; code = c; } if (next_code == next_shift) { if (++bits > max_bits) { write_bits(M_CLR); bits = 9; next_shift = 512; next_code = M_NEW; _clear(d); } else _setsize(d, next_shift *= 2); } } write_bits(code); write_bits(M_EOD); if (tmp) write_bits(tmp); _del(d); _setsize(out, out_len); return out; } byte* lzw_decode(byte *in) { byte *out = _new(byte, 4); int out_len = 0; inline void write_out(byte c) { while (out_len >= _len(out)) _extend(out); out[out_len++] = c; } lzw_dec_t *d = _new(lzw_dec_t, 512); int len, j, next_shift = 512, bits = 9, n_bits = 0; ushort code, c, t, next_code = M_NEW; uint32_t tmp = 0; inline void get_code() { while(n_bits < bits) { if (len > 0) { len --; tmp = (tmp << 8) | *(in++); n_bits += 8; } else { tmp = tmp << (bits - n_bits); n_bits = bits; } } n_bits -= bits; code = tmp >> n_bits; tmp &= (1 << n_bits) - 1; } inline void clear_table() { _clear(d); for (j = 0; j < 256; j++) d[j].c = j; next_code = M_NEW; next_shift = 512; bits = 9; }; clear_table(); for (len = _len(in); len;) { get_code(); if (code == M_EOD) break; if (code == M_CLR) { clear_table(); continue; } if (code >= next_code) { fprintf(stderr, "Bad sequence\n"); _del(out); goto bail; } d[next_code].prev = c = code; while (c > 255) { t = d[c].prev; d[t].back = c; c = t; } d[next_code - 1].c = c; while (d[c].back) { write_out(d[c].c); t = d[c].back; d[c].back = 0; c = t; } write_out(d[c].c); if (++next_code >= next_shift) { if (++bits > 16) { fprintf(stderr, "Too many bits\n"); _del(out); goto bail; } _setsize(d, next_shift *= 2); } } if (code != M_EOD) fputs("Bits did not end in EOD\n", stderr); _setsize(out, out_len); bail: _del(d); return out; } int main() { int i, fd = open("unixdict.txt", O_RDONLY); if (fd == -1) { fprintf(stderr, "Can't read file\n"); return 1; }; struct stat st; fstat(fd, &st); byte *in = _new(char, st.st_size); read(fd, in, st.st_size); _setsize(in, st.st_size); close(fd); printf("input size: %d\n", _len(in)); byte *enc = lzw_encode(in, 9); printf("encoded size: %d\n", _len(enc)); byte *dec = lzw_decode(enc); printf("decoded size: %d\n", _len(dec)); for (i = 0; i < _len(dec); i++) if (dec[i] != in[i]) { printf("bad decode at %d\n", i); break; } if (i == _len(dec)) printf("Decoded ok\n"); _del(in); _del(enc); _del(dec); return 0; }
Preserve the algorithm and functionality while converting the code from Python to C.
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
Convert the following code from Python to C, ensuring the logic remains intact.
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
Convert the following code from Python to C, ensuring the logic remains intact.
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
Convert the following code from Python to C, ensuring the logic remains intact.
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
Convert this Python snippet to C and keep its semantics consistent.
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
Produce a language-to-language conversion: from Python to C, same semantics.
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
from itertools import chain, count, islice from operator import itemgetter from math import gcd from matplotlib import pyplot def yellowstone(): def relativelyPrime(a): return lambda b: 1 == gcd(a, b) def nextWindow(triple): p2, p1, rest = triple [rp2, rp1] = map(relativelyPrime, [p2, p1]) def match(xxs): x, xs = uncons(xxs)['Just'] return (x, xs) if rp1(x) and not rp2(x) else ( second(cons(x))( match(xs) ) ) n, residue = match(rest) return (p1, n, residue) return chain( range(1, 3), map( itemgetter(1), iterate(nextWindow)( (2, 3, count(4)) ) ) ) def main(): print(showList( take(30)(yellowstone()) )) pyplot.plot( take(100)(yellowstone()) ) pyplot.xlabel(main.__doc__) pyplot.show() def Just(x): return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): return {'type': 'Maybe', 'Nothing': True} def cons(x): return lambda xs: [x] + xs if ( isinstance(xs, list) ) else x + xs if ( isinstance(xs, str) ) else chain([x], xs) def iterate(f): def go(x): v = x while True: yield v v = f(v) return go def second(f): return lambda xy: (xy[0], f(xy[1])) def showList(xs): return '[' + ','.join(repr(x) for x in xs) + ']' def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) def uncons(xs): if isinstance(xs, list): return Just((xs[0], xs[1:])) if xs else Nothing() else: nxt = take(1)(xs) return Just((nxt[0], xs)) if nxt else Nothing() if __name__ == '__main__': main()
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
Write the same code in C as shown below in Python.
from itertools import chain, count, islice from operator import itemgetter from math import gcd from matplotlib import pyplot def yellowstone(): def relativelyPrime(a): return lambda b: 1 == gcd(a, b) def nextWindow(triple): p2, p1, rest = triple [rp2, rp1] = map(relativelyPrime, [p2, p1]) def match(xxs): x, xs = uncons(xxs)['Just'] return (x, xs) if rp1(x) and not rp2(x) else ( second(cons(x))( match(xs) ) ) n, residue = match(rest) return (p1, n, residue) return chain( range(1, 3), map( itemgetter(1), iterate(nextWindow)( (2, 3, count(4)) ) ) ) def main(): print(showList( take(30)(yellowstone()) )) pyplot.plot( take(100)(yellowstone()) ) pyplot.xlabel(main.__doc__) pyplot.show() def Just(x): return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): return {'type': 'Maybe', 'Nothing': True} def cons(x): return lambda xs: [x] + xs if ( isinstance(xs, list) ) else x + xs if ( isinstance(xs, str) ) else chain([x], xs) def iterate(f): def go(x): v = x while True: yield v v = f(v) return go def second(f): return lambda xy: (xy[0], f(xy[1])) def showList(xs): return '[' + ','.join(repr(x) for x in xs) + ']' def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) def uncons(xs): if isinstance(xs, list): return Just((xs[0], xs[1:])) if xs else Nothing() else: nxt = take(1)(xs) return Just((nxt[0], xs)) if nxt else Nothing() if __name__ == '__main__': main()
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
Transform the following Python implementation into C, maintaining the same output and logic.
from itertools import chain, count, islice from operator import itemgetter from math import gcd from matplotlib import pyplot def yellowstone(): def relativelyPrime(a): return lambda b: 1 == gcd(a, b) def nextWindow(triple): p2, p1, rest = triple [rp2, rp1] = map(relativelyPrime, [p2, p1]) def match(xxs): x, xs = uncons(xxs)['Just'] return (x, xs) if rp1(x) and not rp2(x) else ( second(cons(x))( match(xs) ) ) n, residue = match(rest) return (p1, n, residue) return chain( range(1, 3), map( itemgetter(1), iterate(nextWindow)( (2, 3, count(4)) ) ) ) def main(): print(showList( take(30)(yellowstone()) )) pyplot.plot( take(100)(yellowstone()) ) pyplot.xlabel(main.__doc__) pyplot.show() def Just(x): return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): return {'type': 'Maybe', 'Nothing': True} def cons(x): return lambda xs: [x] + xs if ( isinstance(xs, list) ) else x + xs if ( isinstance(xs, str) ) else chain([x], xs) def iterate(f): def go(x): v = x while True: yield v v = f(v) return go def second(f): return lambda xy: (xy[0], f(xy[1])) def showList(xs): return '[' + ','.join(repr(x) for x in xs) + ']' def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) def uncons(xs): if isinstance(xs, list): return Just((xs[0], xs[1:])) if xs else Nothing() else: nxt = take(1)(xs) return Just((nxt[0], xs)) if nxt else Nothing() if __name__ == '__main__': main()
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x == w: return count + 1 t = y * (w + 1) + x grid[t] = grid[blen - t] = True if not grid[t + next[0]]: count = walk(y + dirs[0][0], x + dirs[0][1], count) if not grid[t + next[1]]: count = walk(y + dirs[1][0], x + dirs[1][1], count) if not grid[t + next[2]]: count = walk(y + dirs[2][0], x + dirs[2][1], count) if not grid[t + next[3]]: count = walk(y + dirs[3][0], x + dirs[3][1], count) grid[t] = grid[blen - t] = False return count t = h // 2 * (w + 1) + w // 2 if w % 2: grid[t] = grid[t + 1] = True count = walk(h // 2, w // 2 - 1, count) res = count count = 0 count = walk(h // 2 - 1, w // 2, count) return res + count * 2 else: grid[t] = True count = walk(h // 2, w // 2 - 1, count) if h == w: return count * 2 count = walk(h // 2 - 1, w // 2, count) return count def main(): for w in xrange(1, 10): for h in xrange(1, w + 1): if not((w * h) % 2): print "%d x %d: %d" % (w, h, cut_it(w, h)) main()
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
Write the same algorithm in C as shown in this Python implementation.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x == w: return count + 1 t = y * (w + 1) + x grid[t] = grid[blen - t] = True if not grid[t + next[0]]: count = walk(y + dirs[0][0], x + dirs[0][1], count) if not grid[t + next[1]]: count = walk(y + dirs[1][0], x + dirs[1][1], count) if not grid[t + next[2]]: count = walk(y + dirs[2][0], x + dirs[2][1], count) if not grid[t + next[3]]: count = walk(y + dirs[3][0], x + dirs[3][1], count) grid[t] = grid[blen - t] = False return count t = h // 2 * (w + 1) + w // 2 if w % 2: grid[t] = grid[t + 1] = True count = walk(h // 2, w // 2 - 1, count) res = count count = 0 count = walk(h // 2 - 1, w // 2, count) return res + count * 2 else: grid[t] = True count = walk(h // 2, w // 2 - 1, count) if h == w: return count * 2 count = walk(h // 2 - 1, w // 2, count) return count def main(): for w in xrange(1, 10): for h in xrange(1, w + 1): if not((w * h) % 2): print "%d x %d: %d" % (w, h, cut_it(w, h)) main()
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
Port the provided Python code into C while preserving the original functionality.
def cut_it(h, w): dirs = ((1, 0), (-1, 0), (0, -1), (0, 1)) if h % 2: h, w = w, h if h % 2: return 0 if w == 1: return 1 count = 0 next = [w + 1, -w - 1, -1, 1] blen = (h + 1) * (w + 1) - 1 grid = [False] * (blen + 1) def walk(y, x, count): if not y or y == h or not x or x == w: return count + 1 t = y * (w + 1) + x grid[t] = grid[blen - t] = True if not grid[t + next[0]]: count = walk(y + dirs[0][0], x + dirs[0][1], count) if not grid[t + next[1]]: count = walk(y + dirs[1][0], x + dirs[1][1], count) if not grid[t + next[2]]: count = walk(y + dirs[2][0], x + dirs[2][1], count) if not grid[t + next[3]]: count = walk(y + dirs[3][0], x + dirs[3][1], count) grid[t] = grid[blen - t] = False return count t = h // 2 * (w + 1) + w // 2 if w % 2: grid[t] = grid[t + 1] = True count = walk(h // 2, w // 2 - 1, count) res = count count = 0 count = walk(h // 2 - 1, w // 2, count) return res + count * 2 else: grid[t] = True count = walk(h // 2, w // 2 - 1, count) if h == w: return count * 2 count = walk(h // 2 - 1, w // 2, count) return count def main(): for w in xrange(1, 10): for h in xrange(1, w + 1): if not((w * h) % 2): print "%d x %d: %d" % (w, h, cut_it(w, h)) main()
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
Write the same algorithm in C as shown in this Python implementation.
def mertens(count): m = [None, 1] for n in range(2, count+1): m.append(1) for k in range(2, n+1): m[n] -= m[n//k] return m ms = mertens(1000) print("The first 99 Mertens numbers are:") print(" ", end=' ') col = 1 for n in ms[1:100]: print("{:2d}".format(n), end=' ') col += 1 if col == 10: print() col = 0 zeroes = sum(x==0 for x in ms) crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:])) print("M(N) equals zero {} times.".format(zeroes)) print("M(N) crosses zero {} times.".format(crosses))
#include <stdio.h> #include <stdlib.h> int* mertens_numbers(int max) { int* m = malloc((max + 1) * sizeof(int)); if (m == NULL) return m; m[1] = 1; for (int n = 2; n <= max; ++n) { m[n] = 1; for (int k = 2; k <= n; ++k) m[n] -= m[n/k]; } return m; } int main() { const int max = 1000; int* mertens = mertens_numbers(max); if (mertens == NULL) { fprintf(stderr, "Out of memory\n"); return 1; } printf("First 199 Mertens numbers:\n"); const int count = 200; for (int i = 0, column = 0; i < count; ++i) { if (column > 0) printf(" "); if (i == 0) printf(" "); else printf("%2d", mertens[i]); ++column; if (column == 20) { printf("\n"); column = 0; } } int zero = 0, cross = 0, previous = 0; for (int i = 1; i <= max; ++i) { int m = mertens[i]; if (m == 0) { ++zero; if (previous != 0) ++cross; } previous = m; } free(mertens); printf("M(n) is zero %d times for 1 <= n <= %d.\n", zero, max); printf("M(n) crosses zero %d times for 1 <= n <= %d.\n", cross, max); return 0; }
Generate a C translation of this Python snippet without changing its computational steps.
def _insort_right(a, x, q): lo, hi = 0, len(a) while lo < hi: mid = (lo+hi)//2 q += 1 less = input(f"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: ").strip().lower() == 'y' if less: hi = mid else: lo = mid+1 a.insert(lo, x) return q def order(items): ordered, q = [], 0 for item in items: q = _insort_right(ordered, item, q) return ordered, q if __name__ == '__main__': items = 'violet red green indigo blue yellow orange'.split() ans, questions = order(items) print('\n' + ' '.join(ans))
#include <stdio.h> #include <string.h> #include <stdlib.h> int interactiveCompare(const void *x1, const void *x2) { const char *s1 = *(const char * const *)x1; const char *s2 = *(const char * const *)x2; static int count = 0; printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2); int response; scanf("%d", &response); return response; } void printOrder(const char *items[], int len) { printf("{ "); for (int i = 0; i < len; ++i) printf("%s ", items[i]); printf("}\n"); } int main(void) { const char *items[] = { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }; qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare); printOrder(items, sizeof(items)/sizeof(*items)); return 0; }
Ensure the translated C code behaves exactly like the original Python snippet.
from __future__ import division from itertools import islice, count from collections import Counter from math import log10 from random import randint expected = [log10(1+1/d) for d in range(1,10)] def fib(): a,b = 1,1 while True: yield a a,b = b,a+b def power_of_threes(): return (3**k for k in count(0)) def heads(s): for a in s: yield int(str(a)[0]) def show_dist(title, s): c = Counter(s) size = sum(c.values()) res = [c[d]/size for d in range(1,10)] print("\n%s Benfords deviation" % title) for r, e in zip(res, expected): print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.)) def rand1000(): while True: yield randint(1,9999) if __name__ == '__main__': show_dist("fibbed", islice(heads(fib()), 1000)) show_dist("threes", islice(heads(power_of_threes()), 1000)) show_dist("random", islice(heads(rand1000()), 10000))
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
Ensure the translated C code behaves exactly like the original Python snippet.
from __future__ import division from itertools import islice, count from collections import Counter from math import log10 from random import randint expected = [log10(1+1/d) for d in range(1,10)] def fib(): a,b = 1,1 while True: yield a a,b = b,a+b def power_of_threes(): return (3**k for k in count(0)) def heads(s): for a in s: yield int(str(a)[0]) def show_dist(title, s): c = Counter(s) size = sum(c.values()) res = [c[d]/size for d in range(1,10)] print("\n%s Benfords deviation" % title) for r, e in zip(res, expected): print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.)) def rand1000(): while True: yield randint(1,9999) if __name__ == '__main__': show_dist("fibbed", islice(heads(fib()), 1000)) show_dist("threes", islice(heads(power_of_threes()), 1000)) show_dist("random", islice(heads(rand1000()), 10000))
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
Preserve the algorithm and functionality while converting the code from Python to C.
import time, calendar, sched, winsound duration = 750 freq = 1280 bellchar = "\u2407" watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',') def gap(n=1): time.sleep(n * duration / 1000) off = gap def on(n=1): winsound.Beep(freq, n * duration) def bong(): on(); off(0.5) def bongs(m): for i in range(m): print(bellchar, end=' ') bong() if i % 2: print(' ', end='') off(0.5) print('') scheds = sched.scheduler(time.time, time.sleep) def ships_bell(now=None): def adjust_to_half_hour(atime): atime[4] = (atime[4] // 30) * 30 atime[5] = 0 return atime debug = now is not None rightnow = time.gmtime() if not debug: now = adjust_to_half_hour( list(rightnow) ) then = now[::] then[4] += 30 hr, mn = now[3:5] watch, b = divmod(int(2 * hr + mn // 30 - 1), 8) b += 1 bells = '%i bell%s' % (b, 's' if b > 1 else ' ') if debug: print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ') else: print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ') bongs(b) if not debug: scheds.enterabs(calendar.timegm(then), 0, ships_bell) scheds.run() def dbg_tester(): for h in range(24): for m in (0, 30): if (h,m) == (24,30): break ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] ) if __name__ == '__main__': ships_bell()
#include<unistd.h> #include<stdio.h> #include<time.h> #define SHORTLAG 1000 #define LONGLAG 2000 int main(){ int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; while(1){ time(&t); currentTime = localtime(&t); hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec; hour = 12; min = 0; sec = 0; if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; } if(min==0){ min1 = 0; min2 = 0; } else{ min1 = 3; min2 = 0; } if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times); for(i=1;i<=times;i++){ printf("\a"); (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }
Produce a functionally identical C code for the snippet given in Python.
import time, calendar, sched, winsound duration = 750 freq = 1280 bellchar = "\u2407" watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',') def gap(n=1): time.sleep(n * duration / 1000) off = gap def on(n=1): winsound.Beep(freq, n * duration) def bong(): on(); off(0.5) def bongs(m): for i in range(m): print(bellchar, end=' ') bong() if i % 2: print(' ', end='') off(0.5) print('') scheds = sched.scheduler(time.time, time.sleep) def ships_bell(now=None): def adjust_to_half_hour(atime): atime[4] = (atime[4] // 30) * 30 atime[5] = 0 return atime debug = now is not None rightnow = time.gmtime() if not debug: now = adjust_to_half_hour( list(rightnow) ) then = now[::] then[4] += 30 hr, mn = now[3:5] watch, b = divmod(int(2 * hr + mn // 30 - 1), 8) b += 1 bells = '%i bell%s' % (b, 's' if b > 1 else ' ') if debug: print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ') else: print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ') bongs(b) if not debug: scheds.enterabs(calendar.timegm(then), 0, ships_bell) scheds.run() def dbg_tester(): for h in range(24): for m in (0, 30): if (h,m) == (24,30): break ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] ) if __name__ == '__main__': ships_bell()
#include<unistd.h> #include<stdio.h> #include<time.h> #define SHORTLAG 1000 #define LONGLAG 2000 int main(){ int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; while(1){ time(&t); currentTime = localtime(&t); hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec; hour = 12; min = 0; sec = 0; if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; } if(min==0){ min1 = 0; min2 = 0; } else{ min1 = 3; min2 = 0; } if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times); for(i=1;i<=times;i++){ printf("\a"); (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }
Port the provided Python code into C while preserving the original functionality.
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))) >>> [ Y(fib)(i) for i in range(-2, 10) ] [None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#include <stdio.h> long fib(long x) { long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); }; if (x < 0) { printf("Bad argument: fib(%ld)\n", x); return -1; } return fib_i(x); } long fib_i(long n) { printf("This is not the fib you are looking for\n"); return -1; } int main() { long x; for (x = -1; x < 4; x ++) printf("fib %ld = %ld\n", x, fib(x)); printf("calling fib_i from outside fib:\n"); fib_i(3); return 0; }
Write a version of this Python function in C with identical behavior.
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))) >>> [ Y(fib)(i) for i in range(-2, 10) ] [None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#include <stdio.h> long fib(long x) { long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); }; if (x < 0) { printf("Bad argument: fib(%ld)\n", x); return -1; } return fib_i(x); } long fib_i(long n) { printf("This is not the fib you are looking for\n"); return -1; } int main() { long x; for (x = -1; x < 4; x ++) printf("fib %ld = %ld\n", x, fib(x)); printf("calling fib_i from outside fib:\n"); fib_i(3); return 0; }
Convert this Python block to C, preserving its control flow and logic.
from __future__ import annotations import itertools import random from enum import Enum from typing import Any from typing import Tuple import pygame as pg from pygame import Color from pygame import Rect from pygame.surface import Surface from pygame.sprite import AbstractGroup from pygame.sprite import Group from pygame.sprite import RenderUpdates from pygame.sprite import Sprite class Direction(Enum): UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) def opposite(self, other: Direction): return (self[0] + other[0], self[1] + other[1]) == (0, 0) def __getitem__(self, i: int): return self.value[i] class SnakeHead(Sprite): def __init__( self, size: int, position: Tuple[int, int], facing: Direction, bounds: Rect, ) -> None: super().__init__() self.image = Surface((size, size)) self.image.fill(Color("aquamarine4")) self.rect = self.image.get_rect() self.rect.center = position self.facing = facing self.size = size self.speed = size self.bounds = bounds def update(self, *args: Any, **kwargs: Any) -> None: self.rect.move_ip( ( self.facing[0] * self.speed, self.facing[1] * self.speed, ) ) if self.rect.right > self.bounds.right: self.rect.left = 0 elif self.rect.left < 0: self.rect.right = self.bounds.right if self.rect.bottom > self.bounds.bottom: self.rect.top = 0 elif self.rect.top < 0: self.rect.bottom = self.bounds.bottom def change_direction(self, direction: Direction): if not self.facing == direction and not direction.opposite(self.facing): self.facing = direction class SnakeBody(Sprite): def __init__( self, size: int, position: Tuple[int, int], colour: str = "white", ) -> None: super().__init__() self.image = Surface((size, size)) self.image.fill(Color(colour)) self.rect = self.image.get_rect() self.rect.center = position class Snake(RenderUpdates): def __init__(self, game: Game) -> None: self.segment_size = game.segment_size self.colours = itertools.cycle(["aquamarine1", "aquamarine3"]) self.head = SnakeHead( size=self.segment_size, position=game.rect.center, facing=Direction.RIGHT, bounds=game.rect, ) neck = [ SnakeBody( size=self.segment_size, position=game.rect.center, colour=next(self.colours), ) for _ in range(2) ] super().__init__(*[self.head, *neck]) self.body = Group() self.tail = neck[-1] def update(self, *args: Any, **kwargs: Any) -> None: self.head.update() segments = self.sprites() for i in range(len(segments) - 1, 0, -1): segments[i].rect.center = segments[i - 1].rect.center def change_direction(self, direction: Direction): self.head.change_direction(direction) def grow(self): tail = SnakeBody( size=self.segment_size, position=self.tail.rect.center, colour=next(self.colours), ) self.tail = tail self.add(self.tail) self.body.add(self.tail) class SnakeFood(Sprite): def __init__(self, game: Game, size: int, *groups: AbstractGroup) -> None: super().__init__(*groups) self.image = Surface((size, size)) self.image.fill(Color("red")) self.rect = self.image.get_rect() self.rect.topleft = ( random.randint(0, game.rect.width), random.randint(0, game.rect.height), ) self.rect.clamp_ip(game.rect) while pg.sprite.spritecollideany(self, game.snake): self.rect.topleft = ( random.randint(0, game.rect.width), random.randint(0, game.rect.height), ) self.rect.clamp_ip(game.rect) class Game: def __init__(self) -> None: self.rect = Rect(0, 0, 640, 480) self.background = Surface(self.rect.size) self.background.fill(Color("black")) self.score = 0 self.framerate = 16 self.segment_size = 10 self.snake = Snake(self) self.food_group = RenderUpdates(SnakeFood(game=self, size=self.segment_size)) pg.init() def _init_display(self) -> Surface: bestdepth = pg.display.mode_ok(self.rect.size, 0, 32) screen = pg.display.set_mode(self.rect.size, 0, bestdepth) pg.display.set_caption("Snake") pg.mouse.set_visible(False) screen.blit(self.background, (0, 0)) pg.display.flip() return screen def draw(self, screen: Surface): dirty = self.snake.draw(screen) pg.display.update(dirty) dirty = self.food_group.draw(screen) pg.display.update(dirty) def update(self, screen): self.food_group.clear(screen, self.background) self.food_group.update() self.snake.clear(screen, self.background) self.snake.update() def main(self) -> int: screen = self._init_display() clock = pg.time.Clock() while self.snake.head.alive(): for event in pg.event.get(): if event.type == pg.QUIT or ( event.type == pg.KEYDOWN and event.key in (pg.K_ESCAPE, pg.K_q) ): return self.score keystate = pg.key.get_pressed() if keystate[pg.K_RIGHT]: self.snake.change_direction(Direction.RIGHT) elif keystate[pg.K_LEFT]: self.snake.change_direction(Direction.LEFT) elif keystate[pg.K_UP]: self.snake.change_direction(Direction.UP) elif keystate[pg.K_DOWN]: self.snake.change_direction(Direction.DOWN) self.update(screen) for food in pg.sprite.spritecollide( self.snake.head, self.food_group, dokill=False ): food.kill() self.snake.grow() self.score += 1 if self.score % 5 == 0: self.framerate += 1 self.food_group.add(SnakeFood(self, self.segment_size)) if pg.sprite.spritecollideany(self.snake.head, self.snake.body): self.snake.head.kill() self.draw(screen) clock.tick(self.framerate) return self.score if __name__ == "__main__": game = Game() score = game.main() print(score)
char nonblocking_getch(); void positional_putch(int x, int y, char ch); void millisecond_sleep(int n); void init_screen(); void update_screen(); void close_screen(); #ifdef __linux__ #define _POSIX_C_SOURCE 200809L #include <time.h> #include <ncurses.h> char nonblocking_getch() { return getch(); } void positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); } void millisecond_sleep(int n) { struct timespec t = { 0, n * 1000000 }; nanosleep(&t, 0); } void update_screen() { refresh(); } void init_screen() { initscr(); noecho(); cbreak(); nodelay(stdscr, TRUE); } void close_screen() { endwin(); } #endif #ifdef _WIN32 #error "not implemented" #endif #include <time.h> #include <stdlib.h> #define w 80 #define h 40 int board[w * h]; int head; enum Dir { N, E, S, W } dir; int quit; enum State { SPACE=0, FOOD=1, BORDER=2 }; void age() { int i; for(i = 0; i < w * h; ++i) if(board[i] < 0) ++board[i]; } void plant() { int r; do r = rand() % (w * h); while(board[r] != SPACE); board[r] = FOOD; } void start(void) { int i; for(i = 0; i < w; ++i) board[i] = board[i + (h - 1) * w] = BORDER; for(i = 0; i < h; ++i) board[i * w] = board[i * w + w - 1] = BORDER; head = w * (h - 1 - h % 2) / 2; board[head] = -5; dir = N; quit = 0; srand(time(0)); plant(); } void step() { int len = board[head]; switch(dir) { case N: head -= w; break; case S: head += w; break; case W: --head; break; case E: ++head; break; } switch(board[head]) { case SPACE: board[head] = len - 1; age(); break; case FOOD: board[head] = len - 1; plant(); break; default: quit = 1; } } void show() { const char * symbol = " @."; int i; for(i = 0; i < w * h; ++i) positional_putch(i / w, i % w, board[i] < 0 ? '#' : symbol[board[i]]); update_screen(); } int main (int argc, char * argv[]) { init_screen(); start(); do { show(); switch(nonblocking_getch()) { case 'i': dir = N; break; case 'j': dir = W; break; case 'k': dir = S; break; case 'l': dir = E; break; case 'q': quit = 1; break; } step(); millisecond_sleep(100); } while(!quit); millisecond_sleep(999); close_screen(); return 0; }
Convert this Python block to C, preserving its control flow and logic.
print "knight"[1:] print "socks"[:-1] print "brooms"[1:-1]
#include <string.h> #include <stdlib.h> #include <stdio.h> int main( int argc, char ** argv ){ const char * str_a = "knight"; const char * str_b = "socks"; const char * str_c = "brooms"; char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 ); strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); printf( "%s\n%s\n%s\n", new_a, new_b, new_c ); free( new_a ); free( new_b ); free( new_c ); return 0; }
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
print "knight"[1:] print "socks"[:-1] print "brooms"[1:-1]
#include <string.h> #include <stdlib.h> #include <stdio.h> int main( int argc, char ** argv ){ const char * str_a = "knight"; const char * str_b = "socks"; const char * str_c = "brooms"; char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 ); strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); printf( "%s\n%s\n%s\n", new_a, new_b, new_c ); free( new_a ); free( new_b ); free( new_c ); return 0; }
Translate the given Python code snippet into C without altering its behavior.
from primesieve import primes from math import isqrt from functools import cache p = primes(isqrt(1_000_000_000)) @cache def phi(x, a): res = 0 while True: if not a or not x: return x + res a -= 1 res -= phi(x//p[a], a) def legpi(n): if n < 2: return 0 a = legpi(isqrt(n)) return phi(n, a) + a - 1 for e in range(10): print(f'10^{e}', legpi(10**e))
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <stdint.h> #include <time.h> const uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128}; #define half(n) ((int64_t)((n) - 1) >> 1) #define divide(nm, d) ((uint64_t)((double)nm / (double)d)) int64_t countPrimes(uint64_t n) { if (n < 9) return (n < 2) ? 0 : ((int64_t)n + 1) / 2; uint64_t rtlmt = (uint64_t)sqrt((double)n); int64_t mxndx = (int64_t)((rtlmt - 1) / 2); int arrlen = (int)(mxndx + 1); uint32_t *smalls = malloc(arrlen * 4); uint32_t *roughs = malloc(arrlen * 4); int64_t *larges = malloc(arrlen * 8); for (int i = 0; i < arrlen; ++i) { smalls[i] = (uint32_t)i; roughs[i] = (uint32_t)(i + i + 1); larges[i] = (int64_t)((n/(uint64_t)(i + i + 1) - 1) / 2); } int cullbuflen = (int)((mxndx + 8) / 8); uint8_t *cullbuf = calloc(cullbuflen, 1); int64_t nbps = 0; int rilmt = arrlen; for (int64_t i = 1; ; ++i) { int64_t sqri = (i + i) * (i + 1); if (sqri > mxndx) break; if (cullbuf[i >> 3] & masks[i & 7]) continue; cullbuf[i >> 3] |= masks[i & 7]; uint64_t bp = (uint64_t)(i + i + 1); for (int64_t c = sqri; c < (int64_t)arrlen; c += (int64_t)bp) { cullbuf[c >> 3] |= masks[c & 7]; } int nri = 0; for (int ori = 0; ori < rilmt; ++ori) { uint32_t r = roughs[ori]; int64_t rci = (int64_t)(r >> 1); if (cullbuf[rci >> 3] & masks[rci & 7]) continue; uint64_t d = (uint64_t)r * bp; int64_t t = (d <= rtlmt) ? larges[(int64_t)smalls[d >> 1] - nbps] : (int64_t)smalls[half(divide(n, d))]; larges[nri] = larges[ori] - t + nbps; roughs[nri] = r; nri++; } int64_t si = mxndx; for (uint64_t pm = (rtlmt/bp - 1) | 1; pm >= bp; pm -= 2) { uint32_t c = smalls[pm >> 1]; uint64_t e = (pm * bp) >> 1; for ( ; si >= (int64_t)e; --si) smalls[si] -= c - (uint32_t)nbps; } rilmt = nri; nbps++; } int64_t ans = larges[0] + (int64_t)((rilmt + 2*(nbps - 1)) * (rilmt - 1) / 2); int ri, sri; for (ri = 1; ri < rilmt; ++ri) ans -= larges[ri]; for (ri = 1; ; ++ri) { uint64_t p = (uint64_t)roughs[ri]; uint64_t m = n / p; int ei = (int)smalls[half((uint64_t)m/p)] - nbps; if (ei <= ri) break; ans -= (int64_t)((ei - ri) * (nbps + ri - 1)); for (sri = ri + 1; sri < ei + 1; ++sri) { ans += (int64_t)smalls[half(divide(m, (uint64_t)roughs[sri]))]; } } free(smalls); free(roughs); free(larges); free(cullbuf); return ans + 1; } int main() { uint64_t n; int i; clock_t start = clock(); for (i = 0, n = 1; i < 10; ++i, n *= 10) { printf("10^%d %ld\n", i, countPrimes(n)); } clock_t end = clock(); printf("\nTook %f seconds\n", (double) (end - start) / CLOCKS_PER_SEC); return 0; }
Change the following Python code into C without altering its purpose.
def query(buffer_length): message = b'Here am I' L = len(message) return message[0:L*(L <= buffer_length)]
#include <stdio.h> extern int Query (char * Data, size_t * Length); int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer); if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } }
Produce a language-to-language conversion: from Python to C, same semantics.
import fileinput def longer(a, b): try: b[len(a)-1] return False except: return True longest, lines = '', '' for x in fileinput.input(): if longer(x, longest): lines, longest = x, x elif not longer(longest, x): lines += x print(lines, end='')
#include <stdio.h> #include <string.h> int cmp(const char *p, const char *q) { while (*p && *q) p = &p[1], q = &q[1]; return *p; } int main() { char line[65536]; char buf[1000000] = {0}; char *last = buf; char *next = buf; while (gets(line)) { strcat(line, "\n"); if (cmp(last, line)) continue; if (cmp(line, last)) next = buf; last = next; strcpy(next, line); while (*next) next = &next[1]; } printf("%s", buf); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> enum { LEFT, RIGHT, STAY }; typedef struct { int state1; int symbol1; int symbol2; int dir; int state2; } transition_t; typedef struct tape_t tape_t; struct tape_t { int symbol; tape_t *left; tape_t *right; }; typedef struct { int states_len; char **states; int final_states_len; int *final_states; int symbols_len; char *symbols; int blank; int state; int tape_len; tape_t *tape; int transitions_len; transition_t ***transitions; } turing_t; int state_index (turing_t *t, char *state) { int i; for (i = 0; i < t->states_len; i++) { if (!strcmp(t->states[i], state)) { return i; } } return 0; } int symbol_index (turing_t *t, char symbol) { int i; for (i = 0; i < t->symbols_len; i++) { if (t->symbols[i] == symbol) { return i; } } return 0; } void move (turing_t *t, int dir) { tape_t *orig = t->tape; if (dir == RIGHT) { if (orig && orig->right) { t->tape = orig->right; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->left = orig; orig->right = t->tape; } } } else if (dir == LEFT) { if (orig && orig->left) { t->tape = orig->left; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->right = orig; orig->left = t->tape; } } } } turing_t *create (int states_len, ...) { va_list args; va_start(args, states_len); turing_t *t = malloc(sizeof (turing_t)); t->states_len = states_len; t->states = malloc(states_len * sizeof (char *)); int i; for (i = 0; i < states_len; i++) { t->states[i] = va_arg(args, char *); } t->final_states_len = va_arg(args, int); t->final_states = malloc(t->final_states_len * sizeof (int)); for (i = 0; i < t->final_states_len; i++) { t->final_states[i] = state_index(t, va_arg(args, char *)); } t->symbols_len = va_arg(args, int); t->symbols = malloc(t->symbols_len); for (i = 0; i < t->symbols_len; i++) { t->symbols[i] = va_arg(args, int); } t->blank = symbol_index(t, va_arg(args, int)); t->state = state_index(t, va_arg(args, char *)); t->tape_len = va_arg(args, int); t->tape = NULL; for (i = 0; i < t->tape_len; i++) { move(t, RIGHT); t->tape->symbol = symbol_index(t, va_arg(args, int)); } if (!t->tape_len) { move(t, RIGHT); } while (t->tape->left) { t->tape = t->tape->left; } t->transitions_len = va_arg(args, int); t->transitions = malloc(t->states_len * sizeof (transition_t **)); for (i = 0; i < t->states_len; i++) { t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *)); } for (i = 0; i < t->transitions_len; i++) { transition_t *tran = malloc(sizeof (transition_t)); tran->state1 = state_index(t, va_arg(args, char *)); tran->symbol1 = symbol_index(t, va_arg(args, int)); tran->symbol2 = symbol_index(t, va_arg(args, int)); tran->dir = va_arg(args, int); tran->state2 = state_index(t, va_arg(args, char *)); t->transitions[tran->state1][tran->symbol1] = tran; } va_end(args); return t; } void print_state (turing_t *t) { printf("%-10s ", t->states[t->state]); tape_t *tape = t->tape; while (tape->left) { tape = tape->left; } while (tape) { if (tape == t->tape) { printf("[%c]", t->symbols[tape->symbol]); } else { printf(" %c ", t->symbols[tape->symbol]); } tape = tape->right; } printf("\n"); } void run (turing_t *t) { int i; while (1) { print_state(t); for (i = 0; i < t->final_states_len; i++) { if (t->final_states[i] == t->state) { return; } } transition_t *tran = t->transitions[t->state][t->tape->symbol]; t->tape->symbol = tran->symbol2; move(t, tran->dir); t->state = tran->state2; } } int main () { printf("Simple incrementer\n"); turing_t *t = create( 2, "q0", "qf", 1, "qf", 2, 'B', '1', 'B', "q0", 3, '1', '1', '1', 2, "q0", '1', '1', RIGHT, "q0", "q0", 'B', '1', STAY, "qf" ); run(t); printf("\nThree-state busy beaver\n"); t = create( 4, "a", "b", "c", "halt", 1, "halt", 2, '0', '1', '0', "a", 0, 6, "a", '0', '1', RIGHT, "b", "a", '1', '1', LEFT, "c", "b", '0', '1', LEFT, "a", "b", '1', '1', RIGHT, "b", "c", '0', '1', LEFT, "b", "c", '1', '1', STAY, "halt" ); run(t); return 0; printf("\nFive-state two-symbol probable busy beaver\n"); t = create( 6, "A", "B", "C", "D", "E", "H", 1, "H", 2, '0', '1', '0', "A", 0, 10, "A", '0', '1', RIGHT, "B", "A", '1', '1', LEFT, "C", "B", '0', '1', RIGHT, "C", "B", '1', '1', RIGHT, "B", "C", '0', '1', RIGHT, "D", "C", '1', '0', LEFT, "E", "D", '0', '1', LEFT, "A", "D", '1', '1', LEFT, "D", "E", '0', '1', STAY, "H", "E", '1', '0', LEFT, "A" ); run(t); }
Generate an equivalent C version of this Python code.
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> enum { LEFT, RIGHT, STAY }; typedef struct { int state1; int symbol1; int symbol2; int dir; int state2; } transition_t; typedef struct tape_t tape_t; struct tape_t { int symbol; tape_t *left; tape_t *right; }; typedef struct { int states_len; char **states; int final_states_len; int *final_states; int symbols_len; char *symbols; int blank; int state; int tape_len; tape_t *tape; int transitions_len; transition_t ***transitions; } turing_t; int state_index (turing_t *t, char *state) { int i; for (i = 0; i < t->states_len; i++) { if (!strcmp(t->states[i], state)) { return i; } } return 0; } int symbol_index (turing_t *t, char symbol) { int i; for (i = 0; i < t->symbols_len; i++) { if (t->symbols[i] == symbol) { return i; } } return 0; } void move (turing_t *t, int dir) { tape_t *orig = t->tape; if (dir == RIGHT) { if (orig && orig->right) { t->tape = orig->right; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->left = orig; orig->right = t->tape; } } } else if (dir == LEFT) { if (orig && orig->left) { t->tape = orig->left; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->right = orig; orig->left = t->tape; } } } } turing_t *create (int states_len, ...) { va_list args; va_start(args, states_len); turing_t *t = malloc(sizeof (turing_t)); t->states_len = states_len; t->states = malloc(states_len * sizeof (char *)); int i; for (i = 0; i < states_len; i++) { t->states[i] = va_arg(args, char *); } t->final_states_len = va_arg(args, int); t->final_states = malloc(t->final_states_len * sizeof (int)); for (i = 0; i < t->final_states_len; i++) { t->final_states[i] = state_index(t, va_arg(args, char *)); } t->symbols_len = va_arg(args, int); t->symbols = malloc(t->symbols_len); for (i = 0; i < t->symbols_len; i++) { t->symbols[i] = va_arg(args, int); } t->blank = symbol_index(t, va_arg(args, int)); t->state = state_index(t, va_arg(args, char *)); t->tape_len = va_arg(args, int); t->tape = NULL; for (i = 0; i < t->tape_len; i++) { move(t, RIGHT); t->tape->symbol = symbol_index(t, va_arg(args, int)); } if (!t->tape_len) { move(t, RIGHT); } while (t->tape->left) { t->tape = t->tape->left; } t->transitions_len = va_arg(args, int); t->transitions = malloc(t->states_len * sizeof (transition_t **)); for (i = 0; i < t->states_len; i++) { t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *)); } for (i = 0; i < t->transitions_len; i++) { transition_t *tran = malloc(sizeof (transition_t)); tran->state1 = state_index(t, va_arg(args, char *)); tran->symbol1 = symbol_index(t, va_arg(args, int)); tran->symbol2 = symbol_index(t, va_arg(args, int)); tran->dir = va_arg(args, int); tran->state2 = state_index(t, va_arg(args, char *)); t->transitions[tran->state1][tran->symbol1] = tran; } va_end(args); return t; } void print_state (turing_t *t) { printf("%-10s ", t->states[t->state]); tape_t *tape = t->tape; while (tape->left) { tape = tape->left; } while (tape) { if (tape == t->tape) { printf("[%c]", t->symbols[tape->symbol]); } else { printf(" %c ", t->symbols[tape->symbol]); } tape = tape->right; } printf("\n"); } void run (turing_t *t) { int i; while (1) { print_state(t); for (i = 0; i < t->final_states_len; i++) { if (t->final_states[i] == t->state) { return; } } transition_t *tran = t->transitions[t->state][t->tape->symbol]; t->tape->symbol = tran->symbol2; move(t, tran->dir); t->state = tran->state2; } } int main () { printf("Simple incrementer\n"); turing_t *t = create( 2, "q0", "qf", 1, "qf", 2, 'B', '1', 'B', "q0", 3, '1', '1', '1', 2, "q0", '1', '1', RIGHT, "q0", "q0", 'B', '1', STAY, "qf" ); run(t); printf("\nThree-state busy beaver\n"); t = create( 4, "a", "b", "c", "halt", 1, "halt", 2, '0', '1', '0', "a", 0, 6, "a", '0', '1', RIGHT, "b", "a", '1', '1', LEFT, "c", "b", '0', '1', LEFT, "a", "b", '1', '1', RIGHT, "b", "c", '0', '1', LEFT, "b", "c", '1', '1', STAY, "halt" ); run(t); return 0; printf("\nFive-state two-symbol probable busy beaver\n"); t = create( 6, "A", "B", "C", "D", "E", "H", 1, "H", 2, '0', '1', '0', "A", 0, 10, "A", '0', '1', RIGHT, "B", "A", '1', '1', LEFT, "C", "B", '0', '1', RIGHT, "C", "B", '1', '1', RIGHT, "B", "C", '0', '1', RIGHT, "D", "C", '1', '0', LEFT, "E", "D", '0', '1', LEFT, "A", "D", '1', '1', LEFT, "D", "E", '0', '1', STAY, "H", "E", '1', '0', LEFT, "A" ); run(t); }
Keep all operations the same but rewrite the snippet in C.
import os for directory in ['/', './']: open(directory + 'output.txt', 'w').close() os.mkdir(directory + 'docs')
#include <stdio.h> int main() { FILE *fh = fopen("output.txt", "w"); fclose(fh); return 0; }
Convert the following code from Python to C, ensuring the logic remains intact.
from itertools import count, islice def primes(_cache=[2, 3]): yield from _cache for n in count(_cache[-1]+2, 2): if isprime(n): _cache.append(n) yield n def isprime(n, _seen={0: False, 1: False}): def _isprime(n): for p in primes(): if p*p > n: return True if n%p == 0: return False if n not in _seen: _seen[n] = _isprime(n) return _seen[n] def unprime(): for a in count(1): d = 1 while d <= a: base = (a//(d*10))*(d*10) + (a%d) if any(isprime(y) for y in range(base, base + d*10, d)): break d *= 10 else: yield a print('First 35:') print(' '.join(str(i) for i in islice(unprime(), 35))) print('\nThe 600-th:') print(list(islice(unprime(), 599, 600))[0]) print() first, need = [False]*10, 10 for p in unprime(): i = p%10 if first[i]: continue first[i] = p need -= 1 if not need: break for i,v in enumerate(first): print(f'{i} ending: {v}')
#include <assert.h> #include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> typedef struct bit_array_tag { uint32_t size; uint32_t* array; } bit_array; bool bit_array_create(bit_array* b, uint32_t size) { uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t)); if (array == NULL) return false; b->size = size; b->array = array; return true; } void bit_array_destroy(bit_array* b) { free(b->array); b->array = NULL; } void bit_array_set(bit_array* b, uint32_t index, bool value) { assert(index < b->size); uint32_t* p = &b->array[index >> 5]; uint32_t bit = 1 << (index & 31); if (value) *p |= bit; else *p &= ~bit; } bool bit_array_get(const bit_array* b, uint32_t index) { assert(index < b->size); uint32_t* p = &b->array[index >> 5]; uint32_t bit = 1 << (index & 31); return (*p & bit) != 0; } typedef struct sieve_tag { uint32_t limit; bit_array not_prime; } sieve; bool sieve_create(sieve* s, uint32_t limit) { if (!bit_array_create(&s->not_prime, limit/2)) return false; for (uint32_t p = 3; p * p <= limit; p += 2) { if (bit_array_get(&s->not_prime, p/2 - 1) == false) { uint32_t inc = 2 * p; for (uint32_t q = p * p; q <= limit; q += inc) bit_array_set(&s->not_prime, q/2 - 1, true); } } s->limit = limit; return true; } void sieve_destroy(sieve* s) { bit_array_destroy(&s->not_prime); } bool is_prime(const sieve* s, uint32_t n) { assert(n <= s->limit); if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; return bit_array_get(&s->not_prime, n/2 - 1) == false; } uint32_t count_digits(uint32_t n) { uint32_t digits = 0; for (; n > 0; ++digits) n /= 10; return digits; } uint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) { uint32_t p = 1; uint32_t changed = 0; for (; index > 0; p *= 10, n /= 10, --index) changed += p * (n % 10); changed += (10 * (n/10) + new_digit) * p; return changed; } bool unprimeable(const sieve* s, uint32_t n) { if (is_prime(s, n)) return false; uint32_t d = count_digits(n); for (uint32_t i = 0; i < d; ++i) { for (uint32_t j = 0; j <= 9; ++j) { uint32_t m = change_digit(n, i, j); if (m != n && is_prime(s, m)) return false; } } return true; } int main() { const uint32_t limit = 10000000; setlocale(LC_ALL, ""); sieve s = { 0 }; if (!sieve_create(&s, limit)) { fprintf(stderr, "Out of memory\n"); return 1; } printf("First 35 unprimeable numbers:\n"); uint32_t n = 100; uint32_t lowest[10] = { 0 }; for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) { if (unprimeable(&s, n)) { if (count < 35) { if (count != 0) printf(", "); printf("%'u", n); } ++count; if (count == 600) printf("\n600th unprimeable number: %'u\n", n); uint32_t last_digit = n % 10; if (lowest[last_digit] == 0) { lowest[last_digit] = n; ++found; } } } sieve_destroy(&s); for (uint32_t i = 0; i < 10; ++i) printf("Least unprimeable number ending in %u: %'u\n" , i, lowest[i]); return 0; }
Transform the following Python implementation into C, maintaining the same output and logic.
def combine( snl, snr ): cl = {} if isinstance(snl, int): cl['1'] = snl elif isinstance(snl, string): cl[snl] = 1 else: cl.update( snl) if isinstance(snr, int): n = cl.get('1', 0) cl['1'] = n + snr elif isinstance(snr, string): n = cl.get(snr, 0) cl[snr] = n + 1 else: for k,v in snr.items(): n = cl.get(k, 0) cl[k] = n+v return cl def constrain(nsum, vn ): nn = {} nn.update(vn) n = nn.get('1', 0) nn['1'] = n - nsum return nn def makeMatrix( constraints ): vmap = set() for c in constraints: vmap.update( c.keys()) vmap.remove('1') nvars = len(vmap) vmap = sorted(vmap) mtx = [] for c in constraints: row = [] for vv in vmap: row.append(float(c.get(vv, 0))) row.append(-float(c.get('1',0))) mtx.append(row) if len(constraints) == nvars: print 'System appears solvable' elif len(constraints) < nvars: print 'System is not solvable - needs more constraints.' return mtx, vmap def SolvePyramid( vl, cnstr ): vl.reverse() constraints = [cnstr] lvls = len(vl) for lvln in range(1,lvls): lvd = vl[lvln] for k in range(lvls - lvln): sn = lvd[k] ll = vl[lvln-1] vn = combine(ll[k], ll[k+1]) if sn is None: lvd[k] = vn else: constraints.append(constrain( sn, vn )) print 'Constraint Equations:' for cstr in constraints: fset = ('%d*%s'%(v,k) for k,v in cstr.items() ) print ' + '.join(fset), ' = 0' mtx,vmap = makeMatrix(constraints) MtxSolve(mtx) d = len(vmap) for j in range(d): print vmap[j],'=', mtx[j][d] def MtxSolve(mtx): mDim = len(mtx) for j in range(mDim): rw0= mtx[j] f = 1.0/rw0[j] for k in range(j, mDim+1): rw0[k] *= f for l in range(1+j,mDim): rwl = mtx[l] f = -rwl[j] for k in range(j, mDim+1): rwl[k] += f * rw0[k] for j1 in range(1,mDim): j = mDim - j1 rw0= mtx[j] for l in range(0, j): rwl = mtx[l] f = -rwl[j] rwl[j] += f * rw0[j] rwl[mDim] += f * rw0[mDim] return mtx p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ] addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 } SolvePyramid( p, addlConstraint)
#include <stdio.h> #include <math.h> void pascal(int a, int b, int mid, int top, int* x, int* y, int* z) { double ytemp = (top - 4 * (a + b)) / 7.; if(fmod(ytemp, 1.) >= 0.0001) { x = 0; return; } *y = ytemp; *x = mid - 2 * a - *y; *z = *y - *x; } int main() { int a = 11, b = 4, mid = 40, top = 151; int x, y, z; pascal(a, b, mid, top, &x, &y, &z); if(x != 0) printf("x: %d, y: %d, z: %d\n", x, y, z); else printf("No solution\n"); return 0; }
Please provide an equivalent version of this Python code in C.
def combine( snl, snr ): cl = {} if isinstance(snl, int): cl['1'] = snl elif isinstance(snl, string): cl[snl] = 1 else: cl.update( snl) if isinstance(snr, int): n = cl.get('1', 0) cl['1'] = n + snr elif isinstance(snr, string): n = cl.get(snr, 0) cl[snr] = n + 1 else: for k,v in snr.items(): n = cl.get(k, 0) cl[k] = n+v return cl def constrain(nsum, vn ): nn = {} nn.update(vn) n = nn.get('1', 0) nn['1'] = n - nsum return nn def makeMatrix( constraints ): vmap = set() for c in constraints: vmap.update( c.keys()) vmap.remove('1') nvars = len(vmap) vmap = sorted(vmap) mtx = [] for c in constraints: row = [] for vv in vmap: row.append(float(c.get(vv, 0))) row.append(-float(c.get('1',0))) mtx.append(row) if len(constraints) == nvars: print 'System appears solvable' elif len(constraints) < nvars: print 'System is not solvable - needs more constraints.' return mtx, vmap def SolvePyramid( vl, cnstr ): vl.reverse() constraints = [cnstr] lvls = len(vl) for lvln in range(1,lvls): lvd = vl[lvln] for k in range(lvls - lvln): sn = lvd[k] ll = vl[lvln-1] vn = combine(ll[k], ll[k+1]) if sn is None: lvd[k] = vn else: constraints.append(constrain( sn, vn )) print 'Constraint Equations:' for cstr in constraints: fset = ('%d*%s'%(v,k) for k,v in cstr.items() ) print ' + '.join(fset), ' = 0' mtx,vmap = makeMatrix(constraints) MtxSolve(mtx) d = len(vmap) for j in range(d): print vmap[j],'=', mtx[j][d] def MtxSolve(mtx): mDim = len(mtx) for j in range(mDim): rw0= mtx[j] f = 1.0/rw0[j] for k in range(j, mDim+1): rw0[k] *= f for l in range(1+j,mDim): rwl = mtx[l] f = -rwl[j] for k in range(j, mDim+1): rwl[k] += f * rw0[k] for j1 in range(1,mDim): j = mDim - j1 rw0= mtx[j] for l in range(0, j): rwl = mtx[l] f = -rwl[j] rwl[j] += f * rw0[j] rwl[mDim] += f * rw0[mDim] return mtx p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ] addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 } SolvePyramid( p, addlConstraint)
#include <stdio.h> #include <math.h> void pascal(int a, int b, int mid, int top, int* x, int* y, int* z) { double ytemp = (top - 4 * (a + b)) / 7.; if(fmod(ytemp, 1.) >= 0.0001) { x = 0; return; } *y = ytemp; *x = mid - 2 * a - *y; *z = *y - *x; } int main() { int a = 11, b = 4, mid = 40, top = 151; int x, y, z; pascal(a, b, mid, top, &x, &y, &z); if(x != 0) printf("x: %d, y: %d, z: %d\n", x, y, z); else printf("No solution\n"); return 0; }
Generate an equivalent C version of this Python code.
from sympy import isprime def primality_pretest(k): if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23): return (k <= 23) return True def is_chernick(n, m): t = 9 * m if not primality_pretest(6 * m + 1): return False if not primality_pretest(12 * m + 1): return False for i in range(1,n-1): if not primality_pretest((t << i) + 1): return False if not isprime(6 * m + 1): return False if not isprime(12 * m + 1): return False for i in range(1,n - 1): if not isprime((t << i) + 1): return False return True for n in range(3,10): if n > 4: multiplier = 1 << (n - 4) else: multiplier = 1 if n > 5: multiplier *= 5 k = 1 while True: m = k * multiplier if is_chernick(n, m): print("a("+str(n)+") has m = "+str(m)) break k += 1
#include <stdio.h> #include <stdlib.h> #include <gmp.h> typedef unsigned long long int u64; #define TRUE 1 #define FALSE 0 int primality_pretest(u64 k) { if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)) return (k <= 23); return TRUE; } int probprime(u64 k, mpz_t n) { mpz_set_ui(n, k); return mpz_probab_prime_p(n, 0); } int is_chernick(int n, u64 m, mpz_t z) { u64 t = 9 * m; if (primality_pretest(6 * m + 1) == FALSE) return FALSE; if (primality_pretest(12 * m + 1) == FALSE) return FALSE; for (int i = 1; i <= n - 2; i++) if (primality_pretest((t << i) + 1) == FALSE) return FALSE; if (probprime(6 * m + 1, z) == FALSE) return FALSE; if (probprime(12 * m + 1, z) == FALSE) return FALSE; for (int i = 1; i <= n - 2; i++) if (probprime((t << i) + 1, z) == FALSE) return FALSE; return TRUE; } int main(int argc, char const *argv[]) { mpz_t z; mpz_inits(z, NULL); for (int n = 3; n <= 10; n ++) { u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1; if (n > 5) multiplier *= 5; for (u64 k = 1; ; k++) { u64 m = k * multiplier; if (is_chernick(n, m, z) == TRUE) { printf("a(%d) has m = %llu\n", n, m); break; } } } return 0; }
Translate this program into C but keep the logic exactly as in Python.
from sympy.geometry import Point, Triangle def sign(pt1, pt2, pt3): return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y) def iswithin(point, pt1, pt2, pt3): zval1 = sign(point, pt1, pt2) zval2 = sign(point, pt2, pt3) zval3 = sign(point, pt3, pt1) notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0 notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0 return notanyneg or notanypos if __name__ == "__main__": POINTS = [Point(0, 0)] TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5)) for pnt in POINTS: a, b, c = TRI.vertices isornot = "is" if iswithin(pnt, a, b, c) else "is not" print("Point", pnt, isornot, "within the triangle", TRI)
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> const double EPS = 0.001; const double EPS_SQUARE = 0.000001; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = min(x1, min(x2, x3)) - EPS; double xMax = max(x1, max(x2, x3)) + EPS; double yMin = min(y1, min(y2, y3)) - EPS; double yMax = max(y1, max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { printf("(%f, %f)", x, y); } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { printf("Triangle is ["); printPoint(x1, y1); printf(", "); printPoint(x2, y2); printf(", "); printPoint(x3, y3); printf("] \n"); } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); printf("Point "); printPoint(x, y); printf(" is within triangle? "); if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { printf("true\n"); } else { printf("false\n"); } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); printf("\n"); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
from sympy.geometry import Point, Triangle def sign(pt1, pt2, pt3): return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y) def iswithin(point, pt1, pt2, pt3): zval1 = sign(point, pt1, pt2) zval2 = sign(point, pt2, pt3) zval3 = sign(point, pt3, pt1) notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0 notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0 return notanyneg or notanypos if __name__ == "__main__": POINTS = [Point(0, 0)] TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5)) for pnt in POINTS: a, b, c = TRI.vertices isornot = "is" if iswithin(pnt, a, b, c) else "is not" print("Point", pnt, isornot, "within the triangle", TRI)
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> const double EPS = 0.001; const double EPS_SQUARE = 0.000001; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = min(x1, min(x2, x3)) - EPS; double xMax = max(x1, max(x2, x3)) + EPS; double yMin = min(y1, min(y2, y3)) - EPS; double yMax = max(y1, max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { printf("(%f, %f)", x, y); } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { printf("Triangle is ["); printPoint(x1, y1); printf(", "); printPoint(x2, y2); printf(", "); printPoint(x3, y3); printf("] \n"); } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); printf("Point "); printPoint(x, y); printf(" is within triangle? "); if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { printf("true\n"); } else { printf("false\n"); } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); printf("\n"); test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); printf("\n"); return 0; }
Convert this Python block to C, preserving its control flow and logic.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //= p if 0 < k: yield (p,k) p += 2 if 1 < n: yield (n,1) def tau(n): assert(n != 0) ans = 1 for (p,k) in factorize(n): ans *= 1 + k return ans if __name__ == "__main__": print(*map(tau, range(1, 101)))
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Count of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%3d", divisor_count(n)); if (n % 20 == 0) { printf("\n"); } } return 0; }
Generate a C translation of this Python snippet without changing its computational steps.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //= p if 0 < k: yield (p,k) p += 2 if 1 < n: yield (n,1) def tau(n): assert(n != 0) ans = 1 for (p,k) in factorize(n): ans *= 1 + k return ans if __name__ == "__main__": print(*map(tau, range(1, 101)))
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Count of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%3d", divisor_count(n)); if (n % 20 == 0) { printf("\n"); } } return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
import pyprimes def primorial_prime(_pmax=500): isprime = pyprimes.isprime n, primo = 0, 1 for prime in pyprimes.nprimes(_pmax): n, primo = n+1, primo * prime if isprime(primo-1) or isprime(primo+1): yield n if __name__ == '__main__': pyprimes.warn_probably = False for i, n in zip(range(20), primorial_prime()): print('Primorial prime %2i at primorial index: %3i' % (i+1, n))
#include <gmp.h> int main(void) { mpz_t p, s; mpz_init_set_ui(p, 1); mpz_init_set_ui(s, 1); for (int n = 1, i = 0; i < 20; n++) { mpz_nextprime(s, s); mpz_mul(p, p, s); mpz_add_ui(p, p, 1); if (mpz_probab_prime_p(p, 25)) { mpz_sub_ui(p, p, 1); gmp_printf("%d\n", n); i++; continue; } mpz_sub_ui(p, p, 2); if (mpz_probab_prime_p(p, 25)) { mpz_add_ui(p, p, 1); gmp_printf("%d\n", n); i++; continue; } mpz_add_ui(p, p, 1); } mpz_clear(s); mpz_clear(p); }
Write the same code in C as shown below in Python.
from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") if __name__ == '__main__': print("SEQUENCE:") sequence = seq_pp(sequence)
#include<string.h> #include<stdlib.h> #include<stdio.h> typedef struct genome{ char* strand; int length; struct genome* next; }genome; genome* genomeData; int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0; int numDigits(int num){ int len = 1; while(num>10){ num = num/10; len++; } return len; } void buildGenome(char str[100]){ int len = strlen(str),i; genome *genomeIterator, *newGenome; totalLength += len; for(i=0;i<len;i++){ switch(str[i]){ case 'A': Adenine++; break; case 'T': Thymine++; break; case 'C': Cytosine++; break; case 'G': Guanine++; break; }; } if(genomeData==NULL){ genomeData = (genome*)malloc(sizeof(genome)); genomeData->strand = (char*)malloc(len*sizeof(char)); strcpy(genomeData->strand,str); genomeData->length = len; genomeData->next = NULL; } else{ genomeIterator = genomeData; while(genomeIterator->next!=NULL) genomeIterator = genomeIterator->next; newGenome = (genome*)malloc(sizeof(genome)); newGenome->strand = (char*)malloc(len*sizeof(char)); strcpy(newGenome->strand,str); newGenome->length = len; newGenome->next = NULL; genomeIterator->next = newGenome; } } void printGenome(){ genome* genomeIterator = genomeData; int width = numDigits(totalLength), len = 0; printf("Sequence:\n"); while(genomeIterator!=NULL){ printf("\n%*d%3s%3s",width+1,len,":",genomeIterator->strand); len += genomeIterator->length; genomeIterator = genomeIterator->next; } printf("\n\nBase Count\n----------\n\n"); printf("%3c%3s%*d\n",'A',":",width+1,Adenine); printf("%3c%3s%*d\n",'T',":",width+1,Thymine); printf("%3c%3s%*d\n",'C',":",width+1,Cytosine); printf("%3c%3s%*d\n",'G',":",width+1,Guanine); printf("\n%3s%*d\n","Total:",width+1,Adenine + Thymine + Cytosine + Guanine); free(genomeData); } int main(int argc,char** argv) { char str[100]; int counter = 0, len; if(argc!=2){ printf("Usage : %s <Gene file name>\n",argv[0]); return 0; } FILE *fp = fopen(argv[1],"r"); while(fscanf(fp,"%s",str)!=EOF) buildGenome(str); fclose(fp); printGenome(); return 0; }
Convert the following code from Python to C, ensuring the logic remains intact.
from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") if __name__ == '__main__': print("SEQUENCE:") sequence = seq_pp(sequence)
#include<string.h> #include<stdlib.h> #include<stdio.h> typedef struct genome{ char* strand; int length; struct genome* next; }genome; genome* genomeData; int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0; int numDigits(int num){ int len = 1; while(num>10){ num = num/10; len++; } return len; } void buildGenome(char str[100]){ int len = strlen(str),i; genome *genomeIterator, *newGenome; totalLength += len; for(i=0;i<len;i++){ switch(str[i]){ case 'A': Adenine++; break; case 'T': Thymine++; break; case 'C': Cytosine++; break; case 'G': Guanine++; break; }; } if(genomeData==NULL){ genomeData = (genome*)malloc(sizeof(genome)); genomeData->strand = (char*)malloc(len*sizeof(char)); strcpy(genomeData->strand,str); genomeData->length = len; genomeData->next = NULL; } else{ genomeIterator = genomeData; while(genomeIterator->next!=NULL) genomeIterator = genomeIterator->next; newGenome = (genome*)malloc(sizeof(genome)); newGenome->strand = (char*)malloc(len*sizeof(char)); strcpy(newGenome->strand,str); newGenome->length = len; newGenome->next = NULL; genomeIterator->next = newGenome; } } void printGenome(){ genome* genomeIterator = genomeData; int width = numDigits(totalLength), len = 0; printf("Sequence:\n"); while(genomeIterator!=NULL){ printf("\n%*d%3s%3s",width+1,len,":",genomeIterator->strand); len += genomeIterator->length; genomeIterator = genomeIterator->next; } printf("\n\nBase Count\n----------\n\n"); printf("%3c%3s%*d\n",'A',":",width+1,Adenine); printf("%3c%3s%*d\n",'T',":",width+1,Thymine); printf("%3c%3s%*d\n",'C',":",width+1,Cytosine); printf("%3c%3s%*d\n",'G',":",width+1,Guanine); printf("\n%3s%*d\n","Total:",width+1,Adenine + Thymine + Cytosine + Guanine); free(genomeData); } int main(int argc,char** argv) { char str[100]; int counter = 0, len; if(argc!=2){ printf("Usage : %s <Gene file name>\n",argv[0]); return 0; } FILE *fp = fopen(argv[1],"r"); while(fscanf(fp,"%s",str)!=EOF) buildGenome(str); fclose(fp); printGenome(); return 0; }
Convert this Python snippet to C and keep its semantics consistent.
import threading import random import time class Philosopher(threading.Thread): running = True def __init__(self, xname, forkOnLeft, forkOnRight): threading.Thread.__init__(self) self.name = xname self.forkOnLeft = forkOnLeft self.forkOnRight = forkOnRight def run(self): while(self.running): time.sleep( random.uniform(3,13)) print '%s is hungry.' % self.name self.dine() def dine(self): fork1, fork2 = self.forkOnLeft, self.forkOnRight while self.running: fork1.acquire(True) locked = fork2.acquire(False) if locked: break fork1.release() print '%s swaps forks' % self.name fork1, fork2 = fork2, fork1 else: return self.dining() fork2.release() fork1.release() def dining(self): print '%s starts eating '% self.name time.sleep(random.uniform(1,10)) print '%s finishes eating and leaves to think.' % self.name def DiningPhilosophers(): forks = [threading.Lock() for n in range(5)] philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel') philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \ for i in range(5)] random.seed(507129) Philosopher.running = True for p in philosophers: p.start() time.sleep(100) Philosopher.running = False print ("Now we're finishing.") DiningPhilosophers()
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdarg.h> #define N 5 const char *names[N] = { "Aristotle", "Kant", "Spinoza", "Marx", "Russell" }; pthread_mutex_t forks[N]; #define M 5 const char *topic[M] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" }; #define lock pthread_mutex_lock #define unlock pthread_mutex_unlock #define xy(x, y) printf("\033[%d;%dH", x, y) #define clear_eol(x) print(x, 12, "\033[K") void print(int y, int x, const char *fmt, ...) { static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER; va_list ap; va_start(ap, fmt); lock(&screen); xy(y + 1, x), vprintf(fmt, ap); xy(N + 1, 1), fflush(stdout); unlock(&screen); } void eat(int id) { int f[2], ration, i; f[0] = f[1] = id; f[id & 1] = (id + 1) % N; clear_eol(id); print(id, 12, "..oO (forks, need forks)"); for (i = 0; i < 2; i++) { lock(forks + f[i]); if (!i) clear_eol(id); print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]); sleep(1); } for (i = 0, ration = 3 + rand() % 8; i < ration; i++) print(id, 24 + i * 4, "nom"), sleep(1); for (i = 0; i < 2; i++) unlock(forks + f[i]); } void think(int id) { int i, t; char buf[64] = {0}; do { clear_eol(id); sprintf(buf, "..oO (%s)", topic[t = rand() % M]); for (i = 0; buf[i]; i++) { print(id, i+12, "%c", buf[i]); if (i < 5) usleep(200000); } usleep(500000 + rand() % 1000000); } while (t); } void* philosophize(void *a) { int id = *(int*)a; print(id, 1, "%10s", names[id]); while(1) think(id), eat(id); } int main() { int i, id[N]; pthread_t tid[N]; for (i = 0; i < N; i++) pthread_mutex_init(forks + (id[i] = i), 0); for (i = 0; i < N; i++) pthread_create(tid + i, 0, philosophize, id + i); return pthread_join(tid[0], 0); }
Generate an equivalent C version of this Python code.
fact = [1] for n in range(1, 12): fact.append(fact[n-1] * n) for b in range(9, 12+1): print(f"The factorions for base {b} are:") for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j % b fact_sum += fact[d] j = j//b if fact_sum == i: print(i, end=" ") print("\n")
#include <stdio.h> int main() { int n, b, d; unsigned long long i, j, sum, fact[12]; fact[0] = 1; for (n = 1; n < 12; ++n) { fact[n] = fact[n-1] * n; } for (b = 9; b <= 12; ++b) { printf("The factorions for base %d are:\n", b); for (i = 1; i < 1500000; ++i) { sum = 0; j = i; while (j > 0) { d = j % b; sum += fact[d]; j /= b; } if (sum == i) printf("%llu ", i); } printf("\n\n"); } return 0; }
Write the same code in C as shown below in Python.
fact = [1] for n in range(1, 12): fact.append(fact[n-1] * n) for b in range(9, 12+1): print(f"The factorions for base {b} are:") for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j % b fact_sum += fact[d] j = j//b if fact_sum == i: print(i, end=" ") print("\n")
#include <stdio.h> int main() { int n, b, d; unsigned long long i, j, sum, fact[12]; fact[0] = 1; for (n = 1; n < 12; ++n) { fact[n] = fact[n-1] * n; } for (b = 9; b <= 12; ++b) { printf("The factorions for base %d are:\n", b); for (i = 1; i < 1500000; ++i) { sum = 0; j = i; while (j > 0) { d = j % b; sum += fact[d]; j /= b; } if (sum == i) printf("%llu ", i); } printf("\n\n"); } return 0; }
Change the programming language of this snippet from Python to C without modifying what it does.
import numpy as np import scipy.optimize as opt n0, K = 27, 7_800_000_000 def f(t, r): return (n0 * np.exp(r * t)) / (( 1 + n0 * (np.exp(r * t) - 1) / K)) y = [ 27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497, 133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364, 271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704, 656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652, ] x = np.linspace(0.0, 96, 97) r, cov = opt.curve_fit(f, x, y, [0.5]) print("The r for the world Covid-19 data is:", r, ", with covariance of", cov) print("The calculated R0 is then", np.exp(12 * r))
#include <math.h> #include <stdio.h> const double K = 7.8e9; const int n0 = 27; const double actual[] = { 27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497, 133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364, 271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704, 656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652 }; const size_t actual_size = sizeof(actual) / sizeof(double); double f(double r) { double sq = 0; size_t i; for (i = 0; i < actual_size; ++i) { double eri = exp(r * i); double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K); double diff = guess - actual[i]; sq += diff * diff; } return sq; } double solve(double (*fn)(double), double guess, double epsilon) { double delta, f0, factor; for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2; delta > epsilon && guess != guess - delta; delta *= factor) { double nf = (*fn)(guess - delta); if (nf < f0) { f0 = nf; guess -= delta; } else { nf = fn(guess + delta); if (nf < f0) { f0 = nf; guess += delta; } else { factor = 0.5; } } } return guess; } double solve_default(double (*fn)(double)) { return solve(fn, 0.5, 0); } int main() { double r = solve_default(f); double R0 = exp(12 * r); printf("r = %f, R0 = %f\n", r, R0); return 0; }
Port the following code from Python to C with equivalent syntax and logic.
def merge_list(a, b): out = [] while len(a) and len(b): if a[0] < b[0]: out.append(a.pop(0)) else: out.append(b.pop(0)) out += a out += b return out def strand(a): i, s = 0, [a.pop(0)] while i < len(a): if a[i] > s[-1]: s.append(a.pop(i)) else: i += 1 return s def strand_sort(a): out = strand(a) while len(a): out = merge_list(out, strand(a)) return out print strand_sort([1, 6, 3, 2, 1, 7, 5, 3])
#include <stdio.h> typedef struct node_t *node, node_t; struct node_t { int v; node next; }; typedef struct { node head, tail; } slist; void push(slist *l, node e) { if (!l->head) l->head = e; if (l->tail) l->tail->next = e; l->tail = e; } node removehead(slist *l) { node e = l->head; if (e) { l->head = e->next; e->next = 0; } return e; } void join(slist *a, slist *b) { push(a, b->head); a->tail = b->tail; } void merge(slist *a, slist *b) { slist r = {0}; while (a->head && b->head) push(&r, removehead(a->head->v <= b->head->v ? a : b)); join(&r, a->head ? a : b); *a = r; b->head = b->tail = 0; } void sort(int *ar, int len) { node_t all[len]; for (int i = 0; i < len; i++) all[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0; slist list = {all, all + len - 1}, rem, strand = {0}, res = {0}; for (node e = 0; list.head; list = rem) { rem.head = rem.tail = 0; while ((e = removehead(&list))) push((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e); merge(&res, &strand); } for (int i = 0; res.head; i++, res.head = res.head->next) ar[i] = res.head->v; } void show(const char *title, int *x, int len) { printf("%s ", title); for (int i = 0; i < len; i++) printf("%3d ", x[i]); putchar('\n'); } int main(void) { int x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2}; # define SIZE sizeof(x)/sizeof(int) show("before sort:", x, SIZE); sort(x, sizeof(x)/sizeof(int)); show("after sort: ", x, SIZE); return 0; }
Produce a language-to-language conversion: from Python to C, same semantics.
def is_prime(n: int) -> bool: if n <= 3: return n > 1 if n % 2 == 0 or n % 3 == 0: return False i = 5 while i ** 2 <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def digit_sum(n: int) -> int: sum = 0 while n > 0: sum += n % 10 n //= 10 return sum def main() -> None: additive_primes = 0 for i in range(2, 500): if is_prime(i) and is_prime(digit_sum(i)): additive_primes += 1 print(i, end=" ") print(f"\nFound {additive_primes} additive primes less than 500") if __name__ == "__main__": main()
#include <stdbool.h> #include <stdio.h> #include <string.h> void memoizeIsPrime( bool * result, const int N ) { result[2] = true; result[3] = true; int prime[N]; prime[0] = 3; int end = 1; for (int n = 5; n < N; n += 2) { bool n_is_prime = true; for (int i = 0; i < end; ++i) { const int PRIME = prime[i]; if (n % PRIME == 0) { n_is_prime = false; break; } if (PRIME * PRIME > n) { break; } } if (n_is_prime) { prime[end++] = n; result[n] = true; } } } int sumOfDecimalDigits( int n ) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } int main( void ) { const int N = 500; printf( "Rosetta Code: additive primes less than %d:\n", N ); bool is_prime[N]; memset( is_prime, 0, sizeof(is_prime) ); memoizeIsPrime( is_prime, N ); printf( " 2" ); int count = 1; for (int i = 3; i < N; i += 2) { if (is_prime[i] && is_prime[sumOfDecimalDigits( i )]) { printf( "%4d", i ); ++count; if ((count % 10) == 0) { printf( "\n" ); } } } printf( "\nThose were %d additive primes.\n", count ); return 0; }
Convert this Python block to C, preserving its control flow and logic.
x = truevalue if condition else falsevalue
#include <stdio.h> #include <stdlib.h> #define otherwise do { register int _o = 2; do { switch (_o) { case 1: #define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0) int foo() { return 1; } main() { int a = 0; otherwise a = 4 given (foo()); printf("%d\n", a); exit(0); }
Change the following Python code into C without altering its purpose.
x = truevalue if condition else falsevalue
#include <stdio.h> #include <stdlib.h> #define otherwise do { register int _o = 2; do { switch (_o) { case 1: #define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0) int foo() { return 1; } main() { int a = 0; otherwise a = 4 given (foo()); printf("%d\n", a); exit(0); }
Generate an equivalent C version of this Python code.
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts += n if parts == n0: yield n0 if __name__ == '__main__': print(list(islice(perfect_totient(), 20)))
#include<stdlib.h> #include<stdio.h> long totient(long n){ long tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } long* perfectTotients(long n){ long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot; for(m=1;count<n;m++){ tot = m; sum = 0; while(tot != 1){ tot = totient(tot); sum += tot; } if(sum == m) ptList[count++] = m; } return ptList; } long main(long argC, char* argV[]) { long *ptList,i,n; if(argC!=2) printf("Usage : %s <number of perfect Totient numbers required>",argV[0]); else{ n = atoi(argV[1]); ptList = perfectTotients(n); printf("The first %d perfect Totient numbers are : \n[",n); for(i=0;i<n;i++) printf(" %d,",ptList[i]); printf("\b]"); } return 0; }
Convert this Python snippet to C and keep its semantics consistent.
from math import gcd from functools import lru_cache from itertools import islice, count @lru_cache(maxsize=None) def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) def perfect_totient(): for n0 in count(1): parts, n = 0, n0 while n != 1: n = φ(n) parts += n if parts == n0: yield n0 if __name__ == '__main__': print(list(islice(perfect_totient(), 20)))
#include<stdlib.h> #include<stdio.h> long totient(long n){ long tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } long* perfectTotients(long n){ long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot; for(m=1;count<n;m++){ tot = m; sum = 0; while(tot != 1){ tot = totient(tot); sum += tot; } if(sum == m) ptList[count++] = m; } return ptList; } long main(long argC, char* argV[]) { long *ptList,i,n; if(argC!=2) printf("Usage : %s <number of perfect Totient numbers required>",argV[0]); else{ n = atoi(argV[1]); ptList = perfectTotients(n); printf("The first %d perfect Totient numbers are : \n[",n); for(i=0;i<n;i++) printf(" %d,",ptList[i]); printf("\b]"); } return 0; }
Transform the following Python implementation into C, maintaining the same output and logic.
class Delegator: def __init__(self): self.delegate = None def operation(self): if hasattr(self.delegate, 'thing') and callable(self.delegate.thing): return self.delegate.thing() return 'default implementation' class Delegate: def thing(self): return 'delegate implementation' if __name__ == '__main__': a = Delegator() assert a.operation() == 'default implementation' a.delegate = 'A delegate may be any object' assert a.operation() == 'default implementation' a.delegate = Delegate() assert a.operation() == 'delegate implementation'
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef const char * (*Responder)( int p1); typedef struct sDelegate { Responder operation; } *Delegate; Delegate NewDelegate( Responder rspndr ) { Delegate dl = malloc(sizeof(struct sDelegate)); dl->operation = rspndr; return dl; } const char *DelegateThing(Delegate dl, int p1) { return (dl->operation)? (*dl->operation)(p1) : NULL; } typedef struct sDelegator { int param; char *phrase; Delegate delegate; } *Delegator; const char * defaultResponse( int p1) { return "default implementation"; } static struct sDelegate defaultDel = { &defaultResponse }; Delegator NewDelegator( int p, char *phrase) { Delegator d = malloc(sizeof(struct sDelegator)); d->param = p; d->phrase = phrase; d->delegate = &defaultDel; return d; } const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy) { const char *rtn; if (delroy) { rtn = DelegateThing(delroy, p1); if (!rtn) { rtn = DelegateThing(theDelegator->delegate, p1); } } else rtn = DelegateThing(theDelegator->delegate, p1); printf("%s\n", theDelegator->phrase ); return rtn; } const char *thing1( int p1) { printf("We're in thing1 with value %d\n" , p1); return "delegate implementation"; } int main() { Delegate del1 = NewDelegate(&thing1); Delegate del2 = NewDelegate(NULL); Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby."); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, NULL)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del1)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del2)); return 0; }
Convert this Python block to C, preserving its control flow and logic.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //= p if 0 < k: yield (p,k) p += 2 if 1 < n: yield (n,1) def sum_of_divisors(n): assert(n != 0) ans = 1 for (p,k) in factorize(n): ans *= (pow(p,k+1) - 1)//(p-1) return ans if __name__ == "__main__": print([sum_of_divisors(n) for n in range(1,101)])
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Sum of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%4d", divisor_sum(n)); if (n % 10 == 0) { printf("\n"); } } return 0; }
Change the following Python code into C without altering its purpose.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //= p if 0 < k: yield (p,k) p += 2 if 1 < n: yield (n,1) def sum_of_divisors(n): assert(n != 0) ans = 1 for (p,k) in factorize(n): ans *= (pow(p,k+1) - 1)//(p-1) return ans if __name__ == "__main__": print([sum_of_divisors(n) for n in range(1,101)])
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Sum of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%4d", divisor_sum(n)); if (n % 10 == 0) { printf("\n"); } } return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
command_table_text = \ user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() for word in command_table_text.split(): abbr_len = sum(1 for c in word if c.isupper()) if abbr_len == 0: abbr_len = len(word) command_table[word] = abbr_len return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } size_t get_min_length(const char* str, size_t n) { size_t len = 0; while (len < n && isupper((unsigned char)str[len])) ++len; return len; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = get_min_length(word, word_len); new_cmd->cmd = uppercase(word, word_len); new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Write a version of this Python function in C with identical behavior.
command_table_text = \ user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() for word in command_table_text.split(): abbr_len = sum(1 for c in word if c.isupper()) if abbr_len == 0: abbr_len = len(word) command_table[word] = abbr_len return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } size_t get_min_length(const char* str, size_t n) { size_t len = 0; while (len < n && isupper((unsigned char)str[len])) ++len; return len; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = get_min_length(word, word_len); new_cmd->cmd = uppercase(word, word_len); new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Produce a language-to-language conversion: from Python to C, same semantics.
>>> s = "Hello" >>> s[0] = "h" Traceback (most recent call last): File "<pyshell s[0] = "h" TypeError: 'str' object does not support item assignment
#define PI 3.14159265358979323 #define MINSIZE 10 #define MAXSIZE 100
Convert the following code from Python to C, ensuring the logic remains intact.
def clip(subjectPolygon, clipPolygon): def inside(p): return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]) def computeIntersection(): dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ] dp = [ s[0] - e[0], s[1] - e[1] ] n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0] n2 = s[0] * e[1] - s[1] * e[0] n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]) return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3] outputList = subjectPolygon cp1 = clipPolygon[-1] for clipVertex in clipPolygon: cp2 = clipVertex inputList = outputList outputList = [] s = inputList[-1] for subjectVertex in inputList: e = subjectVertex if inside(e): if not inside(s): outputList.append(computeIntersection()) outputList.append(e) elif inside(s): outputList.append(computeIntersection()) s = e cp1 = cp2 return(outputList)
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { double x, y; } vec_t, *vec; inline double dot(vec a, vec b) { return a->x * b->x + a->y * b->y; } inline double cross(vec a, vec b) { return a->x * b->y - a->y * b->x; } inline vec vsub(vec a, vec b, vec res) { res->x = a->x - b->x; res->y = a->y - b->y; return res; } int left_of(vec a, vec b, vec c) { vec_t tmp1, tmp2; double x; vsub(b, a, &tmp1); vsub(c, b, &tmp2); x = cross(&tmp1, &tmp2); return x < 0 ? -1 : x > 0; } int line_sect(vec x0, vec x1, vec y0, vec y1, vec res) { vec_t dx, dy, d; vsub(x1, x0, &dx); vsub(y1, y0, &dy); vsub(x0, y0, &d); double dyx = cross(&dy, &dx); if (!dyx) return 0; dyx = cross(&d, &dx) / dyx; if (dyx <= 0 || dyx >= 1) return 0; res->x = y0->x + dyx * dy.x; res->y = y0->y + dyx * dy.y; return 1; } typedef struct { int len, alloc; vec v; } poly_t, *poly; poly poly_new() { return (poly)calloc(1, sizeof(poly_t)); } void poly_free(poly p) { free(p->v); free(p); } void poly_append(poly p, vec v) { if (p->len >= p->alloc) { p->alloc *= 2; if (!p->alloc) p->alloc = 4; p->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc); } p->v[p->len++] = *v; } int poly_winding(poly p) { return left_of(p->v, p->v + 1, p->v + 2); } void poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res) { int i, side0, side1; vec_t tmp; vec v0 = sub->v + sub->len - 1, v1; res->len = 0; side0 = left_of(x0, x1, v0); if (side0 != -left) poly_append(res, v0); for (i = 0; i < sub->len; i++) { v1 = sub->v + i; side1 = left_of(x0, x1, v1); if (side0 + side1 == 0 && side0) if (line_sect(x0, x1, v0, v1, &tmp)) poly_append(res, &tmp); if (i == sub->len - 1) break; if (side1 != -left) poly_append(res, v1); v0 = v1; side0 = side1; } } poly poly_clip(poly sub, poly clip) { int i; poly p1 = poly_new(), p2 = poly_new(), tmp; int dir = poly_winding(clip); poly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2); for (i = 0; i < clip->len - 1; i++) { tmp = p2; p2 = p1; p1 = tmp; if(p1->len == 0) { p2->len = 0; break; } poly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2); } poly_free(p1); return p2; } int main() { int i; vec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}}; vec_t s[] = { {50,150}, {200,50}, {350,150}, {350,300},{250,300},{200,250}, {150,350},{100,250},{100,200}}; #define clen (sizeof(c)/sizeof(vec_t)) #define slen (sizeof(s)/sizeof(vec_t)) poly_t clipper = {clen, 0, c}; poly_t subject = {slen, 0, s}; poly res = poly_clip(&subject, &clipper); for (i = 0; i < res->len; i++) printf("%g %g\n", res->v[i].x, res->v[i].y); FILE * eps = fopen("test.eps", "w"); fprintf(eps, "%%!PS-Adobe-3.0\n%%%%BoundingBox: 40 40 360 360\n" "/l {lineto} def /m{moveto} def /s{setrgbcolor} def" "/c {closepath} def /gs {fill grestore stroke} def\n"); fprintf(eps, "0 setlinewidth %g %g m ", c[0].x, c[0].y); for (i = 1; i < clen; i++) fprintf(eps, "%g %g l ", c[i].x, c[i].y); fprintf(eps, "c .5 0 0 s gsave 1 .7 .7 s gs\n"); fprintf(eps, "%g %g m ", s[0].x, s[0].y); for (i = 1; i < slen; i++) fprintf(eps, "%g %g l ", s[i].x, s[i].y); fprintf(eps, "c 0 .2 .5 s gsave .4 .7 1 s gs\n"); fprintf(eps, "2 setlinewidth [10 8] 0 setdash %g %g m ", res->v[0].x, res->v[0].y); for (i = 1; i < res->len; i++) fprintf(eps, "%g %g l ", res->v[i].x, res->v[i].y); fprintf(eps, "c .5 0 .5 s gsave .7 .3 .8 s gs\n"); fprintf(eps, "%%%%EOF"); fclose(eps); printf("test.eps written\n"); return 0; }
Generate an equivalent C version of this Python code.
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
#include <stdio.h> #include <string.h> #include <stdlib.h> char *codes[] = { "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", "BBAAA", "BBAAB", "BBBAA" }; char *get_code(const char c) { if (c >= 97 && c <= 122) return codes[c - 97]; return codes[26]; } char get_char(const char *code) { int i; if (!strcmp(codes[26], code)) return ' '; for (i = 0; i < 26; ++i) { if (strcmp(codes[i], code) == 0) return 97 + i; } printf("\nCode \"%s\" is invalid\n", code); exit(1); } void str_tolower(char s[]) { int i; for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]); } char *bacon_encode(char plain_text[], char message[]) { int i, count; int plen = strlen(plain_text), mlen = strlen(message); int elen = 5 * plen; char c; char *p, *et, *mt; et = malloc(elen + 1); str_tolower(plain_text); for (i = 0, p = et; i < plen; ++i, p += 5) { c = plain_text[i]; strncpy(p, get_code(c), 5); } *++p = '\0'; str_tolower(message); mt = calloc(mlen + 1, 1); for (i = 0, count = 0; i < mlen; ++i) { c = message[i]; if (c >= 'a' && c <= 'z') { if (et[count] == 'A') mt[i] = c; else mt[i] = c - 32; if (++count == elen) break; } else mt[i] = c; } free(et); return mt; } char *bacon_decode(char cipher_text[]) { int i, count, clen = strlen(cipher_text); int plen; char *p, *ct, *pt; char c, quintet[6]; ct = calloc(clen + 1, 1); for (i = 0, count = 0; i < clen; ++i) { c = cipher_text[i]; if (c >= 'a' && c <= 'z') ct[count++] = 'A'; else if (c >= 'A' && c <= 'Z') ct[count++] = 'B'; } plen = strlen(ct) / 5; pt = malloc(plen + 1); for (i = 0, p = ct; i < plen; ++i, p += 5) { strncpy(quintet, p, 5); quintet[5] = '\0'; pt[i] = get_char(quintet); } pt[plen] = '\0'; free(ct); return pt; } int main() { char plain_text[] = "the quick brown fox jumps over the lazy dog"; char message[] = "bacon's cipher is a method of steganography created by francis bacon." "this task is to implement a program for encryption and decryption of " "plaintext using the simple alphabet of the baconian cipher or some " "other kind of representation of this alphabet (make anything signify anything). " "the baconian alphabet may optionally be extended to encode all lower " "case characters individually and/or adding a few punctuation characters " "such as the space."; char *cipher_text, *hidden_text; cipher_text = bacon_encode(plain_text, message); printf("Cipher text ->\n\n%s\n", cipher_text); hidden_text = bacon_decode(cipher_text); printf("\nHidden text ->\n\n%s\n", hidden_text); free(cipher_text); free(hidden_text); return 0; }
Generate a C translation of this Python snippet without changing its computational steps.
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
#include <stdio.h> #include <string.h> #include <stdlib.h> char *codes[] = { "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", "BBAAA", "BBAAB", "BBBAA" }; char *get_code(const char c) { if (c >= 97 && c <= 122) return codes[c - 97]; return codes[26]; } char get_char(const char *code) { int i; if (!strcmp(codes[26], code)) return ' '; for (i = 0; i < 26; ++i) { if (strcmp(codes[i], code) == 0) return 97 + i; } printf("\nCode \"%s\" is invalid\n", code); exit(1); } void str_tolower(char s[]) { int i; for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]); } char *bacon_encode(char plain_text[], char message[]) { int i, count; int plen = strlen(plain_text), mlen = strlen(message); int elen = 5 * plen; char c; char *p, *et, *mt; et = malloc(elen + 1); str_tolower(plain_text); for (i = 0, p = et; i < plen; ++i, p += 5) { c = plain_text[i]; strncpy(p, get_code(c), 5); } *++p = '\0'; str_tolower(message); mt = calloc(mlen + 1, 1); for (i = 0, count = 0; i < mlen; ++i) { c = message[i]; if (c >= 'a' && c <= 'z') { if (et[count] == 'A') mt[i] = c; else mt[i] = c - 32; if (++count == elen) break; } else mt[i] = c; } free(et); return mt; } char *bacon_decode(char cipher_text[]) { int i, count, clen = strlen(cipher_text); int plen; char *p, *ct, *pt; char c, quintet[6]; ct = calloc(clen + 1, 1); for (i = 0, count = 0; i < clen; ++i) { c = cipher_text[i]; if (c >= 'a' && c <= 'z') ct[count++] = 'A'; else if (c >= 'A' && c <= 'Z') ct[count++] = 'B'; } plen = strlen(ct) / 5; pt = malloc(plen + 1); for (i = 0, p = ct; i < plen; ++i, p += 5) { strncpy(quintet, p, 5); quintet[5] = '\0'; pt[i] = get_char(quintet); } pt[plen] = '\0'; free(ct); return pt; } int main() { char plain_text[] = "the quick brown fox jumps over the lazy dog"; char message[] = "bacon's cipher is a method of steganography created by francis bacon." "this task is to implement a program for encryption and decryption of " "plaintext using the simple alphabet of the baconian cipher or some " "other kind of representation of this alphabet (make anything signify anything). " "the baconian alphabet may optionally be extended to encode all lower " "case characters individually and/or adding a few punctuation characters " "such as the space."; char *cipher_text, *hidden_text; cipher_text = bacon_encode(plain_text, message); printf("Cipher text ->\n\n%s\n", cipher_text); hidden_text = bacon_decode(cipher_text); printf("\nHidden text ->\n\n%s\n", hidden_text); free(cipher_text); free(hidden_text); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
def spiral(n): dx,dy = 1,0 x,y = 0,0 myarray = [[None]* n for j in range(n)] for i in xrange(n**2): myarray[x][y] = i nx,ny = x+dx, y+dy if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None: x,y = nx,ny else: dx,dy = -dy,dx x,y = x+dx, y+dy return myarray def printspiral(myarray): n = range(len(myarray)) for y in n: for x in n: print "%2i" % myarray[x][y], print printspiral(spiral(5))
#include <stdio.h> #include <stdlib.h> #define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j] int main(int c, char **v) { int i, j, m = 0, n = 0; if (c >= 2) m = atoi(v[1]); if (c >= 3) n = atoi(v[2]); if (m <= 0) m = 5; if (n <= 0) n = m; int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n); s[0] = (int*)(s + m); for (i = 1; i < m; i++) s[i] = s[i - 1] + n; int dx = 1, dy = 0, val = 0, t; for (i = j = 0; valid(i, j); i += dy, j += dx ) { for (; valid(i, j); j += dx, i += dy) s[i][j] = ++val; j -= dx; i -= dy; t = dy; dy = dx; dx = -t; } for (t = 2; val /= 10; t++); for(i = 0; i < m; i++) for(j = 0; j < n || !putchar('\n'); j++) printf("%*d", t, s[i][j]); return 0; }
Preserve the algorithm and functionality while converting the code from Python to C.
>>> def printtable(data): for row in data: print ' '.join('%-5s' % ('"%s"' % cell) for cell in row) >>> import operator >>> def sorttable(table, ordering=None, column=0, reverse=False): return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse) >>> data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]] >>> printtable(data) "a" "b" "c" "" "q" "z" "zap" "zip" "Zot" >>> printtable( sorttable(data) ) "" "q" "z" "a" "b" "c" "zap" "zip" "Zot" >>> printtable( sorttable(data, column=2) ) "zap" "zip" "Zot" "a" "b" "c" "" "q" "z" >>> printtable( sorttable(data, column=1) ) "a" "b" "c" "" "q" "z" "zap" "zip" "Zot" >>> printtable( sorttable(data, column=1, reverse=True) ) "zap" "zip" "Zot" "" "q" "z" "a" "b" "c" >>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) ) "zap" "zip" "Zot" "a" "b" "c" "" "q" "z" >>>
#include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> #include <string.h> typedef const char * String; typedef struct sTable { String * *rows; int n_rows,n_cols; } *Table; typedef int (*CompareFctn)(String a, String b); struct { CompareFctn compare; int column; int reversed; } sortSpec; int CmprRows( const void *aa, const void *bb) { String *rA = *(String *const *)aa; String *rB = *(String *const *)bb; int sortCol = sortSpec.column; String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol]; String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol]; return sortSpec.compare( left, right ); } int sortTable(Table tbl, const char* argSpec,... ) { va_list vl; const char *p; int c; sortSpec.compare = &strcmp; sortSpec.column = 0; sortSpec.reversed = 0; va_start(vl, argSpec); if (argSpec) for (p=argSpec; *p; p++) { switch (*p) { case 'o': sortSpec.compare = va_arg(vl,CompareFctn); break; case 'c': c = va_arg(vl,int); if ( 0<=c && c<tbl->n_cols) sortSpec.column = c; break; case 'r': sortSpec.reversed = (0!=va_arg(vl,int)); break; } } va_end(vl); qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows); return 0; } void printTable( Table tbl, FILE *fout, const char *colFmts[]) { int row, col; for (row=0; row<tbl->n_rows; row++) { fprintf(fout, " "); for(col=0; col<tbl->n_cols; col++) { fprintf(fout, colFmts[col], tbl->rows[row][col]); } fprintf(fout, "\n"); } fprintf(fout, "\n"); } int ord(char v) { return v-'0'; } int cmprStrgs(String s1, String s2) { const char *p1 = s1; const char *p2 = s2; const char *mrk1, *mrk2; while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++; } if (isdigit(*p1) && isdigit(*p2)) { long v1, v2; if ((*p1 == '0') ||(*p2 == '0')) { while (p1 > s1) { p1--; p2--; if (*p1 != '0') break; } if (!isdigit(*p1)) { p1++; p2++; } } mrk1 = p1; mrk2 = p2; v1 = 0; while(isdigit(*p1)) { v1 = 10*v1+ord(*p1); p1++; } v2 = 0; while(isdigit(*p2)) { v2 = 10*v2+ord(*p2); p2++; } if (v1 == v2) return(p2-mrk2)-(p1-mrk1); return v1 - v2; } if (tolower(*p1) != tolower(*p2)) return (tolower(*p1) - tolower(*p2)); for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++); return (*p1 -*p2); } int main() { const char *colFmts[] = {" %-5.5s"," %-5.5s"," %-9.9s"}; String r1[] = { "a101", "red", "Java" }; String r2[] = { "ab40", "gren", "Smalltalk" }; String r3[] = { "ab9", "blue", "Fortran" }; String r4[] = { "ab09", "ylow", "Python" }; String r5[] = { "ab1a", "blak", "Factor" }; String r6[] = { "ab1b", "brwn", "C Sharp" }; String r7[] = { "Ab1b", "pink", "Ruby" }; String r8[] = { "ab1", "orng", "Scheme" }; String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 }; struct sTable table; table.rows = rows; table.n_rows = 8; table.n_cols = 3; sortTable(&table, ""); printf("sort on col 0, ascending\n"); printTable(&table, stdout, colFmts); sortTable(&table, "ro", 1, &cmprStrgs); printf("sort on col 0, reverse.special\n"); printTable(&table, stdout, colFmts); sortTable(&table, "c", 1); printf("sort on col 1, ascending\n"); printTable(&table, stdout, colFmts); sortTable(&table, "cr", 2, 1); printf("sort on col 2, reverse\n"); printTable(&table, stdout, colFmts); return 0; }
Convert the following code from Python to C, ensuring the logic remains intact.
def setup(): size(500, 500) generate_voronoi_diagram(width, height, 25) saveFrame("VoronoiDiagram.png") def generate_voronoi_diagram(w, h, num_cells): nx, ny, nr, ng, nb = [], [], [], [], [] for i in range(num_cells): nx.append(int(random(w))) ny.append(int(random(h))) nr.append(int(random(256))) ng.append(int(random(256))) nb.append(int(random(256))) for y in range(h): for x in range(w): dmin = dist(0, 0, w - 1, h - 1) j = -1 for i in range(num_cells): d = dist(0, 0, nx[i] - x, ny[i] - y) if d < dmin: dmin = d j = i set(x, y, color(nr[j], ng[j], nb[j]))
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N_SITES 150 double site[N_SITES][2]; unsigned char rgb[N_SITES][3]; int size_x = 640, size_y = 480; inline double sq2(double x, double y) { return x * x + y * y; } #define for_k for (k = 0; k < N_SITES; k++) int nearest_site(double x, double y) { int k, ret = 0; double d, dist = 0; for_k { d = sq2(x - site[k][0], y - site[k][1]); if (!k || d < dist) { dist = d, ret = k; } } return ret; } int at_edge(int *color, int y, int x) { int i, j, c = color[y * size_x + x]; for (i = y - 1; i <= y + 1; i++) { if (i < 0 || i >= size_y) continue; for (j = x - 1; j <= x + 1; j++) { if (j < 0 || j >= size_x) continue; if (color[i * size_x + j] != c) return 1; } } return 0; } #define AA_RES 4 void aa_color(unsigned char *pix, int y, int x) { int i, j, n; double r = 0, g = 0, b = 0, xx, yy; for (i = 0; i < AA_RES; i++) { yy = y + 1. / AA_RES * i + .5; for (j = 0; j < AA_RES; j++) { xx = x + 1. / AA_RES * j + .5; n = nearest_site(xx, yy); r += rgb[n][0]; g += rgb[n][1]; b += rgb[n][2]; } } pix[0] = r / (AA_RES * AA_RES); pix[1] = g / (AA_RES * AA_RES); pix[2] = b / (AA_RES * AA_RES); } #define for_i for (i = 0; i < size_y; i++) #define for_j for (j = 0; j < size_x; j++) void gen_map() { int i, j, k; int *nearest = malloc(sizeof(int) * size_y * size_x); unsigned char *ptr, *buf, color; ptr = buf = malloc(3 * size_x * size_y); for_i for_j nearest[i * size_x + j] = nearest_site(j, i); for_i for_j { if (!at_edge(nearest, i, j)) memcpy(ptr, rgb[nearest[i * size_x + j]], 3); else aa_color(ptr, i, j); ptr += 3; } for (k = 0; k < N_SITES; k++) { color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255; for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) { if (i < 0 || i >= size_y) continue; for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) { if (j < 0 || j >= size_x) continue; ptr = buf + 3 * (i * size_x + j); ptr[0] = ptr[1] = ptr[2] = color; } } } printf("P6\n%d %d\n255\n", size_x, size_y); fflush(stdout); fwrite(buf, size_y * size_x * 3, 1, stdout); } #define frand(x) (rand() / (1. + RAND_MAX) * x) int main() { int k; for_k { site[k][0] = frand(size_x); site[k][1] = frand(size_y); rgb [k][0] = frand(256); rgb [k][1] = frand(256); rgb [k][2] = frand(256); } gen_map(); return 0; }
Write the same code in C as shown below in Python.
def setup(): size(500, 500) generate_voronoi_diagram(width, height, 25) saveFrame("VoronoiDiagram.png") def generate_voronoi_diagram(w, h, num_cells): nx, ny, nr, ng, nb = [], [], [], [], [] for i in range(num_cells): nx.append(int(random(w))) ny.append(int(random(h))) nr.append(int(random(256))) ng.append(int(random(256))) nb.append(int(random(256))) for y in range(h): for x in range(w): dmin = dist(0, 0, w - 1, h - 1) j = -1 for i in range(num_cells): d = dist(0, 0, nx[i] - x, ny[i] - y) if d < dmin: dmin = d j = i set(x, y, color(nr[j], ng[j], nb[j]))
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N_SITES 150 double site[N_SITES][2]; unsigned char rgb[N_SITES][3]; int size_x = 640, size_y = 480; inline double sq2(double x, double y) { return x * x + y * y; } #define for_k for (k = 0; k < N_SITES; k++) int nearest_site(double x, double y) { int k, ret = 0; double d, dist = 0; for_k { d = sq2(x - site[k][0], y - site[k][1]); if (!k || d < dist) { dist = d, ret = k; } } return ret; } int at_edge(int *color, int y, int x) { int i, j, c = color[y * size_x + x]; for (i = y - 1; i <= y + 1; i++) { if (i < 0 || i >= size_y) continue; for (j = x - 1; j <= x + 1; j++) { if (j < 0 || j >= size_x) continue; if (color[i * size_x + j] != c) return 1; } } return 0; } #define AA_RES 4 void aa_color(unsigned char *pix, int y, int x) { int i, j, n; double r = 0, g = 0, b = 0, xx, yy; for (i = 0; i < AA_RES; i++) { yy = y + 1. / AA_RES * i + .5; for (j = 0; j < AA_RES; j++) { xx = x + 1. / AA_RES * j + .5; n = nearest_site(xx, yy); r += rgb[n][0]; g += rgb[n][1]; b += rgb[n][2]; } } pix[0] = r / (AA_RES * AA_RES); pix[1] = g / (AA_RES * AA_RES); pix[2] = b / (AA_RES * AA_RES); } #define for_i for (i = 0; i < size_y; i++) #define for_j for (j = 0; j < size_x; j++) void gen_map() { int i, j, k; int *nearest = malloc(sizeof(int) * size_y * size_x); unsigned char *ptr, *buf, color; ptr = buf = malloc(3 * size_x * size_y); for_i for_j nearest[i * size_x + j] = nearest_site(j, i); for_i for_j { if (!at_edge(nearest, i, j)) memcpy(ptr, rgb[nearest[i * size_x + j]], 3); else aa_color(ptr, i, j); ptr += 3; } for (k = 0; k < N_SITES; k++) { color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255; for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) { if (i < 0 || i >= size_y) continue; for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) { if (j < 0 || j >= size_x) continue; ptr = buf + 3 * (i * size_x + j); ptr[0] = ptr[1] = ptr[2] = color; } } } printf("P6\n%d %d\n255\n", size_x, size_y); fflush(stdout); fwrite(buf, size_y * size_x * 3, 1, stdout); } #define frand(x) (rand() / (1. + RAND_MAX) * x) int main() { int k; for_k { site[k][0] = frand(size_x); site[k][1] = frand(size_y); rgb [k][0] = frand(256); rgb [k][1] = frand(256); rgb [k][2] = frand(256); } gen_map(); return 0; }
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
import ctypes libc = ctypes.CDLL("/lib/libc.so.6") libc.strcmp("abc", "def") libc.strcmp("hello", "hello")
#include <stdio.h> void sayHello(char* name){ printf("Hello %s!\n", name); } int doubleNum(int num){ return num * 2; }
Write the same algorithm in C as shown in this Python implementation.
from random import randrange def s_of_n_creator(n): sample, i = [], 0 def s_of_n(item): nonlocal i i += 1 if i <= n: sample.append(item) elif randrange(i) < n: sample[randrange(n)] = item return sample return s_of_n if __name__ == '__main__': bin = [0]* 10 items = range(10) print("Single run samples for n = 3:") s_of_n = s_of_n_creator(3) for item in items: sample = s_of_n(item) print(" Item: %i -> sample: %s" % (item, sample)) for trial in range(100000): s_of_n = s_of_n_creator(3) for item in items: sample = s_of_n(item) for s in sample: bin[s] += 1 print("\nTest item frequencies for 100000 runs:\n ", '\n '.join("%i:%i" % x for x in enumerate(bin)))
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> struct s_env { unsigned int n, i; size_t size; void *sample; }; void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n) { s_env->i = 0; s_env->n = n; s_env->size = size; s_env->sample = malloc(n * size); } void sample_set_i(struct s_env *s_env, unsigned int i, void *item) { memcpy(s_env->sample + i * s_env->size, item, s_env->size); } void *s_of_n(struct s_env *s_env, void *item) { s_env->i++; if (s_env->i <= s_env->n) sample_set_i(s_env, s_env->i - 1, item); else if ((rand() % s_env->i) < s_env->n) sample_set_i(s_env, rand() % s_env->n, item); return s_env->sample; } int *test(unsigned int n, int *items_set, unsigned int num_items) { int i; struct s_env s_env; s_of_n_init(&s_env, sizeof(items_set[0]), n); for (i = 0; i < num_items; i++) { s_of_n(&s_env, (void *) &items_set[i]); } return (int *)s_env.sample; } int main() { unsigned int i, j; unsigned int n = 3; unsigned int num_items = 10; unsigned int *frequencies; int *items_set; srand(time(NULL)); items_set = malloc(num_items * sizeof(int)); frequencies = malloc(num_items * sizeof(int)); for (i = 0; i < num_items; i++) { items_set[i] = i; frequencies[i] = 0; } for (i = 0; i < 100000; i++) { int *res = test(n, items_set, num_items); for (j = 0; j < n; j++) { frequencies[res[j]]++; } free(res); } for (i = 0; i < num_items; i++) { printf(" %d", frequencies[i]); } puts(""); return 0; }
Generate a C translation of this Python snippet without changing its computational steps.
from random import randrange def s_of_n_creator(n): sample, i = [], 0 def s_of_n(item): nonlocal i i += 1 if i <= n: sample.append(item) elif randrange(i) < n: sample[randrange(n)] = item return sample return s_of_n if __name__ == '__main__': bin = [0]* 10 items = range(10) print("Single run samples for n = 3:") s_of_n = s_of_n_creator(3) for item in items: sample = s_of_n(item) print(" Item: %i -> sample: %s" % (item, sample)) for trial in range(100000): s_of_n = s_of_n_creator(3) for item in items: sample = s_of_n(item) for s in sample: bin[s] += 1 print("\nTest item frequencies for 100000 runs:\n ", '\n '.join("%i:%i" % x for x in enumerate(bin)))
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> struct s_env { unsigned int n, i; size_t size; void *sample; }; void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n) { s_env->i = 0; s_env->n = n; s_env->size = size; s_env->sample = malloc(n * size); } void sample_set_i(struct s_env *s_env, unsigned int i, void *item) { memcpy(s_env->sample + i * s_env->size, item, s_env->size); } void *s_of_n(struct s_env *s_env, void *item) { s_env->i++; if (s_env->i <= s_env->n) sample_set_i(s_env, s_env->i - 1, item); else if ((rand() % s_env->i) < s_env->n) sample_set_i(s_env, rand() % s_env->n, item); return s_env->sample; } int *test(unsigned int n, int *items_set, unsigned int num_items) { int i; struct s_env s_env; s_of_n_init(&s_env, sizeof(items_set[0]), n); for (i = 0; i < num_items; i++) { s_of_n(&s_env, (void *) &items_set[i]); } return (int *)s_env.sample; } int main() { unsigned int i, j; unsigned int n = 3; unsigned int num_items = 10; unsigned int *frequencies; int *items_set; srand(time(NULL)); items_set = malloc(num_items * sizeof(int)); frequencies = malloc(num_items * sizeof(int)); for (i = 0; i < num_items; i++) { items_set[i] = i; frequencies[i] = 0; } for (i = 0; i < 100000; i++) { int *res = test(n, items_set, num_items); for (j = 0; j < n; j++) { frequencies[res[j]]++; } free(res); } for (i = 0; i < num_items; i++) { printf(" %d", frequencies[i]); } puts(""); return 0; }
Port the provided Python code into C while preserving the original functionality.
from random import randrange def s_of_n_creator(n): sample, i = [], 0 def s_of_n(item): nonlocal i i += 1 if i <= n: sample.append(item) elif randrange(i) < n: sample[randrange(n)] = item return sample return s_of_n if __name__ == '__main__': bin = [0]* 10 items = range(10) print("Single run samples for n = 3:") s_of_n = s_of_n_creator(3) for item in items: sample = s_of_n(item) print(" Item: %i -> sample: %s" % (item, sample)) for trial in range(100000): s_of_n = s_of_n_creator(3) for item in items: sample = s_of_n(item) for s in sample: bin[s] += 1 print("\nTest item frequencies for 100000 runs:\n ", '\n '.join("%i:%i" % x for x in enumerate(bin)))
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> struct s_env { unsigned int n, i; size_t size; void *sample; }; void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n) { s_env->i = 0; s_env->n = n; s_env->size = size; s_env->sample = malloc(n * size); } void sample_set_i(struct s_env *s_env, unsigned int i, void *item) { memcpy(s_env->sample + i * s_env->size, item, s_env->size); } void *s_of_n(struct s_env *s_env, void *item) { s_env->i++; if (s_env->i <= s_env->n) sample_set_i(s_env, s_env->i - 1, item); else if ((rand() % s_env->i) < s_env->n) sample_set_i(s_env, rand() % s_env->n, item); return s_env->sample; } int *test(unsigned int n, int *items_set, unsigned int num_items) { int i; struct s_env s_env; s_of_n_init(&s_env, sizeof(items_set[0]), n); for (i = 0; i < num_items; i++) { s_of_n(&s_env, (void *) &items_set[i]); } return (int *)s_env.sample; } int main() { unsigned int i, j; unsigned int n = 3; unsigned int num_items = 10; unsigned int *frequencies; int *items_set; srand(time(NULL)); items_set = malloc(num_items * sizeof(int)); frequencies = malloc(num_items * sizeof(int)); for (i = 0; i < num_items; i++) { items_set[i] = i; frequencies[i] = 0; } for (i = 0; i < 100000; i++) { int *res = test(n, items_set, num_items); for (j = 0; j < n; j++) { frequencies[res[j]]++; } free(res); } for (i = 0; i < num_items; i++) { printf(" %d", frequencies[i]); } puts(""); return 0; }
Rewrite the snippet below in C so it works the same as the original Python code.
from itertools import accumulate, chain, count, islice from fractions import Fraction def faulhaberTriangle(m): def go(rs, n): def f(x, y): return Fraction(n, x) * y xs = list(map(f, islice(count(2), m), rs)) return [Fraction(1 - sum(xs), 1)] + xs return list(accumulate( [[]] + list(islice(count(0), 1 + m)), go ))[1:] def faulhaberSum(p, n): def go(x, y): return y * (n ** x) return sum( map(go, count(1), faulhaberTriangle(p)[-1]) ) def main(): fs = faulhaberTriangle(9) print( fTable(__doc__ + ':\n')(str)( compose(concat)( fmap(showRatio(3)(3)) ) )( index(fs) )(range(0, len(fs))) ) print('') print( faulhaberSum(17, 1000) ) def fTable(s): def gox(xShow): def gofx(fxShow): def gof(f): def goxs(xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) def arrowed(x, y): return y.rjust(w, ' ') + ' -> ' + ( fxShow(f(x)) ) return s + '\n' + '\n'.join( map(arrowed, xs, ys) ) return goxs return gof return gofx return gox def compose(g): return lambda f: lambda x: g(f(x)) def concat(xs): def f(ys): zs = list(chain(*ys)) return ''.join(zs) if isinstance(ys[0], str) else zs return ( f(xs) if isinstance(xs, list) else ( chain.from_iterable(xs) ) ) if xs else [] def fmap(f): def go(xs): return list(map(f, xs)) return go def index(xs): return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, "__getitem__") ) else next(islice(xs, n, None)) ) def showRatio(m): def go(n): def f(r): d = r.denominator return str(r.numerator).rjust(m, ' ') + ( ('/' + str(d).ljust(n, ' ')) if 1 != d else ( ' ' * (1 + n) ) ) return f return go if __name__ == '__main__': main()
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int binomial(int n, int k) { int num, denom, i; if (n < 0 || k < 0 || n < k) return -1; if (n == 0 || k == 0) return 1; num = 1; for (i = k + 1; i <= n; ++i) { num = num * i; } denom = 1; for (i = 2; i <= n - k; ++i) { denom *= i; } return num / denom; } int gcd(int a, int b) { int temp; while (b != 0) { temp = a % b; a = b; b = temp; } return a; } typedef struct tFrac { int num, denom; } Frac; Frac makeFrac(int n, int d) { Frac result; int g; if (d == 0) { result.num = 0; result.denom = 0; return result; } if (n == 0) { d = 1; } else if (d < 0) { n = -n; d = -d; } g = abs(gcd(n, d)); if (g > 1) { n = n / g; d = d / g; } result.num = n; result.denom = d; return result; } Frac negateFrac(Frac f) { return makeFrac(-f.num, f.denom); } Frac subFrac(Frac lhs, Frac rhs) { return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom); } Frac multFrac(Frac lhs, Frac rhs) { return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom); } bool equalFrac(Frac lhs, Frac rhs) { return (lhs.num == rhs.num) && (lhs.denom == rhs.denom); } bool lessFrac(Frac lhs, Frac rhs) { return (lhs.num * rhs.denom) < (rhs.num * lhs.denom); } void printFrac(Frac f) { char buffer[7]; int len; if (f.denom != 1) { snprintf(buffer, 7, "%d/%d", f.num, f.denom); } else { snprintf(buffer, 7, "%d", f.num); } len = 7 - strlen(buffer); while (len-- > 0) { putc(' ', stdout); } printf(buffer); } Frac bernoulli(int n) { Frac a[16]; int j, m; if (n < 0) { a[0].num = 0; a[0].denom = 0; return a[0]; } for (m = 0; m <= n; ++m) { a[m] = makeFrac(1, m + 1); for (j = m; j >= 1; --j) { a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1)); } } if (n != 1) { return a[0]; } return negateFrac(a[0]); } void faulhaber(int p) { Frac q, *coeffs; int j, sign; coeffs = malloc(sizeof(Frac)*(p + 1)); q = makeFrac(1, p + 1); sign = -1; for (j = 0; j <= p; ++j) { sign = -1 * sign; coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j)); } for (j = 0; j <= p; ++j) { printFrac(coeffs[j]); } printf("\n"); free(coeffs); } int main() { int i; for (i = 0; i < 10; ++i) { faulhaber(i); } return 0; }
Convert the following code from Python to C, ensuring the logic remains intact.
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
#include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
Preserve the algorithm and functionality while converting the code from Python to C.
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
#include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
Change the following Python code into C without altering its purpose.
import urllib.request from collections import Counter GRID = def getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'): "Return lowercased words of 3 to 9 characters" words = urllib.request.urlopen(url).read().decode().strip().lower().split() return (w for w in words if 2 < len(w) < 10) def solve(grid, dictionary): gridcount = Counter(grid) mid = grid[4] return [word for word in dictionary if mid in word and not (Counter(word) - gridcount)] if __name__ == '__main__': chars = ''.join(GRID.strip().lower().split()) found = solve(chars, dictionary=getwords()) print('\n'.join(found))
#include <stdbool.h> #include <stdio.h> #define MAX_WORD 80 #define LETTERS 26 bool is_letter(char c) { return c >= 'a' && c <= 'z'; } int index(char c) { return c - 'a'; } void word_wheel(const char* letters, char central, int min_length, FILE* dict) { int max_count[LETTERS] = { 0 }; for (const char* p = letters; *p; ++p) { char c = *p; if (is_letter(c)) ++max_count[index(c)]; } char word[MAX_WORD + 1] = { 0 }; while (fgets(word, MAX_WORD, dict)) { int count[LETTERS] = { 0 }; for (const char* p = word; *p; ++p) { char c = *p; if (c == '\n') { if (p >= word + min_length && count[index(central)] > 0) printf("%s", word); } else if (is_letter(c)) { int i = index(c); if (++count[i] > max_count[i]) { break; } } else { break; } } } } int main(int argc, char** argv) { const char* dict = argc == 2 ? argv[1] : "unixdict.txt"; FILE* in = fopen(dict, "r"); if (in == NULL) { perror(dict); return 1; } word_wheel("ndeokgelw", 'k', 3, in); fclose(in); return 0; }
Write the same code in C as shown below in Python.
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 assert arr4 == [1, 2, 3, 4, 5, 6] arr4.extend(arr3) assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
#include <stdlib.h> #include <stdio.h> #include <string.h> #define ARRAY_CONCAT(TYPE, A, An, B, Bn) \ (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE)); void *array_concat(const void *a, size_t an, const void *b, size_t bn, size_t s) { char *p = malloc(s * (an + bn)); memcpy(p, a, an*s); memcpy(p + an*s, b, bn*s); return p; } const int a[] = { 1, 2, 3, 4, 5 }; const int b[] = { 6, 7, 8, 9, 0 }; int main(void) { unsigned int i; int *c = ARRAY_CONCAT(int, a, 5, b, 5); for(i = 0; i < 10; i++) printf("%d\n", c[i]); free(c); return EXIT_SUCCCESS; }
Change the programming language of this snippet from Python to C without modifying what it does.
string = raw_input("Input a string: ")
#include <stdio.h> #include <stdlib.h> int main(void) { char str[BUFSIZ]; puts("Enter a string: "); fgets(str, sizeof(str), stdin); long num; char buf[BUFSIZ]; do { puts("Enter 75000: "); fgets(buf, sizeof(buf), stdin); num = strtol(buf, NULL, 10); } while (num != 75000); return EXIT_SUCCESS; }
Generate a C translation of this Python snippet without changing its computational steps.
>>> import winsound >>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]: winsound.Beep(int(note+.5), 500) >>>
#include<stdio.h> #include<conio.h> #include<math.h> #include<dos.h> typedef struct{ char str[3]; int key; }note; note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}}; int main(void) { int i=0; while(!kbhit()) { printf("\t%s",sequence[i].str); sound(261.63*pow(2,sequence[i].key/12.0)); delay(sequence[i].key%12==0?500:1000); i = (i+1)%8; i==0?printf("\n"):printf(""); } nosound(); return 0; }
Port the provided Python code into C while preserving the original functionality.
>>> import winsound >>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]: winsound.Beep(int(note+.5), 500) >>>
#include<stdio.h> #include<conio.h> #include<math.h> #include<dos.h> typedef struct{ char str[3]; int key; }note; note sequence[] = {{"Do",0},{"Re",2},{"Mi",4},{"Fa",5},{"So",7},{"La",9},{"Ti",11},{"Do",12}}; int main(void) { int i=0; while(!kbhit()) { printf("\t%s",sequence[i].str); sound(261.63*pow(2,sequence[i].key/12.0)); delay(sequence[i].key%12==0?500:1000); i = (i+1)%8; i==0?printf("\n"):printf(""); } nosound(); return 0; }
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
from itertools import combinations def anycomb(items): ' return combinations of any length from the items ' return ( comb for r in range(1, len(items)+1) for comb in combinations(items, r) ) def totalvalue(comb): ' Totalise a particular combination of items' totwt = totval = 0 for item, wt, val in comb: totwt += wt totval += val return (totval, -totwt) if totwt <= 400 else (0, 0) items = ( ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160), ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40), ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30), ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40), ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75), ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12), ("socks", 4, 50), ("book", 30, 10), ) bagged = max( anycomb(items), key=totalvalue) print("Bagged the following items\n " + '\n '.join(sorted(item for item,_,_ in bagged))) val, wt = totalvalue(bagged) print("for a total value of %i and a total weight of %i" % (val, -wt))
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; int weight; int value; } item_t; item_t items[] = { {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"beer", 52, 10}, {"suntan cream", 11, 70}, {"camera", 32, 30}, {"T-shirt", 24, 15}, {"trousers", 48, 10}, {"umbrella", 73, 40}, {"waterproof trousers", 42, 70}, {"waterproof overclothes", 43, 75}, {"note-case", 22, 80}, {"sunglasses", 7, 20}, {"towel", 18, 12}, {"socks", 4, 50}, {"book", 30, 10}, }; int *knapsack (item_t *items, int n, int w) { int i, j, a, b, *mm, **m, *s; mm = calloc((n + 1) * (w + 1), sizeof (int)); m = malloc((n + 1) * sizeof (int *)); m[0] = mm; for (i = 1; i <= n; i++) { m[i] = &mm[i * (w + 1)]; for (j = 0; j <= w; j++) { if (items[i - 1].weight > j) { m[i][j] = m[i - 1][j]; } else { a = m[i - 1][j]; b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value; m[i][j] = a > b ? a : b; } } } s = calloc(n, sizeof (int)); for (i = n, j = w; i > 0; i--) { if (m[i][j] > m[i - 1][j]) { s[i - 1] = 1; j -= items[i - 1].weight; } } free(mm); free(m); return s; } int main () { int i, n, tw = 0, tv = 0, *s; n = sizeof (items) / sizeof (item_t); s = knapsack(items, n, 400); for (i = 0; i < n; i++) { if (s[i]) { printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value); tw += items[i].weight; tv += items[i].value; } } printf("%-22s %5d %5d\n", "totals:", tw, tv); return 0; }
Can you help me rewrite this code in C instead of Python, keeping it the same logically?
from __future__ import print_function from itertools import takewhile maxsum = 99 def get_primes(max): if max < 2: return [] lprimes = [2] for x in range(3, max + 1, 2): for p in lprimes: if x % p == 0: break else: lprimes.append(x) return lprimes descendants = [[] for _ in range(maxsum + 1)] ancestors = [[] for _ in range(maxsum + 1)] primes = get_primes(maxsum) for p in primes: descendants[p].append(p) for s in range(1, len(descendants) - p): descendants[s + p] += [p * pr for pr in descendants[s]] for p in primes + [4]: descendants[p].pop() total = 0 for s in range(1, maxsum + 1): descendants[s].sort() for d in takewhile(lambda x: x <= maxsum, descendants[s]): ancestors[d] = ancestors[s] + [s] print([s], "Level:", len(ancestors[s])) print("Ancestors:", ancestors[s] if len(ancestors[s]) else "None") print("Descendants:", len(descendants[s]) if len(descendants[s]) else "None") if len(descendants[s]): print(descendants[s]) print() total += len(descendants[s]) print("Total descendants", total)
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXPRIME 99 #define MAXPARENT 99 #define NBRPRIMES 30 #define NBRANCESTORS 10 FILE *FileOut; char format[] = ", %lld"; int Primes[NBRPRIMES]; int iPrimes; short Ancestors[NBRANCESTORS]; struct Children { long long Child; struct Children *pNext; }; struct Children *Parents[MAXPARENT+1][2]; int CptDescendants[MAXPARENT+1]; long long MaxDescendant = (long long) pow(3.0, 33.0); short GetParent(long long child); struct Children *AppendChild(struct Children *node, long long child); short GetAncestors(short child); void PrintDescendants(struct Children *node); int GetPrimes(int primes[], int maxPrime); int main() { long long Child; short i, Parent, Level; int TotDesc = 0; if ((iPrimes = GetPrimes(Primes, MAXPRIME)) < 0) return 1; for (Child = 1; Child <= MaxDescendant; Child++) { if (Parent = GetParent(Child)) { Parents[Parent][1] = AppendChild(Parents[Parent][1], Child); if (Parents[Parent][0] == NULL) Parents[Parent][0] = Parents[Parent][1]; CptDescendants[Parent]++; } } if (MAXPARENT > MAXPRIME) if (GetPrimes(Primes, MAXPARENT) < 0) return 1; if (fopen_s(&FileOut, "Ancestors.txt", "w")) return 1; for (Parent = 1; Parent <= MAXPARENT; Parent++) { Level = GetAncestors(Parent); fprintf(FileOut, "[%d] Level: %d\n", Parent, Level); if (Level) { fprintf(FileOut, "Ancestors: %d", Ancestors[0]); for (i = 1; i < Level; i++) fprintf(FileOut, ", %d", Ancestors[i]); } else fprintf(FileOut, "Ancestors: None"); if (CptDescendants[Parent]) { fprintf(FileOut, "\nDescendants: %d\n", CptDescendants[Parent]); strcpy_s(format, "%lld"); PrintDescendants(Parents[Parent][0]); fprintf(FileOut, "\n"); } else fprintf(FileOut, "\nDescendants: None\n"); fprintf(FileOut, "\n"); TotDesc += CptDescendants[Parent]; } fprintf(FileOut, "Total descendants %d\n\n", TotDesc); if (fclose(FileOut)) return 1; return 0; } short GetParent(long long child) { long long Child = child; short Parent = 0; short Index = 0; while (Child > 1 && Parent <= MAXPARENT) { if (Index > iPrimes) return 0; while (Child % Primes[Index] == 0) { Child /= Primes[Index]; Parent += Primes[Index]; } Index++; } if (Parent == child || Parent > MAXPARENT || child == 1) return 0; return Parent; } struct Children *AppendChild(struct Children *node, long long child) { static struct Children *NodeNew; if (NodeNew = (struct Children *) malloc(sizeof(struct Children))) { NodeNew->Child = child; NodeNew->pNext = NULL; if (node != NULL) node->pNext = NodeNew; } return NodeNew; } short GetAncestors(short child) { short Child = child; short Parent = 0; short Index = 0; while (Child > 1) { while (Child % Primes[Index] == 0) { Child /= Primes[Index]; Parent += Primes[Index]; } Index++; } if (Parent == child || child == 1) return 0; Index = GetAncestors(Parent); Ancestors[Index] = Parent; return ++Index; } void PrintDescendants(struct Children *node) { static struct Children *NodeCurr; static struct Children *NodePrev; NodeCurr = node; NodePrev = NULL; while (NodeCurr) { fprintf(FileOut, format, NodeCurr->Child); strcpy_s(format, ", %lld"); NodePrev = NodeCurr; NodeCurr = NodeCurr->pNext; free(NodePrev); } return; } int GetPrimes(int primes[], int maxPrime) { if (maxPrime < 2) return -1; int Index = 0, Value = 1; int Max, i; primes[0] = 2; while ((Value += 2) <= maxPrime) { Max = (int) floor(sqrt((double) Value)); for (i = 0; i <= Index; i++) { if (primes[i] > Max) { if (++Index >= NBRPRIMES) return -1; primes[Index] = Value; break; } if (Value % primes[i] == 0) break; } } return Index; }
Port the following code from Python to C with equivalent syntax and logic.
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
#include<string.h> #include<stdlib.h> #include<stdio.h> void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){ int i,j; if(times==numSets){ printf("("); for(i=0;i<times;i++){ printf("%d,",currentSet[i]); } printf("\b),"); } else{ for(j=0;j<setLengths[times];j++){ currentSet[times] = sets[times][j]; cartesianProduct(sets,setLengths,currentSet,numSets,times+1); } } } void printSets(int** sets, int* setLengths, int numSets){ int i,j; printf("\nNumber of sets : %d",numSets); for(i=0;i<numSets+1;i++){ printf("\nSet %d : ",i+1); for(j=0;j<setLengths[i];j++){ printf(" %d ",sets[i][j]); } } } void processInputString(char* str){ int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0; char *token,*holder,*holderToken; for(i=0;str[i]!=00;i++) if(str[i]=='x') numSets++; if(numSets==0){ printf("\n%s",str); return; } currentSet = (int*)calloc(sizeof(int),numSets + 1); setLengths = (int*)calloc(sizeof(int),numSets + 1); sets = (int**)malloc((numSets + 1)*sizeof(int*)); token = strtok(str,"x"); while(token!=NULL){ holder = (char*)malloc(strlen(token)*sizeof(char)); j = 0; for(i=0;token[i]!=00;i++){ if(token[i]>='0' && token[i]<='9') holder[j++] = token[i]; else if(token[i]==',') holder[j++] = ' '; } holder[j] = 00; setLength = 0; for(i=0;holder[i]!=00;i++) if(holder[i]==' ') setLength++; if(setLength==0 && strlen(holder)==0){ printf("\n{}"); return; } setLengths[counter] = setLength+1; sets[counter] = (int*)malloc((1+setLength)*sizeof(int)); k = 0; start = 0; for(l=0;holder[l]!=00;l++){ if(holder[l+1]==' '||holder[l+1]==00){ holderToken = (char*)malloc((l+1-start)*sizeof(char)); strncpy(holderToken,holder + start,l+1-start); sets[counter][k++] = atoi(holderToken); start = l+2; } } counter++; token = strtok(NULL,"x"); } printf("\n{"); cartesianProduct(sets,setLengths,currentSet,numSets + 1,0); printf("\b}"); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]); else processInputString(argV[1]); return 0; }
Port the provided Python code into C while preserving the original functionality.
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
#include<string.h> #include<stdlib.h> #include<stdio.h> void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){ int i,j; if(times==numSets){ printf("("); for(i=0;i<times;i++){ printf("%d,",currentSet[i]); } printf("\b),"); } else{ for(j=0;j<setLengths[times];j++){ currentSet[times] = sets[times][j]; cartesianProduct(sets,setLengths,currentSet,numSets,times+1); } } } void printSets(int** sets, int* setLengths, int numSets){ int i,j; printf("\nNumber of sets : %d",numSets); for(i=0;i<numSets+1;i++){ printf("\nSet %d : ",i+1); for(j=0;j<setLengths[i];j++){ printf(" %d ",sets[i][j]); } } } void processInputString(char* str){ int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0; char *token,*holder,*holderToken; for(i=0;str[i]!=00;i++) if(str[i]=='x') numSets++; if(numSets==0){ printf("\n%s",str); return; } currentSet = (int*)calloc(sizeof(int),numSets + 1); setLengths = (int*)calloc(sizeof(int),numSets + 1); sets = (int**)malloc((numSets + 1)*sizeof(int*)); token = strtok(str,"x"); while(token!=NULL){ holder = (char*)malloc(strlen(token)*sizeof(char)); j = 0; for(i=0;token[i]!=00;i++){ if(token[i]>='0' && token[i]<='9') holder[j++] = token[i]; else if(token[i]==',') holder[j++] = ' '; } holder[j] = 00; setLength = 0; for(i=0;holder[i]!=00;i++) if(holder[i]==' ') setLength++; if(setLength==0 && strlen(holder)==0){ printf("\n{}"); return; } setLengths[counter] = setLength+1; sets[counter] = (int*)malloc((1+setLength)*sizeof(int)); k = 0; start = 0; for(l=0;holder[l]!=00;l++){ if(holder[l+1]==' '||holder[l+1]==00){ holderToken = (char*)malloc((l+1-start)*sizeof(char)); strncpy(holderToken,holder + start,l+1-start); sets[counter][k++] = atoi(holderToken); start = l+2; } } counter++; token = strtok(NULL,"x"); } printf("\n{"); cartesianProduct(sets,setLengths,currentSet,numSets + 1,0); printf("\b}"); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]); else processInputString(argV[1]); return 0; }
Write the same code in C as shown below in Python.
>>> >>> from math import sin, cos, acos, asin >>> >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> >>> >>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) ) >>> >>> funclist = [sin, cos, cube] >>> funclisti = [asin, acos, croot] >>> >>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)] [0.5, 0.4999999999999999, 0.5] >>>
#include <stdlib.h> #include <stdio.h> #include <math.h> typedef double (*Class2Func)(double); double functionA( double v) { return v*v*v; } double functionB(double v) { return exp(log(v)/3); } double Function1( Class2Func f2, double val ) { return f2(val); } Class2Func WhichFunc( int idx) { return (idx < 4) ? &functionA : &functionB; } Class2Func funcListA[] = {&functionA, &sin, &cos, &tan }; Class2Func funcListB[] = {&functionB, &asin, &acos, &atan }; double InvokeComposed( Class2Func f1, Class2Func f2, double val ) { return f1(f2(val)); } typedef struct sComposition { Class2Func f1; Class2Func f2; } *Composition; Composition Compose( Class2Func f1, Class2Func f2) { Composition comp = malloc(sizeof(struct sComposition)); comp->f1 = f1; comp->f2 = f2; return comp; } double CallComposed( Composition comp, double val ) { return comp->f1( comp->f2(val) ); } int main(int argc, char *argv[]) { int ix; Composition c; printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0)); for (ix=0; ix<4; ix++) { c = Compose(funcListA[ix], funcListB[ix]); printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9)); } return 0; }
Preserve the algorithm and functionality while converting the code from Python to C.
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
#include <stdio.h> #include <stdbool.h> int proper_divisors(const int n, bool print_flag) { int count = 0; for (int i = 1; i < n; ++i) { if (n % i == 0) { count++; if (print_flag) printf("%d ", i); } } if (print_flag) printf("\n"); return count; } int main(void) { for (int i = 1; i <= 10; ++i) { printf("%d: ", i); proper_divisors(i, true); } int max = 0; int max_i = 1; for (int i = 1; i <= 20000; ++i) { int v = proper_divisors(i, false); if (v >= max) { max = v; max_i = i; } } printf("%d with %d divisors\n", max_i, max); return 0; }
Convert this Python block to C, preserving its control flow and logic.
>>> from xml.etree import ElementTree as ET >>> from itertools import izip >>> def characterstoxml(names, remarks): root = ET.Element("CharacterRemarks") for name, remark in izip(names, remarks): c = ET.SubElement(root, "Character", {'name': name}) c.text = remark return ET.tostring(root) >>> print characterstoxml( names = ["April", "Tam O'Shanter", "Emily"], remarks = [ "Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', 'Short & shrift' ] ).replace('><','>\n<')
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libxml/parser.h> #include <libxml/tree.h> const char *names[] = { "April", "Tam O'Shanter", "Emily", NULL }; const char *remarks[] = { "Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift", NULL }; int main() { xmlDoc *doc = NULL; xmlNode *root = NULL, *node; const char **next; int a; doc = xmlNewDoc("1.0"); root = xmlNewNode(NULL, "CharacterRemarks"); xmlDocSetRootElement(doc, root); for(next = names, a = 0; *next != NULL; next++, a++) { node = xmlNewNode(NULL, "Character"); (void)xmlNewProp(node, "name", *next); xmlAddChild(node, xmlNewText(remarks[a])); xmlAddChild(root, node); } xmlElemDump(stdout, doc, root); xmlFreeDoc(doc); xmlCleanupParser(); return EXIT_SUCCESS; }
Transform the following Python implementation into C, maintaining the same output and logic.
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] >>> import pylab >>> pylab.plot(x, y, 'bo') >>> pylab.savefig('qsort-range-10-9.png')
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <plot.h> #define NP 10 double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; void minmax(double *x, double *y, double *minx, double *maxx, double *miny, double *maxy, int n) { int i; *minx = *maxx = x[0]; *miny = *maxy = y[0]; for(i=1; i < n; i++) { if ( x[i] < *minx ) *minx = x[i]; if ( x[i] > *maxx ) *maxx = x[i]; if ( y[i] < *miny ) *miny = y[i]; if ( y[i] > *maxy ) *maxy = y[i]; } } #define YLAB_HEIGHT_F 0.1 #define XLAB_WIDTH_F 0.2 #define XDIV (NP*1.0) #define YDIV (NP*1.0) #define EXTRA_W 0.01 #define EXTRA_H 0.01 #define DOTSCALE (1.0/150.0) #define MAXLABLEN 32 #define PUSHSCALE(X,Y) pl_fscale((X),(Y)) #define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y)) #define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy) int main() { int plotter, i; double minx, miny, maxx, maxy; double lx, ly; double xticstep, yticstep, nx, ny; double sx, sy; char labs[MAXLABLEN+1]; plotter = pl_newpl("png", NULL, stdout, NULL); if ( plotter < 0 ) exit(1); pl_selectpl(plotter); if ( pl_openpl() < 0 ) exit(1); minmax(x, y, &minx, &maxx, &miny, &maxy, NP); lx = maxx - minx; ly = maxy - miny; pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly, ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly); xticstep = (ceil(maxx) - floor(minx)) / XDIV; yticstep = (ceil(maxy) - floor(miny)) / YDIV; pl_flinewidth(0.25); if ( lx < ly ) { sx = lx/ly; sy = 1.0; } else { sx = 1.0; sy = ly/lx; } pl_erase(); pl_fbox(floor(minx), floor(miny), ceil(maxx), ceil(maxy)); pl_fontname("HersheySerif"); for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) { pl_fline(floor(minx), ny, ceil(maxx), ny); snprintf(labs, MAXLABLEN, "%6.2lf", ny); FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny); PUSHSCALE(sx,sy); pl_label(labs); POPSCALE(sx,sy); } for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) { pl_fline(nx, floor(miny), nx, ceil(maxy)); snprintf(labs, MAXLABLEN, "%6.2lf", nx); FMOVESCALE(nx, floor(miny)); PUSHSCALE(sx,sy); pl_ftextangle(-90); pl_alabel('l', 'b', labs); POPSCALE(sx,sy); } pl_fillcolorname("red"); pl_filltype(1); for(i=0; i < NP; i++) { pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE, x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE); } pl_flushpl(); pl_closepl(); }
Translate this program into C but keep the logic exactly as in Python.
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] >>> import pylab >>> pylab.plot(x, y, 'bo') >>> pylab.savefig('qsort-range-10-9.png')
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <plot.h> #define NP 10 double x[NP] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; double y[NP] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; void minmax(double *x, double *y, double *minx, double *maxx, double *miny, double *maxy, int n) { int i; *minx = *maxx = x[0]; *miny = *maxy = y[0]; for(i=1; i < n; i++) { if ( x[i] < *minx ) *minx = x[i]; if ( x[i] > *maxx ) *maxx = x[i]; if ( y[i] < *miny ) *miny = y[i]; if ( y[i] > *maxy ) *maxy = y[i]; } } #define YLAB_HEIGHT_F 0.1 #define XLAB_WIDTH_F 0.2 #define XDIV (NP*1.0) #define YDIV (NP*1.0) #define EXTRA_W 0.01 #define EXTRA_H 0.01 #define DOTSCALE (1.0/150.0) #define MAXLABLEN 32 #define PUSHSCALE(X,Y) pl_fscale((X),(Y)) #define POPSCALE(X,Y) pl_fscale(1.0/(X), 1.0/(Y)) #define FMOVESCALE(X,Y) pl_fmove((X)/sx, (Y)/sy) int main() { int plotter, i; double minx, miny, maxx, maxy; double lx, ly; double xticstep, yticstep, nx, ny; double sx, sy; char labs[MAXLABLEN+1]; plotter = pl_newpl("png", NULL, stdout, NULL); if ( plotter < 0 ) exit(1); pl_selectpl(plotter); if ( pl_openpl() < 0 ) exit(1); minmax(x, y, &minx, &maxx, &miny, &maxy, NP); lx = maxx - minx; ly = maxy - miny; pl_fspace(floor(minx) - XLAB_WIDTH_F * lx, floor(miny) - YLAB_HEIGHT_F * ly, ceil(maxx) + EXTRA_W * lx, ceil(maxy) + EXTRA_H * ly); xticstep = (ceil(maxx) - floor(minx)) / XDIV; yticstep = (ceil(maxy) - floor(miny)) / YDIV; pl_flinewidth(0.25); if ( lx < ly ) { sx = lx/ly; sy = 1.0; } else { sx = 1.0; sy = ly/lx; } pl_erase(); pl_fbox(floor(minx), floor(miny), ceil(maxx), ceil(maxy)); pl_fontname("HersheySerif"); for(ny=floor(miny); ny < ceil(maxy); ny += yticstep) { pl_fline(floor(minx), ny, ceil(maxx), ny); snprintf(labs, MAXLABLEN, "%6.2lf", ny); FMOVESCALE(floor(minx) - XLAB_WIDTH_F * lx, ny); PUSHSCALE(sx,sy); pl_label(labs); POPSCALE(sx,sy); } for(nx=floor(minx); nx < ceil(maxx); nx += xticstep) { pl_fline(nx, floor(miny), nx, ceil(maxy)); snprintf(labs, MAXLABLEN, "%6.2lf", nx); FMOVESCALE(nx, floor(miny)); PUSHSCALE(sx,sy); pl_ftextangle(-90); pl_alabel('l', 'b', labs); POPSCALE(sx,sy); } pl_fillcolorname("red"); pl_filltype(1); for(i=0; i < NP; i++) { pl_fbox(x[i] - lx * DOTSCALE, y[i] - ly * DOTSCALE, x[i] + lx * DOTSCALE, y[i] + ly * DOTSCALE); } pl_flushpl(); pl_closepl(); }
Keep all operations the same but rewrite the snippet in C.
import re string = "This is a string" if re.search('string$', string): print("Ends with string.") string = re.sub(" a ", " another ", string) print(string)
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <regex.h> #include <string.h> int main() { regex_t preg; regmatch_t substmatch[1]; const char *tp = "string$"; const char *t1 = "this is a matching string"; const char *t2 = "this is not a matching string!"; const char *ss = "istyfied"; regcomp(&preg, "string$", REG_EXTENDED); printf("'%s' %smatched with '%s'\n", t1, (regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp); printf("'%s' %smatched with '%s'\n", t2, (regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp); regfree(&preg); regcomp(&preg, "a[a-z]+", REG_EXTENDED); if ( regexec(&preg, t1, 1, substmatch, 0) == 0 ) { char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) + (strlen(t1) - substmatch[0].rm_eo) + 2); memcpy(ns, t1, substmatch[0].rm_so+1); memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss)); memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo], strlen(&t1[substmatch[0].rm_eo])); ns[ substmatch[0].rm_so + strlen(ss) + strlen(&t1[substmatch[0].rm_eo]) ] = 0; printf("mod string: '%s'\n", ns); free(ns); } else { printf("the string '%s' is the same: no matching!\n", t1); } regfree(&preg); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
inclusive_range = mn, mx = (1, 10) print( % inclusive_range) i = 0 while True: i += 1 guess = (mn+mx)//2 txt = input("Guess %2i is: %2i. The score for which is (h,l,=): " % (i, guess)).strip().lower()[0] if txt not in 'hl=': print(" I don't understand your input of '%s' ?" % txt) continue if txt == 'h': mx = guess-1 if txt == 'l': mn = guess+1 if txt == '=': print(" Ye-Haw!!") break if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]): print("Please check your scoring as I cannot find the value") break print("\nThanks for keeping score.")
#include <stdio.h> int main(){ int bounds[ 2 ] = {1, 100}; char input[ 2 ] = " "; int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] ); do{ switch( input[ 0 ] ){ case 'H': bounds[ 1 ] = choice; break; case 'L': bounds[ 0 ] = choice; break; case 'Y': printf( "\nAwwwright\n" ); return 0; } choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Is the number %d? (Y/H/L) ", choice ); }while( scanf( "%1s", input ) == 1 ); return 0; }
Port the provided Python code into C while preserving the original functionality.
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = {key: value for key, value in zip(keys, values)}
#include <stdio.h> #include <stdlib.h> #include <string.h> #define KeyType const char * #define ValType int #define HASH_SIZE 4096 unsigned strhashkey( const char * key, int max) { unsigned h=0; unsigned hl, hr; while(*key) { h += *key; hl= 0x5C5 ^ (h&0xfff00000 )>>18; hr =(h&0x000fffff ); h = hl ^ hr ^ *key++; } return h % max; } typedef struct sHme { KeyType key; ValType value; struct sHme *link; } *MapEntry; typedef struct he { MapEntry first, last; } HashElement; HashElement hash[HASH_SIZE]; typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc); typedef void (*ValCopyF)(ValType *vdest, ValType vsrc); typedef unsigned (*KeyHashF)( KeyType key, int upperBound ); typedef int (*KeyCmprF)(KeyType key1, KeyType key2); void HashAddH( KeyType key, ValType value, KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { (*copyVal)(&m_ent->value, value); } else { MapEntry last; MapEntry hme = malloc(sizeof(struct sHme)); (*copyKey)(&hme->key, key); (*copyVal)(&hme->value, value); hme->link = NULL; last = hash[hix].last; if (last) { last->link = hme; } else hash[hix].first = hme; hash[hix].last = hme; } } int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { *val = m_ent->value; } return (m_ent != NULL); } void copyStr(const char**dest, const char *src) { *dest = strdup(src); } void copyInt( int *dest, int src) { *dest = src; } int strCompare( const char *key1, const char *key2) { return strcmp(key1, key2) == 0; } void HashAdd( KeyType key, ValType value ) { HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare); } int HashGet(ValType *val, KeyType key) { return HashGetH( val, key, &strhashkey, &strCompare); } int main() { static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" }; static int valuList[] = {1,43,640, 747, 42, 42}; int ix; for (ix=0; ix<6; ix++) { HashAdd(keyList[ix], valuList[ix]); } return 0; }
Translate the given Python code snippet into C without altering its behavior.
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
Convert this Python snippet to C and keep its semantics consistent.
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
Preserve the algorithm and functionality while converting the code from Python to C.
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
Convert the following code from Python to C, ensuring the logic remains intact.
def setup(): size(600, 600) background(0) stroke(255) drawTree(300, 550, 9) def drawTree(x, y, depth): fork_ang = radians(20) base_len = 10 if depth > 0: pushMatrix() translate(x, y - baseLen * depth) line(0, baseLen * depth, 0, 0) rotate(fork_ang) drawTree(0, 0, depth - 1) rotate(2 * -fork_ang) drawTree(0, 0, depth - 1) popMatrix()
#include <SDL/SDL.h> #ifdef WITH_CAIRO #include <cairo.h> #else #include <SDL/sge.h> #endif #include <cairo.h> #include <stdlib.h> #include <time.h> #include <math.h> #ifdef WITH_CAIRO #define PI 3.1415926535 #endif #define SIZE 800 #define SCALE 5 #define BRANCHES 14 #define ROTATION_SCALE 0.75 #define INITIAL_LENGTH 50 double rand_fl(){ return (double)rand() / (double)RAND_MAX; } void draw_tree(SDL_Surface * surface, double offsetx, double offsety, double directionx, double directiony, double size, double rotation, int depth) { #ifdef WITH_CAIRO cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels, CAIRO_FORMAT_RGB24, surface->w, surface->h, surface->pitch ); cairo_t *ct = cairo_create(surf); cairo_set_line_width(ct, 1); cairo_set_source_rgba(ct, 0,0,0,1); cairo_move_to(ct, (int)offsetx, (int)offsety); cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size)); cairo_stroke(ct); #else sge_AALine(surface, (int)offsetx, (int)offsety, (int)(offsetx + directionx * size), (int)(offsety + directiony * size), SDL_MapRGB(surface->format, 0, 0, 0)); #endif if (depth > 0){ draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(rotation) + directiony * sin(rotation), directionx * -sin(rotation) + directiony * cos(rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(-rotation) + directiony * sin(-rotation), directionx * -sin(-rotation) + directiony * cos(-rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); } } void render(SDL_Surface * surface){ SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255)); draw_tree(surface, surface->w / 2.0, surface->h - 10.0, 0.0, -1.0, INITIAL_LENGTH, PI / 8, BRANCHES); SDL_UpdateRect(surface, 0, 0, 0, 0); } int main(){ SDL_Surface * screen; SDL_Event evt; SDL_Init(SDL_INIT_VIDEO); srand((unsigned)time(NULL)); screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE); render(screen); while(1){ if (SDL_PollEvent(&evt)){ if(evt.type == SDL_QUIT) break; } SDL_Delay(1); } SDL_Quit(); return 0; }
Generate an equivalent C version of this Python code.
from turtle import * colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"] screen = getscreen() left_edge = -screen.window_width()//2 right_edge = screen.window_width()//2 quarter_height = screen.window_height()//4 half_height = quarter_height * 2 speed("fastest") for quarter in range(4): pensize(quarter+1) colornum = 0 min_y = half_height - ((quarter + 1) * quarter_height) max_y = half_height - ((quarter) * quarter_height) for x in range(left_edge,right_edge,quarter+1): penup() pencolor(colors[colornum]) colornum = (colornum + 1) % len(colors) setposition(x,min_y) pendown() setposition(x,max_y) notused = input("Hit enter to continue: ")
#include<graphics.h> #include<conio.h> #define sections 4 int main() { int d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1; initgraph(&d,&m,"c:/turboc3/bgi"); maxX = getmaxx(); maxY = getmaxy(); for(y=0;y<maxY;y+=maxY/sections) { for(x=0;x<maxX;x+=increment) { setfillstyle(SOLID_FILL,(colour++)%16); bar(x,y,x+increment,y+maxY/sections); } increment++; colour = 0; } getch(); closegraph(); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
from datetime import date from calendar import isleap def weekday(d): days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] dooms = [ [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5], [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] ] c = d.year // 100 r = d.year % 100 s = r // 12 t = r % 12 c_anchor = (5 * (c % 4) + 2) % 7 doomsday = (s + t + (t // 4) + c_anchor) % 7 anchorday = dooms[isleap(d.year)][d.month - 1] weekday = (doomsday + d.day - anchorday + 7) % 7 return days[weekday] dates = [date(*x) for x in [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23), (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)] ] for d in dates: tense = "was" if d < date.today() else "is" if d == date.today() else "will be" print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
#include <stdio.h> #include <stdint.h> #include <stdbool.h> typedef struct { uint16_t year; uint8_t month; uint8_t day; } Date; bool leap(uint16_t year) { return year%4==0 && (year%100!=0 || year%400==0); } const char *weekday(Date date) { static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned c = date.year/100, r = date.year%100; unsigned s = r/12, t = r%12; unsigned c_anchor = (5 * (c%4) + 2) % 7; unsigned doom = (s + t + (t/4) + c_anchor) % 7; unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const char *past = "was", *future = "will be"; const char *months[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; int i; for (i=0; i < sizeof(dates)/sizeof(Date); i++) { printf("%s %d, %d %s on a %s.\n", months[dates[i].month], dates[i].day, dates[i].year, dates[i].year > 2021 ? future : past, weekday(dates[i])); } return 0; }
Port the provided Python code into C while preserving the original functionality.
from datetime import date from calendar import isleap def weekday(d): days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] dooms = [ [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5], [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] ] c = d.year // 100 r = d.year % 100 s = r // 12 t = r % 12 c_anchor = (5 * (c % 4) + 2) % 7 doomsday = (s + t + (t // 4) + c_anchor) % 7 anchorday = dooms[isleap(d.year)][d.month - 1] weekday = (doomsday + d.day - anchorday + 7) % 7 return days[weekday] dates = [date(*x) for x in [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23), (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)] ] for d in dates: tense = "was" if d < date.today() else "is" if d == date.today() else "will be" print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
#include <stdio.h> #include <stdint.h> #include <stdbool.h> typedef struct { uint16_t year; uint8_t month; uint8_t day; } Date; bool leap(uint16_t year) { return year%4==0 && (year%100!=0 || year%400==0); } const char *weekday(Date date) { static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned c = date.year/100, r = date.year%100; unsigned s = r/12, t = r%12; unsigned c_anchor = (5 * (c%4) + 2) % 7; unsigned doom = (s + t + (t/4) + c_anchor) % 7; unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const char *past = "was", *future = "will be"; const char *months[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; int i; for (i=0; i < sizeof(dates)/sizeof(Date); i++) { printf("%s %d, %d %s on a %s.\n", months[dates[i].month], dates[i].day, dates[i].year, dates[i].year > 2021 ? future : past, weekday(dates[i])); } return 0; }
Change the following Python code into C without altering its purpose.
def cocktailshiftingbounds(A): beginIdx = 0 endIdx = len(A) - 1 while beginIdx <= endIdx: newBeginIdx = endIdx newEndIdx = beginIdx for ii in range(beginIdx,endIdx): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newEndIdx = ii endIdx = newEndIdx for ii in range(endIdx,beginIdx-1,-1): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newBeginIdx = ii beginIdx = newBeginIdx + 1 test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] cocktailshiftingbounds(test1) print(test1) test2=list('big fjords vex quick waltz nymph') cocktailshiftingbounds(test2) print(''.join(test2))
#include <stdio.h> #include <string.h> void swap(char* p1, char* p2, size_t size) { for (; size-- > 0; ++p1, ++p2) { char tmp = *p1; *p1 = *p2; *p2 = tmp; } } void cocktail_shaker_sort(void* base, size_t count, size_t size, int (*cmp)(const void*, const void*)) { char* begin = base; char* end = base + size * count; if (end == begin) return; for (end -= size; begin < end; ) { char* new_begin = end; char* new_end = begin; for (char* p = begin; p < end; p += size) { char* q = p + size; if (cmp(p, q) > 0) { swap(p, q, size); new_end = p; } } end = new_end; for (char* p = end; p > begin; p -= size) { char* q = p - size; if (cmp(q, p) > 0) { swap(p, q, size); new_begin = p; } } begin = new_begin; } } int string_compare(const void* p1, const void* p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } void print(const char** a, size_t len) { for (size_t i = 0; i < len; ++i) printf("%s ", a[i]); printf("\n"); } int main() { const char* a[] = { "one", "two", "three", "four", "five", "six", "seven", "eight" }; const size_t len = sizeof(a)/sizeof(a[0]); printf("before: "); print(a, len); cocktail_shaker_sort(a, len, sizeof(char*), string_compare); printf("after: "); print(a, len); return 0; }
Port the provided Python code into C while preserving the original functionality.
import pygame, sys from pygame.locals import * from math import sin, cos, radians pygame.init() WINDOWSIZE = 250 TIMETICK = 100 BOBSIZE = 15 window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE)) pygame.display.set_caption("Pendulum") screen = pygame.display.get_surface() screen.fill((255,255,255)) PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10) SWINGLENGTH = PIVOT[1]*4 class BobMass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.theta = 45 self.dtheta = 0 self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)), PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)), 1,1) self.draw() def recomputeAngle(self): scaling = 3000.0/(SWINGLENGTH**2) firstDDtheta = -sin(radians(self.theta))*scaling midDtheta = self.dtheta + firstDDtheta midtheta = self.theta + (self.dtheta + midDtheta)/2.0 midDDtheta = -sin(radians(midtheta))*scaling midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2 midtheta = self.theta + (self.dtheta + midDtheta)/2 midDDtheta = -sin(radians(midtheta)) * scaling lastDtheta = midDtheta + midDDtheta lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 lastDDtheta = -sin(radians(lasttheta)) * scaling lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0 lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 self.dtheta = lastDtheta self.theta = lasttheta self.rect = pygame.Rect(PIVOT[0]- SWINGLENGTH*sin(radians(self.theta)), PIVOT[1]+ SWINGLENGTH*cos(radians(self.theta)),1,1) def draw(self): pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0) pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0) pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center) pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1])) def update(self): self.recomputeAngle() screen.fill((255,255,255)) self.draw() bob = BobMass() TICK = USEREVENT + 2 pygame.time.set_timer(TICK, TIMETICK) def input(events): for event in events: if event.type == QUIT: sys.exit(0) elif event.type == TICK: bob.update() while True: input(pygame.event.get()) pygame.display.flip()
#include <stdlib.h> #include <math.h> #include <GL/glut.h> #include <GL/gl.h> #include <sys/time.h> #define length 5 #define g 9.8 double alpha, accl, omega = 0, E; struct timeval tv; double elappsed() { struct timeval now; gettimeofday(&now, 0); int ret = (now.tv_sec - tv.tv_sec) * 1000000 + now.tv_usec - tv.tv_usec; tv = now; return ret / 1.e6; } void resize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); } void render() { double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha); resize(640, 320); glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_LINES); glVertex2d(320, 0); glVertex2d(x, y); glEnd(); glFlush(); double us = elappsed(); alpha += (omega + us * accl / 2) * us; omega += accl * us; if (length * g * (1 - cos(alpha)) >= E) { alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g); omega = 0; } accl = -g / length * sin(alpha); } void init_gfx(int *c, char **v) { glutInit(c, v); glutInitDisplayMode(GLUT_RGB); glutInitWindowSize(640, 320); glutIdleFunc(render); glutCreateWindow("Pendulum"); } int main(int c, char **v) { alpha = 4 * atan2(1, 1) / 2.1; E = length * g * (1 - cos(alpha)); accl = -g / length * sin(alpha); omega = 0; gettimeofday(&tv, 0); init_gfx(&c, v); glutMainLoop(); return 0; }
Change the following Python code into C without altering its purpose.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
int gray_encode(int n) { return n ^ (n >> 1); } int gray_decode(int n) { int p = n; while (n >>= 1) p ^= n; return p; }
Rewrite this program in C while keeping its functionality equivalent to the Python version.
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
int gray_encode(int n) { return n ^ (n >> 1); } int gray_decode(int n) { int p = n; while (n >>= 1) p ^= n; return p; }
Translate this program into C but keep the logic exactly as in Python.
>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n') ... >>>
#include<stdio.h> int main() { FILE* fp = fopen("TAPE.FILE","w"); fprintf(fp,"This code should be able to write a file to magnetic tape.\n"); fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n"); fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n"); fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n"); fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n"); fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n"); fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n"); fprintf(fp,"EOF"); fclose(fp); return 0; }