Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same code in C as shown below in Python. | import curses
import random
import time
ROW_DELAY=.0001
def get_rand_in_range(min, max):
return random.randrange(min,max+1)
try:
chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
total_chars = len(chars)
stdscr = curses.initscr()
curses.noecho()
curses.curs_set(False)
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
stdscr.attron(curses.color_pair(1))
max_x = curses.COLS - 1
max_y = curses.LINES - 1
columns_row = []
columns_active = []
for i in range(max_x+1):
columns_row.append(-1)
columns_active.append(0)
while(True):
for i in range(max_x):
if columns_row[i] == -1:
columns_row[i] = get_rand_in_range(0, max_y)
columns_active[i] = get_rand_in_range(0, 1)
for i in range(max_x):
if columns_active[i] == 1:
char_index = get_rand_in_range(0, total_chars-1)
stdscr.addstr(columns_row[i], i, chars[char_index])
else:
stdscr.addstr(columns_row[i], i, " ");
columns_row[i]+=1
if columns_row[i] >= max_y:
columns_row[i] = -1
if get_rand_in_range(0, 1000) == 0:
if columns_active[i] == 0:
columns_active[i] = 1
else:
columns_active[i] = 0
time.sleep(ROW_DELAY)
stdscr.refresh()
except KeyboardInterrupt as err:
curses.endwin()
|
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#define ROW_DELAY 40000
int get_rand_in_range(int min, int max)
{
return (rand() % ((max + 1) - min) + min);
}
int main(void)
{
srand(time(NULL));
char chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int total_chars = sizeof(chars);
initscr();
noecho();
curs_set(FALSE);
start_color();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
attron(COLOR_PAIR(1));
int max_x = 0, max_y = 0;
getmaxyx(stdscr, max_y, max_x);
int columns_row[max_x];
int columns_active[max_x];
int i;
for (i = 0; i < max_x; i++)
{
columns_row[i] = -1;
columns_active[i] = 0;
}
while (1)
{
for (i = 0; i < max_x; i++)
{
if (columns_row[i] == -1)
{
columns_row[i] = get_rand_in_range(0, max_y);
columns_active[i] = get_rand_in_range(0, 1);
}
}
for (i = 0; i < max_x; i++)
{
if (columns_active[i] == 1)
{
int char_index = get_rand_in_range(0, total_chars);
mvprintw(columns_row[i], i, "%c", chars[char_index]);
}
else
{
mvprintw(columns_row[i], i, " ");
}
columns_row[i]++;
if (columns_row[i] >= max_y)
{
columns_row[i] = -1;
}
if (get_rand_in_range(0, 1000) == 0)
{
columns_active[i] = (columns_active[i] == 0) ? 1 : 0;
}
}
usleep(ROW_DELAY);
refresh();
}
endwin();
return 0;
}
|
Change the following Python code into C without altering its purpose. | import random
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2)
reds = [Red] * (n // 2)
pack = blacks + reds
random.shuffle(pack)
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.append(pack.pop())
discard.append(top)
print('(Discards:', ' '.join(d[0] for d in discard), ')\n')
max_swaps = min(len(black_stack), len(red_stack))
swap_count = random.randint(0, max_swaps)
print('Swapping', swap_count)
def random_partition(stack, count):
"Partition the stack into 'count' randomly selected members and the rest"
sample = random.sample(stack, count)
rest = stack[::]
for card in sample:
rest.remove(card)
return rest, sample
black_stack, black_swap = random_partition(black_stack, swap_count)
red_stack, red_swap = random_partition(red_stack, swap_count)
black_stack += red_swap
red_stack += black_swap
if black_stack.count(Black) == red_stack.count(Red):
print('Yeha! The mathematicians assertion is correct.')
else:
print('Whoops - The mathematicians (or my card manipulations) are flakey')
| #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out = rand() & mask;
} while (out >= n);
return out;
}
card_t rand_card() {
return rand_n(52);
}
void print_card(card_t card) {
static char *suits = "HCDS";
static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
printf(" %s%c", cards[card>>2], suits[card&3]);
}
void shuffle(card_t *pack) {
int card;
card_t temp, randpos;
for (card=0; card<52; card++) {
randpos = rand_card();
temp = pack[card];
pack[card] = pack[randpos];
pack[randpos] = temp;
}
}
int trick() {
card_t pack[52];
card_t blacks[52/4], reds[52/4];
card_t top, x, card;
int blackn=0, redn=0, blacksw=0, redsw=0, result;
for (card=0; card<52; card++) pack[card] = card;
shuffle(pack);
#if PRINT_DISCARDED
printf("Discarded:");
#endif
for (card=0; card<52; card += 2) {
top = pack[card];
if (top & 1) {
blacks[blackn++] = pack[card+1];
} else {
reds[redn++] = pack[card+1];
}
#if PRINT_DISCARDED
print_card(top);
#endif
}
#if PRINT_DISCARDED
printf("\n");
#endif
x = rand_n(min(blackn, redn));
for (card=0; card<x; card++) {
blacksw = rand_n(blackn);
redsw = rand_n(redn);
top = blacks[blacksw];
blacks[blacksw] = reds[redsw];
reds[redsw] = top;
}
result = 0;
for (card=0; card<blackn; card++)
result += (blacks[card] & 1) == 1;
for (card=0; card<redn; card++)
result -= (reds[card] & 1) == 0;
result = !result;
printf("The number of black cards in the 'black' pile"
" %s the number of red cards in the 'red' pile.\n",
result? "equals" : "does not equal");
return result;
}
int main() {
unsigned int seed, i, successes = 0;
FILE *r;
if ((r = fopen("/dev/urandom", "r")) == NULL) {
fprintf(stderr, "cannot open /dev/urandom\n");
return 255;
}
if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
fprintf(stderr, "failed to read from /dev/urandom\n");
return 255;
}
fclose(r);
srand(seed);
for (i=1; i<=SIM_N; i++) {
printf("Simulation %d\n", i);
successes += trick();
printf("\n");
}
printf("Result: %d successes out of %d simulations\n",
successes, SIM_N);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Python version. | import random
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2)
reds = [Red] * (n // 2)
pack = blacks + reds
random.shuffle(pack)
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.append(pack.pop())
discard.append(top)
print('(Discards:', ' '.join(d[0] for d in discard), ')\n')
max_swaps = min(len(black_stack), len(red_stack))
swap_count = random.randint(0, max_swaps)
print('Swapping', swap_count)
def random_partition(stack, count):
"Partition the stack into 'count' randomly selected members and the rest"
sample = random.sample(stack, count)
rest = stack[::]
for card in sample:
rest.remove(card)
return rest, sample
black_stack, black_swap = random_partition(black_stack, swap_count)
red_stack, red_swap = random_partition(red_stack, swap_count)
black_stack += red_swap
red_stack += black_swap
if black_stack.count(Black) == red_stack.count(Red):
print('Yeha! The mathematicians assertion is correct.')
else:
print('Whoops - The mathematicians (or my card manipulations) are flakey')
| #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5
#define PRINT_DISCARDED 1
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out = rand() & mask;
} while (out >= n);
return out;
}
card_t rand_card() {
return rand_n(52);
}
void print_card(card_t card) {
static char *suits = "HCDS";
static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
printf(" %s%c", cards[card>>2], suits[card&3]);
}
void shuffle(card_t *pack) {
int card;
card_t temp, randpos;
for (card=0; card<52; card++) {
randpos = rand_card();
temp = pack[card];
pack[card] = pack[randpos];
pack[randpos] = temp;
}
}
int trick() {
card_t pack[52];
card_t blacks[52/4], reds[52/4];
card_t top, x, card;
int blackn=0, redn=0, blacksw=0, redsw=0, result;
for (card=0; card<52; card++) pack[card] = card;
shuffle(pack);
#if PRINT_DISCARDED
printf("Discarded:");
#endif
for (card=0; card<52; card += 2) {
top = pack[card];
if (top & 1) {
blacks[blackn++] = pack[card+1];
} else {
reds[redn++] = pack[card+1];
}
#if PRINT_DISCARDED
print_card(top);
#endif
}
#if PRINT_DISCARDED
printf("\n");
#endif
x = rand_n(min(blackn, redn));
for (card=0; card<x; card++) {
blacksw = rand_n(blackn);
redsw = rand_n(redn);
top = blacks[blacksw];
blacks[blacksw] = reds[redsw];
reds[redsw] = top;
}
result = 0;
for (card=0; card<blackn; card++)
result += (blacks[card] & 1) == 1;
for (card=0; card<redn; card++)
result -= (reds[card] & 1) == 0;
result = !result;
printf("The number of black cards in the 'black' pile"
" %s the number of red cards in the 'red' pile.\n",
result? "equals" : "does not equal");
return result;
}
int main() {
unsigned int seed, i, successes = 0;
FILE *r;
if ((r = fopen("/dev/urandom", "r")) == NULL) {
fprintf(stderr, "cannot open /dev/urandom\n");
return 255;
}
if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
fprintf(stderr, "failed to read from /dev/urandom\n");
return 255;
}
fclose(r);
srand(seed);
for (i=1; i<=SIM_N; i++) {
printf("Simulation %d\n", i);
successes += trick();
printf("\n");
}
printf("Result: %d successes out of %d simulations\n",
successes, SIM_N);
return 0;
}
|
Write the same code in C as shown below in Python. | from collections import defaultdict
import urllib.request
CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}
URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
def getwords(url):
return urllib.request.urlopen(url).read().decode("utf-8").lower().split()
def mapnum2words(words):
number2words = defaultdict(list)
reject = 0
for word in words:
try:
number2words[''.join(CH2NUM[ch] for ch in word)].append(word)
except KeyError:
reject += 1
return dict(number2words), reject
def interactiveconversions():
global inp, ch, num
while True:
inp = input("\nType a number or a word to get the translation and textonyms: ").strip().lower()
if inp:
if all(ch in '23456789' for ch in inp):
if inp in num2words:
print(" Number {0} has the following textonyms in the dictionary: {1}".format(inp, ', '.join(
num2words[inp])))
else:
print(" Number {0} has no textonyms in the dictionary.".format(inp))
elif all(ch in CH2NUM for ch in inp):
num = ''.join(CH2NUM[ch] for ch in inp)
print(" Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}".format(
inp, ('' if inp in wordset else "n't"), num, ', '.join(num2words[num])))
else:
print(" I don't understand %r" % inp)
else:
print("Thank you")
break
if __name__ == '__main__':
words = getwords(URL)
print("Read %i words from %r" % (len(words), URL))
wordset = set(words)
num2words, reject = mapnum2words(words)
morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)
maxwordpernum = max(len(values) for values in num2words.values())
print(.format(len(words) - reject, URL, len(num2words), morethan1word))
print("\nThe numbers mapping to the most words map to %i words each:" % maxwordpernum)
maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)
for num, wrds in maxwpn:
print(" %s maps to: %s" % (num, ', '.join(wrds)))
interactiveconversions()
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
char text_char(char c) {
switch (c) {
case 'a': case 'b': case 'c':
return '2';
case 'd': case 'e': case 'f':
return '3';
case 'g': case 'h': case 'i':
return '4';
case 'j': case 'k': case 'l':
return '5';
case 'm': case 'n': case 'o':
return '6';
case 'p': case 'q': case 'r': case 's':
return '7';
case 't': case 'u': case 'v':
return '8';
case 'w': case 'x': case 'y': case 'z':
return '9';
default:
return 0;
}
}
bool text_string(const GString* word, GString* text) {
g_string_set_size(text, word->len);
for (size_t i = 0; i < word->len; ++i) {
char c = text_char(g_ascii_tolower(word->str[i]));
if (c == 0)
return false;
text->str[i] = c;
}
return true;
}
typedef struct textonym_tag {
const char* text;
size_t length;
GPtrArray* words;
} textonym_t;
int compare_by_text_length(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->length > t2->length)
return -1;
if (t1->length < t2->length)
return 1;
return strcmp(t1->text, t2->text);
}
int compare_by_word_count(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->words->len > t2->words->len)
return -1;
if (t1->words->len < t2->words->len)
return 1;
return strcmp(t1->text, t2->text);
}
void print_words(GPtrArray* words) {
for (guint i = 0, n = words->len; i < n; ++i) {
if (i > 0)
printf(", ");
printf("%s", g_ptr_array_index(words, i));
}
printf("\n");
}
void print_top_words(GArray* textonyms, guint top) {
for (guint i = 0; i < top; ++i) {
const textonym_t* t = &g_array_index(textonyms, textonym_t, i);
printf("%s = ", t->text);
print_words(t->words);
}
}
void free_strings(gpointer ptr) {
g_ptr_array_free(ptr, TRUE);
}
bool find_textonyms(const char* filename, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(filename, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return false;
}
GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, free_strings);
GString* word = g_string_sized_new(64);
GString* text = g_string_sized_new(64);
guint count = 0;
gsize term_pos;
while (g_io_channel_read_line_string(channel, word, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
g_string_truncate(word, term_pos);
if (!text_string(word, text))
continue;
GPtrArray* words = g_hash_table_lookup(ht, text->str);
if (words == NULL) {
words = g_ptr_array_new_full(1, g_free);
g_hash_table_insert(ht, g_strdup(text->str), words);
}
g_ptr_array_add(words, g_strdup(word->str));
++count;
}
g_io_channel_unref(channel);
g_string_free(word, TRUE);
g_string_free(text, TRUE);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_hash_table_destroy(ht);
return false;
}
GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, ht);
while (g_hash_table_iter_next(&iter, &key, &value)) {
GPtrArray* v = value;
if (v->len > 1) {
textonym_t textonym;
textonym.text = key;
textonym.length = strlen(key);
textonym.words = v;
g_array_append_val(words, textonym);
}
}
printf("There are %u words in '%s' which can be represented by the digit key mapping.\n",
count, filename);
guint size = g_hash_table_size(ht);
printf("They require %u digit combinations to represent them.\n", size);
guint textonyms = words->len;
printf("%u digit combinations represent Textonyms.\n", textonyms);
guint top = 5;
if (textonyms < top)
top = textonyms;
printf("\nTop %u by number of words:\n", top);
g_array_sort(words, compare_by_word_count);
print_top_words(words, top);
printf("\nTop %u by length:\n", top);
g_array_sort(words, compare_by_text_length);
print_top_words(words, top);
g_array_free(words, TRUE);
g_hash_table_destroy(ht);
return true;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s word-list\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
if (!find_textonyms(argv[1], &error)) {
if (error != NULL) {
fprintf(stderr, "%s: %s\n", argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
Write the same code in C as shown below in Python. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <iso646.h>
#include <math.h>
#define map_size_rows 10
#define map_size_cols 10
char map[map_size_rows][map_size_cols] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
struct stop {
double col, row;
int * n;
int n_len;
double f, g, h;
int from;
};
int ind[map_size_rows][map_size_cols] = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
struct route {
int x;
int y;
double d;
};
int main() {
int i, j, k, l, b, found;
int p_len = 0;
int * path = NULL;
int c_len = 0;
int * closed = NULL;
int o_len = 1;
int * open = (int*)calloc(o_len, sizeof(int));
double min, tempg;
int s;
int e;
int current;
int s_len = 0;
struct stop * stops = NULL;
int r_len = 0;
struct route * routes = NULL;
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (!map[i][j]) {
++s_len;
stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));
int t = s_len - 1;
stops[t].col = j;
stops[t].row = i;
stops[t].from = -1;
stops[t].g = DBL_MAX;
stops[t].n_len = 0;
stops[t].n = NULL;
ind[i][j] = t;
}
}
}
s = 0;
e = s_len - 1;
for (i = 0; i < s_len; i++) {
stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));
}
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (ind[i][j] >= 0) {
for (k = i - 1; k <= i + 1; k++) {
for (l = j - 1; l <= j + 1; l++) {
if ((k == i) and (l == j)) {
continue;
}
if (ind[k][l] >= 0) {
++r_len;
routes = (struct route *)realloc(routes, r_len * sizeof(struct route));
int t = r_len - 1;
routes[t].x = ind[i][j];
routes[t].y = ind[k][l];
routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));
++stops[routes[t].x].n_len;
stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));
stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;
}
}
}
}
}
}
open[0] = s;
stops[s].g = 0;
stops[s].f = stops[s].g + stops[s].h;
found = 0;
while (o_len and not found) {
min = DBL_MAX;
for (i = 0; i < o_len; i++) {
if (stops[open[i]].f < min) {
current = open[i];
min = stops[open[i]].f;
}
}
if (current == e) {
found = 1;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
while (stops[current].from >= 0) {
current = stops[current].from;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
}
}
for (i = 0; i < o_len; i++) {
if (open[i] == current) {
if (i not_eq (o_len - 1)) {
for (j = i; j < (o_len - 1); j++) {
open[j] = open[j + 1];
}
}
--o_len;
open = (int*)realloc(open, o_len * sizeof(int));
break;
}
}
++c_len;
closed = (int*)realloc(closed, c_len * sizeof(int));
closed[c_len - 1] = current;
for (i = 0; i < stops[current].n_len; i++) {
b = 0;
for (j = 0; j < c_len; j++) {
if (routes[stops[current].n[i]].y == closed[j]) {
b = 1;
}
}
if (b) {
continue;
}
tempg = stops[current].g + routes[stops[current].n[i]].d;
b = 1;
if (o_len > 0) {
for (j = 0; j < o_len; j++) {
if (routes[stops[current].n[i]].y == open[j]) {
b = 0;
}
}
}
if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {
stops[routes[stops[current].n[i]].y].from = current;
stops[routes[stops[current].n[i]].y].g = tempg;
stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;
if (b) {
++o_len;
open = (int*)realloc(open, o_len * sizeof(int));
open[o_len - 1] = routes[stops[current].n[i]].y;
}
}
}
}
for (i = 0; i < map_size_rows; i++) {
for (j = 0; j < map_size_cols; j++) {
if (map[i][j]) {
putchar(0xdb);
} else {
b = 0;
for (k = 0; k < p_len; k++) {
if (ind[i][j] == path[k]) {
++b;
}
}
if (b) {
putchar('x');
} else {
putchar('.');
}
}
}
putchar('\n');
}
if (not found) {
puts("IMPOSSIBLE");
} else {
printf("path cost is %d:\n", p_len);
for (i = p_len - 1; i >= 0; i--) {
printf("(%1.0f, %1.0f)\n", stops[path[i]].col, stops[path[i]].row);
}
}
for (i = 0; i < s_len; ++i) {
free(stops[i].n);
}
free(stops);
free(routes);
free(path);
free(open);
free(closed);
return 0;
}
|
Generate a C translation of this Python snippet without changing its computational steps. | from __future__ import print_function
import matplotlib.pyplot as plt
class AStarGraph(object):
def __init__(self):
self.barriers = []
self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)])
def heuristic(self, start, goal):
D = 1
D2 = 1
dx = abs(start[0] - goal[0])
dy = abs(start[1] - goal[1])
return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy)
def get_vertex_neighbours(self, pos):
n = []
for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
continue
n.append((x2, y2))
return n
def move_cost(self, a, b):
for barrier in self.barriers:
if b in barrier:
return 100
return 1
def AStarSearch(start, end, graph):
G = {}
F = {}
G[start] = 0
F[start] = graph.heuristic(start, end)
closedVertices = set()
openVertices = set([start])
cameFrom = {}
while len(openVertices) > 0:
current = None
currentFscore = None
for pos in openVertices:
if current is None or F[pos] < currentFscore:
currentFscore = F[pos]
current = pos
if current == end:
path = [current]
while current in cameFrom:
current = cameFrom[current]
path.append(current)
path.reverse()
return path, F[end]
openVertices.remove(current)
closedVertices.add(current)
for neighbour in graph.get_vertex_neighbours(current):
if neighbour in closedVertices:
continue
candidateG = G[current] + graph.move_cost(current, neighbour)
if neighbour not in openVertices:
openVertices.add(neighbour)
elif candidateG >= G[neighbour]:
continue
cameFrom[neighbour] = current
G[neighbour] = candidateG
H = graph.heuristic(neighbour, end)
F[neighbour] = G[neighbour] + H
raise RuntimeError("A* failed to find a solution")
if __name__=="__main__":
graph = AStarGraph()
result, cost = AStarSearch((0,0), (7,7), graph)
print ("route", result)
print ("cost", cost)
plt.plot([v[0] for v in result], [v[1] for v in result])
for barrier in graph.barriers:
plt.plot([v[0] for v in barrier], [v[1] for v in barrier])
plt.xlim(-1,8)
plt.ylim(-1,8)
plt.show()
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <iso646.h>
#include <math.h>
#define map_size_rows 10
#define map_size_cols 10
char map[map_size_rows][map_size_cols] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 1, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
struct stop {
double col, row;
int * n;
int n_len;
double f, g, h;
int from;
};
int ind[map_size_rows][map_size_cols] = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
struct route {
int x;
int y;
double d;
};
int main() {
int i, j, k, l, b, found;
int p_len = 0;
int * path = NULL;
int c_len = 0;
int * closed = NULL;
int o_len = 1;
int * open = (int*)calloc(o_len, sizeof(int));
double min, tempg;
int s;
int e;
int current;
int s_len = 0;
struct stop * stops = NULL;
int r_len = 0;
struct route * routes = NULL;
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (!map[i][j]) {
++s_len;
stops = (struct stop *)realloc(stops, s_len * sizeof(struct stop));
int t = s_len - 1;
stops[t].col = j;
stops[t].row = i;
stops[t].from = -1;
stops[t].g = DBL_MAX;
stops[t].n_len = 0;
stops[t].n = NULL;
ind[i][j] = t;
}
}
}
s = 0;
e = s_len - 1;
for (i = 0; i < s_len; i++) {
stops[i].h = sqrt(pow(stops[e].row - stops[i].row, 2) + pow(stops[e].col - stops[i].col, 2));
}
for (i = 1; i < map_size_rows - 1; i++) {
for (j = 1; j < map_size_cols - 1; j++) {
if (ind[i][j] >= 0) {
for (k = i - 1; k <= i + 1; k++) {
for (l = j - 1; l <= j + 1; l++) {
if ((k == i) and (l == j)) {
continue;
}
if (ind[k][l] >= 0) {
++r_len;
routes = (struct route *)realloc(routes, r_len * sizeof(struct route));
int t = r_len - 1;
routes[t].x = ind[i][j];
routes[t].y = ind[k][l];
routes[t].d = sqrt(pow(stops[routes[t].y].row - stops[routes[t].x].row, 2) + pow(stops[routes[t].y].col - stops[routes[t].x].col, 2));
++stops[routes[t].x].n_len;
stops[routes[t].x].n = (int*)realloc(stops[routes[t].x].n, stops[routes[t].x].n_len * sizeof(int));
stops[routes[t].x].n[stops[routes[t].x].n_len - 1] = t;
}
}
}
}
}
}
open[0] = s;
stops[s].g = 0;
stops[s].f = stops[s].g + stops[s].h;
found = 0;
while (o_len and not found) {
min = DBL_MAX;
for (i = 0; i < o_len; i++) {
if (stops[open[i]].f < min) {
current = open[i];
min = stops[open[i]].f;
}
}
if (current == e) {
found = 1;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
while (stops[current].from >= 0) {
current = stops[current].from;
++p_len;
path = (int*)realloc(path, p_len * sizeof(int));
path[p_len - 1] = current;
}
}
for (i = 0; i < o_len; i++) {
if (open[i] == current) {
if (i not_eq (o_len - 1)) {
for (j = i; j < (o_len - 1); j++) {
open[j] = open[j + 1];
}
}
--o_len;
open = (int*)realloc(open, o_len * sizeof(int));
break;
}
}
++c_len;
closed = (int*)realloc(closed, c_len * sizeof(int));
closed[c_len - 1] = current;
for (i = 0; i < stops[current].n_len; i++) {
b = 0;
for (j = 0; j < c_len; j++) {
if (routes[stops[current].n[i]].y == closed[j]) {
b = 1;
}
}
if (b) {
continue;
}
tempg = stops[current].g + routes[stops[current].n[i]].d;
b = 1;
if (o_len > 0) {
for (j = 0; j < o_len; j++) {
if (routes[stops[current].n[i]].y == open[j]) {
b = 0;
}
}
}
if (b or (tempg < stops[routes[stops[current].n[i]].y].g)) {
stops[routes[stops[current].n[i]].y].from = current;
stops[routes[stops[current].n[i]].y].g = tempg;
stops[routes[stops[current].n[i]].y].f = stops[routes[stops[current].n[i]].y].g + stops[routes[stops[current].n[i]].y].h;
if (b) {
++o_len;
open = (int*)realloc(open, o_len * sizeof(int));
open[o_len - 1] = routes[stops[current].n[i]].y;
}
}
}
}
for (i = 0; i < map_size_rows; i++) {
for (j = 0; j < map_size_cols; j++) {
if (map[i][j]) {
putchar(0xdb);
} else {
b = 0;
for (k = 0; k < p_len; k++) {
if (ind[i][j] == path[k]) {
++b;
}
}
if (b) {
putchar('x');
} else {
putchar('.');
}
}
}
putchar('\n');
}
if (not found) {
puts("IMPOSSIBLE");
} else {
printf("path cost is %d:\n", p_len);
for (i = p_len - 1; i >= 0; i--) {
printf("(%1.0f, %1.0f)\n", stops[path[i]].col, stops[path[i]].row);
}
}
for (i = 0; i < s_len; ++i) {
free(stops[i].n);
}
free(stops);
free(routes);
free(path);
free(open);
free(closed);
return 0;
}
|
Produce a functionally identical C code for the snippet given in Python. |
from itertools import chain, groupby
from os.path import expanduser
from functools import reduce
def main():
print('\n'.join(
concatMap(circularGroup)(
anagrams(3)(
lines(readFile('~/mitWords.txt'))
)
)
))
def anagrams(n):
def go(ws):
def f(xs):
return [
[snd(x) for x in xs]
] if n <= len(xs) >= len(xs[0][0]) else []
return concatMap(f)(groupBy(fst)(sorted(
[(''.join(sorted(w)), w) for w in ws],
key=fst
)))
return go
def circularGroup(ws):
lex = set(ws)
iLast = len(ws) - 1
(i, blnCircular) = until(
lambda tpl: tpl[1] or (tpl[0] > iLast)
)(
lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))
)(
(0, False)
)
return [' -> '.join(allRotations(ws[i]))] if blnCircular else []
def isCircular(lexicon):
def go(w):
def f(tpl):
(i, _, x) = tpl
return (1 + i, x in lexicon, rotated(x))
iLast = len(w) - 1
return until(
lambda tpl: iLast < tpl[0] or (not tpl[1])
)(f)(
(0, True, rotated(w))
)[1]
return go
def allRotations(w):
return takeIterate(len(w) - 1)(
rotated
)(w)
def concatMap(f):
def go(xs):
return chain.from_iterable(map(f, xs))
return go
def fst(tpl):
return tpl[0]
def groupBy(f):
def go(xs):
return [
list(x[1]) for x in groupby(xs, key=f)
]
return go
def lines(s):
return s.splitlines()
def mapAccumL(f):
def go(a, x):
tpl = f(a[0], x)
return (tpl[0], a[1] + [tpl[1]])
return lambda acc: lambda xs: (
reduce(go, xs, (acc, []))
)
def readFile(fp):
with open(expanduser(fp), 'r', encoding='utf-8') as f:
return f.read()
def rotated(s):
return s[1:] + s[0]
def snd(tpl):
return tpl[1]
def takeIterate(n):
def go(f):
def g(x):
def h(a, i):
v = f(a) if i else x
return (v, v)
return mapAccumL(h)(x)(
range(0, 1 + n)
)[1]
return g
return go
def until(p):
def go(f):
def g(x):
v = x
while not p(v):
v = f(v)
return v
return g
return go
if __name__ == '__main__':
main()
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
int string_compare(gconstpointer p1, gconstpointer p2) {
const char* const* s1 = p1;
const char* const* s2 = p2;
return strcmp(*s1, *s2);
}
GPtrArray* load_dictionary(const char* file, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(file, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return NULL;
}
GPtrArray* dict = g_ptr_array_new_full(1024, g_free);
GString* line = g_string_sized_new(64);
gsize term_pos;
while (g_io_channel_read_line_string(channel, line, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
char* word = g_strdup(line->str);
word[term_pos] = '\0';
g_ptr_array_add(dict, word);
}
g_string_free(line, TRUE);
g_io_channel_unref(channel);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_ptr_array_free(dict, TRUE);
return NULL;
}
g_ptr_array_sort(dict, string_compare);
return dict;
}
void rotate(char* str, size_t len) {
char c = str[0];
memmove(str, str + 1, len - 1);
str[len - 1] = c;
}
char* dictionary_search(const GPtrArray* dictionary, const char* word) {
char** result = bsearch(&word, dictionary->pdata, dictionary->len,
sizeof(char*), string_compare);
return result != NULL ? *result : NULL;
}
void find_teacup_words(GPtrArray* dictionary) {
GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);
GPtrArray* teacup_words = g_ptr_array_new();
GString* temp = g_string_sized_new(8);
for (size_t i = 0, n = dictionary->len; i < n; ++i) {
char* word = g_ptr_array_index(dictionary, i);
size_t len = strlen(word);
if (len < 3 || g_hash_table_contains(found, word))
continue;
g_ptr_array_set_size(teacup_words, 0);
g_string_assign(temp, word);
bool is_teacup_word = true;
for (size_t i = 0; i < len - 1; ++i) {
rotate(temp->str, len);
char* w = dictionary_search(dictionary, temp->str);
if (w == NULL) {
is_teacup_word = false;
break;
}
if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))
g_ptr_array_add(teacup_words, w);
}
if (is_teacup_word && teacup_words->len > 0) {
printf("%s", word);
g_hash_table_add(found, word);
for (size_t i = 0; i < teacup_words->len; ++i) {
char* teacup_word = g_ptr_array_index(teacup_words, i);
printf(" %s", teacup_word);
g_hash_table_add(found, teacup_word);
}
printf("\n");
}
}
g_string_free(temp, TRUE);
g_ptr_array_free(teacup_words, TRUE);
g_hash_table_destroy(found);
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s dictionary\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
GPtrArray* dictionary = load_dictionary(argv[1], &error);
if (dictionary == NULL) {
if (error != NULL) {
fprintf(stderr, "Cannot load dictionary file '%s': %s\n",
argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
find_teacup_words(dictionary);
g_ptr_array_free(dictionary, TRUE);
return EXIT_SUCCESS;
}
|
Port the provided Python code into C while preserving the original functionality. |
def digit_sum(n, sum):
sum += 1
while n > 0 and n % 10 == 0:
sum -= 9
n /= 10
return sum
previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1
print("Gap index Gap Niven index Niven number")
niven = 1
while gap_index <= 22:
sum = digit_sum(niven, sum)
if niven % sum == 0:
if niven > previous + gap:
gap = niven - previous;
print('{0:9d} {1:4d} {2:13d} {3:11d}'.format(gap_index, gap, niven_index, previous))
gap_index += 1
previous = niven
niven_index += 1
niven += 1
| #include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t digit_sum(uint64_t n, uint64_t sum) {
++sum;
while (n > 0 && n % 10 == 0) {
sum -= 9;
n /= 10;
}
return sum;
}
inline bool divisible(uint64_t n, uint64_t d) {
if ((d & 1) == 0 && (n & 1) == 1)
return false;
return n % d == 0;
}
int main() {
setlocale(LC_ALL, "");
uint64_t previous = 1, gap = 0, sum = 0;
int niven_index = 0, gap_index = 1;
printf("Gap index Gap Niven index Niven number\n");
for (uint64_t niven = 1; gap_index <= 32; ++niven) {
sum = digit_sum(niven, sum);
if (divisible(niven, sum)) {
if (niven > previous + gap) {
gap = niven - previous;
printf("%'9d %'4llu %'14d %'15llu\n", gap_index++,
gap, niven_index, previous);
}
previous = niven;
++niven_index;
}
}
return 0;
}
|
Convert the following code from Python to C, ensuring the logic remains intact. | import logging, logging.handlers
LOG_FILENAME = "logdemo.log"
FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s"
LOGLEVEL = logging.DEBUG
def print_squares(number):
logger.info("In print_squares")
for i in range(number):
print("square of {0} is {1}".format(i , i*i))
logger.debug(f'square of {i} is {i*i}')
def print_cubes(number):
logger.info("In print_cubes")
for j in range(number):
print("cube of {0} is {1}".format(j, j*j*j))
logger.debug(f'cube of {j} is {j*j*j}')
if __name__ == "__main__":
logger = logging.getLogger("logdemo")
logger.setLevel(LOGLEVEL)
handler = logging.FileHandler(LOG_FILENAME)
handler.setFormatter(logging.Formatter(FORMAT_STRING))
logger.addHandler(handler)
print_squares(10)
print_cubes(10)
logger.info("All done")
| #include <stdio.h>
#define DEBUG_INT(x) printf( #x " at line %d\nresult: %d\n\n", __LINE__, x)
int add(int x, int y) {
int result = x + y;
DEBUG_INT(x);
DEBUG_INT(y);
DEBUG_INT(result);
DEBUG_INT(result+1);
return result;
}
int main() {
add(2, 7);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Python version. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def isBackPrime(n):
if not isPrime(n):
return False
m = 0
while n:
m *= 10
m += n % 10
n //= 10
return isPrime(m)
if __name__ == '__main__':
for n in range(2, 499):
if isBackPrime(n):
print(n, end=' ');
| #include <stdbool.h>
#include <stdio.h>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int reverse(unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= 10)
rev = rev * 10 + n % 10;
return rev;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 1; n < 500; ++n) {
if (is_prime(n) && is_prime(reverse(n)))
printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
printf("\nCount = %u\n", count);
return 0;
}
|
Translate the given Python code snippet into C without altering its behavior. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def isBackPrime(n):
if not isPrime(n):
return False
m = 0
while n:
m *= 10
m += n % 10
n //= 10
return isPrime(m)
if __name__ == '__main__':
for n in range(2, 499):
if isBackPrime(n):
print(n, end=' ');
| #include <stdbool.h>
#include <stdio.h>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int reverse(unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= 10)
rev = rev * 10 + n % 10;
return rev;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 1; n < 500; ++n) {
if (is_prime(n) && is_prime(reverse(n)))
printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
printf("\nCount = %u\n", count);
return 0;
}
|
Generate an equivalent C version of this Python code. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def isBackPrime(n):
if not isPrime(n):
return False
m = 0
while n:
m *= 10
m += n % 10
n //= 10
return isPrime(m)
if __name__ == '__main__':
for n in range(2, 499):
if isBackPrime(n):
print(n, end=' ');
| #include <stdbool.h>
#include <stdio.h>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
unsigned int reverse(unsigned int n) {
unsigned int rev = 0;
for (; n > 0; n /= 10)
rev = rev * 10 + n % 10;
return rev;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 1; n < 500; ++n) {
if (is_prime(n) && is_prime(reverse(n)))
printf("%3u%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
printf("\nCount = %u\n", count);
return 0;
}
|
Write the same algorithm in C as shown in this Python implementation. |
import matplotlib.pyplot as plt
from math import sin, cos, pi
def sgn(x):
return ((x>0)-(x<0))*1
a,b,n=200,200,2.5
na=2/n
step=100
piece=(pi*2)/step
xp=[];yp=[]
t=0
for t1 in range(step+1):
x=(abs((cos(t)))**na)*a*sgn(cos(t))
y=(abs((sin(t)))**na)*b*sgn(sin(t))
xp.append(x);yp.append(y)
t+=piece
plt.plot(xp,yp)
plt.title("Superellipse with parameter "+str(n))
plt.show()
| #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
double a,b,n,i,incr = 0.0001;
printf("Enter major and minor axes of the SuperEllipse : ");
scanf("%lf%lf",&a,&b);
printf("Enter n : ");
scanf("%lf",&n);
initwindow(500,500,"Superellipse");
for(i=0;i<2*pi;i+=incr){
putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);
}
printf("Done. %lf",i);
getch();
closegraph();
}
|
Convert this Python snippet to C and keep its semantics consistent. |
import matplotlib.pyplot as plt
from math import sin, cos, pi
def sgn(x):
return ((x>0)-(x<0))*1
a,b,n=200,200,2.5
na=2/n
step=100
piece=(pi*2)/step
xp=[];yp=[]
t=0
for t1 in range(step+1):
x=(abs((cos(t)))**na)*a*sgn(cos(t))
y=(abs((sin(t)))**na)*b*sgn(sin(t))
xp.append(x);yp.append(y)
t+=piece
plt.plot(xp,yp)
plt.title("Superellipse with parameter "+str(n))
plt.show()
| #include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
double a,b,n,i,incr = 0.0001;
printf("Enter major and minor axes of the SuperEllipse : ");
scanf("%lf%lf",&a,&b);
printf("Enter n : ");
scanf("%lf",&n);
initwindow(500,500,"Superellipse");
for(i=0;i<2*pi;i+=incr){
putpixel(250 + a*pow(fabs(cos(i)),2/n)*(pi/2<i && i<3*pi/2?-1:1),250 + b*pow(fabs(sin(i)),2/n)*(pi<i && i<2*pi?-1:1),15);
}
printf("Done. %lf",i);
getch();
closegraph();
}
|
Can you help me rewrite this code in C instead of Python, keeping it the same logically? | from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return pi
def init_pi1(n, pi):
pi1 = [-1] * n
for i in range(n):
pi1[pi[i]] = i
return pi1
def ranker1(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s + n * ranker1(n1, pi, pi1)
def unranker2(n, r, pi):
while n > 0:
n1 = n-1
s, rmodf = divmod(r, fact(n1))
pi[n1], pi[s] = pi[s], pi[n1]
n = n1
r = rmodf
return pi
def ranker2(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s * fact(n1) + ranker2(n1, pi, pi1)
def get_random_ranks(permsize, samplesize):
perms = fact(permsize)
ranks = set()
while len(ranks) < samplesize:
ranks |= set( randrange(perms)
for r in range(samplesize - len(ranks)) )
return ranks
def test1(comment, unranker, ranker):
n, samplesize, n2 = 3, 4, 12
print(comment)
perms = []
for r in range(fact(n)):
pi = identity_perm(n)
perm = unranker(n, r, pi)
perms.append((r, perm))
for r, pi in perms:
pi1 = init_pi1(n, pi)
print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))
print('\n %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))
print('')
def test2(comment, unranker):
samplesize, n2 = 4, 144
print(comment)
print(' %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi)))))
print('')
if __name__ == '__main__':
test1('First ordering:', unranker1, ranker1)
test1('Second ordering:', unranker2, ranker2)
test2('First ordering, large number of perms:', unranker1)
| #include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv) {
int s, t;
if (n < 2) return 0;
s = vec[n-1];
SWAP(vec[n-1], vec[inv[n-1]]);
SWAP(inv[s], inv[n-1]);
return s + n * _mr_rank1(n-1, vec, inv);
}
void get_permutation(int rank, int n, int *vec) {
int i;
for (i = 0; i < n; ++i) vec[i] = i;
_mr_unrank1(rank, n, vec);
}
int get_rank(int n, int *vec) {
int i, r, *v, *inv;
v = malloc(n * sizeof(int));
inv = malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
v[i] = vec[i];
inv[vec[i]] = i;
}
r = _mr_rank1(n, v, inv);
free(inv);
free(v);
return r;
}
int main(int argc, char *argv[]) {
int i, r, tv[4];
for (r = 0; r < 24; ++r) {
printf("%3d: ", r);
get_permutation(r, 4, tv);
for (i = 0; i < 4; ++i) {
if (0 == i) printf("[ ");
else printf(", ");
printf("%d", tv[i]);
}
printf(" ] = %d\n", get_rank(4, tv));
}
}
|
Convert the following code from Python to C, ensuring the logic remains intact. | from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return pi
def init_pi1(n, pi):
pi1 = [-1] * n
for i in range(n):
pi1[pi[i]] = i
return pi1
def ranker1(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s + n * ranker1(n1, pi, pi1)
def unranker2(n, r, pi):
while n > 0:
n1 = n-1
s, rmodf = divmod(r, fact(n1))
pi[n1], pi[s] = pi[s], pi[n1]
n = n1
r = rmodf
return pi
def ranker2(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s * fact(n1) + ranker2(n1, pi, pi1)
def get_random_ranks(permsize, samplesize):
perms = fact(permsize)
ranks = set()
while len(ranks) < samplesize:
ranks |= set( randrange(perms)
for r in range(samplesize - len(ranks)) )
return ranks
def test1(comment, unranker, ranker):
n, samplesize, n2 = 3, 4, 12
print(comment)
perms = []
for r in range(fact(n)):
pi = identity_perm(n)
perm = unranker(n, r, pi)
perms.append((r, perm))
for r, pi in perms:
pi1 = init_pi1(n, pi)
print(' From rank %2i to %r back to %2i' % (r, pi, ranker(n, pi[:], pi1)))
print('\n %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + ' '.join('%2i' % i for i in unranker(n2, r, pi)))
print('')
def test2(comment, unranker):
samplesize, n2 = 4, 144
print(comment)
print(' %i random individual samples of %i items:' % (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi)))))
print('')
if __name__ == '__main__':
test1('First ordering:', unranker1, ranker1)
test1('Second ordering:', unranker2, ranker2)
test2('First ordering, large number of perms:', unranker1)
| #include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv) {
int s, t;
if (n < 2) return 0;
s = vec[n-1];
SWAP(vec[n-1], vec[inv[n-1]]);
SWAP(inv[s], inv[n-1]);
return s + n * _mr_rank1(n-1, vec, inv);
}
void get_permutation(int rank, int n, int *vec) {
int i;
for (i = 0; i < n; ++i) vec[i] = i;
_mr_unrank1(rank, n, vec);
}
int get_rank(int n, int *vec) {
int i, r, *v, *inv;
v = malloc(n * sizeof(int));
inv = malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
v[i] = vec[i];
inv[vec[i]] = i;
}
r = _mr_rank1(n, v, inv);
free(inv);
free(v);
return r;
}
int main(int argc, char *argv[]) {
int i, r, tv[4];
for (r = 0; r < 24; ++r) {
printf("%3d: ", r);
get_permutation(r, 4, tv);
for (i = 0; i < 4; ++i) {
if (0 == i) printf("[ ");
else printf(", ");
printf("%d", tv[i]);
}
printf(" ] = %d\n", get_rank(4, tv));
}
}
|
Change the following Python code into C without altering its purpose. | def main():
resources = int(input("Cantidad de recursos: "))
processes = int(input("Cantidad de procesos: "))
max_resources = [int(i) for i in input("Recursos máximos: ").split()]
print("\n-- recursos asignados para cada proceso --")
currently_allocated = [[int(i) for i in input(f"proceso {j + 1}: ").split()] for j in range(processes)]
print("\n--- recursos máximos para cada proceso ---")
max_need = [[int(i) for i in input(f"proceso {j + 1}: ").split()] for j in range(processes)]
allocated = [0] * resources
for i in range(processes):
for j in range(resources):
allocated[j] += currently_allocated[i][j]
print(f"\nRecursos totales asignados : {allocated}")
available = [max_resources[i] - allocated[i] for i in range(resources)]
print(f"Recursos totales disponibles: {available}\n")
running = [True] * processes
count = processes
while count != 0:
safe = False
for i in range(processes):
if running[i]:
executing = True
for j in range(resources):
if max_need[i][j] - currently_allocated[i][j] > available[j]:
executing = False
break
if executing:
print(f"proceso {i + 1} ejecutándose")
running[i] = False
count -= 1
safe = True
for j in range(resources):
available[j] += currently_allocated[i][j]
break
if not safe:
print("El proceso está en un estado inseguro.")
break
print(f"El proceso está en un estado seguro.\nRecursos disponibles: {available}\n")
if __name__ == '__main__':
main()
| #include <stdio.h>
#include <stdbool.h>
int main() {
int curr[5][5];
int max_claim[5][5];
int avl[5];
int alloc[5] = {0, 0, 0, 0, 0};
int max_res[5];
int running[5];
int i, j, exec, r, p;
int count = 0;
bool safe = false;
printf("\nEnter the number of resources: ");
scanf("%d", &r);
printf("\nEnter the number of processes: ");
scanf("%d", &p);
for (i = 0; i < p; i++) {
running[i] = 1;
count++;
}
printf("\nEnter Claim Vector: ");
for (i = 0; i < r; i++)
scanf("%d", &max_res[i]);
printf("\nEnter Allocated Resource Table: ");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
scanf("%d", &curr[i][j]);
}
printf("\nEnter Maximum Claim table: ");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
scanf("%d", &max_claim[i][j]);
}
printf("\nThe Claim Vector is: ");
for (i = 0; i < r; i++)
printf("%d ", max_res[i]);
printf("\nThe Allocated Resource Table:\n");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
printf("\t%d", curr[i][j]);
printf("\n");
}
printf("\nThe Maximum Claim Table:\n");
for (i = 0; i < p; i++) {
for (j = 0; j < r; j++)
printf("\t%d", max_claim[i][j]);
printf("\n");
}
for (i = 0; i < p; i++)
for (j = 0; j < r; j++)
alloc[j] += curr[i][j];
printf("\nAllocated resources: ");
for (i = 0; i < r; i++)
printf("%d ", alloc[i]);
for (i = 0; i < r; i++)
avl[i] = max_res[i] - alloc[i];
printf("\nAvailable resources: ");
for (i = 0; i < r; i++)
printf("%d ", avl[i]);
printf("\n");
while (count != 0) {
safe = false;
for (i = 0; i < p; i++) {
if (running[i]) {
exec = 1;
for (j = 0; j < r; j++) {
if (max_claim[i][j] - curr[i][j] > avl[j]) {
exec = 0;
break;
}
}
if (exec) {
printf("\nProcess%d is executing.\n", i + 1);
running[i] = 0;
count--;
safe = true;
for (j = 0; j < r; j++)
avl[j] += curr[i][j];
break;
}
}
}
if (!safe) {
printf("\nThe processes are in unsafe state.");
break;
}
if (safe)
printf("\nThe process is in safe state.");
printf("\nAvailable vector: ");
for (i = 0; i < r; i++)
printf("%d ", avl[i]);
}
return 0;
}
|
Can you help me rewrite this code in C instead of Python, keeping it the same logically? | def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
elif hi - low == 1:
yield (low,)
yield (hi,)
else:
yield (low,)
i += 1
def printr(ranges):
print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
for r in ranges ) )
if __name__ == '__main__':
for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
printr(range_extract(lst))
| #include <stdio.h>
#include <stdlib.h>
size_t rprint(char *s, int *x, int len)
{
#define sep (a > s ? "," : "")
#define ol (s ? 100 : 0)
int i, j;
char *a = s;
for (i = j = 0; i < len; i = ++j) {
for (; j < len - 1 && x[j + 1] == x[j] + 1; j++);
if (i + 1 < j)
a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]);
else
while (i <= j)
a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]);
}
return a - s;
#undef sep
#undef ol
}
int main()
{
int x[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39 };
char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);
rprint(s, x, sizeof(x) / sizeof(int));
printf("%s\n", s);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Python to C. | import ctypes
import os
from ctypes import c_ubyte, c_int
code = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])
code_size = len(code)
if (os.name == 'posix'):
import mmap
executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
executable_map.write(code)
func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map))
elif (os.name == 'nt'):
code_buffer = ctypes.create_string_buffer(code)
PAGE_EXECUTE_READWRITE = 0x40
MEM_COMMIT = 0x1000
executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)
if (executable_buffer_address == 0):
print('Warning: Failed to enable code execution, call will likely cause a protection fault.')
func_address = ctypes.addressof(code_buffer)
else:
ctypes.memmove(executable_buffer_address, code_buffer, code_size)
func_address = executable_buffer_address
else:
code_buffer = ctypes.create_string_buffer(code)
func_address = ctypes.addressof(code_buffer)
prototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte)
func = prototype(func_address)
res = func(7,12)
print(res)
| #include <stdio.h>
#include <sys/mman.h>
#include <string.h>
int test (int a, int b)
{
char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3};
void *buf;
int c;
buf = mmap (0,sizeof(code),PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE|MAP_ANON,-1,0);
memcpy (buf, code, sizeof(code));
c = ((int (*) (int, int))buf)(a, b);
munmap (buf, sizeof(code));
return c;
}
int main ()
{
printf("%d\n", test(7,12));
return 0;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. | fun maxpathsum(t):
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
a[r, c] += max(a[r+1, c], a[r=1, c+1])
return a[1, 1]
let test = [
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[07, 36, 79, 16, 37, 68],
[48, 07, 09, 18, 70, 26, 06],
[18, 72, 79, 46, 59, 79, 29, 90],
[20, 76, 87, 11, 32, 07, 07, 49, 18],
[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]
@print maxpathsum test
| #include <stdio.h>
#include <math.h>
#define max(x,y) ((x) > (y) ? (x) : (y))
int tri[] = {
55,
94, 48,
95, 30, 96,
77, 71, 26, 67,
97, 13, 76, 38, 45,
7, 36, 79, 16, 37, 68,
48, 7, 9, 18, 70, 26, 6,
18, 72, 79, 46, 59, 79, 29, 90,
20, 76, 87, 11, 32, 7, 7, 49, 18,
27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
};
int main(void)
{
const int len = sizeof(tri) / sizeof(tri[0]);
const int base = (sqrt(8*len + 1) - 1) / 2;
int step = base - 1;
int stepc = 0;
int i;
for (i = len - base - 1; i >= 0; --i) {
tri[i] += max(tri[i + step], tri[i + step + 1]);
if (++stepc == step) {
step--;
stepc = 0;
}
}
printf("%d\n", tri[0]);
return 0;
}
|
Write a version of this Python function in C with identical behavior. | fun maxpathsum(t):
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
a[r, c] += max(a[r+1, c], a[r=1, c+1])
return a[1, 1]
let test = [
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[07, 36, 79, 16, 37, 68],
[48, 07, 09, 18, 70, 26, 06],
[18, 72, 79, 46, 59, 79, 29, 90],
[20, 76, 87, 11, 32, 07, 07, 49, 18],
[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]
@print maxpathsum test
| #include <stdio.h>
#include <math.h>
#define max(x,y) ((x) > (y) ? (x) : (y))
int tri[] = {
55,
94, 48,
95, 30, 96,
77, 71, 26, 67,
97, 13, 76, 38, 45,
7, 36, 79, 16, 37, 68,
48, 7, 9, 18, 70, 26, 6,
18, 72, 79, 46, 59, 79, 29, 90,
20, 76, 87, 11, 32, 7, 7, 49, 18,
27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
};
int main(void)
{
const int len = sizeof(tri) / sizeof(tri[0]);
const int base = (sqrt(8*len + 1) - 1) / 2;
int step = base - 1;
int stepc = 0;
int i;
for (i = len - base - 1; i >= 0; --i) {
tri[i] += max(tri[i + step], tri[i + step + 1]);
if (++stepc == step) {
step--;
stepc = 0;
}
}
printf("%d\n", tri[0]);
return 0;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. |
beforeTxt =
smallrc01 =
rc01 =
def intarray(binstring):
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
Return 8-neighbours of point p1 of picture, in order'''
i = image
x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1],
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]
def transitions(neighbours):
n = neighbours + neighbours[0:1]
return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))
def zhangSuen(image):
changing1 = changing2 = [(-1, -1)]
while changing1 or changing2:
changing1 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P4 * P6 * P8 == 0 and
P2 * P4 * P6 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing1.append((x,y))
for x, y in changing1: image[y][x] = 0
changing2 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P2 * P6 * P8 == 0 and
P2 * P4 * P8 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing2.append((x,y))
for x, y in changing2: image[y][x] = 0
return image
if __name__ == '__main__':
for picture in (beforeTxt, smallrc01, rc01):
image = intarray(picture)
print('\nFrom:\n%s' % toTxt(image))
after = zhangSuen(image)
print('\nTo thinned:\n%s' % toTxt(after))
| #include<stdlib.h>
#include<stdio.h>
char** imageMatrix;
char blankPixel,imagePixel;
typedef struct{
int row,col;
}pixel;
int getBlackNeighbours(int row,int col){
int i,j,sum = 0;
for(i=-1;i<=1;i++){
for(j=-1;j<=1;j++){
if(i!=0 || j!=0)
sum+= (imageMatrix[row+i][col+j]==imagePixel);
}
}
return sum;
}
int getBWTransitions(int row,int col){
return ((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel)
+(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel)
+(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel)
+(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel)
+(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel)
+(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel)
+(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel)
+(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel));
}
int zhangSuenTest1(int row,int col){
int neighbours = getBlackNeighbours(row,col);
return ((neighbours>=2 && neighbours<=6)
&& (getBWTransitions(row,col)==1)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel)
&& (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel));
}
int zhangSuenTest2(int row,int col){
int neighbours = getBlackNeighbours(row,col);
return ((neighbours>=2 && neighbours<=6)
&& (getBWTransitions(row,col)==1)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel)
&& (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel));
}
void zhangSuen(char* inputFile, char* outputFile){
int startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed;
pixel* markers;
FILE* inputP = fopen(inputFile,"r");
fscanf(inputP,"%d%d",&rows,&cols);
fscanf(inputP,"%d%d",&blankPixel,&imagePixel);
blankPixel<=9?blankPixel+='0':blankPixel;
imagePixel<=9?imagePixel+='0':imagePixel;
printf("\nPrinting original image :\n");
imageMatrix = (char**)malloc(rows*sizeof(char*));
for(i=0;i<rows;i++){
imageMatrix[i] = (char*)malloc((cols+1)*sizeof(char));
fscanf(inputP,"%s\n",imageMatrix[i]);
printf("\n%s",imageMatrix[i]);
}
fclose(inputP);
endRow = rows-2;
endCol = cols-2;
do{
markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));
count = 0;
for(i=startRow;i<=endRow;i++){
for(j=startCol;j<=endCol;j++){
if(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){
markers[count].row = i;
markers[count].col = j;
count++;
}
}
}
processed = (count>0);
for(i=0;i<count;i++){
imageMatrix[markers[i].row][markers[i].col] = blankPixel;
}
free(markers);
markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel));
count = 0;
for(i=startRow;i<=endRow;i++){
for(j=startCol;j<=endCol;j++){
if(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){
markers[count].row = i;
markers[count].col = j;
count++;
}
}
}
if(processed==0)
processed = (count>0);
for(i=0;i<count;i++){
imageMatrix[markers[i].row][markers[i].col] = blankPixel;
}
free(markers);
}while(processed==1);
FILE* outputP = fopen(outputFile,"w");
printf("\n\n\nPrinting image after applying Zhang Suen Thinning Algorithm : \n\n\n");
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
printf("%c",imageMatrix[i][j]);
fprintf(outputP,"%c",imageMatrix[i][j]);
}
printf("\n");
fprintf(outputP,"\n");
}
fclose(outputP);
printf("\nImage also written to : %s",outputFile);
}
int main()
{
char inputFile[100],outputFile[100];
printf("Enter full path of input image file : ");
scanf("%s",inputFile);
printf("Enter full path of output image file : ");
scanf("%s",outputFile);
zhangSuen(inputFile,outputFile);
return 0;
}
|
Convert the following code from Python to C, ensuring the logic remains intact. | import Image, ImageFilter
im = Image.open('image.ppm')
median = im.filter(ImageFilter.MedianFilter(3))
median.save('image2.ppm')
| #include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
typedef struct { unsigned char r, g, b; } rgb_t;
typedef struct {
int w, h;
rgb_t **pix;
} image_t, *image;
typedef struct {
int r[256], g[256], b[256];
int n;
} color_histo_t;
int write_ppm(image im, char *fn)
{
FILE *fp = fopen(fn, "w");
if (!fp) return 0;
fprintf(fp, "P6\n%d %d\n255\n", im->w, im->h);
fwrite(im->pix[0], 1, sizeof(rgb_t) * im->w * im->h, fp);
fclose(fp);
return 1;
}
image img_new(int w, int h)
{
int i;
image im = malloc(sizeof(image_t) + h * sizeof(rgb_t*)
+ sizeof(rgb_t) * w * h);
im->w = w; im->h = h;
im->pix = (rgb_t**)(im + 1);
for (im->pix[0] = (rgb_t*)(im->pix + h), i = 1; i < h; i++)
im->pix[i] = im->pix[i - 1] + w;
return im;
}
int read_num(FILE *f)
{
int n;
while (!fscanf(f, "%d ", &n)) {
if ((n = fgetc(f)) == '#') {
while ((n = fgetc(f)) != '\n')
if (n == EOF) break;
if (n == '\n') continue;
} else return 0;
}
return n;
}
image read_ppm(char *fn)
{
FILE *fp = fopen(fn, "r");
int w, h, maxval;
image im = 0;
if (!fp) return 0;
if (fgetc(fp) != 'P' || fgetc(fp) != '6' || !isspace(fgetc(fp)))
goto bail;
w = read_num(fp);
h = read_num(fp);
maxval = read_num(fp);
if (!w || !h || !maxval) goto bail;
im = img_new(w, h);
fread(im->pix[0], 1, sizeof(rgb_t) * w * h, fp);
bail:
if (fp) fclose(fp);
return im;
}
void del_pixels(image im, int row, int col, int size, color_histo_t *h)
{
int i;
rgb_t *pix;
if (col < 0 || col >= im->w) return;
for (i = row - size; i <= row + size && i < im->h; i++) {
if (i < 0) continue;
pix = im->pix[i] + col;
h->r[pix->r]--;
h->g[pix->g]--;
h->b[pix->b]--;
h->n--;
}
}
void add_pixels(image im, int row, int col, int size, color_histo_t *h)
{
int i;
rgb_t *pix;
if (col < 0 || col >= im->w) return;
for (i = row - size; i <= row + size && i < im->h; i++) {
if (i < 0) continue;
pix = im->pix[i] + col;
h->r[pix->r]++;
h->g[pix->g]++;
h->b[pix->b]++;
h->n++;
}
}
void init_histo(image im, int row, int size, color_histo_t*h)
{
int j;
memset(h, 0, sizeof(color_histo_t));
for (j = 0; j < size && j < im->w; j++)
add_pixels(im, row, j, size, h);
}
int median(const int *x, int n)
{
int i;
for (n /= 2, i = 0; i < 256 && (n -= x[i]) > 0; i++);
return i;
}
void median_color(rgb_t *pix, const color_histo_t *h)
{
pix->r = median(h->r, h->n);
pix->g = median(h->g, h->n);
pix->b = median(h->b, h->n);
}
image median_filter(image in, int size)
{
int row, col;
image out = img_new(in->w, in->h);
color_histo_t h;
for (row = 0; row < in->h; row ++) {
for (col = 0; col < in->w; col++) {
if (!col) init_histo(in, row, size, &h);
else {
del_pixels(in, row, col - size, size, &h);
add_pixels(in, row, col + size, size, &h);
}
median_color(out->pix[row] + col, &h);
}
}
return out;
}
int main(int c, char **v)
{
int size;
image in, out;
if (c <= 3) {
printf("Usage: %s size ppm_in ppm_out\n", v[0]);
return 0;
}
size = atoi(v[1]);
printf("filter size %d\n", size);
if (size < 0) size = 1;
in = read_ppm(v[2]);
out = median_filter(in, size);
write_ppm(out, v[3]);
free(in);
free(out);
return 0;
}
|
Translate the given Python code snippet into C without altering its behavior. |
import posix
import os
import sys
pid = posix.fork()
if pid != 0:
print("Child process detached with pid %s" % pid)
sys.exit(0)
old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdin = open('/dev/null', 'rt')
sys.stdout = open('/tmp/dmn.log', 'wt')
sys.stderr = sys.stdout
old_stdin.close()
old_stdout.close()
old_stderr.close()
posix.setsid()
import time
t = time.time()
while time.time() < t + 10:
print("timer running, %s seconds" % str(time.time() - t))
time.sleep(1)
| #include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
extern char *__progname;
time_t clock;
int fd;
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", __progname);
exit(1);
}
fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);
if (fd < 0)
err(1, argv[1]);
if (daemon(0, 0) < 0)
err(1, "daemon");
if (dup2(fd, STDOUT_FILENO) < 0) {
syslog(LOG_ERR, "dup2: %s", strerror(errno));
exit(1);
}
close(fd);
for (;;) {
time(&clock);
fputs(ctime(&clock), stdout);
if (fflush(stdout) == EOF) {
syslog(LOG_ERR, "%s: %s", argv[1], strerror(errno));
exit(1);
}
sleep(1);
}
}
|
Change the programming language of this snippet from Python to C without modifying what it does. |
import posix
import os
import sys
pid = posix.fork()
if pid != 0:
print("Child process detached with pid %s" % pid)
sys.exit(0)
old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdin = open('/dev/null', 'rt')
sys.stdout = open('/tmp/dmn.log', 'wt')
sys.stderr = sys.stdout
old_stdin.close()
old_stdout.close()
old_stderr.close()
posix.setsid()
import time
t = time.time()
while time.time() < t + 10:
print("timer running, %s seconds" % str(time.time() - t))
time.sleep(1)
| #include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
extern char *__progname;
time_t clock;
int fd;
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", __progname);
exit(1);
}
fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0666);
if (fd < 0)
err(1, argv[1]);
if (daemon(0, 0) < 0)
err(1, "daemon");
if (dup2(fd, STDOUT_FILENO) < 0) {
syslog(LOG_ERR, "dup2: %s", strerror(errno));
exit(1);
}
close(fd);
for (;;) {
time(&clock);
fputs(ctime(&clock), stdout);
if (fflush(stdout) == EOF) {
syslog(LOG_ERR, "%s: %s", argv[1], strerror(errno));
exit(1);
}
sleep(1);
}
}
|
Rewrite the snippet below in C so it works the same as the original Python code. |
def Gcd(v1, v2):
a, b = v1, v2
if (a < b):
a, b = v2, v1
r = 1
while (r != 0):
r = a % b
if (r != 0):
a = b
b = r
return b
a = [1, 2]
n = 3
while (n < 50):
gcd1 = Gcd(n, a[-1])
gcd2 = Gcd(n, a[-2])
if (gcd1 == 1 and gcd2 == 1 and not(n in a)):
a.append(n)
n = 3
else:
n += 1
for i in range(0, len(a)):
if (i % 10 == 0):
print('')
print("%4d" % a[i], end = '');
print("\n\nNumber of elements in coprime triplets = " + str(len(a)), end = "\n")
|
#include <stdio.h>
int Gcd(int v1, int v2)
{
int a, b, r;
if (v1 < v2)
{
a = v2;
b = v1;
}
else
{
a = v1;
b = v2;
}
do
{
r = a % b;
if (r == 0)
{
break;
}
else
{
a = b;
b = r;
}
} while (1 == 1);
return b;
}
int NotInList(int num, int numtrip, int *tripletslist)
{
for (int i = 0; i < numtrip; i++)
{
if (num == tripletslist[i])
{
return 0;
}
}
return 1;
}
int main()
{
int coprime[50];
int gcd1, gcd2;
int ntrip = 2;
int n = 3;
coprime[0] = 1;
coprime[1] = 2;
while ( n < 50)
{
gcd1 = Gcd(n, coprime[ntrip-1]);
gcd2 = Gcd(n, coprime[ntrip-2]);
if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))
{
coprime[ntrip++] = n;
n = 3;
}
else
{
n++;
}
}
printf("\n");
for (int i = 0; i < ntrip; i++)
{
printf("%2d ", coprime[i]);
if ((i+1) % 10 == 0)
{
printf("\n");
}
}
printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip);
return 0;
}
|
Write the same algorithm in C as shown in this Python implementation. |
def Gcd(v1, v2):
a, b = v1, v2
if (a < b):
a, b = v2, v1
r = 1
while (r != 0):
r = a % b
if (r != 0):
a = b
b = r
return b
a = [1, 2]
n = 3
while (n < 50):
gcd1 = Gcd(n, a[-1])
gcd2 = Gcd(n, a[-2])
if (gcd1 == 1 and gcd2 == 1 and not(n in a)):
a.append(n)
n = 3
else:
n += 1
for i in range(0, len(a)):
if (i % 10 == 0):
print('')
print("%4d" % a[i], end = '');
print("\n\nNumber of elements in coprime triplets = " + str(len(a)), end = "\n")
|
#include <stdio.h>
int Gcd(int v1, int v2)
{
int a, b, r;
if (v1 < v2)
{
a = v2;
b = v1;
}
else
{
a = v1;
b = v2;
}
do
{
r = a % b;
if (r == 0)
{
break;
}
else
{
a = b;
b = r;
}
} while (1 == 1);
return b;
}
int NotInList(int num, int numtrip, int *tripletslist)
{
for (int i = 0; i < numtrip; i++)
{
if (num == tripletslist[i])
{
return 0;
}
}
return 1;
}
int main()
{
int coprime[50];
int gcd1, gcd2;
int ntrip = 2;
int n = 3;
coprime[0] = 1;
coprime[1] = 2;
while ( n < 50)
{
gcd1 = Gcd(n, coprime[ntrip-1]);
gcd2 = Gcd(n, coprime[ntrip-2]);
if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))
{
coprime[ntrip++] = n;
n = 3;
}
else
{
n++;
}
}
printf("\n");
for (int i = 0; i < ntrip; i++)
{
printf("%2d ", coprime[i]);
if ((i+1) % 10 == 0)
{
printf("\n");
}
}
printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip);
return 0;
}
|
Change the following Python code into C without altering its purpose. |
def Gcd(v1, v2):
a, b = v1, v2
if (a < b):
a, b = v2, v1
r = 1
while (r != 0):
r = a % b
if (r != 0):
a = b
b = r
return b
a = [1, 2]
n = 3
while (n < 50):
gcd1 = Gcd(n, a[-1])
gcd2 = Gcd(n, a[-2])
if (gcd1 == 1 and gcd2 == 1 and not(n in a)):
a.append(n)
n = 3
else:
n += 1
for i in range(0, len(a)):
if (i % 10 == 0):
print('')
print("%4d" % a[i], end = '');
print("\n\nNumber of elements in coprime triplets = " + str(len(a)), end = "\n")
|
#include <stdio.h>
int Gcd(int v1, int v2)
{
int a, b, r;
if (v1 < v2)
{
a = v2;
b = v1;
}
else
{
a = v1;
b = v2;
}
do
{
r = a % b;
if (r == 0)
{
break;
}
else
{
a = b;
b = r;
}
} while (1 == 1);
return b;
}
int NotInList(int num, int numtrip, int *tripletslist)
{
for (int i = 0; i < numtrip; i++)
{
if (num == tripletslist[i])
{
return 0;
}
}
return 1;
}
int main()
{
int coprime[50];
int gcd1, gcd2;
int ntrip = 2;
int n = 3;
coprime[0] = 1;
coprime[1] = 2;
while ( n < 50)
{
gcd1 = Gcd(n, coprime[ntrip-1]);
gcd2 = Gcd(n, coprime[ntrip-2]);
if (gcd1 == 1 && gcd2 == 1 && NotInList(n, ntrip, coprime))
{
coprime[ntrip++] = n;
n = 3;
}
else
{
n++;
}
}
printf("\n");
for (int i = 0; i < ntrip; i++)
{
printf("%2d ", coprime[i]);
if ((i+1) % 10 == 0)
{
printf("\n");
}
}
printf("\n\nNumber of elements in coprime triplets: %d\n\n", ntrip);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Python. | s = [1, 2, 2, 3, 4, 4, 5]
for i in range(len(s)):
curr = s[i]
if i > 0 and curr == prev:
print(i)
prev = curr
| #include <stdio.h>
int main() {
int i, gprev = 0;
int s[7] = {1, 2, 2, 3, 4, 4, 5};
for (i = 0; i < 7; ++i) {
int curr = s[i];
int prev = 0;
if (i > 0 && curr == prev) printf("%d\n", i);
prev = curr;
}
for (i = 0; i < 7; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) printf("%d\n", i);
gprev = curr;
}
return 0;
}
|
Change the programming language of this snippet from Python to C without modifying what it does. | from SOAPpy import WSDL
proxy = WSDL.Proxy("http://example.com/soap/wsdl")
result = proxy.soapFunc("hello")
result = proxy.anotherSoapFunc(34234)
| #include <curl/curl.h>
#include <string.h>
#include <stdio.h>
size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fwrite(ptr,size,nmeb,stream);
}
size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fread(ptr,size,nmeb,stream);
}
void callSOAP(char* URL, char * inFile, char * outFile) {
FILE * rfp = fopen(inFile, "r");
if(!rfp)
perror("Read File Open:");
FILE * wfp = fopen(outFile, "w+");
if(!wfp)
perror("Write File Open:");
struct curl_slist *header = NULL;
header = curl_slist_append (header, "Content-Type:text/xml");
header = curl_slist_append (header, "SOAPAction: rsc");
header = curl_slist_append (header, "Transfer-Encoding: chunked");
header = curl_slist_append (header, "Expect:");
CURL *curl;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);
curl_easy_setopt(curl, CURLOPT_READDATA, rfp);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);
curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
}
int main(int argC,char* argV[])
{
if(argC!=4)
printf("Usage : %s <URL of WSDL> <Input file path> <Output File Path>",argV[0]);
else
callSOAP(argV[1],argV[2],argV[3]);
return 0;
}
|
Change the following Python code into C without altering its purpose. | from SOAPpy import WSDL
proxy = WSDL.Proxy("http://example.com/soap/wsdl")
result = proxy.soapFunc("hello")
result = proxy.anotherSoapFunc(34234)
| #include <curl/curl.h>
#include <string.h>
#include <stdio.h>
size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fwrite(ptr,size,nmeb,stream);
}
size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fread(ptr,size,nmeb,stream);
}
void callSOAP(char* URL, char * inFile, char * outFile) {
FILE * rfp = fopen(inFile, "r");
if(!rfp)
perror("Read File Open:");
FILE * wfp = fopen(outFile, "w+");
if(!wfp)
perror("Write File Open:");
struct curl_slist *header = NULL;
header = curl_slist_append (header, "Content-Type:text/xml");
header = curl_slist_append (header, "SOAPAction: rsc");
header = curl_slist_append (header, "Transfer-Encoding: chunked");
header = curl_slist_append (header, "Expect:");
CURL *curl;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);
curl_easy_setopt(curl, CURLOPT_READDATA, rfp);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);
curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
}
int main(int argC,char* argV[])
{
if(argC!=4)
printf("Usage : %s <URL of WSDL> <Input file path> <Output File Path>",argV[0]);
else
callSOAP(argV[1],argV[2],argV[3]);
return 0;
}
|
Generate a C translation of this Python snippet without changing its computational steps. | Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import __future__
>>> __future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL']
>>>
|
#include<stdio.h>
#define Hi printf("Hi There.");
#define start int main(){
#define end return 0;}
start
Hi
#warning "Don't you have anything better to do ?"
#ifdef __unix__
#warning "What are you doing still working on Unix ?"
printf("\nThis is an Unix system.");
#elif _WIN32
#warning "You couldn't afford a 64 bit ?"
printf("\nThis is a 32 bit Windows system.");
#elif _WIN64
#warning "You couldn't afford an Apple ?"
printf("\nThis is a 64 bit Windows system.");
#endif
end
|
Port the following code from Python to C with equivalent syntax and logic. | def msb(x):
return x.bit_length() - 1
def lsb(x):
return msb(x & -x)
for i in range(6):
x = 42 ** i
print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
for i in range(6):
x = 1302 ** i
print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
| #include <stdio.h>
#include <stdint.h>
uint32_t msb32(uint32_t n)
{
uint32_t b = 1;
if (!n) return 0;
#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
int msb32_idx(uint32_t n)
{
int b = 0;
if (!n) return -1;
#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )
inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }
int main()
{
int32_t n;
int i;
for (i = 0, n = 1; ; i++, n *= 42) {
printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n, n,
msb32(n), msb32_idx(n),
lsb32(n), lsb32_idx(n));
if (n >= INT32_MAX / 42) break;
}
return 0;
}
|
Transform the following Python implementation into C, maintaining the same output and logic. | def msb(x):
return x.bit_length() - 1
def lsb(x):
return msb(x & -x)
for i in range(6):
x = 42 ** i
print("%10d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
for i in range(6):
x = 1302 ** i
print("%20d MSB: %2d LSB: %2d" % (x, msb(x), lsb(x)))
| #include <stdio.h>
#include <stdint.h>
uint32_t msb32(uint32_t n)
{
uint32_t b = 1;
if (!n) return 0;
#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
int msb32_idx(uint32_t n)
{
int b = 0;
if (!n) return -1;
#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x
step(16); step(8); step(4); step(2); step(1);
#undef step
return b;
}
#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )
inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }
int main()
{
int32_t n;
int i;
for (i = 0, n = 1; ; i++, n *= 42) {
printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
i, n, n,
msb32(n), msb32_idx(n),
lsb32(n), lsb32_idx(n));
if (n >= INT32_MAX / 42) break;
}
return 0;
}
|
Write the same algorithm in C as shown in this Python implementation. | import itertools
def riseEqFall(num):
height = 0
d1 = num % 10
num //= 10
while num:
d2 = num % 10
height += (d1<d2) - (d1>d2)
d1 = d2
num //= 10
return height == 0
def sequence(start, fn):
num=start-1
while True:
num += 1
while not fn(num): num += 1
yield num
a296712 = sequence(1, riseEqFall)
print("The first 200 numbers are:")
print(*itertools.islice(a296712, 200))
print("The 10,000,000th number is:")
print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
| #include <stdio.h>
int riseEqFall(int num) {
int rdigit = num % 10;
int netHeight = 0;
while (num /= 10) {
netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);
rdigit = num % 10;
}
return netHeight == 0;
}
int nextNum() {
static int num = 0;
do {num++;} while (!riseEqFall(num));
return num;
}
int main(void) {
int total, num;
printf("The first 200 numbers are: \n");
for (total = 0; total < 200; total++)
printf("%d ", nextNum());
printf("\n\nThe 10,000,000th number is: ");
for (; total < 10000000; total++) num = nextNum();
printf("%d\n", num);
return 0;
}
|
Write a version of this Python function in C with identical behavior. | import curses
scr = curses.initscr()
def move_left():
y,x = curses.getyx()
curses.move(y,x-1)
def move_right():
y,x = curses.getyx()
curses.move(y,x+1)
def move_up():
y,x = curses.getyx()
curses.move(y-1,x)
def move_down():
y,x = curses.getyx()
curses.move(y+1,x)
def move_line_home()
y,x = curses.getyx()
curses.move(y,0)
def move_line_end()
y,x = curses.getyx()
maxy,maxx = scr.getmaxyx()
curses.move(y,maxx)
def move_page_home():
curses.move(0,0)
def move_page_end():
y,x = scr.getmaxyx()
curses.move(y,x)
| #include<conio.h>
#include<dos.h>
char *strings[] = {"The cursor will move one position to the left",
"The cursor will move one position to the right",
"The cursor will move vetically up one line",
"The cursor will move vertically down one line",
"The cursor will move to the beginning of the line",
"The cursor will move to the end of the line",
"The cursor will move to the top left corner of the screen",
"The cursor will move to the bottom right corner of the screen"};
int main()
{
int i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
clrscr();
cprintf("This is a demonstration of cursor control using gotoxy(). Press any key to continue.");
getch();
for(i=0;i<8;i++)
{
clrscr();
gotoxy(5,MAXROW/2);
cprintf("%s",strings[i]);
getch();
switch(i){
case 0:gotoxy(wherex()-1,wherey());
break;
case 1:gotoxy(wherex()+1,wherey());
break;
case 2:gotoxy(wherex(),wherey()-1);
break;
case 3:gotoxy(wherex(),wherey()+1);
break;
case 4:for(j=0;j<strlen(strings[i]);j++){
gotoxy(wherex()-1,wherey());
delay(100);
}
break;
case 5:gotoxy(wherex()-strlen(strings[i]),wherey());
for(j=0;j<strlen(strings[i]);j++){
gotoxy(wherex()+1,wherey());
delay(100);
}
break;
case 6:while(wherex()!=1)
{
gotoxy(wherex()-1,wherey());
delay(100);
}
while(wherey()!=1)
{
gotoxy(wherex(),wherey()-1);
delay(100);
}
break;
case 7:while(wherex()!=MAXCOL)
{
gotoxy(wherex()+1,wherey());
delay(100);
}
while(wherey()!=MAXROW)
{
gotoxy(wherex(),wherey()+1);
delay(100);
}
break;
};
getch();
}
clrscr();
cprintf("End of demonstration.");
getch();
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Python code. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
suma = 2
n = 1
for i in range(3, 2000000, 2):
if isPrime(i):
suma += i
n+=1
print(suma)
| #include<stdio.h>
#include<stdlib.h>
int isprime( int p ) {
int i;
if(p==2) return 1;
if(!(p%2)) return 0;
for(i=3; i*i<=p; i+=2) {
if(!(p%i)) return 0;
}
return 1;
}
int main( void ) {
int p;
long int s = 2;
for(p=3;p<2000000;p+=2) {
if(isprime(p)) s+=p;
}
printf( "%ld\n", s );
return 0;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. | l = 300
def setup():
size(400, 400)
background(0, 0, 255)
stroke(255)
translate(width / 2.0, height / 2.0)
translate(-l / 2.0, l * sqrt(3) / 6.0)
for i in range(4):
kcurve(0, l)
rotate(radians(120))
translate(-l, 0)
def kcurve(x1, x2):
s = (x2 - x1) / 3.0
if s < 5:
pushMatrix()
translate(x1, 0)
line(0, 0, s, 0)
line(2 * s, 0, 3 * s, 0)
translate(s, 0)
rotate(radians(60))
line(0, 0, s, 0)
translate(s, 0)
rotate(radians(-120))
line(0, 0, s, 0)
popMatrix()
return
pushMatrix()
translate(x1, 0)
kcurve(0, s)
kcurve(2 * s, 3 * s)
translate(s, 0)
rotate(radians(60))
kcurve(0, s)
translate(s, 0)
rotate(radians(-120))
kcurve(0, s)
popMatrix()
| #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
typedef struct{
double x,y;
}point;
void kochCurve(point p1,point p2,int times){
point p3,p4,p5;
double theta = pi/3;
if(times>0){
p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};
p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};
p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};
kochCurve(p1,p3,times-1);
kochCurve(p3,p4,times-1);
kochCurve(p4,p5,times-1);
kochCurve(p5,p2,times-1);
}
else{
line(p1.x,p1.y,p2.x,p2.y);
}
}
int main(int argC, char** argV)
{
int w,h,r;
point p1,p2;
if(argC!=4){
printf("Usage : %s <window width> <window height> <recursion level>",argV[0]);
}
else{
w = atoi(argV[1]);
h = atoi(argV[2]);
r = atoi(argV[3]);
initwindow(w,h,"Koch Curve");
p1 = (point){10,h-10};
p2 = (point){w-10,h-10};
kochCurve(p1,p2,r);
getch();
closegraph();
}
return 0;
}
|
Port the following code from Python to C with equivalent syntax and logic. | import Tkinter,random
def draw_pixel_2 ( sizex=640,sizey=480 ):
pos = random.randint( 0,sizex-1 ),random.randint( 0,sizey-1 )
root = Tkinter.Tk()
can = Tkinter.Canvas( root,width=sizex,height=sizey,bg='black' )
can.create_rectangle( pos*2,outline='yellow' )
can.pack()
root.title('press ESCAPE to quit')
root.bind('<Escape>',lambda e : root.quit())
root.mainloop()
draw_pixel_2()
| #include<graphics.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand(time(NULL));
initwindow(640,480,"Yellow Random Pixel");
putpixel(rand()%640,rand()%480,YELLOW);
getch();
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Python version. | def isvowel(c):
return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U']
def isletter(c):
return 'a' <= c <= 'z' or 'A' <= c <= 'Z'
def isconsonant(c):
return not isvowel(c) and isletter(c)
def vccounts(s):
a = list(s.lower())
au = set(a)
return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \
sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])
def testvccount():
teststrings = [
"Forever Python programming language",
"Now is the time for all good men to come to the aid of their country."]
for s in teststrings:
vcnt, ccnt, vu, cu = vccounts(s)
print(f"String: {s}\n Vowels: {vcnt} (distinct {vu})\n Consonants: {ccnt} (distinct {cu})\n")
testvccount()
|
#include <stdio.h>
char vowels[] = {'a','e','i','o','u','\n'};
int len(char * str) {
int i = 0;
while (str[i] != '\n') i++;
return i;
}
int isvowel(char c){
int b = 0;
int v = len(vowels);
for(int i = 0; i < v;i++) {
if(c == vowels[i]) {
b = 1;
break;
}
}
return b;
}
int isletter(char c){
return ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));
}
int isconsonant(char c){
return isletter(c) && !isvowel(c);
}
int cVowels(char * str) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isvowel(str[i])) {
count++;;
}
i++;
}
return count;
}
int cConsonants(char * str ) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isconsonant(str[i])) {
count++;
}
i++;
}
return count;
}
int main() {
char buff[] = "This is 1 string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff), cConsonants(buff), len(buff), buff);
char buff2[] = "This is a second string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff2), cConsonants(buff2), len(buff2), buff2);
printf("a: %d\n", isvowel('a'));
printf("b: %d\n", isvowel('b'));
printf("Z: %d\n", isconsonant('Z'));
printf("1: %d\n", isletter('1'));
}
|
Generate a C translation of this Python snippet without changing its computational steps. | def isvowel(c):
return c in ['a', 'e', 'i', 'o', 'u', 'A', 'E', "I", 'O', 'U']
def isletter(c):
return 'a' <= c <= 'z' or 'A' <= c <= 'Z'
def isconsonant(c):
return not isvowel(c) and isletter(c)
def vccounts(s):
a = list(s.lower())
au = set(a)
return sum([isvowel(c) for c in a]), sum([isconsonant(c) for c in a]), \
sum([isvowel(c) for c in au]), sum([isconsonant(c) for c in au])
def testvccount():
teststrings = [
"Forever Python programming language",
"Now is the time for all good men to come to the aid of their country."]
for s in teststrings:
vcnt, ccnt, vu, cu = vccounts(s)
print(f"String: {s}\n Vowels: {vcnt} (distinct {vu})\n Consonants: {ccnt} (distinct {cu})\n")
testvccount()
|
#include <stdio.h>
char vowels[] = {'a','e','i','o','u','\n'};
int len(char * str) {
int i = 0;
while (str[i] != '\n') i++;
return i;
}
int isvowel(char c){
int b = 0;
int v = len(vowels);
for(int i = 0; i < v;i++) {
if(c == vowels[i]) {
b = 1;
break;
}
}
return b;
}
int isletter(char c){
return ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z'));
}
int isconsonant(char c){
return isletter(c) && !isvowel(c);
}
int cVowels(char * str) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isvowel(str[i])) {
count++;;
}
i++;
}
return count;
}
int cConsonants(char * str ) {
int i = 0;
int count = 0;
while (str[i] != '\n') {
if (isconsonant(str[i])) {
count++;
}
i++;
}
return count;
}
int main() {
char buff[] = "This is 1 string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff), cConsonants(buff), len(buff), buff);
char buff2[] = "This is a second string\n";
printf("%4d, %4d, %4d, %s\n", cVowels(buff2), cConsonants(buff2), len(buff2), buff2);
printf("a: %d\n", isvowel('a'));
printf("b: %d\n", isvowel('b'));
printf("Z: %d\n", isconsonant('Z'));
printf("1: %d\n", isletter('1'));
}
|
Convert the following code from Python to C, ensuring the logic remains intact. | def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name)
gettok()
elif tok is an Integer constant
x = make_leaf(Integer, integer value)
gettok()
else
error()
while tok is a binary operator and precedence of tok >= p
save_tok = tok
gettok()
q = precedence of save_tok
if save_tok is not right associative
q += 1
x = make_node(Operator save_tok represents, x, expr(q))
return x
def paren_expr()
expect("(")
x = expr(0)
expect(")")
return x
def stmt()
t = NULL
if accept("if")
e = paren_expr()
s = stmt()
t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
elif accept("putc")
t = make_node(Prtc, paren_expr())
expect(";")
elif accept("print")
expect("(")
repeat
if tok is a string
e = make_node(Prts, make_leaf(String, the string))
gettok()
else
e = make_node(Prti, expr(0))
t = make_node(Sequence, t, e)
until not accept(",")
expect(")")
expect(";")
elif tok is ";"
gettok()
elif tok is an Identifier
v = make_leaf(Identifier, variable name)
gettok()
expect("=")
t = make_node(Assign, v, expr(0))
expect(";")
elif accept("while")
e = paren_expr()
t = make_node(While, e, stmt()
elif accept("{")
while tok not equal "}" and tok not equal end-of-file
t = make_node(Sequence, t, stmt())
expect("}")
elif tok is end-of-file
pass
else
error()
return t
def parse()
t = NULL
gettok()
repeat
t = make_node(Sequence, t, stmt())
until tok is end-of-file
return t
| count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. | def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name)
gettok()
elif tok is an Integer constant
x = make_leaf(Integer, integer value)
gettok()
else
error()
while tok is a binary operator and precedence of tok >= p
save_tok = tok
gettok()
q = precedence of save_tok
if save_tok is not right associative
q += 1
x = make_node(Operator save_tok represents, x, expr(q))
return x
def paren_expr()
expect("(")
x = expr(0)
expect(")")
return x
def stmt()
t = NULL
if accept("if")
e = paren_expr()
s = stmt()
t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
elif accept("putc")
t = make_node(Prtc, paren_expr())
expect(";")
elif accept("print")
expect("(")
repeat
if tok is a string
e = make_node(Prts, make_leaf(String, the string))
gettok()
else
e = make_node(Prti, expr(0))
t = make_node(Sequence, t, e)
until not accept(",")
expect(")")
expect(";")
elif tok is ";"
gettok()
elif tok is an Identifier
v = make_leaf(Identifier, variable name)
gettok()
expect("=")
t = make_node(Assign, v, expr(0))
expect(";")
elif accept("while")
e = paren_expr()
t = make_node(While, e, stmt()
elif accept("{")
while tok not equal "}" and tok not equal end-of-file
t = make_node(Sequence, t, stmt())
expect("}")
elif tok is end-of-file
pass
else
error()
return t
def parse()
t = NULL
gettok()
repeat
t = make_node(Sequence, t, stmt())
until tok is end-of-file
return t
| count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
Produce a functionally identical C code for the snippet given in Python. | def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name)
gettok()
elif tok is an Integer constant
x = make_leaf(Integer, integer value)
gettok()
else
error()
while tok is a binary operator and precedence of tok >= p
save_tok = tok
gettok()
q = precedence of save_tok
if save_tok is not right associative
q += 1
x = make_node(Operator save_tok represents, x, expr(q))
return x
def paren_expr()
expect("(")
x = expr(0)
expect(")")
return x
def stmt()
t = NULL
if accept("if")
e = paren_expr()
s = stmt()
t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
elif accept("putc")
t = make_node(Prtc, paren_expr())
expect(";")
elif accept("print")
expect("(")
repeat
if tok is a string
e = make_node(Prts, make_leaf(String, the string))
gettok()
else
e = make_node(Prti, expr(0))
t = make_node(Sequence, t, e)
until not accept(",")
expect(")")
expect(";")
elif tok is ";"
gettok()
elif tok is an Identifier
v = make_leaf(Identifier, variable name)
gettok()
expect("=")
t = make_node(Assign, v, expr(0))
expect(";")
elif accept("while")
e = paren_expr()
t = make_node(While, e, stmt()
elif accept("{")
while tok not equal "}" and tok not equal end-of-file
t = make_node(Sequence, t, stmt())
expect("}")
elif tok is end-of-file
pass
else
error()
return t
def parse()
t = NULL
gettok()
repeat
t = make_node(Sequence, t, stmt())
until tok is end-of-file
return t
| count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
Translate the given Python code snippet into C without altering its behavior. | from PIL import Image
img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show()
| #include<graphics.h>
int main()
{
initwindow(320,240,"Red Pixel");
putpixel(100,100,RED);
getch();
return 0;
}
|
Change the following Python code into C without altering its purpose. |
def digitSumsPrime(n):
def go(bases):
return all(
isPrime(digitSum(b)(n))
for b in bases
)
return go
def digitSum(base):
def go(n):
q, r = divmod(n, base)
return go(q) + r if n else 0
return go
def main():
xs = [
str(n) for n in range(1, 200)
if digitSumsPrime(n)([2, 3])
]
print(f'{len(xs)} matches in [1..199]\n')
print(table(10)(xs))
def chunksOf(n):
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
def isPrime(n):
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
def p(x):
return 0 == n % x or 0 == n % (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
def table(n):
def go(xs):
w = len(xs[-1])
return '\n'.join(
' '.join(row) for row in chunksOf(n)([
s.rjust(w, ' ') for s in xs
])
)
return go
if __name__ == '__main__':
main()
| #include <stdio.h>
#include <stdint.h>
uint8_t prime(uint8_t n) {
uint8_t f;
if (n < 2) return 0;
for (f = 2; f < n; f++) {
if (n % f == 0) return 0;
}
return 1;
}
uint8_t digit_sum(uint8_t n, uint8_t base) {
uint8_t s = 0;
do {s += n % base;} while (n /= base);
return s;
}
int main() {
uint8_t n, s = 0;
for (n = 0; n < 200; n++) {
if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {
printf("%4d",n);
if (++s>=10) {
printf("\n");
s=0;
}
}
}
printf("\n");
return 0;
}
|
Write a version of this Python function in C with identical behavior. |
def digitSumsPrime(n):
def go(bases):
return all(
isPrime(digitSum(b)(n))
for b in bases
)
return go
def digitSum(base):
def go(n):
q, r = divmod(n, base)
return go(q) + r if n else 0
return go
def main():
xs = [
str(n) for n in range(1, 200)
if digitSumsPrime(n)([2, 3])
]
print(f'{len(xs)} matches in [1..199]\n')
print(table(10)(xs))
def chunksOf(n):
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
def isPrime(n):
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
def p(x):
return 0 == n % x or 0 == n % (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
def table(n):
def go(xs):
w = len(xs[-1])
return '\n'.join(
' '.join(row) for row in chunksOf(n)([
s.rjust(w, ' ') for s in xs
])
)
return go
if __name__ == '__main__':
main()
| #include <stdio.h>
#include <stdint.h>
uint8_t prime(uint8_t n) {
uint8_t f;
if (n < 2) return 0;
for (f = 2; f < n; f++) {
if (n % f == 0) return 0;
}
return 1;
}
uint8_t digit_sum(uint8_t n, uint8_t base) {
uint8_t s = 0;
do {s += n % base;} while (n /= base);
return s;
}
int main() {
uint8_t n, s = 0;
for (n = 0; n < 200; n++) {
if (prime(digit_sum(n,2)) && prime(digit_sum(n,3))) {
printf("%4d",n);
if (++s>=10) {
printf("\n");
s=0;
}
}
}
printf("\n");
return 0;
}
|
Port the provided Python code into C while preserving the original functionality. |
import urllib.request
from collections import Counter
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
dictionary = open("unixdict.txt","r")
wordList = dictionary.read().split('\n')
dictionary.close()
filteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]
for word in filteredWords[:-9]:
position = filteredWords.index(word)
newWord = "".join([filteredWords[position+i][i] for i in range(0,9)])
if newWord in filteredWords:
print(newWord)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_SIZE 80
#define MIN_LENGTH 9
#define WORD_SIZE (MIN_LENGTH + 1)
void fatal(const char* message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
void* xmalloc(size_t n) {
void* ptr = malloc(n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
void* xrealloc(void* p, size_t n) {
void* ptr = realloc(p, n);
if (ptr == NULL)
fatal("Out of memory");
return ptr;
}
int word_compare(const void* p1, const void* p2) {
return memcmp(p1, p2, WORD_SIZE);
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
FILE* in = fopen(filename, "r");
if (!in) {
perror(filename);
return EXIT_FAILURE;
}
char line[MAX_WORD_SIZE];
size_t size = 0, capacity = 1024;
char* words = xmalloc(WORD_SIZE * capacity);
while (fgets(line, sizeof(line), in)) {
size_t len = strlen(line) - 1;
if (len < MIN_LENGTH)
continue;
line[len] = '\0';
if (size == capacity) {
capacity *= 2;
words = xrealloc(words, WORD_SIZE * capacity);
}
memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);
++size;
}
fclose(in);
qsort(words, size, WORD_SIZE, word_compare);
int count = 0;
char prev_word[WORD_SIZE] = { 0 };
for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {
char word[WORD_SIZE] = { 0 };
for (size_t j = 0; j < MIN_LENGTH; ++j)
word[j] = words[(i + j) * WORD_SIZE + j];
if (word_compare(word, prev_word) == 0)
continue;
if (bsearch(word, words, size, WORD_SIZE, word_compare))
printf("%2d. %s\n", ++count, word);
memcpy(prev_word, word, WORD_SIZE);
}
free(words);
return EXIT_SUCCESS;
}
|
Convert this Python block to C, preserving its control flow and logic. |
from functools import reduce
from operator import mul
def p(n):
digits = [int(c) for c in str(n)]
return not 0 in digits and (
0 != (n % reduce(mul, digits, 1))
) and all(0 == n % d for d in digits)
def main():
xs = [
str(n) for n in range(1, 1000)
if p(n)
]
w = len(xs[-1])
print(f'{len(xs)} matching numbers:\n')
print('\n'.join(
' '.join(cell.rjust(w, ' ') for cell in row)
for row in chunksOf(10)(xs)
))
def chunksOf(n):
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
if __name__ == '__main__':
main()
| #include <stdio.h>
int divisible(int n) {
int p = 1;
int c, d;
for (c=n; c; c /= 10) {
d = c % 10;
if (!d || n % d) return 0;
p *= d;
}
return n % p;
}
int main() {
int n, c=0;
for (n=1; n<1000; n++) {
if (divisible(n)) {
printf("%5d", n);
if (!(++c % 10)) printf("\n");
}
}
printf("\n");
return 0;
}
|
Write the same algorithm in C as shown in this Python implementation. |
from functools import reduce
from operator import mul
def p(n):
digits = [int(c) for c in str(n)]
return not 0 in digits and (
0 != (n % reduce(mul, digits, 1))
) and all(0 == n % d for d in digits)
def main():
xs = [
str(n) for n in range(1, 1000)
if p(n)
]
w = len(xs[-1])
print(f'{len(xs)} matching numbers:\n')
print('\n'.join(
' '.join(cell.rjust(w, ' ') for cell in row)
for row in chunksOf(10)(xs)
))
def chunksOf(n):
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
if __name__ == '__main__':
main()
| #include <stdio.h>
int divisible(int n) {
int p = 1;
int c, d;
for (c=n; c; c /= 10) {
d = c % 10;
if (!d || n % d) return 0;
p *= d;
}
return n % p;
}
int main() {
int n, c=0;
for (n=1; n<1000; n++) {
if (divisible(n)) {
printf("%5d", n);
if (!(++c % 10)) printf("\n");
}
}
printf("\n");
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Python to C. |
from myhdl import *
@block
def NOTgate( a, q ):
@always_comb
def NOTgateLogic():
q.next = not a
return NOTgateLogic
@block
def ANDgate( a, b, q ):
@always_comb
def ANDgateLogic():
q.next = a and b
return ANDgateLogic
@block
def ORgate( a, b, q ):
@always_comb
def ORgateLogic():
q.next = a or b
return ORgateLogic
@block
def XORgate( a, b, q ):
nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]
inv0 = NOTgate( a, nota )
inv1 = NOTgate( b, notb )
and2a = ANDgate( a, notb, annotb )
and2b = ANDgate( b, nota, bnnota )
or2a = ORgate( annotb, bnnota, q )
return inv0, inv1, and2a, and2b, or2a
@block
def HalfAdder( in_a, in_b, summ, carry ):
and2a = ANDgate(in_a, in_b, carry)
xor2a = XORgate(in_a, in_b, summ)
return and2a, xor2a
@block
def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ):
ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]
HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 )
HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 )
or2a = ORgate(ha1_c1, ha2_c1, fa_c1)
return HalfAdder01, HalfAdder02, or2a
@block
def Adder4b( ina, inb, cOut, sum4):
cl = [Signal(bool()) for i in range(0,4)]
sl = [Signal(bool()) for i in range(4)]
HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] )
FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] )
FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] )
FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut )
sc = ConcatSignal(*reversed(sl))
@always_comb
def list2intbv():
sum4.next = sc
return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv
t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)]
ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)]
from random import randrange
@block
def Test_Adder4b():
dut = Adder4b( ina4, inb4, t_co, sum4 )
@instance
def check():
print( "\n b a | c1 s \n -------------------" )
for i in range(15):
ina4.next, inb4.next = randrange(2**4), randrange(2**4)
yield delay(5)
print( " %2d %2d | %2d %2d " \
% (ina4,inb4, t_co,sum4) )
assert t_co * 16 + sum4 == ina4 + inb4
print()
return dut, check
def main():
simInst = Test_Adder4b()
simInst.name = "mySimInst"
simInst.config_sim(trace=True)
simInst.run_sim(duration=None)
inst = Adder4b( ina4, inb4, t_co, sum4 )
inst.convert(hdl='VHDL')
inst.convert(hdl='Verilog')
if __name__ == '__main__':
main()
| #include <stdio.h>
typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))
#define NOT(X) (~(X)&1)
#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))
void halfadder(IN a, IN b, OUT s, OUT c)
{
V(s) = XOR(V(a), V(b));
V(c) = V(a) & V(b);
}
void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
PIN(ps); PIN(pc); PIN(tc);
halfadder(a, b, ps, pc);
halfadder(ps, ic, s, tc);
V(oc) = V(tc) | V(pc);
}
void fourbitsadder(IN a0, IN a1, IN a2, IN a3,
IN b0, IN b1, IN b2, IN b3,
OUT o0, OUT o1, OUT o2, OUT o3,
OUT overflow)
{
PIN(zero); V(zero) = 0;
PIN(tc0); PIN(tc1); PIN(tc2);
fulladder(a0, b0, zero, o0, tc0);
fulladder(a1, b1, tc0, o1, tc1);
fulladder(a2, b2, tc1, o2, tc2);
fulladder(a3, b3, tc2, o3, overflow);
}
int main()
{
PIN(a0); PIN(a1); PIN(a2); PIN(a3);
PIN(b0); PIN(b1); PIN(b2); PIN(b3);
PIN(s0); PIN(s1); PIN(s2); PIN(s3);
PIN(overflow);
V(a3) = 0; V(b3) = 1;
V(a2) = 0; V(b2) = 1;
V(a1) = 1; V(b1) = 1;
V(a0) = 0; V(b0) = 0;
fourbitsadder(a0, a1, a2, a3,
b0, b1, b2, b3,
s0, s1, s2, s3,
overflow);
printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n",
V(a3), V(a2), V(a1), V(a0),
V(b3), V(b2), V(b1), V(b0),
V(s3), V(s2), V(s1), V(s0),
V(overflow));
return 0;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. |
from myhdl import *
@block
def NOTgate( a, q ):
@always_comb
def NOTgateLogic():
q.next = not a
return NOTgateLogic
@block
def ANDgate( a, b, q ):
@always_comb
def ANDgateLogic():
q.next = a and b
return ANDgateLogic
@block
def ORgate( a, b, q ):
@always_comb
def ORgateLogic():
q.next = a or b
return ORgateLogic
@block
def XORgate( a, b, q ):
nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]
inv0 = NOTgate( a, nota )
inv1 = NOTgate( b, notb )
and2a = ANDgate( a, notb, annotb )
and2b = ANDgate( b, nota, bnnota )
or2a = ORgate( annotb, bnnota, q )
return inv0, inv1, and2a, and2b, or2a
@block
def HalfAdder( in_a, in_b, summ, carry ):
and2a = ANDgate(in_a, in_b, carry)
xor2a = XORgate(in_a, in_b, summ)
return and2a, xor2a
@block
def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ):
ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]
HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 )
HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 )
or2a = ORgate(ha1_c1, ha2_c1, fa_c1)
return HalfAdder01, HalfAdder02, or2a
@block
def Adder4b( ina, inb, cOut, sum4):
cl = [Signal(bool()) for i in range(0,4)]
sl = [Signal(bool()) for i in range(4)]
HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] )
FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] )
FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] )
FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut )
sc = ConcatSignal(*reversed(sl))
@always_comb
def list2intbv():
sum4.next = sc
return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv
t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)]
ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)]
from random import randrange
@block
def Test_Adder4b():
dut = Adder4b( ina4, inb4, t_co, sum4 )
@instance
def check():
print( "\n b a | c1 s \n -------------------" )
for i in range(15):
ina4.next, inb4.next = randrange(2**4), randrange(2**4)
yield delay(5)
print( " %2d %2d | %2d %2d " \
% (ina4,inb4, t_co,sum4) )
assert t_co * 16 + sum4 == ina4 + inb4
print()
return dut, check
def main():
simInst = Test_Adder4b()
simInst.name = "mySimInst"
simInst.config_sim(trace=True)
simInst.run_sim(duration=None)
inst = Adder4b( ina4, inb4, t_co, sum4 )
inst.convert(hdl='VHDL')
inst.convert(hdl='Verilog')
if __name__ == '__main__':
main()
| #include <stdio.h>
typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))
#define NOT(X) (~(X)&1)
#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))
void halfadder(IN a, IN b, OUT s, OUT c)
{
V(s) = XOR(V(a), V(b));
V(c) = V(a) & V(b);
}
void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
PIN(ps); PIN(pc); PIN(tc);
halfadder(a, b, ps, pc);
halfadder(ps, ic, s, tc);
V(oc) = V(tc) | V(pc);
}
void fourbitsadder(IN a0, IN a1, IN a2, IN a3,
IN b0, IN b1, IN b2, IN b3,
OUT o0, OUT o1, OUT o2, OUT o3,
OUT overflow)
{
PIN(zero); V(zero) = 0;
PIN(tc0); PIN(tc1); PIN(tc2);
fulladder(a0, b0, zero, o0, tc0);
fulladder(a1, b1, tc0, o1, tc1);
fulladder(a2, b2, tc1, o2, tc2);
fulladder(a3, b3, tc2, o3, overflow);
}
int main()
{
PIN(a0); PIN(a1); PIN(a2); PIN(a3);
PIN(b0); PIN(b1); PIN(b2); PIN(b3);
PIN(s0); PIN(s1); PIN(s2); PIN(s3);
PIN(overflow);
V(a3) = 0; V(b3) = 1;
V(a2) = 0; V(b2) = 1;
V(a1) = 1; V(b1) = 1;
V(a0) = 0; V(b0) = 0;
fourbitsadder(a0, a1, a2, a3,
b0, b1, b2, b3,
s0, s1, s2, s3,
overflow);
printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n",
V(a3), V(a2), V(a1), V(a0),
V(b3), V(b2), V(b1), V(b0),
V(s3), V(s2), V(s1), V(s0),
V(overflow));
return 0;
}
|
Write a version of this Python function in C with identical behavior. |
from myhdl import *
@block
def NOTgate( a, q ):
@always_comb
def NOTgateLogic():
q.next = not a
return NOTgateLogic
@block
def ANDgate( a, b, q ):
@always_comb
def ANDgateLogic():
q.next = a and b
return ANDgateLogic
@block
def ORgate( a, b, q ):
@always_comb
def ORgateLogic():
q.next = a or b
return ORgateLogic
@block
def XORgate( a, b, q ):
nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)]
inv0 = NOTgate( a, nota )
inv1 = NOTgate( b, notb )
and2a = ANDgate( a, notb, annotb )
and2b = ANDgate( b, nota, bnnota )
or2a = ORgate( annotb, bnnota, q )
return inv0, inv1, and2a, and2b, or2a
@block
def HalfAdder( in_a, in_b, summ, carry ):
and2a = ANDgate(in_a, in_b, carry)
xor2a = XORgate(in_a, in_b, summ)
return and2a, xor2a
@block
def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ):
ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]
HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 )
HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 )
or2a = ORgate(ha1_c1, ha2_c1, fa_c1)
return HalfAdder01, HalfAdder02, or2a
@block
def Adder4b( ina, inb, cOut, sum4):
cl = [Signal(bool()) for i in range(0,4)]
sl = [Signal(bool()) for i in range(4)]
HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] )
FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] )
FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] )
FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut )
sc = ConcatSignal(*reversed(sl))
@always_comb
def list2intbv():
sum4.next = sc
return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv
t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)]
ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)]
from random import randrange
@block
def Test_Adder4b():
dut = Adder4b( ina4, inb4, t_co, sum4 )
@instance
def check():
print( "\n b a | c1 s \n -------------------" )
for i in range(15):
ina4.next, inb4.next = randrange(2**4), randrange(2**4)
yield delay(5)
print( " %2d %2d | %2d %2d " \
% (ina4,inb4, t_co,sum4) )
assert t_co * 16 + sum4 == ina4 + inb4
print()
return dut, check
def main():
simInst = Test_Adder4b()
simInst.name = "mySimInst"
simInst.config_sim(trace=True)
simInst.run_sim(duration=None)
inst = Adder4b( ina4, inb4, t_co, sum4 )
inst.convert(hdl='VHDL')
inst.convert(hdl='Verilog')
if __name__ == '__main__':
main()
| #include <stdio.h>
typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))
#define NOT(X) (~(X)&1)
#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))
void halfadder(IN a, IN b, OUT s, OUT c)
{
V(s) = XOR(V(a), V(b));
V(c) = V(a) & V(b);
}
void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
PIN(ps); PIN(pc); PIN(tc);
halfadder(a, b, ps, pc);
halfadder(ps, ic, s, tc);
V(oc) = V(tc) | V(pc);
}
void fourbitsadder(IN a0, IN a1, IN a2, IN a3,
IN b0, IN b1, IN b2, IN b3,
OUT o0, OUT o1, OUT o2, OUT o3,
OUT overflow)
{
PIN(zero); V(zero) = 0;
PIN(tc0); PIN(tc1); PIN(tc2);
fulladder(a0, b0, zero, o0, tc0);
fulladder(a1, b1, tc0, o1, tc1);
fulladder(a2, b2, tc1, o2, tc2);
fulladder(a3, b3, tc2, o3, overflow);
}
int main()
{
PIN(a0); PIN(a1); PIN(a2); PIN(a3);
PIN(b0); PIN(b1); PIN(b2); PIN(b3);
PIN(s0); PIN(s1); PIN(s2); PIN(s3);
PIN(overflow);
V(a3) = 0; V(b3) = 1;
V(a2) = 0; V(b2) = 1;
V(a1) = 1; V(b1) = 1;
V(a0) = 0; V(b0) = 0;
fourbitsadder(a0, a1, a2, a3,
b0, b1, b2, b3,
s0, s1, s2, s3,
overflow);
printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n",
V(a3), V(a2), V(a1), V(a0),
V(b3), V(b2), V(b1), V(b0),
V(s3), V(s2), V(s1), V(s0),
V(overflow));
return 0;
}
|
Generate a C translation of this Python snippet without changing its computational steps. | import math
from sys import stdout
LOG_10 = 2.302585092994
def build_oms(s):
if s % 2 == 0:
s += 1
q = [[0 for j in range(s)] for i in range(s)]
p = 1
i = s // 2
j = 0
while p <= (s * s):
q[i][j] = p
ti = i + 1
if ti >= s: ti = 0
tj = j - 1
if tj < 0: tj = s - 1
if q[ti][tj] != 0:
ti = i
tj = j + 1
i = ti
j = tj
p = p + 1
return q, s
def build_sems(s):
if s % 2 == 1:
s += 1
while s % 4 == 0:
s += 2
q = [[0 for j in range(s)] for i in range(s)]
z = s // 2
b = z * z
c = 2 * b
d = 3 * b
o = build_oms(z)
for j in range(0, z):
for i in range(0, z):
a = o[0][i][j]
q[i][j] = a
q[i + z][j + z] = a + b
q[i + z][j] = a + c
q[i][j + z] = a + d
lc = z // 2
rc = lc
for j in range(0, z):
for i in range(0, s):
if i < lc or i > s - rc or (i == lc and j == lc):
if not (i == 0 and j == lc):
t = q[i][j]
q[i][j] = q[i][j + z]
q[i][j + z] = t
return q, s
def format_sqr(s, l):
for i in range(0, l - len(s)):
s = "0" + s
return s + " "
def display(q):
s = q[1]
print(" - {0} x {1}\n".format(s, s))
k = 1 + math.floor(math.log(s * s) / LOG_10)
for j in range(0, s):
for i in range(0, s):
stdout.write(format_sqr("{0}".format(q[0][i][j]), k))
print()
print("Magic sum: {0}\n".format(s * ((s * s) + 1) // 2))
stdout.write("Singly Even Magic Square")
display(build_sems(6))
| #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** oddMagicSquare(int n) {
if (n < 3 || n % 2 == 0)
return NULL;
int value = 0;
int squareSize = n * n;
int c = n / 2, r = 0,i;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
while (++value <= squareSize) {
result[r][c] = value;
if (r == 0) {
if (c == n - 1) {
r++;
} else {
r = n - 1;
c++;
}
} else if (c == n - 1) {
r--;
c = 0;
} else if (result[r - 1][c + 1] == 0) {
r--;
c++;
} else {
r++;
}
}
return result;
}
int** singlyEvenMagicSquare(int n) {
if (n < 6 || (n - 2) % 4 != 0)
return NULL;
int size = n * n;
int halfN = n / 2;
int subGridSize = size / 4, i;
int** subGrid = oddMagicSquare(halfN);
int gridFactors[] = {0, 2, 3, 1};
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
int grid = (r / halfN) * 2 + (c / halfN);
result[r][c] = subGrid[r % halfN][c % halfN];
result[r][c] += gridFactors[grid] * subGridSize;
}
}
int nColsLeft = halfN / 2;
int nColsRight = nColsLeft - 1;
for (int r = 0; r < halfN; r++)
for (int c = 0; c < n; c++) {
if (c < nColsLeft || c >= n - nColsRight
|| (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft)
continue;
int tmp = result[r][c];
result[r][c] = result[r + halfN][c];
result[r + halfN][c] = tmp;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j;
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2);
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(singlyEvenMagicSquare(n),n);
}
return 0;
}
|
Convert this Python block to C, preserving its control flow and logic. | >>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
if p.index('B') % 2 != p.index('b') % 2
and ( p.index('r') < p.index('K') < p.index('R')
or p.index('R') < p.index('K') < p.index('r') ) }
>>> len(starts)
960
>>> starts.pop()
'QNBRNKRB'
>>>
| #include<stdlib.h>
#include<locale.h>
#include<wchar.h>
#include<stdio.h>
#include<time.h>
char rank[9];
int pos[8];
void swap(int i,int j){
int temp = pos[i];
pos[i] = pos[j];
pos[j] = temp;
}
void generateFirstRank(){
int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;
for(i=0;i<8;i++){
rank[i] = 'e';
pos[i] = i;
}
do{
kPos = rand()%8;
rPos1 = rand()%8;
rPos2 = rand()%8;
}while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));
rank[pos[rPos1]] = 'R';
rank[pos[kPos]] = 'K';
rank[pos[rPos2]] = 'R';
swap(rPos1,7);
swap(rPos2,6);
swap(kPos,5);
do{
bPos1 = rand()%5;
bPos2 = rand()%5;
}while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));
rank[pos[bPos1]] = 'B';
rank[pos[bPos2]] = 'B';
swap(bPos1,4);
swap(bPos2,3);
do{
qPos = rand()%3;
nPos1 = rand()%3;
}while(qPos==nPos1);
rank[pos[qPos]] = 'Q';
rank[pos[nPos1]] = 'N';
for(i=0;i<8;i++)
if(rank[i]=='e'){
rank[i] = 'N';
break;
}
}
void printRank(){
int i;
#ifdef _WIN32
printf("%s\n",rank);
#else
{
setlocale(LC_ALL,"");
printf("\n");
for(i=0;i<8;i++){
if(rank[i]=='K')
printf("%lc",(wint_t)9812);
else if(rank[i]=='Q')
printf("%lc",(wint_t)9813);
else if(rank[i]=='R')
printf("%lc",(wint_t)9814);
else if(rank[i]=='B')
printf("%lc",(wint_t)9815);
if(rank[i]=='N')
printf("%lc",(wint_t)9816);
}
}
#endif
}
int main()
{
int i;
srand((unsigned)time(NULL));
for(i=0;i<9;i++){
generateFirstRank();
printRank();
}
return 0;
}
|
Can you help me rewrite this code in C instead of Python, keeping it the same logically? |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
| int meaning_of_life();
|
Write a version of this Python function in C with identical behavior. |
def meaning_of_life():
return 42
if __name__ == "__main__":
print("Main: The meaning of life is %s" % meaning_of_life())
| int meaning_of_life();
|
Write the same algorithm in C as shown in this Python implementation. | import math
def perlin_noise(x, y, z):
X = math.floor(x) & 255
Y = math.floor(y) & 255
Z = math.floor(z) & 255
x -= math.floor(x)
y -= math.floor(y)
z -= math.floor(z)
u = fade(x)
v = fade(y)
w = fade(z)
A = p[X ]+Y; AA = p[A]+Z; AB = p[A+1]+Z
B = p[X+1]+Y; BA = p[B]+Z; BB = p[B+1]+Z
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ),
grad(p[BA+1], x-1, y , z-1 )),
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))))
def fade(t):
return t ** 3 * (t * (t * 6 - 15) + 10)
def lerp(t, a, b):
return a + t * (b - a)
def grad(hash, x, y, z):
h = hash & 15
u = x if h<8 else y
v = y if h<4 else (x if h in (12, 14) else z)
return (u if (h&1) == 0 else -u) + (v if (h&2) == 0 else -v)
p = [None] * 512
permutation = [151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]
for i in range(256):
p[256+i] = p[i] = permutation[i]
if __name__ == '__main__':
print("%1.17f" % perlin_noise(3.14, 42, 7))
| #include<stdlib.h>
#include<stdio.h>
#include<math.h>
int p[512];
double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
double lerp(double t, double a, double b) { return a + t * (b - a); }
double grad(int hash, double x, double y, double z) {
int h = hash & 15;
double u = h<8 ? x : y,
v = h<4 ? y : h==12||h==14 ? x : z;
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
double noise(double x, double y, double z) {
int X = (int)floor(x) & 255,
Y = (int)floor(y) & 255,
Z = (int)floor(z) & 255;
x -= floor(x);
y -= floor(y);
z -= floor(z);
double u = fade(x),
v = fade(y),
w = fade(z);
int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,
B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ),
grad(p[BA+1], x-1, y , z-1 )),
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))));
}
void loadPermutation(char* fileName){
FILE* fp = fopen(fileName,"r");
int permutation[256],i;
for(i=0;i<256;i++)
fscanf(fp,"%d",&permutation[i]);
fclose(fp);
for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];
}
int main(int argC,char* argV[])
{
if(argC!=5)
printf("Usage : %s <permutation data file> <x,y,z co-ordinates separated by space>");
else{
loadPermutation(argV[1]);
printf("Perlin Noise for (%s,%s,%s) is %.17lf",argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));
}
return 0;
}
|
Port the following code from Python to C with equivalent syntax and logic. | import sys, os
from collections import Counter
def dodir(path):
global h
for name in os.listdir(path):
p = os.path.join(path, name)
if os.path.islink(p):
pass
elif os.path.isfile(p):
h[os.stat(p).st_size] += 1
elif os.path.isdir(p):
dodir(p)
else:
pass
def main(arg):
global h
h = Counter()
for dir in arg:
dodir(dir)
s = n = 0
for k, v in sorted(h.items()):
print("Size %d -> %d file(s)" % (k, v))
n += v
s += k * v
print("Total %d bytes for %d files" % (s, n))
main(sys.argv[1:])
| #include<windows.h>
#include<string.h>
#include<stdio.h>
#define MAXORDER 25
int main(int argC, char* argV[])
{
char str[MAXORDER],commandString[1000],*startPath;
long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;
int i,j,len;
double scale;
FILE* fp;
if(argC==1)
printf("Usage : %s <followed by directory to start search from(. for current dir), followed by \n optional parameters (T or G) to show text or graph output>",argV[0]);
else{
if(strchr(argV[1],' ')!=NULL){
len = strlen(argV[1]);
startPath = (char*)malloc((len+2)*sizeof(char));
startPath[0] = '\"';
startPath[len+1]='\"';
strncpy(startPath+1,argV[1],len);
startPath[len+2] = argV[1][len];
sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",startPath);
}
else if(strlen(argV[1])==1 && argV[1][0]=='.')
strcpy(commandString,"forfiles /s /c \"cmd /c echo @fsize\" 2>&1");
else
sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",argV[1]);
fp = popen(commandString,"r");
while(fgets(str,100,fp)!=NULL){
if(str[0]=='0')
fileSizeLog[0]++;
else
fileSizeLog[strlen(str)]++;
}
if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){
for(i=0;i<MAXORDER;i++){
printf("\nSize Order < 10^%2d bytes : %Ld",i,fileSizeLog[i]);
}
}
else if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){
CONSOLE_SCREEN_BUFFER_INFO csbi;
int val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);
if(val)
{
max = fileSizeLog[0];
for(i=1;i<MAXORDER;i++)
(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;
(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);
for(i=0;i<MAXORDER;i++){
printf("\nSize Order < 10^%2d bytes |",i);
for(j=0;j<(int)(scale*fileSizeLog[i]);j++)
printf("%c",219);
printf("%Ld",fileSizeLog[i]);
}
}
}
return 0;
}
}
|
Convert the following code from Python to C, ensuring the logic remains intact. | >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
int cmpstr(const void *a, const void *b)
{
return strcmp(*(const char**)a, *(const char**)b);
}
int main(void)
{
DIR *basedir;
char path[PATH_MAX];
struct dirent *entry;
char **dirnames;
int diralloc = 128;
int dirsize = 0;
if (!(dirnames = malloc(diralloc * sizeof(char*)))) {
perror("malloc error:");
return 1;
}
if (!getcwd(path, PATH_MAX)) {
perror("getcwd error:");
return 1;
}
if (!(basedir = opendir(path))) {
perror("opendir error:");
return 1;
}
while ((entry = readdir(basedir))) {
if (dirsize >= diralloc) {
diralloc *= 2;
if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {
perror("realloc error:");
return 1;
}
}
dirnames[dirsize++] = strdup(entry->d_name);
}
qsort(dirnames, dirsize, sizeof(char*), cmpstr);
int i;
for (i = 0; i < dirsize; ++i) {
if (dirnames[i][0] != '.') {
printf("%s\n", dirnames[i]);
}
}
for (i = 0; i < dirsize; ++i)
free(dirnames[i]);
free(dirnames);
closedir(basedir);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. |
from __future__ import annotations
import asyncio
import sys
from typing import Optional
from typing import TextIO
class OutOfInkError(Exception):
class Printer:
def __init__(self, name: str, backup: Optional[Printer]):
self.name = name
self.backup = backup
self.ink_level: int = 5
self.output_stream: TextIO = sys.stdout
async def print(self, msg):
if self.ink_level <= 0:
if self.backup:
await self.backup.print(msg)
else:
raise OutOfInkError(self.name)
else:
self.ink_level -= 1
self.output_stream.write(f"({self.name}): {msg}\n")
async def main():
reserve = Printer("reserve", None)
main = Printer("main", reserve)
humpty_lines = [
"Humpty Dumpty sat on a wall.",
"Humpty Dumpty had a great fall.",
"All the king's horses and all the king's men,",
"Couldn't put Humpty together again.",
]
goose_lines = [
"Old Mother Goose,",
"When she wanted to wander,",
"Would ride through the air,",
"On a very fine gander.",
"Jack's mother came in,",
"And caught the goose soon,",
"And mounting its back,",
"Flew up to the moon.",
]
async def print_humpty():
for line in humpty_lines:
try:
task = asyncio.Task(main.print(line))
await task
except OutOfInkError:
print("\t Humpty Dumpty out of ink!")
break
async def print_goose():
for line in goose_lines:
try:
task = asyncio.Task(main.print(line))
await task
except OutOfInkError:
print("\t Mother Goose out of ink!")
break
await asyncio.gather(print_goose(), print_humpty())
if __name__ == "__main__":
asyncio.run(main(), debug=True)
| #include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
typedef struct rendezvous {
pthread_mutex_t lock;
pthread_cond_t cv_entering;
pthread_cond_t cv_accepting;
pthread_cond_t cv_done;
int (*accept_func)(void*);
int entering;
int accepting;
int done;
} rendezvous_t;
#define RENDEZVOUS_INITILIZER(accept_function) { \
.lock = PTHREAD_MUTEX_INITIALIZER, \
.cv_entering = PTHREAD_COND_INITIALIZER, \
.cv_accepting = PTHREAD_COND_INITIALIZER, \
.cv_done = PTHREAD_COND_INITIALIZER, \
.accept_func = accept_function, \
.entering = 0, \
.accepting = 0, \
.done = 0, \
}
int enter_rendezvous(rendezvous_t *rv, void* data)
{
pthread_mutex_lock(&rv->lock);
rv->entering++;
pthread_cond_signal(&rv->cv_entering);
while (!rv->accepting) {
pthread_cond_wait(&rv->cv_accepting, &rv->lock);
}
int ret = rv->accept_func(data);
rv->done = 1;
pthread_cond_signal(&rv->cv_done);
rv->entering--;
rv->accepting = 0;
pthread_mutex_unlock(&rv->lock);
return ret;
}
void accept_rendezvous(rendezvous_t *rv)
{
pthread_mutex_lock(&rv->lock);
rv->accepting = 1;
while (!rv->entering) {
pthread_cond_wait(&rv->cv_entering, &rv->lock);
}
pthread_cond_signal(&rv->cv_accepting);
while (!rv->done) {
pthread_cond_wait(&rv->cv_done, &rv->lock);
}
rv->done = 0;
rv->accepting = 0;
pthread_mutex_unlock(&rv->lock);
}
typedef struct printer {
rendezvous_t rv;
struct printer *backup;
int id;
int remaining_lines;
} printer_t;
typedef struct print_args {
struct printer *printer;
const char* line;
} print_args_t;
int print_line(printer_t *printer, const char* line) {
print_args_t args;
args.printer = printer;
args.line = line;
return enter_rendezvous(&printer->rv, &args);
}
int accept_print(void* data) {
print_args_t *args = (print_args_t*)data;
printer_t *printer = args->printer;
const char* line = args->line;
if (printer->remaining_lines) {
printf("%d: ", printer->id);
while (*line != '\0') {
putchar(*line++);
}
putchar('\n');
printer->remaining_lines--;
return 1;
}
else if (printer->backup) {
return print_line(printer->backup, line);
}
else {
return -1;
}
}
printer_t backup_printer = {
.rv = RENDEZVOUS_INITILIZER(accept_print),
.backup = NULL,
.id = 2,
.remaining_lines = 5,
};
printer_t main_printer = {
.rv = RENDEZVOUS_INITILIZER(accept_print),
.backup = &backup_printer,
.id = 1,
.remaining_lines = 5,
};
void* printer_thread(void* thread_data) {
printer_t *printer = (printer_t*) thread_data;
while (1) {
accept_rendezvous(&printer->rv);
}
}
typedef struct poem {
char* name;
char* lines[];
} poem_t;
poem_t humpty_dumpty = {
.name = "Humpty Dumpty",
.lines = {
"Humpty Dumpty sat on a wall.",
"Humpty Dumpty had a great fall.",
"All the king's horses and all the king's men",
"Couldn't put Humpty together again.",
""
},
};
poem_t mother_goose = {
.name = "Mother Goose",
.lines = {
"Old Mother Goose",
"When she wanted to wander,",
"Would ride through the air",
"On a very fine gander.",
"Jack's mother came in,",
"And caught the goose soon,",
"And mounting its back,",
"Flew up to the moon.",
""
},
};
void* poem_thread(void* thread_data) {
poem_t *poem = (poem_t*)thread_data;
for (unsigned i = 0; poem->lines[i] != ""; i++) {
int ret = print_line(&main_printer, poem->lines[i]);
if (ret < 0) {
printf(" %s out of ink!\n", poem->name);
exit(1);
}
}
return NULL;
}
int main(void)
{
pthread_t threads[4];
pthread_create(&threads[0], NULL, poem_thread, &humpty_dumpty);
pthread_create(&threads[1], NULL, poem_thread, &mother_goose);
pthread_create(&threads[2], NULL, printer_thread, &main_printer);
pthread_create(&threads[3], NULL, printer_thread, &backup_printer);
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
pthread_cancel(threads[2]);
pthread_cancel(threads[3]);
return 0;
}
|
Port the provided Python code into C while preserving the original functionality. | environments = [{'cnt':0, 'seq':i+1} for i in range(12)]
code =
while any(env['seq'] > 1 for env in environments):
for env in environments:
exec(code, globals(), env)
print()
print('Counts')
for env in environments:
print('% 4d' % env['cnt'], end='')
print()
| #include <stdio.h>
#define JOBS 12
#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf("\n"); switch_to(++a))
typedef struct { int seq, cnt; } env_t;
env_t env[JOBS] = {{0, 0}};
int *seq, *cnt;
void hail()
{
printf("% 4d", *seq);
if (*seq == 1) return;
++*cnt;
*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2;
}
void switch_to(int id)
{
seq = &env[id].seq;
cnt = &env[id].cnt;
}
int main()
{
int i;
jobs(i) { env[i].seq = i + 1; }
again: jobs(i) { hail(); }
jobs(i) { if (1 != *seq) goto again; }
printf("COUNTS:\n");
jobs(i) { printf("% 4d", *cnt); }
return 0;
}
|
Port the following code from Python to C with equivalent syntax and logic. |
from unicodedata import name
def unicode_code(ch):
return 'U+{:04x}'.format(ord(ch))
def utf8hex(ch):
return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()
if __name__ == "__main__":
print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))
chars = ['A', 'ö', 'Ж', '€', '𝄞']
for char in chars:
print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
| #include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
typedef struct {
char mask;
char lead;
uint32_t beg;
uint32_t end;
int bits_stored;
}utf_t;
utf_t * utf[] = {
[0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 },
[1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 },
[2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 },
[3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 },
[4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 },
&(utf_t){0},
};
int codepoint_len(const uint32_t cp);
int utf8_len(const char ch);
char *to_utf8(const uint32_t cp);
uint32_t to_cp(const char chr[4]);
int codepoint_len(const uint32_t cp)
{
int len = 0;
for(utf_t **u = utf; *u; ++u) {
if((cp >= (*u)->beg) && (cp <= (*u)->end)) {
break;
}
++len;
}
if(len > 4)
exit(1);
return len;
}
int utf8_len(const char ch)
{
int len = 0;
for(utf_t **u = utf; *u; ++u) {
if((ch & ~(*u)->mask) == (*u)->lead) {
break;
}
++len;
}
if(len > 4) {
exit(1);
}
return len;
}
char *to_utf8(const uint32_t cp)
{
static char ret[5];
const int bytes = codepoint_len(cp);
int shift = utf[0]->bits_stored * (bytes - 1);
ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead;
shift -= utf[0]->bits_stored;
for(int i = 1; i < bytes; ++i) {
ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead;
shift -= utf[0]->bits_stored;
}
ret[bytes] = '\0';
return ret;
}
uint32_t to_cp(const char chr[4])
{
int bytes = utf8_len(*chr);
int shift = utf[0]->bits_stored * (bytes - 1);
uint32_t codep = (*chr++ & utf[bytes]->mask) << shift;
for(int i = 1; i < bytes; ++i, ++chr) {
shift -= utf[0]->bits_stored;
codep |= ((char)*chr & utf[0]->mask) << shift;
}
return codep;
}
int main(void)
{
const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};
printf("Character Unicode UTF-8 encoding (hex)\n");
printf("----------------------------------------\n");
char *utf8;
uint32_t codepoint;
for(in = input; *in; ++in) {
utf8 = to_utf8(*in);
codepoint = to_cp(utf8);
printf("%s U+%-7.4x", utf8, codepoint);
for(int i = 0; utf8[i] && i < 4; ++i) {
printf("%hhx ", utf8[i]);
}
printf("\n");
}
return 0;
}
|
Generate a C translation of this Python snippet without changing its computational steps. |
from __future__ import division
import sys
from PIL import Image
def _fpart(x):
return x - int(x)
def _rfpart(x):
return 1 - _fpart(x)
def putpixel(img, xy, color, alpha=1):
compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))
c = compose_color(img.getpixel(xy), color)
img.putpixel(xy, c)
def draw_line(img, p1, p2, color):
x1, y1 = p1
x2, y2 = p2
dx, dy = x2-x1, y2-y1
steep = abs(dx) < abs(dy)
p = lambda px, py: ((px,py), (py,px))[steep]
if steep:
x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx
if x2 < x1:
x1, x2, y1, y2 = x2, x1, y2, y1
grad = dy/dx
intery = y1 + _rfpart(x1) * grad
def draw_endpoint(pt):
x, y = pt
xend = round(x)
yend = y + grad * (xend - x)
xgap = _rfpart(x + 0.5)
px, py = int(xend), int(yend)
putpixel(img, p(px, py), color, _rfpart(yend) * xgap)
putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)
return px
xstart = draw_endpoint(p(*p1)) + 1
xend = draw_endpoint(p(*p2))
for x in range(xstart, xend):
y = int(intery)
putpixel(img, p(x, y), color, _rfpart(intery))
putpixel(img, p(x, y+1), color, _fpart(intery))
intery += grad
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'usage: python xiaolinwu.py [output-file]'
sys.exit(-1)
blue = (0, 0, 255)
yellow = (255, 255, 0)
img = Image.new("RGB", (500,500), blue)
for a in range(10, 431, 60):
draw_line(img, (10, 10), (490, a), yellow)
draw_line(img, (10, 10), (a, 490), yellow)
draw_line(img, (10, 10), (490, 490), yellow)
filename = sys.argv[1]
img.save(filename)
print 'image saved to', filename
| void draw_line_antialias(
image img,
unsigned int x0, unsigned int y0,
unsigned int x1, unsigned int y1,
color_component r,
color_component g,
color_component b );
|
Rewrite the snippet below in C so it works the same as the original Python code. |
import curses
def print_message():
stdscr.addstr('This is the message.\n')
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
stdscr.addstr('CTRL+P for message or q to quit.\n')
while True:
c = stdscr.getch()
if c == 16: print_message()
elif c == ord('q'): break
curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
| #include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>
int main()
{
Display *d;
XEvent event;
d = XOpenDisplay(NULL);
if ( d != NULL ) {
XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")),
Mod1Mask,
DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);
XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")),
Mod1Mask,
DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);
for(;;)
{
XNextEvent(d, &event);
if ( event.type == KeyPress ) {
KeySym s = XLookupKeysym(&event.xkey, 0);
if ( s == XK_F7 ) {
printf("something's happened\n");
} else if ( s == XK_F6 ) {
break;
}
}
}
XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d));
XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d));
}
return EXIT_SUCCESS;
}
|
Generate an equivalent C version of this Python code. | >>> from itertools import product
>>> nuggets = set(range(101))
>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):
nuggets.discard(6*s + 9*n + 20*t)
>>> max(nuggets)
43
>>>
| #include <stdio.h>
int
main() {
int max = 0, i = 0, sixes, nines, twenties;
loopstart: while (i < 100) {
for (sixes = 0; sixes*6 < i; sixes++) {
if (sixes*6 == i) {
i++;
goto loopstart;
}
for (nines = 0; nines*9 < i; nines++) {
if (sixes*6 + nines*9 == i) {
i++;
goto loopstart;
}
for (twenties = 0; twenties*20 < i; twenties++) {
if (sixes*6 + nines*9 + twenties*20 == i) {
i++;
goto loopstart;
}
}
}
}
max = i;
i++;
}
printf("Maximum non-McNuggets number is %d\n", max);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Python. | >>> from itertools import product
>>> nuggets = set(range(101))
>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):
nuggets.discard(6*s + 9*n + 20*t)
>>> max(nuggets)
43
>>>
| #include <stdio.h>
int
main() {
int max = 0, i = 0, sixes, nines, twenties;
loopstart: while (i < 100) {
for (sixes = 0; sixes*6 < i; sixes++) {
if (sixes*6 == i) {
i++;
goto loopstart;
}
for (nines = 0; nines*9 < i; nines++) {
if (sixes*6 + nines*9 == i) {
i++;
goto loopstart;
}
for (twenties = 0; twenties*20 < i; twenties++) {
if (sixes*6 + nines*9 + twenties*20 == i) {
i++;
goto loopstart;
}
}
}
}
max = i;
i++;
}
printf("Maximum non-McNuggets number is %d\n", max);
return 0;
}
|
Write a version of this Python function in C with identical behavior. | def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
for r in range(n1, order-n1):
r1 = sq[r][:n1]
r2 = sq[order -r - 1][order-n1:]
r1.reverse()
r2.reverse()
sq[r][:n1] = r2
sq[order -r - 1][order-n1:] = r1
return sq
def printsq(s):
n = len(s)
bl = len(str(n**2))+1
for i in range(n):
print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] )
print "\nMagic constant = %d"%sum(s[0])
printsq(MagicSquareDoublyEven(8))
| #include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
int** doublyEvenMagicSquare(int n) {
if (n < 4 || n % 4 != 0)
return NULL;
int bits = 38505;
int size = n * n;
int mult = n / 4,i,r,c,bitPos;
int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));
for (r = 0, i = 0; r < n; r++) {
for (c = 0; c < n; c++, i++) {
bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}
int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}
void printMagicSquare(int** square,int rows){
int i,j,baseWidth = numDigits(rows*rows) + 3;
printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2);
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
}
int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(doublyEvenMagicSquare(n),n);
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. | >>>
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>>
>>> for value in (inf, _inf, _zero, nan): print (value)
inf
-inf
-0.0
nan
>>>
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>>
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> inf * 0.0
nan
| #include <stdio.h>
int main()
{
double inf = 1/0.0;
double minus_inf = -1/0.0;
double minus_zero = -1/ inf ;
double nan = 0.0/0.0;
printf("positive infinity: %f\n",inf);
printf("negative infinity: %f\n",minus_inf);
printf("negative zero: %f\n",minus_zero);
printf("not a number: %f\n",nan);
printf("+inf + 2.0 = %f\n",inf + 2.0);
printf("+inf - 10.1 = %f\n",inf - 10.1);
printf("+inf + -inf = %f\n",inf + minus_inf);
printf("0.0 * +inf = %f\n",0.0 * inf);
printf("1.0/-0.0 = %f\n",1.0/minus_zero);
printf("NaN + 1.0 = %f\n",nan + 1.0);
printf("NaN + NaN = %f\n",nan + nan);
printf("NaN == NaN = %s\n",nan == nan ? "true" : "false");
printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false");
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | >>>
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>>
>>> for value in (inf, _inf, _zero, nan): print (value)
inf
-inf
-0.0
nan
>>>
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>>
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> inf * 0.0
nan
| #include <stdio.h>
int main()
{
double inf = 1/0.0;
double minus_inf = -1/0.0;
double minus_zero = -1/ inf ;
double nan = 0.0/0.0;
printf("positive infinity: %f\n",inf);
printf("negative infinity: %f\n",minus_inf);
printf("negative zero: %f\n",minus_zero);
printf("not a number: %f\n",nan);
printf("+inf + 2.0 = %f\n",inf + 2.0);
printf("+inf - 10.1 = %f\n",inf - 10.1);
printf("+inf + -inf = %f\n",inf + minus_inf);
printf("0.0 * +inf = %f\n",0.0 * inf);
printf("1.0/-0.0 = %f\n",1.0/minus_zero);
printf("NaN + 1.0 = %f\n",nan + 1.0);
printf("NaN + NaN = %f\n",nan + nan);
printf("NaN == NaN = %s\n",nan == nan ? "true" : "false");
printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false");
return 0;
}
|
Change the following Python code into C without altering its purpose. | mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
const = 0x2545F4914F6CDD1D
class Xorshift_star():
def __init__(self, seed=0):
self.state = seed & mask64
def seed(self, num):
self.state = num & mask64
def next_int(self):
"return random int between 0 and 2**32"
x = self.state
x = (x ^ (x >> 12)) & mask64
x = (x ^ (x << 25)) & mask64
x = (x ^ (x >> 27)) & mask64
self.state = x
answer = (((x * const) & mask64) >> 32) & mask32
return answer
def next_float(self):
"return random float between 0 and 1"
return self.next_int() / (1 << 32)
if __name__ == '__main__':
random_gen = Xorshift_star()
random_gen.seed(1234567)
for i in range(5):
print(random_gen.next_int())
random_gen.seed(987654321)
hist = {i:0 for i in range(5)}
for i in range(100_000):
hist[int(random_gen.next_float() *5)] += 1
print(hist)
| #include <math.h>
#include <stdint.h>
#include <stdio.h>
static uint64_t state;
static const uint64_t STATE_MAGIC = 0x2545F4914F6CDD1D;
void seed(uint64_t num) {
state = num;
}
uint32_t next_int() {
uint64_t x;
uint32_t answer;
x = state;
x = x ^ (x >> 12);
x = x ^ (x << 25);
x = x ^ (x >> 27);
state = x;
answer = ((x * STATE_MAGIC) >> 32);
return answer;
}
float next_float() {
return (float)next_int() / (1LL << 32);
}
int main() {
int counts[5] = { 0, 0, 0, 0, 0 };
int i;
seed(1234567);
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("%u\n", next_int());
printf("\n");
seed(987654321);
for (i = 0; i < 100000; i++) {
int j = (int)floor(next_float() * 5.0);
counts[j]++;
}
for (i = 0; i < 5; i++) {
printf("%d: %d\n", i, counts[i]);
}
return 0;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. |
import inflect
def count_letters(word):
count = 0
for letter in word:
if letter != ',' and letter !='-' and letter !=' ':
count += 1
return count
def split_with_spaces(sentence):
sentence_list = []
curr_word = ""
for c in sentence:
if c == " " and curr_word != "":
sentence_list.append(curr_word+" ")
curr_word = ""
else:
curr_word += c
if len(curr_word) > 0:
sentence_list.append(curr_word)
return sentence_list
def my_num_to_words(p, my_number):
number_string_list = p.number_to_words(my_number, wantlist=True, andword='')
number_string = number_string_list[0]
for i in range(1,len(number_string_list)):
number_string += " " + number_string_list[i]
return number_string
def build_sentence(p, max_words):
sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,")
num_words = 13
word_number = 2
while num_words < max_words:
ordinal_string = my_num_to_words(p, p.ordinal(word_number))
word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))
new_string = " "+word_number_string+" in the "+ordinal_string+","
new_list = split_with_spaces(new_string)
sentence_list += new_list
num_words += len(new_list)
word_number += 1
return sentence_list, num_words
def word_and_counts(word_num):
sentence_list, num_words = build_sentence(p, word_num)
word_str = sentence_list[word_num - 1].strip(' ,')
num_letters = len(word_str)
num_characters = 0
for word in sentence_list:
num_characters += len(word)
print('Word {0:8d} is "{1}", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters))
p = inflect.engine()
sentence_list, num_words = build_sentence(p, 201)
print(" ")
print("The lengths of the first 201 words are:")
print(" ")
print('{0:3d}: '.format(1),end='')
total_characters = 0
for word_index in range(201):
word_length = count_letters(sentence_list[word_index])
total_characters += len(sentence_list[word_index])
print('{0:2d}'.format(word_length),end='')
if (word_index+1) % 20 == 0:
print(" ")
print('{0:3d}: '.format(word_index + 2),end='')
else:
print(" ",end='')
print(" ")
print(" ")
print("Length of the sentence so far: "+str(total_characters))
print(" ")
word_and_counts(1000)
word_and_counts(10000)
word_and_counts(100000)
word_and_counts(1000000)
word_and_counts(10000000)
| #include <ctype.h>
#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <glib.h>
typedef uint64_t integer;
typedef struct number_names_tag {
const char* cardinal;
const char* ordinal;
} number_names;
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "four", "fourth" }, { "five", "fifth" },
{ "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" },
{ "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" },
{ "twelve", "twelfth" }, { "thirteen", "thirteenth" },
{ "fourteen", "fourteenth" }, { "fifteen", "fifteenth" },
{ "sixteen", "sixteenth" }, { "seventeen", "seventeenth" },
{ "eighteen", "eighteenth" }, { "nineteen", "nineteenth" }
};
const number_names tens[] = {
{ "twenty", "twentieth" }, { "thirty", "thirtieth" },
{ "forty", "fortieth" }, { "fifty", "fiftieth" },
{ "sixty", "sixtieth" }, { "seventy", "seventieth" },
{ "eighty", "eightieth" }, { "ninety", "ninetieth" }
};
typedef struct named_number_tag {
const char* cardinal;
const char* ordinal;
integer number;
} named_number;
const named_number named_numbers[] = {
{ "hundred", "hundredth", 100 },
{ "thousand", "thousandth", 1000 },
{ "million", "millionth", 1000000 },
{ "billion", "biliionth", 1000000000 },
{ "trillion", "trillionth", 1000000000000 },
{ "quadrillion", "quadrillionth", 1000000000000000ULL },
{ "quintillion", "quintillionth", 1000000000000000000ULL }
};
const char* get_small_name(const number_names* n, bool ordinal) {
return ordinal ? n->ordinal : n->cardinal;
}
const char* get_big_name(const named_number* n, bool ordinal) {
return ordinal ? n->ordinal : n->cardinal;
}
const named_number* get_named_number(integer n) {
const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]);
for (size_t i = 0; i + 1 < names_len; ++i) {
if (n < named_numbers[i + 1].number)
return &named_numbers[i];
}
return &named_numbers[names_len - 1];
}
typedef struct word_tag {
size_t offset;
size_t length;
} word_t;
typedef struct word_list_tag {
GArray* words;
GString* str;
} word_list;
void word_list_create(word_list* words) {
words->words = g_array_new(FALSE, FALSE, sizeof(word_t));
words->str = g_string_new(NULL);
}
void word_list_destroy(word_list* words) {
g_string_free(words->str, TRUE);
g_array_free(words->words, TRUE);
}
void word_list_clear(word_list* words) {
g_string_truncate(words->str, 0);
g_array_set_size(words->words, 0);
}
void word_list_append(word_list* words, const char* str) {
size_t offset = words->str->len;
size_t len = strlen(str);
g_string_append_len(words->str, str, len);
word_t word;
word.offset = offset;
word.length = len;
g_array_append_val(words->words, word);
}
word_t* word_list_get(word_list* words, size_t index) {
return &g_array_index(words->words, word_t, index);
}
void word_list_extend(word_list* words, const char* str) {
word_t* word = word_list_get(words, words->words->len - 1);
size_t len = strlen(str);
word->length += len;
g_string_append_len(words->str, str, len);
}
size_t append_number_name(word_list* words, integer n, bool ordinal) {
size_t count = 0;
if (n < 20) {
word_list_append(words, get_small_name(&small[n], ordinal));
count = 1;
} else if (n < 100) {
if (n % 10 == 0) {
word_list_append(words, get_small_name(&tens[n/10 - 2], ordinal));
} else {
word_list_append(words, get_small_name(&tens[n/10 - 2], false));
word_list_extend(words, "-");
word_list_extend(words, get_small_name(&small[n % 10], ordinal));
}
count = 1;
} else {
const named_number* num = get_named_number(n);
integer p = num->number;
count += append_number_name(words, n/p, false);
if (n % p == 0) {
word_list_append(words, get_big_name(num, ordinal));
++count;
} else {
word_list_append(words, get_big_name(num, false));
++count;
count += append_number_name(words, n % p, ordinal);
}
}
return count;
}
size_t count_letters(word_list* words, size_t index) {
const word_t* word = word_list_get(words, index);
size_t letters = 0;
const char* s = words->str->str + word->offset;
for (size_t i = 0, n = word->length; i < n; ++i) {
if (isalpha((unsigned char)s[i]))
++letters;
}
return letters;
}
void sentence(word_list* result, size_t count) {
static const char* words[] = {
"Four", "is", "the", "number", "of", "letters", "in", "the",
"first", "word", "of", "this", "sentence,"
};
word_list_clear(result);
size_t n = sizeof(words)/sizeof(words[0]);
for (size_t i = 0; i < n; ++i)
word_list_append(result, words[i]);
for (size_t i = 1; count > n; ++i) {
n += append_number_name(result, count_letters(result, i), false);
word_list_append(result, "in");
word_list_append(result, "the");
n += 2;
n += append_number_name(result, i + 1, true);
word_list_extend(result, ",");
}
}
size_t sentence_length(const word_list* words) {
size_t n = words->words->len;
if (n == 0)
return 0;
return words->str->len + n - 1;
}
int main() {
setlocale(LC_ALL, "");
size_t n = 201;
word_list result = { 0 };
word_list_create(&result);
sentence(&result, n);
printf("Number of letters in first %'lu words in the sequence:\n", n);
for (size_t i = 0; i < n; ++i) {
if (i != 0)
printf("%c", i % 25 == 0 ? '\n' : ' ');
printf("%'2lu", count_letters(&result, i));
}
printf("\nSentence length: %'lu\n", sentence_length(&result));
for (n = 1000; n <= 10000000; n *= 10) {
sentence(&result, n);
const word_t* word = word_list_get(&result, n - 1);
const char* s = result.str->str + word->offset;
printf("The %'luth word is '%.*s' and has %lu letters. ", n,
(int)word->length, s, count_letters(&result, n - 1));
printf("Sentence length: %'lu\n" , sentence_length(&result));
}
word_list_destroy(&result);
return 0;
}
|
Please provide an equivalent version of this Python code in C. |
def validate(diagram):
rawlines = diagram.splitlines()
lines = []
for line in rawlines:
if line != '':
lines.append(line)
if len(lines) == 0:
print('diagram has no non-empty lines!')
return None
width = len(lines[0])
cols = (width - 1) // 3
if cols not in [8, 16, 32, 64]:
print('number of columns should be 8, 16, 32 or 64')
return None
if len(lines)%2 == 0:
print('number of non-empty lines should be odd')
return None
if lines[0] != (('+--' * cols)+'+'):
print('incorrect header line')
return None
for i in range(len(lines)):
line=lines[i]
if i == 0:
continue
elif i%2 == 0:
if line != lines[0]:
print('incorrect separator line')
return None
elif len(line) != width:
print('inconsistent line widths')
return None
elif line[0] != '|' or line[width-1] != '|':
print("non-separator lines must begin and end with '|'")
return None
return lines
def decode(lines):
print("Name Bits Start End")
print("======= ==== ===== ===")
startbit = 0
results = []
for line in lines:
infield=False
for c in line:
if not infield and c == '|':
infield = True
spaces = 0
name = ''
elif infield:
if c == ' ':
spaces += 1
elif c != '|':
name += c
else:
bits = (spaces + len(name) + 1) // 3
endbit = startbit + bits - 1
print('{0:7} {1:2d} {2:2d} {3:2d}'.format(name, bits, startbit, endbit))
reslist = [name, bits, startbit, endbit]
results.append(reslist)
spaces = 0
name = ''
startbit += bits
return results
def unpack(results, hex):
print("\nTest string in hex:")
print(hex)
print("\nTest string in binary:")
bin = f'{int(hex, 16):0>{4*len(hex)}b}'
print(bin)
print("\nUnpacked:\n")
print("Name Size Bit pattern")
print("======= ==== ================")
for r in results:
name = r[0]
size = r[1]
startbit = r[2]
endbit = r[3]
bitpattern = bin[startbit:endbit+1]
print('{0:7} {1:2d} {2:16}'.format(name, size, bitpattern))
diagram =
lines = validate(diagram)
if lines == None:
print("No lines returned")
else:
print(" ")
print("Diagram after trimming whitespace and removal of blank lines:")
print(" ")
for line in lines:
print(line)
print(" ")
print("Decoded:")
print(" ")
results = decode(lines)
hex = "78477bbf5496e12e1bf169a4"
unpack(results, hex)
| #include <stdlib.h>
#include <stdio.h>
#include <string.h>
enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };
char *Lines[MAX_ROWS] = {
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ID |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" |QR| Opcode |AA|TC|RD|RA| Z | RCODE |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | QDCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ANCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | NSCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ARCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
};
typedef struct {
unsigned bit3s;
unsigned mask;
unsigned data;
char A[NAME_SZ+2];
}NAME_T;
NAME_T names[MAX_NAMES];
unsigned idx_name;
enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};
unsigned header[MAX_HDR];
unsigned idx_hdr;
int bit_hdr(char *pLine);
int bit_names(char *pLine);
void dump_names(void);
void make_test_hdr(void);
int main(void){
char *p1; int rv;
printf("Extract meta-data from bit-encoded text form\n");
make_test_hdr();
idx_name = 0;
for( int i=0; i<MAX_ROWS;i++ ){
p1 = Lines[i];
if( p1==NULL ) break;
if( rv = bit_hdr(Lines[i]), rv>0) continue;
if( rv = bit_names(Lines[i]),rv>0) continue;
}
dump_names();
}
int bit_hdr(char *pLine){
char *p1 = strchr(pLine,'+');
if( p1==NULL ) return 0;
int numbits=0;
for( int i=0; i<strlen(p1)-1; i+=3 ){
if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;
numbits++;
}
return numbits;
}
int bit_names(char *pLine){
char *p1,*p2 = pLine, tmp[80];
unsigned sz=0, maskbitcount = 15;
while(1){
p1 = strchr(p2,'|'); if( p1==NULL ) break;
p1++;
p2 = strchr(p1,'|'); if( p2==NULL ) break;
sz = p2-p1;
tmp[sz] = 0;
int k=0;
for(int j=0; j<sz;j++){
if( p1[j] > ' ') tmp[k++] = p1[j];
}
tmp[k]= 0; sz++;
NAME_T *pn = &names[idx_name++];
strcpy(&pn->A[0], &tmp[0]);
pn->bit3s = sz/3;
if( pn->bit3s < 16 ){
for( int i=0; i<pn->bit3s; i++){
pn->mask |= 1 << maskbitcount--;
}
pn->data = header[idx_hdr] & pn->mask;
unsigned m2 = pn->mask;
while( (m2 & 1)==0 ){
m2>>=1;
pn->data >>= 1;
}
if( pn->mask == 0xf ) idx_hdr++;
}
else{
pn->data = header[idx_hdr++];
}
}
return sz;
}
void dump_names(void){
NAME_T *pn;
printf("-name-bits-mask-data-\n");
for( int i=0; i<MAX_NAMES; i++ ){
pn = &names[i];
if( pn->bit3s < 1 ) break;
printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data);
}
puts("bye..");
}
void make_test_hdr(void){
header[ID] = 1024;
header[QDCOUNT] = 12;
header[ANCOUNT] = 34;
header[NSCOUNT] = 56;
header[ARCOUNT] = 78;
header[BITS] = 0xB50A;
}
|
Write the same code in C as shown below in Python. | from difflib import ndiff
def levenshtein(str1, str2):
result = ""
pos, removed = 0, 0
for x in ndiff(str1, str2):
if pos<len(str1) and str1[pos] == x[2]:
pos += 1
result += x[2]
if x[0] == "-":
removed += 1
continue
else:
if removed > 0:
removed -=1
else:
result += "-"
print(result)
levenshtein("place","palace")
levenshtein("rosettacode","raisethysword")
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct edit_s edit_t, *edit;
struct edit_s {
char c1, c2;
int n;
edit next;
};
void leven(char *a, char *b)
{
int i, j, la = strlen(a), lb = strlen(b);
edit *tbl = malloc(sizeof(edit) * (1 + la));
tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t));
for (i = 1; i <= la; i++)
tbl[i] = tbl[i-1] + (1+lb);
for (i = la; i >= 0; i--) {
char *aa = a + i;
for (j = lb; j >= 0; j--) {
char *bb = b + j;
if (!*aa && !*bb) continue;
edit e = &tbl[i][j];
edit repl = &tbl[i+1][j+1];
edit dela = &tbl[i+1][j];
edit delb = &tbl[i][j+1];
e->c1 = *aa;
e->c2 = *bb;
if (!*aa) {
e->next = delb;
e->n = e->next->n + 1;
continue;
}
if (!*bb) {
e->next = dela;
e->n = e->next->n + 1;
continue;
}
e->next = repl;
if (*aa == *bb) {
e->n = e->next->n;
continue;
}
if (e->next->n > delb->n) {
e->next = delb;
e->c1 = 0;
}
if (e->next->n > dela->n) {
e->next = dela;
e->c1 = *aa;
e->c2 = 0;
}
e->n = e->next->n + 1;
}
}
edit p = tbl[0];
printf("%s -> %s: %d edits\n", a, b, p->n);
while (p->next) {
if (p->c1 == p->c2)
printf("%c", p->c1);
else {
putchar('(');
if (p->c1) putchar(p->c1);
putchar(',');
if (p->c2) putchar(p->c2);
putchar(')');
}
p = p->next;
}
putchar('\n');
free(tbl[0]);
free(tbl);
}
int main(void)
{
leven("raisethysword", "rosettacode");
return 0;
}
|
Port the provided Python code into C while preserving the original functionality. | def builtinsort(x):
x.sort()
def partition(seq, pivot):
low, middle, up = [], [], []
for x in seq:
if x < pivot:
low.append(x)
elif x == pivot:
middle.append(x)
else:
up.append(x)
return low, middle, up
import random
def qsortranpart(seq):
size = len(seq)
if size < 2: return seq
low, middle, up = partition(seq, random.choice(seq))
return qsortranpart(low) + middle + qsortranpart(up)
| #ifndef _CSEQUENCE_H
#define _CSEQUENCE_H
#include <stdlib.h>
void setfillconst(double c);
void fillwithconst(double *v, int n);
void fillwithrrange(double *v, int n);
void shuffledrange(double *v, int n);
#endif
|
Write a version of this Python function in C with identical behavior. | def builtinsort(x):
x.sort()
def partition(seq, pivot):
low, middle, up = [], [], []
for x in seq:
if x < pivot:
low.append(x)
elif x == pivot:
middle.append(x)
else:
up.append(x)
return low, middle, up
import random
def qsortranpart(seq):
size = len(seq)
if size < 2: return seq
low, middle, up = partition(seq, random.choice(seq))
return qsortranpart(low) + middle + qsortranpart(up)
| #ifndef _CSEQUENCE_H
#define _CSEQUENCE_H
#include <stdlib.h>
void setfillconst(double c);
void fillwithconst(double *v, int n);
void fillwithrrange(double *v, int n);
void shuffledrange(double *v, int n);
#endif
|
Write the same code in C as shown below in Python. | try:
from itertools import zip_longest as izip_longest
except:
from itertools import izip_longest
def fringe(tree):
for node1 in tree:
if isinstance(node1, tuple):
for node2 in fringe(node1):
yield node2
else:
yield node1
def same_fringe(tree1, tree2):
return all(node1 == node2 for node1, node2 in
izip_longest(fringe(tree1), fringe(tree2)))
if __name__ == '__main__':
a = 1, 2, 3, 4, 5, 6, 7, 8
b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8))))
c = (((1, 2), 3), 4), 5, 6, 7, 8
x = 1, 2, 3, 4, 5, 6, 7, 8, 9
y = 0, 2, 3, 4, 5, 6, 7, 8
z = 1, 2, (4, 3), 5, 6, 7, 8
assert same_fringe(a, a)
assert same_fringe(a, b)
assert same_fringe(a, c)
assert not same_fringe(a, x)
assert not same_fringe(a, y)
assert not same_fringe(a, z)
| #include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>
typedef struct {
ucontext_t caller, callee;
char stack[8192];
void *in, *out;
} co_t;
co_t * co_new(void(*f)(), void *data)
{
co_t * c = malloc(sizeof(*c));
getcontext(&c->callee);
c->in = data;
c->callee.uc_stack.ss_sp = c->stack;
c->callee.uc_stack.ss_size = sizeof(c->stack);
c->callee.uc_link = &c->caller;
makecontext(&c->callee, f, 1, (int)c);
return c;
}
void co_del(co_t *c)
{
free(c);
}
inline void
co_yield(co_t *c, void *data)
{
c->out = data;
swapcontext(&c->callee, &c->caller);
}
inline void *
co_collect(co_t *c)
{
c->out = 0;
swapcontext(&c->caller, &c->callee);
return c->out;
}
typedef struct node node;
struct node {
int v;
node *left, *right;
};
node *newnode(int v)
{
node *n = malloc(sizeof(node));
n->left = n->right = 0;
n->v = v;
return n;
}
void tree_insert(node **root, node *n)
{
while (*root) root = ((*root)->v > n->v)
? &(*root)->left
: &(*root)->right;
*root = n;
}
void tree_trav(int x)
{
co_t *c = (co_t *) x;
void trav(node *root) {
if (!root) return;
trav(root->left);
co_yield(c, root);
trav(root->right);
}
trav(c->in);
}
int tree_eq(node *t1, node *t2)
{
co_t *c1 = co_new(tree_trav, t1);
co_t *c2 = co_new(tree_trav, t2);
node *p = 0, *q = 0;
do {
p = co_collect(c1);
q = co_collect(c2);
} while (p && q && (p->v == q->v));
co_del(c1);
co_del(c2);
return !p && !q;
}
int main()
{
int x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1 };
int y[] = { 2, 5, 7, 1, 9, 0, 6, 4, 8, 3, -1 };
int z[] = { 0, 1, 2, 3, 4, 5, 6, 8, 9, -1 };
node *t1 = 0, *t2 = 0, *t3 = 0;
void mktree(int *buf, node **root) {
int i;
for (i = 0; buf[i] >= 0; i++)
tree_insert(root, newnode(buf[i]));
}
mktree(x, &t1);
mktree(y, &t2);
mktree(z, &t3);
printf("t1 == t2: %s\n", tree_eq(t1, t2) ? "yes" : "no");
printf("t1 == t3: %s\n", tree_eq(t1, t3) ? "yes" : "no");
return 0;
}
|
Write the same code in C as shown below in Python. | from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
example:
<yourscript> --file=outfile -q
| #include <stdio.h>
int main(int argc, char **argv){
int i;
const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL};
enum {CREATE,PRINT,TITLE,DATE,AUTH};
if (argc<2) {
usage: printf ("Usage: %s [commands]\n"
"-c Create new entry.\n"
"-p Print the latest entry.\n"
"-t Sort by title.\n"
"-d Sort by date.\n"
"-a Sort by author.\n",argv[0]);
return 0;
}
for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);
switch (i) {
case CREATE:
...
break;
case PRINT:
...
break;
...
...
default:
printf ("Unknown command..." ...);
goto usage;
}
return 0;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. | from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
example:
<yourscript> --file=outfile -q
| #include <stdio.h>
int main(int argc, char **argv){
int i;
const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL};
enum {CREATE,PRINT,TITLE,DATE,AUTH};
if (argc<2) {
usage: printf ("Usage: %s [commands]\n"
"-c Create new entry.\n"
"-p Print the latest entry.\n"
"-t Sort by title.\n"
"-d Sort by date.\n"
"-a Sort by author.\n",argv[0]);
return 0;
}
for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);
switch (i) {
case CREATE:
...
break;
case PRINT:
...
break;
...
...
default:
printf ("Unknown command..." ...);
goto usage;
}
return 0;
}
|
Convert this Python snippet to C and keep its semantics consistent. | [print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
| #include <stdio.h>
#include <stdint.h>
uint64_t ones_plus_three(uint64_t ones) {
uint64_t r = 0;
while (ones--) r = r*10 + 1;
return r*10 + 3;
}
int main() {
uint64_t n;
for (n=0; n<8; n++) {
uint64_t x = ones_plus_three(n);
printf("%8lu^2 = %15lu\n", x, x*x);
}
return 0;
}
|
Write the same algorithm in C as shown in this Python implementation. | [print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
| #include <stdio.h>
#include <stdint.h>
uint64_t ones_plus_three(uint64_t ones) {
uint64_t r = 0;
while (ones--) r = r*10 + 1;
return r*10 + 3;
}
int main() {
uint64_t n;
for (n=0; n<8; n++) {
uint64_t x = ones_plus_three(n);
printf("%8lu^2 = %15lu\n", x, x*x);
}
return 0;
}
|
Write a version of this Python function in C with identical behavior. | import autopy
autopy.key.type_string("Hello, world!")
autopy.key.type_string("Hello, world!", wpm=60)
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW)
| #include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
int main(int argc, char *argv[])
{
Display *dpy;
Window win;
GC gc;
int scr;
Atom WM_DELETE_WINDOW;
XEvent ev;
XEvent ev2;
KeySym keysym;
int loop;
dpy = XOpenDisplay(NULL);
if (dpy == NULL) {
fputs("Cannot open display", stderr);
exit(1);
}
scr = XDefaultScreen(dpy);
win = XCreateSimpleWindow(dpy,
XRootWindow(dpy, scr),
10, 10, 300, 200, 1,
XBlackPixel(dpy, scr), XWhitePixel(dpy, scr));
XStoreName(dpy, win, argv[0]);
XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask);
XMapWindow(dpy, win);
XFlush(dpy);
gc = XDefaultGC(dpy, scr);
WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", True);
XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1);
loop = 1;
while (loop) {
XNextEvent(dpy, &ev);
switch (ev.type)
{
case Expose:
{
char msg1[] = "Clic in the window to generate";
char msg2[] = "a key press event";
XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1);
XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1);
}
break;
case ButtonPress:
puts("ButtonPress event received");
ev2.type = KeyPress;
ev2.xkey.state = ShiftMask;
ev2.xkey.keycode = 24 + (rand() % 33);
ev2.xkey.same_screen = True;
XSendEvent(dpy, win, True, KeyPressMask, &ev2);
break;
case ClientMessage:
if (ev.xclient.data.l[0] == WM_DELETE_WINDOW)
loop = 0;
break;
case KeyPress:
puts("KeyPress event received");
printf("> keycode: %d\n", ev.xkey.keycode);
keysym = XLookupKeysym(&(ev.xkey), 0);
if (keysym == XK_q ||
keysym == XK_Escape) {
loop = 0;
} else {
char buffer[] = " ";
int nchars = XLookupString(
&(ev.xkey),
buffer,
2,
&keysym,
NULL );
if (nchars == 1)
printf("> Key '%c' pressed\n", buffer[0]);
}
break;
}
}
XDestroyWindow(dpy, win);
XCloseDisplay(dpy);
return 1;
}
|
Write a version of this Python function in C with identical behavior. | from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
"Place m black and white queens, peacefully, on an n-by-n board"
board = set(product(range(n), repeat=2))
placements = {frozenset(c) for c in combinations(board, m)}
for blacks in placements:
black_attacks = reduce(_or,
(queen_attacks_from(pos, n) for pos in blacks),
set())
for whites in {frozenset(c)
for c in combinations(board - black_attacks, m)}:
if not black_attacks & whites:
return blacks, whites
return set(), set()
@lru_cache(maxsize=None)
def queen_attacks_from(pos, n):
x0, y0 = pos
a = set([pos])
a.update((x, y0) for x in range(n))
a.update((x0, y) for y in range(n))
for x1 in range(n):
y1 = y0 -x0 +x1
if 0 <= y1 < n:
a.add((x1, y1))
y1 = y0 +x0 -x1
if 0 <= y1 < n:
a.add((x1, y1))
return a
def pboard(black_white, n):
"Print board"
if black_white is None:
blk, wht = set(), set()
else:
blk, wht = black_white
print(f"
f"on a {n}-by-{n} board:", end='')
for x, y in product(range(n), repeat=2):
if y == 0:
print()
xy = (x, y)
ch = ('?' if xy in blk and xy in wht
else 'B' if xy in blk
else 'W' if xy in wht
else _bbullet if (x + y)%2 else _wbullet)
print('%s' % ch, end='')
print()
if __name__ == '__main__':
n=2
for n in range(2, 7):
print()
for m in count(1):
ans = place(m, n)
if ans[0]:
pboard(ans, n)
else:
print (f"
break
print('\n')
m, n = 5, 7
ans = place(m, n)
pboard(ans, n)
| #include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
enum Piece {
Empty,
Black,
White,
};
typedef struct Position_t {
int x, y;
} Position;
struct Node_t {
Position pos;
struct Node_t *next;
};
void releaseNode(struct Node_t *head) {
if (head == NULL) return;
releaseNode(head->next);
head->next = NULL;
free(head);
}
typedef struct List_t {
struct Node_t *head;
struct Node_t *tail;
size_t length;
} List;
List makeList() {
return (List) { NULL, NULL, 0 };
}
void releaseList(List *lst) {
if (lst == NULL) return;
releaseNode(lst->head);
lst->head = NULL;
lst->tail = NULL;
}
void addNode(List *lst, Position pos) {
struct Node_t *newNode;
if (lst == NULL) {
exit(EXIT_FAILURE);
}
newNode = malloc(sizeof(struct Node_t));
if (newNode == NULL) {
exit(EXIT_FAILURE);
}
newNode->next = NULL;
newNode->pos = pos;
if (lst->head == NULL) {
lst->head = lst->tail = newNode;
} else {
lst->tail->next = newNode;
lst->tail = newNode;
}
lst->length++;
}
void removeAt(List *lst, size_t pos) {
if (lst == NULL) return;
if (pos == 0) {
struct Node_t *temp = lst->head;
if (lst->tail == lst->head) {
lst->tail = NULL;
}
lst->head = lst->head->next;
temp->next = NULL;
free(temp);
lst->length--;
} else {
struct Node_t *temp = lst->head;
struct Node_t *rem;
size_t i = pos;
while (i-- > 1) {
temp = temp->next;
}
rem = temp->next;
if (rem == lst->tail) {
lst->tail = temp;
}
temp->next = rem->next;
rem->next = NULL;
free(rem);
lst->length--;
}
}
bool isAttacking(Position queen, Position pos) {
return queen.x == pos.x
|| queen.y == pos.y
|| abs(queen.x - pos.x) == abs(queen.y - pos.y);
}
bool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) {
struct Node_t *queenNode;
bool placingBlack = true;
int i, j;
if (pBlackQueens == NULL || pWhiteQueens == NULL) {
exit(EXIT_FAILURE);
}
if (m == 0) return true;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
Position pos = { i, j };
queenNode = pBlackQueens->head;
while (queenNode != NULL) {
if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) {
goto inner;
}
queenNode = queenNode->next;
}
queenNode = pWhiteQueens->head;
while (queenNode != NULL) {
if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) {
goto inner;
}
queenNode = queenNode->next;
}
if (placingBlack) {
addNode(pBlackQueens, pos);
placingBlack = false;
} else {
addNode(pWhiteQueens, pos);
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true;
}
removeAt(pBlackQueens, pBlackQueens->length - 1);
removeAt(pWhiteQueens, pWhiteQueens->length - 1);
placingBlack = true;
}
inner: {}
}
}
if (!placingBlack) {
removeAt(pBlackQueens, pBlackQueens->length - 1);
}
return false;
}
void printBoard(int n, List *pBlackQueens, List *pWhiteQueens) {
size_t length = n * n;
struct Node_t *queenNode;
char *board;
size_t i, j, k;
if (pBlackQueens == NULL || pWhiteQueens == NULL) {
exit(EXIT_FAILURE);
}
board = calloc(length, sizeof(char));
if (board == NULL) {
exit(EXIT_FAILURE);
}
queenNode = pBlackQueens->head;
while (queenNode != NULL) {
board[queenNode->pos.x * n + queenNode->pos.y] = Black;
queenNode = queenNode->next;
}
queenNode = pWhiteQueens->head;
while (queenNode != NULL) {
board[queenNode->pos.x * n + queenNode->pos.y] = White;
queenNode = queenNode->next;
}
for (i = 0; i < length; i++) {
if (i != 0 && i % n == 0) {
printf("\n");
}
switch (board[i]) {
case Black:
printf("B ");
break;
case White:
printf("W ");
break;
default:
j = i / n;
k = i - j * n;
if (j % 2 == k % 2) {
printf(" ");
} else {
printf("# ");
}
break;
}
}
printf("\n\n");
}
void test(int n, int q) {
List blackQueens = makeList();
List whiteQueens = makeList();
printf("%d black and %d white queens on a %d x %d board:\n", q, q, n, n);
if (place(q, n, &blackQueens, &whiteQueens)) {
printBoard(n, &blackQueens, &whiteQueens);
} else {
printf("No solution exists.\n\n");
}
releaseList(&blackQueens);
releaseList(&whiteQueens);
}
int main() {
test(2, 1);
test(3, 1);
test(3, 2);
test(4, 1);
test(4, 2);
test(4, 3);
test(5, 1);
test(5, 2);
test(5, 3);
test(5, 4);
test(5, 5);
test(6, 1);
test(6, 2);
test(6, 3);
test(6, 4);
test(6, 5);
test(6, 6);
test(7, 1);
test(7, 2);
test(7, 3);
test(7, 4);
test(7, 5);
test(7, 6);
test(7, 7);
return EXIT_SUCCESS;
}
|
Ensure the translated C code behaves exactly like the original Python snippet. | from macropy.core.macros import *
from macropy.core.quotes import macros, q, ast, u
macros = Macros()
@macros.expr
def expand(tree, **kw):
addition = 10
return q[lambda x: x * ast[tree] + u[addition]]
|
#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1]
#define COMPILE_TIME_ASSERT3(X,L) STATIC_ASSERT(X,static_assertion_at_line_##L)
#define COMPILE_TIME_ASSERT2(X,L) COMPILE_TIME_ASSERT3(X,L)
#define COMPILE_TIME_ASSERT(X) COMPILE_TIME_ASSERT2(X,__LINE__)
COMPILE_TIME_ASSERT(sizeof(long)==8);
int main()
{
COMPILE_TIME_ASSERT(sizeof(int)==4);
}
|
Please provide an equivalent version of this Python code in C. | col = 0
for i in range(100000):
if set(str(i)) == set(hex(i)[2:]):
col += 1
print("{:7}".format(i), end='\n'[:col % 10 == 0])
print()
| #include <stdio.h>
#define LIMIT 100000
int digitset(int num, int base) {
int set;
for (set = 0; num; num /= base)
set |= 1 << num % base;
return set;
}
int main() {
int i, c = 0;
for (i = 0; i < LIMIT; i++)
if (digitset(i,10) == digitset(i,16))
printf("%6d%c", i, ++c%10 ? ' ' : '\n');
printf("\n");
return 0;
}
|
Convert the following code from Python to C, ensuring the logic remains intact. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
n = 600851475143
j = 3
while not isPrime(n):
if n % j == 0:
n /= j
j += 2
print(n);
| #include <stdio.h>
#include <stdlib.h>
int isprime( long int n ) {
int i=3;
if(!(n%2)) return 0;
while( i*i < n ) {
if(!(n%i)) return 0;
i+=2;
}
return 1;
}
int main(void) {
long int n=600851475143, j=3;
while(!isprime(n)) {
if(!(n%j)) n/=j;
j+=2;
}
printf( "%ld\n", n );
return 0;
}
|
Convert this Python snippet to C and keep its semantics consistent. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
n = 600851475143
j = 3
while not isPrime(n):
if n % j == 0:
n /= j
j += 2
print(n);
| #include <stdio.h>
#include <stdlib.h>
int isprime( long int n ) {
int i=3;
if(!(n%2)) return 0;
while( i*i < n ) {
if(!(n%i)) return 0;
i+=2;
}
return 1;
}
int main(void) {
long int n=600851475143, j=3;
while(!isprime(n)) {
if(!(n%j)) n/=j;
j+=2;
}
printf( "%ld\n", n );
return 0;
}
|
Rewrite the snippet below in C so it works the same as the original Python code. | def lpd(n):
for i in range(n-1,0,-1):
if n%i==0: return i
return 1
for i in range(1,101):
print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
| #include <stdio.h>
unsigned int lpd(unsigned int n) {
if (n<=1) return 1;
int i;
for (i=n-1; i>0; i--)
if (n%i == 0) return i;
}
int main() {
int i;
for (i=1; i<=100; i++) {
printf("%3d", lpd(i));
if (i % 10 == 0) printf("\n");
}
return 0;
}
|
Port the provided Python code into C while preserving the original functionality. | from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
assert s == decode, 'Whoops!'
| #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 100
int move_to_front(char *str,char c)
{
char *q,*p;
int shift=0;
p=(char *)malloc(strlen(str)+1);
strcpy(p,str);
q=strchr(p,c);
shift=q-p;
strncpy(str+1,p,shift);
str[0]=c;
free(p);
return shift;
}
void decode(int* pass,int size,char *sym)
{
int i,index;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=table[pass[i]];
index=move_to_front(table,c);
if(pass[i]!=index) printf("there is an error");
sym[i]=c;
}
sym[size]='\0';
}
void encode(char *sym,int size,int *pass)
{
int i=0;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=sym[i];
pass[i]=move_to_front(table,c);
}
}
int check(char *sym,int size,int *pass)
{
int *pass2=malloc(sizeof(int)*size);
char *sym2=malloc(sizeof(char)*size);
int i,val=1;
encode(sym,size,pass2);
i=0;
while(i<size && pass[i]==pass2[i])i++;
if(i!=size)val=0;
decode(pass,size,sym2);
if(strcmp(sym,sym2)!=0)val=0;
free(sym2);
free(pass2);
return val;
}
int main()
{
char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"};
int pass[MAX_SIZE]={0};
int i,len,j;
for(i=0;i<3;i++)
{
len=strlen(sym[i]);
encode(sym[i],len,pass);
printf("%s : [",sym[i]);
for(j=0;j<len;j++)
printf("%d ",pass[j]);
printf("]\n");
if(check(sym[i],len,pass))
printf("Correct :)\n");
else
printf("Incorrect :(\n");
}
return 0;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. | Import-Module ActiveDirectory
$searchData = "user name"
$searchBase = "DC=example,DC=com"
get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
| #include <ldap.h>
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
LDAPMessage **result;
ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE,
"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))",
NULL,
0,
result);
ldap_msgfree(*result);
ldap_unbind(ld);
|
Change the programming language of this snippet from Python to C without modifying what it does. | from numpy import *
A = matrix([[3, 0], [4, 5]])
U, Sigma, VT = linalg.svd(A)
print(U)
print(Sigma)
print(VT)
| #include <stdio.h>
#include <gsl/gsl_linalg.h>
void gsl_matrix_print(const gsl_matrix *M) {
int rows = M->size1;
int cols = M->size2;
for (int i = 0; i < rows; i++) {
printf("|");
for (int j = 0; j < cols; j++) {
printf("% 12.10f ", gsl_matrix_get(M, i, j));
}
printf("\b|\n");
}
printf("\n");
}
int main(){
double a[] = {3, 0, 4, 5};
gsl_matrix_view A = gsl_matrix_view_array(a, 2, 2);
gsl_matrix *V = gsl_matrix_alloc(2, 2);
gsl_vector *S = gsl_vector_alloc(2);
gsl_vector *work = gsl_vector_alloc(2);
gsl_linalg_SV_decomp(&A.matrix, V, S, work);
gsl_matrix_transpose(V);
double s[] = {S->data[0], 0, 0, S->data[1]};
gsl_matrix_view SM = gsl_matrix_view_array(s, 2, 2);
printf("U:\n");
gsl_matrix_print(&A.matrix);
printf("S:\n");
gsl_matrix_print(&SM.matrix);
printf("VT:\n");
gsl_matrix_print(V);
gsl_matrix_free(V);
gsl_vector_free(S);
gsl_vector_free(work);
return 0;
}
|
Convert this Python snippet to C and keep its semantics consistent. | def main():
fila = 0
lenCubos = 51
print("Suma de N cubos para n = [0..49]\n")
for n in range(1, lenCubos):
sumCubos = 0
for m in range(1, n):
sumCubos = sumCubos + (m ** 3)
fila += 1
print(f'{sumCubos:7} ', end='')
if fila % 5 == 0:
print(" ")
print(f"\nEncontrados {fila} cubos.")
if __name__ == '__main__': main()
| #include <stdio.h>
int main() {
for (int i = 0, sum = 0; i < 50; ++i) {
sum += i * i * i;
printf("%7d%c", sum, (i + 1) % 5 == 0 ? '\n' : ' ');
}
return 0;
}
|
Change the programming language of this snippet from Python to C without modifying what it does. | >>> def isint(f):
return complex(f).imag == 0 and complex(f).real.is_integer()
>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]
[True, True, True, False, False, False]
>>>
...
>>> isint(25.000000)
True
>>> isint(24.999999)
False
>>> isint(25.000100)
False
>>> isint(-2.1e120)
True
>>> isint(-5e-2)
False
>>> isint(float('nan'))
False
>>> isint(float('inf'))
False
>>> isint(5.0+0.0j)
True
>>> isint(5-5j)
False
| #include <stdio.h>
#include <complex.h>
#include <math.h>
#define FMTSPEC(arg) _Generic((arg), \
float: "%f", double: "%f", \
long double: "%Lf", unsigned int: "%u", \
unsigned long: "%lu", unsigned long long: "%llu", \
int: "%d", long: "%ld", long long: "%lld", \
default: "(invalid type (%p)")
#define CMPPARTS(x, y) ((long double complex)((long double)(x) + \
I * (long double)(y)))
#define TEST_CMPL(i, j)\
printf(FMTSPEC(i), i), printf(" + "), printf(FMTSPEC(j), j), \
printf("i = %s\n", (isint(CMPPARTS(i, j)) ? "true" : "false"))
#define TEST_REAL(i)\
printf(FMTSPEC(i), i), printf(" = %s\n", (isint(i) ? "true" : "false"))
static inline int isint(long double complex n)
{
return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);
}
int main(void)
{
TEST_REAL(0);
TEST_REAL(-0);
TEST_REAL(-2);
TEST_REAL(-2.00000000000001);
TEST_REAL(5);
TEST_REAL(7.3333333333333);
TEST_REAL(3.141592653589);
TEST_REAL(-9.223372036854776e18);
TEST_REAL(5e-324);
TEST_REAL(NAN);
TEST_CMPL(6, 0);
TEST_CMPL(0, 1);
TEST_CMPL(0, 0);
TEST_CMPL(3.4, 0);
double complex test1 = 5 + 0*I,
test2 = 3.4f,
test3 = 3,
test4 = 0 + 1.2*I;
printf("Test 1 (5+i) = %s\n", isint(test1) ? "true" : "false");
printf("Test 2 (3.4+0i) = %s\n", isint(test2) ? "true" : "false");
printf("Test 3 (3+0i) = %s\n", isint(test3) ? "true" : "false");
printf("Test 4 (0+1.2i) = %s\n", isint(test4) ? "true" : "false");
}
|
Port the following code from Python to C with equivalent syntax and logic. | import os
exit_code = os.system('ls')
output = os.popen('ls').read()
| #include <stdlib.h>
int main()
{
system("ls");
return 0;
}
|
Generate a C translation of this Python snippet without changing its computational steps. |
from __future__ import print_function
import lxml
from lxml import etree
if __name__=="__main__":
parser = etree.XMLParser(dtd_validation=True)
schema_root = etree.XML()
schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5</a>", parser)
print ("Finished validating good xml")
except lxml.etree.XMLSyntaxError as err:
print (err)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
except lxml.etree.XMLSyntaxError as err:
print (err)
| #include <libxml/xmlschemastypes.h>
int main(int argC, char** argV)
{
if (argC <= 2) {
printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]);
return 0;
}
xmlDocPtr doc;
xmlSchemaPtr schema = NULL;
xmlSchemaParserCtxtPtr ctxt;
char *XMLFileName = argV[1];
char *XSDFileName = argV[2];
int ret;
xmlLineNumbersDefault(1);
ctxt = xmlSchemaNewParserCtxt(XSDFileName);
xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
schema = xmlSchemaParse(ctxt);
xmlSchemaFreeParserCtxt(ctxt);
doc = xmlReadFile(XMLFileName, NULL, 0);
if (doc == NULL){
fprintf(stderr, "Could not parse %s\n", XMLFileName);
}
else{
xmlSchemaValidCtxtPtr ctxt;
ctxt = xmlSchemaNewValidCtxt(schema);
xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
ret = xmlSchemaValidateDoc(ctxt, doc);
if (ret == 0){
printf("%s validates\n", XMLFileName);
}
else if (ret > 0){
printf("%s fails to validate\n", XMLFileName);
}
else{
printf("%s validation generated an internal error\n", XMLFileName);
}
xmlSchemaFreeValidCtxt(ctxt);
xmlFreeDoc(doc);
}
if(schema != NULL)
xmlSchemaFree(schema);
xmlSchemaCleanupTypes();
xmlCleanupParser();
xmlMemoryDump();
return 0;
}
|
Write the same algorithm in C as shown in this Python implementation. | def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return S[::-1]
if __name__ == '__main__':
for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
| #include <stdio.h>
#include <stdlib.h>
struct node {
int val, len;
struct node *next;
};
void lis(int *v, int len)
{
int i;
struct node *p, *n = calloc(len, sizeof *n);
for (i = 0; i < len; i++)
n[i].val = v[i];
for (i = len; i--; ) {
for (p = n + i; p++ < n + len; ) {
if (p->val > n[i].val && p->len >= n[i].len) {
n[i].next = p;
n[i].len = p->len + 1;
}
}
}
for (i = 0, p = n; i < len; i++)
if (n[i].len > p->len) p = n + i;
do printf(" %d", p->val); while ((p = p->next));
putchar('\n');
free(n);
}
int main(void)
{
int x[] = { 3, 2, 6, 4, 5, 1 };
int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
lis(x, sizeof(x) / sizeof(int));
lis(y, sizeof(y) / sizeof(int));
return 0;
}
|
Produce a language-to-language conversion: from Python to C, same semantics. | import sys, math, collections
Sphere = collections.namedtuple("Sphere", "cx cy cz r")
V3 = collections.namedtuple("V3", "x y z")
def normalize((x, y, z)):
len = math.sqrt(x**2 + y**2 + z**2)
return V3(x / len, y / len, z / len)
def dot(v1, v2):
d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z
return -d if d < 0 else 0.0
def hit_sphere(sph, x0, y0):
x = x0 - sph.cx
y = y0 - sph.cy
zsq = sph.r ** 2 - (x ** 2 + y ** 2)
if zsq < 0:
return (False, 0, 0)
szsq = math.sqrt(zsq)
return (True, sph.cz - szsq, sph.cz + szsq)
def draw_sphere(k, ambient, light):
shades = ".:!*oe&
pos = Sphere(20.0, 20.0, 0.0, 20.0)
neg = Sphere(1.0, 1.0, -6.0, 20.0)
for i in xrange(int(math.floor(pos.cy - pos.r)),
int(math.ceil(pos.cy + pos.r) + 1)):
y = i + 0.5
for j in xrange(int(math.floor(pos.cx - 2 * pos.r)),
int(math.ceil(pos.cx + 2 * pos.r) + 1)):
x = (j - pos.cx) / 2.0 + 0.5 + pos.cx
(h, zb1, zb2) = hit_sphere(pos, x, y)
if not h:
hit_result = 0
else:
(h, zs1, zs2) = hit_sphere(neg, x, y)
if not h:
hit_result = 1
elif zs1 > zb1:
hit_result = 1
elif zs2 > zb2:
hit_result = 0
elif zs2 > zb1:
hit_result = 2
else:
hit_result = 1
if hit_result == 0:
sys.stdout.write(' ')
continue
elif hit_result == 1:
vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz)
elif hit_result == 2:
vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2)
vec = normalize(vec)
b = dot(light, vec) ** k + ambient
intensity = int((1 - b) * len(shades))
intensity = min(len(shades), max(0, intensity))
sys.stdout.write(shades[intensity])
print
light = normalize(V3(-50, 30, 50))
draw_sphere(2, 0.5, light)
| #include <stdio.h>
#include <math.h>
#include <unistd.h>
const char *shades = ".:!*oe&#%@";
double light[3] = { -50, 0, 50 };
void normalize(double * v)
{
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
}
double dot(double *x, double *y)
{
double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return d < 0 ? -d : 0;
}
typedef struct { double cx, cy, cz, r; } sphere_t;
sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 };
int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2)
{
double zsq;
x -= sph->cx;
y -= sph->cy;
zsq = sph->r * sph->r - (x * x + y * y);
if (zsq < 0) return 0;
zsq = sqrt(zsq);
*z1 = sph->cz - zsq;
*z2 = sph->cz + zsq;
return 1;
}
void draw_sphere(double k, double ambient)
{
int i, j, intensity, hit_result;
double b;
double vec[3], x, y, zb1, zb2, zs1, zs2;
for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) {
y = i + .5;
for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) {
x = (j - pos.cx) / 2. + .5 + pos.cx;
if (!hit_sphere(&pos, x, y, &zb1, &zb2))
hit_result = 0;
else if (!hit_sphere(&neg, x, y, &zs1, &zs2))
hit_result = 1;
else if (zs1 > zb1) hit_result = 1;
else if (zs2 > zb2) hit_result = 0;
else if (zs2 > zb1) hit_result = 2;
else hit_result = 1;
switch(hit_result) {
case 0:
putchar('+');
continue;
case 1:
vec[0] = x - pos.cx;
vec[1] = y - pos.cy;
vec[2] = zb1 - pos.cz;
break;
default:
vec[0] = neg.cx - x;
vec[1] = neg.cy - y;
vec[2] = neg.cz - zs2;
}
normalize(vec);
b = pow(dot(light, vec), k) + ambient;
intensity = (1 - b) * (sizeof(shades) - 1);
if (intensity < 0) intensity = 0;
if (intensity >= sizeof(shades) - 1)
intensity = sizeof(shades) - 2;
putchar(shades[intensity]);
}
putchar('\n');
}
}
int main()
{
double ang = 0;
while (1) {
printf("\033[H");
light[1] = cos(ang * 2);
light[2] = cos(ang);
light[0] = sin(ang);
normalize(light);
ang += .05;
draw_sphere(2, .3);
usleep(100000);
}
return 0;
}
|
Generate a C translation of this Python snippet without changing its computational steps. | from __future__ import print_function
def lgen(even=False, nmax=1000000):
start = 2 if even else 1
n, lst = 1, list(range(start, nmax + 1, 2))
lenlst = len(lst)
yield lst[0]
while n < lenlst and lst[n] < lenlst:
yield lst[n]
n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]]
lenlst = len(lst)
for i in lst[n:]:
yield i
| #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define LUCKY_SIZE 60000
int luckyOdd[LUCKY_SIZE];
int luckyEven[LUCKY_SIZE];
void compactLucky(int luckyArray[]) {
int i, j, k;
for (i = 0; i < LUCKY_SIZE; i++) {
if (luckyArray[i] == 0) {
j = i;
break;
}
}
for (j = i + 1; j < LUCKY_SIZE; j++) {
if (luckyArray[j] > 0) {
luckyArray[i++] = luckyArray[j];
}
}
for (; i < LUCKY_SIZE; i++) {
luckyArray[i] = 0;
}
}
void initialize() {
int i, j;
for (i = 0; i < LUCKY_SIZE; i++) {
luckyEven[i] = 2 * i + 2;
luckyOdd[i] = 2 * i + 1;
}
for (i = 1; i < LUCKY_SIZE; i++) {
if (luckyOdd[i] > 0) {
for (j = luckyOdd[i] - 1; j < LUCKY_SIZE; j += luckyOdd[i]) {
luckyOdd[j] = 0;
}
compactLucky(luckyOdd);
}
}
for (i = 1; i < LUCKY_SIZE; i++) {
if (luckyEven[i] > 0) {
for (j = luckyEven[i] - 1; j < LUCKY_SIZE; j += luckyEven[i]) {
luckyEven[j] = 0;
}
compactLucky(luckyEven);
}
}
}
void printBetween(size_t j, size_t k, bool even) {
int i;
if (even) {
if (luckyEven[j] == 0 || luckyEven[k] == 0) {
fprintf(stderr, "At least one argument is too large\n");
exit(EXIT_FAILURE);
}
printf("Lucky even numbers between %d and %d are:", j, k);
for (i = 0; luckyEven[i] != 0; i++) {
if (luckyEven[i] > k) {
break;
}
if (luckyEven[i] > j) {
printf(" %d", luckyEven[i]);
}
}
} else {
if (luckyOdd[j] == 0 || luckyOdd[k] == 0) {
fprintf(stderr, "At least one argument is too large\n");
exit(EXIT_FAILURE);
}
printf("Lucky numbers between %d and %d are:", j, k);
for (i = 0; luckyOdd[i] != 0; i++) {
if (luckyOdd[i] > k) {
break;
}
if (luckyOdd[i] > j) {
printf(" %d", luckyOdd[i]);
}
}
}
printf("\n");
}
void printRange(size_t j, size_t k, bool even) {
int i;
if (even) {
if (luckyEven[k] == 0) {
fprintf(stderr, "The argument is too large\n");
exit(EXIT_FAILURE);
}
printf("Lucky even numbers %d to %d are:", j, k);
for (i = j - 1; i < k; i++) {
printf(" %d", luckyEven[i]);
}
} else {
if (luckyOdd[k] == 0) {
fprintf(stderr, "The argument is too large\n");
exit(EXIT_FAILURE);
}
printf("Lucky numbers %d to %d are:", j, k);
for (i = j - 1; i < k; i++) {
printf(" %d", luckyOdd[i]);
}
}
printf("\n");
}
void printSingle(size_t j, bool even) {
if (even) {
if (luckyEven[j] == 0) {
fprintf(stderr, "The argument is too large\n");
exit(EXIT_FAILURE);
}
printf("Lucky even number %d=%d\n", j, luckyEven[j - 1]);
} else {
if (luckyOdd[j] == 0) {
fprintf(stderr, "The argument is too large\n");
exit(EXIT_FAILURE);
}
printf("Lucky number %d=%d\n", j, luckyOdd[j - 1]);
}
}
void help() {
printf("./lucky j [k] [--lucky|--evenLucky]\n");
printf("\n");
printf(" argument(s) | what is displayed\n");
printf("==============================================\n");
printf("-j=m | mth lucky number\n");
printf("-j=m --lucky | mth lucky number\n");
printf("-j=m --evenLucky | mth even lucky number\n");
printf("-j=m -k=n | mth through nth (inclusive) lucky numbers\n");
printf("-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\n");
printf("-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\n");
printf("-j=m -k=-n | all lucky numbers in the range [m, n]\n");
printf("-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\n");
printf("-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\n");
}
void process(int argc, char *argv[]) {
bool evenLucky = false;
int j = 0;
int k = 0;
bool good = false;
int i;
for (i = 1; i < argc; ++i) {
if ('-' == argv[i][0]) {
if ('-' == argv[i][1]) {
if (0 == strcmp("--lucky", argv[i])) {
evenLucky = false;
} else if (0 == strcmp("--evenLucky", argv[i])) {
evenLucky = true;
} else {
fprintf(stderr, "Unknown long argument: [%s]\n", argv[i]);
exit(EXIT_FAILURE);
}
} else {
if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) {
good = true;
j = atoi(&argv[i][3]);
} else if ('k' == argv[i][1] && '=' == argv[i][2]) {
k = atoi(&argv[i][3]);
} else {
fprintf(stderr, "Unknown short argument: [%s]\n", argv[i]);
exit(EXIT_FAILURE);
}
}
} else {
fprintf(stderr, "Unknown argument: [%s]\n", argv[i]);
exit(EXIT_FAILURE);
}
}
if (!good) {
help();
exit(EXIT_FAILURE);
}
if (k > 0) {
printRange(j, k, evenLucky);
} else if (k < 0) {
printBetween(j, -k, evenLucky);
} else {
printSingle(j, evenLucky);
}
}
void test() {
printRange(1, 20, false);
printRange(1, 20, true);
printBetween(6000, 6100, false);
printBetween(6000, 6100, true);
printSingle(10000, false);
printSingle(10000, true);
}
int main(int argc, char *argv[]) {
initialize();
if (argc < 2) {
help();
return 1;
}
process(argc, argv);
return 0;
}
|
Convert the following code from Python to C, ensuring the logic remains intact. | >>> x="From global scope"
>>> def outerfunc():
x = "From scope at outerfunc"
def scoped_local():
x = "scope local"
return "scoped_local scope gives x = " + x
print(scoped_local())
def scoped_nonlocal():
nonlocal x
return "scoped_nonlocal scope gives x = " + x
print(scoped_nonlocal())
def scoped_global():
global x
return "scoped_global scope gives x = " + x
print(scoped_global())
def scoped_notdefinedlocally():
return "scoped_notdefinedlocally scope gives x = " + x
print(scoped_notdefinedlocally())
>>> outerfunc()
scoped_local scope gives x = scope local
scoped_nonlocal scope gives x = From scope at outerfunc
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
>>>
| int a;
static int p;
extern float v;
int code(int arg)
{
int myp;
static int myc;
}
static void code2(void)
{
v = v * 1.02;
}
|
Preserve the algorithm and functionality while converting the code from Python to C. |
import argparse
from argparse import Namespace
import datetime
import shlex
def parse_args():
'Set up, parse, and return arguments'
parser = argparse.ArgumentParser(epilog=globals()['__doc__'])
parser.add_argument('command', choices='add pl plc pa'.split(),
help=)
parser.add_argument('-d', '--description',
help='A description of the item. (e.g., title, name)')
parser.add_argument('-t', '--tag',
help=(
))
parser.add_argument('-f', '--field', nargs=2, action='append',
help='Other optional fields with value (can be repeated)')
return parser
def do_add(args, dbname):
'Add a new entry'
if args.description is None:
args.description = ''
if args.tag is None:
args.tag = ''
del args.command
print('Writing record to %s' % dbname)
with open(dbname, 'a') as db:
db.write('%r\n' % args)
def do_pl(args, dbname):
'Print the latest entry'
print('Getting last record from %s' % dbname)
with open(dbname, 'r') as db:
for line in db: pass
record = eval(line)
del record._date
print(str(record))
def do_plc(args, dbname):
'Print the latest entry for each category/tag'
print('Getting latest record for each tag from %s' % dbname)
with open(dbname, 'r') as db:
records = [eval(line) for line in db]
tags = set(record.tag for record in records)
records.reverse()
for record in records:
if record.tag in tags:
del record._date
print(str(record))
tags.discard(record.tag)
if not tags: break
def do_pa(args, dbname):
'Print all entries sorted by a date'
print('Getting all records by date from %s' % dbname)
with open(dbname, 'r') as db:
records = [eval(line) for line in db]
for record in records:
del record._date
print(str(record))
def test():
import time
parser = parse_args()
for cmdline in [
,
,
,
,
,
]:
args = parser.parse_args(shlex.split(cmdline))
now = datetime.datetime.utcnow()
args._date = now.isoformat()
do_command[args.command](args, dbname)
time.sleep(0.5)
do_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa)
dbname = '_simple_db_db.py'
if __name__ == '__main__':
if 0:
test()
else:
parser = parse_args()
args = parser.parse_args()
now = datetime.datetime.utcnow()
args._date = now.isoformat()
do_command[args.command](args, dbname)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _XOPEN_SOURCE
#define __USE_XOPEN
#include <time.h>
#define DB "database.csv"
#define TRY(a) if (!(a)) {perror(#a);exit(1);}
#define TRY2(a) if((a)<0) {perror(#a);exit(1);}
#define FREE(a) if(a) {free(a);a=NULL;}
#define sort_by(foo) \
static int by_##foo (const void*p1, const void*p2) { \
return strcmp ((*(const pdb_t*)p1)->foo, (*(const pdb_t*)p2)->foo); }
typedef struct db {
char title[26];
char first_name[26];
char last_name[26];
time_t date;
char publ[100];
struct db *next;
}
db_t,*pdb_t;
typedef int (sort)(const void*, const void*);
enum {CREATE,PRINT,TITLE,DATE,AUTH,READLINE,READ,SORT,DESTROY};
static pdb_t dao (int cmd, FILE *f, pdb_t db, sort sortby);
static char *time2str (time_t *time);
static time_t str2time (char *date);
sort_by(last_name);
sort_by(title);
static int by_date(pdb_t *p1, pdb_t *p2);
int main (int argc, char **argv) {
char buf[100];
const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL};
db_t db;
db.next=NULL;
pdb_t dblist;
int i;
FILE *f;
TRY (f=fopen(DB,"a+"));
if (argc<2) {
usage: printf ("Usage: %s [commands]\n"
"-c Create new entry.\n"
"-p Print the latest entry.\n"
"-t Print all entries sorted by title.\n"
"-d Print all entries sorted by date.\n"
"-a Print all entries sorted by author.\n",argv[0]);
fclose (f);
return 0;
}
for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++);
switch (i) {
case CREATE:
printf("-c Create a new entry.\n");
printf("Title :");if((scanf(" %25[^\n]",db.title ))<0)break;
printf("Author Firstname:");if((scanf(" %25[^\n]",db.first_name))<0)break;
printf("Author Lastname :");if((scanf(" %25[^\n]",db.last_name ))<0)break;
printf("Date 10-12-2000 :");if((scanf(" %10[^\n]",buf ))<0)break;
printf("Publication :");if((scanf(" %99[^\n]",db.publ ))<0)break;
db.date=str2time (buf);
dao (CREATE,f,&db,NULL);
break;
case PRINT:
printf ("-p Print the latest entry.\n");
while (!feof(f)) dao (READLINE,f,&db,NULL);
dao (PRINT,f,&db,NULL);
break;
case TITLE:
printf ("-t Print all entries sorted by title.\n");
dblist = dao (READ,f,&db,NULL);
dblist = dao (SORT,f,dblist,by_title);
dao (PRINT,f,dblist,NULL);
dao (DESTROY,f,dblist,NULL);
break;
case DATE:
printf ("-d Print all entries sorted by date.\n");
dblist = dao (READ,f,&db,NULL);
dblist = dao (SORT,f,dblist,(int (*)(const void *,const void *)) by_date);
dao (PRINT,f,dblist,NULL);
dao (DESTROY,f,dblist,NULL);
break;
case AUTH:
printf ("-a Print all entries sorted by author.\n");
dblist = dao (READ,f,&db,NULL);
dblist = dao (SORT,f,dblist,by_last_name);
dao (PRINT,f,dblist,NULL);
dao (DESTROY,f,dblist,NULL);
break;
default: {
printf ("Unknown command: %s.\n",strlen(argv[1])<10?argv[1]:"");
goto usage;
} }
fclose (f);
return 0;
}
static pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) {
pdb_t *pdb=NULL,rec=NULL,hd=NULL;
int i=0,ret;
char buf[100];
switch (cmd) {
case CREATE:
fprintf (f,"\"%s\",",in_db->title);
fprintf (f,"\"%s\",",in_db->first_name);
fprintf (f,"\"%s\",",in_db->last_name);
fprintf (f,"\"%s\",",time2str(&in_db->date));
fprintf (f,"\"%s\" \n",in_db->publ);
break;
case PRINT:
for (;in_db;i++) {
printf ("Title : %s\n", in_db->title);
printf ("Author : %s %s\n", in_db->first_name, in_db->last_name);
printf ("Date : %s\n", time2str(&in_db->date));
printf ("Publication : %s\n\n", in_db->publ);
if (!((i+1)%3)) {
printf ("Press Enter to continue.\n");
ret = scanf ("%*[^\n]");
if (ret<0) return rec;
else getchar();
}
in_db=in_db->next;
}
break;
case READLINE:
if((fscanf(f," \"%[^\"]\",",in_db->title ))<0)break;
if((fscanf(f," \"%[^\"]\",",in_db->first_name))<0)break;
if((fscanf(f," \"%[^\"]\",",in_db->last_name ))<0)break;
if((fscanf(f," \"%[^\"]\",",buf ))<0)break;
if((fscanf(f," \"%[^\"]\" ",in_db->publ ))<0)break;
in_db->date=str2time (buf);
break;
case READ:
while (!feof(f)) {
dao (READLINE,f,in_db,NULL);
TRY (rec=malloc(sizeof(db_t)));
*rec=*in_db;
rec->next=hd;
hd=rec;i++;
}
if (i<2) {
puts ("Empty database. Please create some entries.");
fclose (f);
exit (0);
}
break;
case SORT:
rec=in_db;
for (;in_db;i++) in_db=in_db->next;
TRY (pdb=malloc(i*sizeof(pdb_t)));
in_db=rec;
for (i=0;in_db;i++) {
pdb[i]=in_db;
in_db=in_db->next;
}
qsort (pdb,i,sizeof in_db,sortby);
pdb[i-1]->next=NULL;
for (i=i-1;i;i--) {
pdb[i-1]->next=pdb[i];
}
rec=pdb[0];
FREE (pdb);
pdb=NULL;
break;
case DESTROY: {
while ((rec=in_db)) {
in_db=in_db->next;
FREE (rec);
} } }
return rec;
}
static char *time2str (time_t *time) {
static char buf[255];
struct tm *ptm;
ptm=localtime (time);
strftime(buf, 255, "%m-%d-%Y", ptm);
return buf;
}
static time_t str2time (char *date) {
struct tm tm;
memset (&tm, 0, sizeof(struct tm));
strptime(date, "%m-%d-%Y", &tm);
return mktime(&tm);
}
static int by_date (pdb_t *p1, pdb_t *p2) {
if ((*p1)->date < (*p2)->date) {
return -1;
}
else return ((*p1)->date > (*p2)->date);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.