Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Ensure the translated C code behaves exactly like the original Java snippet.
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Bins { public static <T extends Comparable<? super T>> int[] bins( List<? extends T> limits, Iterable<? extends T> data) { int[] result = new int[limits.size() + 1]; for (T n : data) { int i = Collections.binarySearch(limits, n); if (i >= 0) { i = i+1; } else { i = ~i; } result[i]++; } return result; } public static void printBins(List<?> limits, int[] bins) { int n = limits.size(); if (n == 0) { return; } assert n+1 == bins.length; System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]); for (int i = 1; i < n; i++) { System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]); } System.out.printf(">= %3s  : %2d\n", limits.get(n-1), bins[n]); } public static void main(String[] args) { List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83); List<Integer> data = Arrays.asList( 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55); System.out.println("Example 1:"); printBins(limits, bins(limits, data)); limits = Arrays.asList(14, 18, 249, 312, 389, 392, 513, 591, 634, 720); data = Arrays.asList( 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749); System.out.println(); System.out.println("Example 2:"); printBins(limits, bins(limits, data)); } }
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
Rewrite this program in C while keeping its functionality equivalent to the Java version.
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Bins { public static <T extends Comparable<? super T>> int[] bins( List<? extends T> limits, Iterable<? extends T> data) { int[] result = new int[limits.size() + 1]; for (T n : data) { int i = Collections.binarySearch(limits, n); if (i >= 0) { i = i+1; } else { i = ~i; } result[i]++; } return result; } public static void printBins(List<?> limits, int[] bins) { int n = limits.size(); if (n == 0) { return; } assert n+1 == bins.length; System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]); for (int i = 1; i < n; i++) { System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]); } System.out.printf(">= %3s  : %2d\n", limits.get(n-1), bins[n]); } public static void main(String[] args) { List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83); List<Integer> data = Arrays.asList( 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55); System.out.println("Example 1:"); printBins(limits, bins(limits, data)); limits = Arrays.asList(14, 18, 249, 312, 389, 392, 513, 591, 634, 720); data = Arrays.asList( 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749); System.out.println(); System.out.println("Example 2:"); printBins(limits, bins(limits, data)); } }
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
Write the same algorithm in C as shown in this Java implementation.
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class FractalTree extends JFrame { public FractalTree() { super("Fractal Tree"); setBounds(100, 100, 800, 600); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void drawTree(Graphics g, int x1, int y1, double angle, int depth) { if (depth == 0) return; int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0); int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0); g.drawLine(x1, y1, x2, y2); drawTree(g, x2, y2, angle - 20, depth - 1); drawTree(g, x2, y2, angle + 20, depth - 1); } @Override public void paint(Graphics g) { g.setColor(Color.BLACK); drawTree(g, 400, 500, -90, 9); } public static void main(String[] args) { new FractalTree().setVisible(true); } }
#include <SDL/SDL.h> #ifdef WITH_CAIRO #include <cairo.h> #else #include <SDL/sge.h> #endif #include <cairo.h> #include <stdlib.h> #include <time.h> #include <math.h> #ifdef WITH_CAIRO #define PI 3.1415926535 #endif #define SIZE 800 #define SCALE 5 #define BRANCHES 14 #define ROTATION_SCALE 0.75 #define INITIAL_LENGTH 50 double rand_fl(){ return (double)rand() / (double)RAND_MAX; } void draw_tree(SDL_Surface * surface, double offsetx, double offsety, double directionx, double directiony, double size, double rotation, int depth) { #ifdef WITH_CAIRO cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels, CAIRO_FORMAT_RGB24, surface->w, surface->h, surface->pitch ); cairo_t *ct = cairo_create(surf); cairo_set_line_width(ct, 1); cairo_set_source_rgba(ct, 0,0,0,1); cairo_move_to(ct, (int)offsetx, (int)offsety); cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size)); cairo_stroke(ct); #else sge_AALine(surface, (int)offsetx, (int)offsety, (int)(offsetx + directionx * size), (int)(offsety + directiony * size), SDL_MapRGB(surface->format, 0, 0, 0)); #endif if (depth > 0){ draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(rotation) + directiony * sin(rotation), directionx * -sin(rotation) + directiony * cos(rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(-rotation) + directiony * sin(-rotation), directionx * -sin(-rotation) + directiony * cos(-rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); } } void render(SDL_Surface * surface){ SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255)); draw_tree(surface, surface->w / 2.0, surface->h - 10.0, 0.0, -1.0, INITIAL_LENGTH, PI / 8, BRANCHES); SDL_UpdateRect(surface, 0, 0, 0, 0); } int main(){ SDL_Surface * screen; SDL_Event evt; SDL_Init(SDL_INIT_VIDEO); srand((unsigned)time(NULL)); screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE); render(screen); while(1){ if (SDL_PollEvent(&evt)){ if(evt.type == SDL_QUIT) break; } SDL_Delay(1); } SDL_Quit(); return 0; }
Preserve the algorithm and functionality while converting the code from Java to C.
import java.awt.*; import static java.awt.Color.*; import javax.swing.*; public class ColourPinstripeDisplay extends JPanel { final static Color[] palette = {black, red, green, blue, magenta,cyan, yellow, white}; final int bands = 4; public ColourPinstripeDisplay() { setPreferredSize(new Dimension(900, 600)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); int h = getHeight(); for (int b = 1; b <= bands; b++) { for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) { g.setColor(palette[colIndex % palette.length]); g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands)); } } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("ColourPinstripeDisplay"); f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include<graphics.h> #include<conio.h> #define sections 4 int main() { int d=DETECT,m,maxX,maxY,x,y,colour=0,increment=1; initgraph(&d,&m,"c:/turboc3/bgi"); maxX = getmaxx(); maxY = getmaxy(); for(y=0;y<maxY;y+=maxY/sections) { for(x=0;x<maxX;x+=increment) { setfillstyle(SOLID_FILL,(colour++)%16); bar(x,y,x+increment,y+maxY/sections); } increment++; colour = 0; } getch(); closegraph(); return 0; }
Convert the following code from Java to C, ensuring the logic remains intact.
class Doom { public static void main(String[] args) { final Date[] dates = { new Date(1800,1,6), new Date(1875,3,29), new Date(1915,12,7), new Date(1970,12,23), new Date(2043,5,14), new Date(2077,2,12), new Date(2101,4,2) }; for (Date d : dates) System.out.println( String.format("%s: %s", d.format(), d.weekday())); } } class Date { private int year, month, day; private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5}; private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5}; public static final String[] weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; public Date(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public boolean isLeapYear() { return year%4 == 0 && (year%100 != 0 || year%400 == 0); } public String format() { return String.format("%02d/%02d/%04d", month, day, year); } public String weekday() { final int c = year/100; final int r = year%100; final int s = r/12; final int t = r%12; final int c_anchor = (5 * (c%4) + 2) % 7; final int doom = (s + t + t/4 + c_anchor) % 7; final int anchor = isLeapYear() ? leapdoom[month-1] : normdoom[month-1]; return weekdays[(doom + day - anchor + 7) % 7]; } }
#include <stdio.h> #include <stdint.h> #include <stdbool.h> typedef struct { uint16_t year; uint8_t month; uint8_t day; } Date; bool leap(uint16_t year) { return year%4==0 && (year%100!=0 || year%400==0); } const char *weekday(Date date) { static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned c = date.year/100, r = date.year%100; unsigned s = r/12, t = r%12; unsigned c_anchor = (5 * (c%4) + 2) % 7; unsigned doom = (s + t + (t/4) + c_anchor) % 7; unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const char *past = "was", *future = "will be"; const char *months[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; int i; for (i=0; i < sizeof(dates)/sizeof(Date); i++) { printf("%s %d, %d %s on a %s.\n", months[dates[i].month], dates[i].day, dates[i].year, dates[i].year > 2021 ? future : past, weekday(dates[i])); } return 0; }
Generate a C translation of this Java snippet without changing its computational steps.
class Doom { public static void main(String[] args) { final Date[] dates = { new Date(1800,1,6), new Date(1875,3,29), new Date(1915,12,7), new Date(1970,12,23), new Date(2043,5,14), new Date(2077,2,12), new Date(2101,4,2) }; for (Date d : dates) System.out.println( String.format("%s: %s", d.format(), d.weekday())); } } class Date { private int year, month, day; private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5}; private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5}; public static final String[] weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; public Date(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public boolean isLeapYear() { return year%4 == 0 && (year%100 != 0 || year%400 == 0); } public String format() { return String.format("%02d/%02d/%04d", month, day, year); } public String weekday() { final int c = year/100; final int r = year%100; final int s = r/12; final int t = r%12; final int c_anchor = (5 * (c%4) + 2) % 7; final int doom = (s + t + t/4 + c_anchor) % 7; final int anchor = isLeapYear() ? leapdoom[month-1] : normdoom[month-1]; return weekdays[(doom + day - anchor + 7) % 7]; } }
#include <stdio.h> #include <stdint.h> #include <stdbool.h> typedef struct { uint16_t year; uint8_t month; uint8_t day; } Date; bool leap(uint16_t year) { return year%4==0 && (year%100!=0 || year%400==0); } const char *weekday(Date date) { static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned c = date.year/100, r = date.year%100; unsigned s = r/12, t = r%12; unsigned c_anchor = (5 * (c%4) + 2) % 7; unsigned doom = (s + t + (t/4) + c_anchor) % 7; unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const char *past = "was", *future = "will be"; const char *months[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; int i; for (i=0; i < sizeof(dates)/sizeof(Date); i++) { printf("%s %d, %d %s on a %s.\n", months[dates[i].month], dates[i].day, dates[i].year, dates[i].year > 2021 ? future : past, weekday(dates[i])); } return 0; }
Generate a C translation of this Java snippet without changing its computational steps.
class Doom { public static void main(String[] args) { final Date[] dates = { new Date(1800,1,6), new Date(1875,3,29), new Date(1915,12,7), new Date(1970,12,23), new Date(2043,5,14), new Date(2077,2,12), new Date(2101,4,2) }; for (Date d : dates) System.out.println( String.format("%s: %s", d.format(), d.weekday())); } } class Date { private int year, month, day; private static final int[] leapdoom = {4,1,7,4,2,6,4,1,5,3,7,5}; private static final int[] normdoom = {3,7,7,4,2,6,4,1,5,3,7,5}; public static final String[] weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; public Date(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public boolean isLeapYear() { return year%4 == 0 && (year%100 != 0 || year%400 == 0); } public String format() { return String.format("%02d/%02d/%04d", month, day, year); } public String weekday() { final int c = year/100; final int r = year%100; final int s = r/12; final int t = r%12; final int c_anchor = (5 * (c%4) + 2) % 7; final int doom = (s + t + t/4 + c_anchor) % 7; final int anchor = isLeapYear() ? leapdoom[month-1] : normdoom[month-1]; return weekdays[(doom + day - anchor + 7) % 7]; } }
#include <stdio.h> #include <stdint.h> #include <stdbool.h> typedef struct { uint16_t year; uint8_t month; uint8_t day; } Date; bool leap(uint16_t year) { return year%4==0 && (year%100!=0 || year%400==0); } const char *weekday(Date date) { static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned c = date.year/100, r = date.year%100; unsigned s = r/12, t = r%12; unsigned c_anchor = (5 * (c%4) + 2) % 7; unsigned doom = (s + t + (t/4) + c_anchor) % 7; unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const char *past = "was", *future = "will be"; const char *months[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; int i; for (i=0; i < sizeof(dates)/sizeof(Date); i++) { printf("%s %d, %d %s on a %s.\n", months[dates[i].month], dates[i].day, dates[i].year, dates[i].year > 2021 ? future : past, weekday(dates[i])); } return 0; }
Please provide an equivalent version of this Java code in C.
import java.util.*; public class CocktailSort { public static void main(String[] args) { Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 }; System.out.println("before: " + Arrays.toString(array)); cocktailSort(array); System.out.println("after: " + Arrays.toString(array)); } public static void cocktailSort(Object[] array) { int begin = 0; int end = array.length; if (end == 0) return; for (--end; begin < end; ) { int new_begin = end; int new_end = begin; for (int i = begin; i < end; ++i) { Comparable c1 = (Comparable)array[i]; Comparable c2 = (Comparable)array[i + 1]; if (c1.compareTo(c2) > 0) { swap(array, i, i + 1); new_end = i; } } end = new_end; for (int i = end; i > begin; --i) { Comparable c1 = (Comparable)array[i - 1]; Comparable c2 = (Comparable)array[i]; if (c1.compareTo(c2) > 0) { swap(array, i, i - 1); new_begin = i; } } begin = new_begin; } } private static void swap(Object[] array, int i, int j) { Object tmp = array[i]; array[i] = array[j]; array[j] = tmp; } }
#include <stdio.h> #include <string.h> void swap(char* p1, char* p2, size_t size) { for (; size-- > 0; ++p1, ++p2) { char tmp = *p1; *p1 = *p2; *p2 = tmp; } } void cocktail_shaker_sort(void* base, size_t count, size_t size, int (*cmp)(const void*, const void*)) { char* begin = base; char* end = base + size * count; if (end == begin) return; for (end -= size; begin < end; ) { char* new_begin = end; char* new_end = begin; for (char* p = begin; p < end; p += size) { char* q = p + size; if (cmp(p, q) > 0) { swap(p, q, size); new_end = p; } } end = new_end; for (char* p = end; p > begin; p -= size) { char* q = p - size; if (cmp(q, p) > 0) { swap(p, q, size); new_begin = p; } } begin = new_begin; } } int string_compare(const void* p1, const void* p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } void print(const char** a, size_t len) { for (size_t i = 0; i < len; ++i) printf("%s ", a[i]); printf("\n"); } int main() { const char* a[] = { "one", "two", "three", "four", "five", "six", "seven", "eight" }; const size_t len = sizeof(a)/sizeof(a[0]); printf("before: "); print(a, len); cocktail_shaker_sort(a, len, sizeof(char*), string_compare); printf("after: "); print(a, len); return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.util.*; public class CocktailSort { public static void main(String[] args) { Integer[] array = new Integer[]{ 5, 1, -6, 12, 3, 13, 2, 4, 0, 15 }; System.out.println("before: " + Arrays.toString(array)); cocktailSort(array); System.out.println("after: " + Arrays.toString(array)); } public static void cocktailSort(Object[] array) { int begin = 0; int end = array.length; if (end == 0) return; for (--end; begin < end; ) { int new_begin = end; int new_end = begin; for (int i = begin; i < end; ++i) { Comparable c1 = (Comparable)array[i]; Comparable c2 = (Comparable)array[i + 1]; if (c1.compareTo(c2) > 0) { swap(array, i, i + 1); new_end = i; } } end = new_end; for (int i = end; i > begin; --i) { Comparable c1 = (Comparable)array[i - 1]; Comparable c2 = (Comparable)array[i]; if (c1.compareTo(c2) > 0) { swap(array, i, i - 1); new_begin = i; } } begin = new_begin; } } private static void swap(Object[] array, int i, int j) { Object tmp = array[i]; array[i] = array[j]; array[j] = tmp; } }
#include <stdio.h> #include <string.h> void swap(char* p1, char* p2, size_t size) { for (; size-- > 0; ++p1, ++p2) { char tmp = *p1; *p1 = *p2; *p2 = tmp; } } void cocktail_shaker_sort(void* base, size_t count, size_t size, int (*cmp)(const void*, const void*)) { char* begin = base; char* end = base + size * count; if (end == begin) return; for (end -= size; begin < end; ) { char* new_begin = end; char* new_end = begin; for (char* p = begin; p < end; p += size) { char* q = p + size; if (cmp(p, q) > 0) { swap(p, q, size); new_end = p; } } end = new_end; for (char* p = end; p > begin; p -= size) { char* q = p - size; if (cmp(q, p) > 0) { swap(p, q, size); new_begin = p; } } begin = new_begin; } } int string_compare(const void* p1, const void* p2) { const char* const* s1 = p1; const char* const* s2 = p2; return strcmp(*s1, *s2); } void print(const char** a, size_t len) { for (size_t i = 0; i < len; ++i) printf("%s ", a[i]); printf("\n"); } int main() { const char* a[] = { "one", "two", "three", "four", "five", "six", "seven", "eight" }; const size_t len = sizeof(a)/sizeof(a[0]); printf("before: "); print(a, len); cocktail_shaker_sort(a, len, sizeof(char*), string_compare); printf("after: "); print(a, len); return 0; }
Write the same code in C as shown below in Java.
import java.awt.*; import javax.swing.*; public class Pendulum extends JPanel implements Runnable { private double angle = Math.PI / 2; private int length; public Pendulum(int length) { this.length = length; setDoubleBuffered(true); } @Override public void paint(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.BLACK); int anchorX = getWidth() / 2, anchorY = getHeight() / 4; int ballX = anchorX + (int) (Math.sin(angle) * length); int ballY = anchorY + (int) (Math.cos(angle) * length); g.drawLine(anchorX, anchorY, ballX, ballY); g.fillOval(anchorX - 3, anchorY - 4, 7, 7); g.fillOval(ballX - 7, ballY - 7, 14, 14); } public void run() { double angleAccel, angleVelocity = 0, dt = 0.1; while (true) { angleAccel = -9.81 / length * Math.sin(angle); angleVelocity += angleAccel * dt; angle += angleVelocity * dt; repaint(); try { Thread.sleep(15); } catch (InterruptedException ex) {} } } @Override public Dimension getPreferredSize() { return new Dimension(2 * length + 50, length / 2 * 3); } public static void main(String[] args) { JFrame f = new JFrame("Pendulum"); Pendulum p = new Pendulum(200); f.add(p); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); new Thread(p).start(); } }
#include <stdlib.h> #include <math.h> #include <GL/glut.h> #include <GL/gl.h> #include <sys/time.h> #define length 5 #define g 9.8 double alpha, accl, omega = 0, E; struct timeval tv; double elappsed() { struct timeval now; gettimeofday(&now, 0); int ret = (now.tv_sec - tv.tv_sec) * 1000000 + now.tv_usec - tv.tv_usec; tv = now; return ret / 1.e6; } void resize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); } void render() { double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha); resize(640, 320); glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_LINES); glVertex2d(320, 0); glVertex2d(x, y); glEnd(); glFlush(); double us = elappsed(); alpha += (omega + us * accl / 2) * us; omega += accl * us; if (length * g * (1 - cos(alpha)) >= E) { alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g); omega = 0; } accl = -g / length * sin(alpha); } void init_gfx(int *c, char **v) { glutInit(c, v); glutInitDisplayMode(GLUT_RGB); glutInitWindowSize(640, 320); glutIdleFunc(render); glutCreateWindow("Pendulum"); } int main(int c, char **v) { alpha = 4 * atan2(1, 1) / 2.1; E = length * g * (1 - cos(alpha)); accl = -g / length * sin(alpha); omega = 0; gettimeofday(&tv, 0); init_gfx(&c, v); glutMainLoop(); return 0; }
Write the same code in C as shown below in Java.
public class Gray { public static long grayEncode(long n){ return n ^ (n >>> 1); } public static long grayDecode(long n) { long p = n; while ((n >>>= 1) != 0) p ^= n; return p; } public static void main(String[] args){ System.out.println("i\tBinary\tGray\tDecoded"); for(int i = -1; i < 32;i++){ System.out.print(i +"\t"); System.out.print(Integer.toBinaryString(i) + "\t"); System.out.print(Long.toBinaryString(grayEncode(i))+ "\t"); System.out.println(grayDecode(grayEncode(i))); } } }
int gray_encode(int n) { return n ^ (n >> 1); } int gray_decode(int n) { int p = n; while (n >>= 1) p ^= n; return p; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
public class Gray { public static long grayEncode(long n){ return n ^ (n >>> 1); } public static long grayDecode(long n) { long p = n; while ((n >>>= 1) != 0) p ^= n; return p; } public static void main(String[] args){ System.out.println("i\tBinary\tGray\tDecoded"); for(int i = -1; i < 32;i++){ System.out.print(i +"\t"); System.out.print(Integer.toBinaryString(i) + "\t"); System.out.print(Long.toBinaryString(grayEncode(i))+ "\t"); System.out.println(grayDecode(grayEncode(i))); } } }
int gray_encode(int n) { return n ^ (n >> 1); } int gray_decode(int n) { int p = n; while (n >>= 1) p ^= n; return p; }
Generate an equivalent C version of this Java code.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; public class CreateFile { public static void main(String[] args) throws IOException { String os = System.getProperty("os.name"); if (os.contains("Windows")) { Path path = Paths.get("tape.file"); Files.write(path, Collections.singletonList("Hello World!")); } else { Path path = Paths.get("/dev/tape"); Files.write(path, Collections.singletonList("Hello World!")); } } }
#include<stdio.h> int main() { FILE* fp = fopen("TAPE.FILE","w"); fprintf(fp,"This code should be able to write a file to magnetic tape.\n"); fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n"); fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n"); fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n"); fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n"); fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n"); fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n"); fprintf(fp,"EOF"); fclose(fp); return 0; }
Change the following Java code into C without altering its purpose.
public static void heapSort(int[] a){ int count = a.length; heapify(a, count); int end = count - 1; while(end > 0){ int tmp = a[end]; a[end] = a[0]; a[0] = tmp; siftDown(a, 0, end - 1); end--; } } public static void heapify(int[] a, int count){ int start = (count - 2) / 2; while(start >= 0){ siftDown(a, start, count - 1); start--; } } public static void siftDown(int[] a, int start, int end){ int root = start; while((root * 2 + 1) <= end){ int child = root * 2 + 1; if(child + 1 <= end && a[child] < a[child + 1]) child = child + 1; if(a[root] < a[child]){ int tmp = a[root]; a[root] = a[child]; a[child] = tmp; root = child; }else return; } }
#include <stdio.h> int max (int *a, int n, int i, int j, int k) { int m = i; if (j < n && a[j] > a[m]) { m = j; } if (k < n && a[k] > a[m]) { m = k; } return m; } void downheap (int *a, int n, int i) { while (1) { int j = max(a, n, i, 2 * i + 1, 2 * i + 2); if (j == i) { break; } int t = a[i]; a[i] = a[j]; a[j] = t; i = j; } } void heapsort (int *a, int n) { int i; for (i = (n - 2) / 2; i >= 0; i--) { downheap(a, n, i); } for (i = 0; i < n; i++) { int t = a[n - i - 1]; a[n - i - 1] = a[0]; a[0] = t; downheap(a, n - i - 1, 0); } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); heapsort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
Ensure the translated C code behaves exactly like the original Java snippet.
public enum Pip { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }
#include <stdio.h> #include <stdlib.h> #include <locale.h> int locale_ok = 0; wchar_t s_suits[] = L"♠♥♦♣"; const char *s_suits_ascii[] = { "S", "H", "D", "C" }; const char *s_nums[] = { "WHAT", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "OVERFLOW" }; typedef struct { int suit, number, _s; } card_t, *card; typedef struct { int n; card_t cards[52]; } deck_t, *deck; void show_card(card c) { if (locale_ok) printf(" %lc%s", s_suits[c->suit], s_nums[c->number]); else printf(" %s%s", s_suits_ascii[c->suit], s_nums[c->number]); } deck new_deck() { int i, j, k; deck d = malloc(sizeof(deck_t)); d->n = 52; for (i = k = 0; i < 4; i++) for (j = 1; j <= 13; j++, k++) { d->cards[k].suit = i; d->cards[k].number = j; } return d; } void show_deck(deck d) { int i; printf("%d cards:", d->n); for (i = 0; i < d->n; i++) show_card(d->cards + i); printf("\n"); } int cmp_card(const void *a, const void *b) { int x = ((card)a)->_s, y = ((card)b)->_s; return x < y ? -1 : x > y; } card deal_card(deck d) { if (!d->n) return 0; return d->cards + --d->n; } void shuffle_deck(deck d) { int i; for (i = 0; i < d->n; i++) d->cards[i]._s = rand(); qsort(d->cards, d->n, sizeof(card_t), cmp_card); } int main() { int i, j; deck d = new_deck(); locale_ok = (0 != setlocale(LC_CTYPE, "")); printf("New deck, "); show_deck(d); printf("\nShuffle and deal to three players:\n"); shuffle_deck(d); for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) show_card(deal_card(d)); printf("\n"); } printf("Left in deck "); show_deck(d); return 0; }
Rewrite the snippet below in C so it works the same as the original Java code.
Int[] literalArray = [1,2,3]; Int[] fixedLengthArray = new Int[10]; Int[] variableArray = new Int[]; assert literalArray.size == 3; Int n = literalArray[2]; fixedLengthArray[4] = 12345; fixedLengthArray += 6789; variableArray += 6789;
char foo() { char array[5] = {3,6,9,12,15}; return array[2]; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
public static boolean inCarpet(long x, long y) { while (x!=0 && y!=0) { if (x % 3 == 1 && y % 3 == 1) return false; x /= 3; y /= 3; } return true; } public static void carpet(final int n) { final double power = Math.pow(3,n); for(long i = 0; i < power; i++) { for(long j = 0; j < power; j++) { System.out.print(inCarpet(i, j) ? "*" : " "); } System.out.println(); } }
#include <stdio.h> int main() { int i, j, dim, d; int depth = 3; for (i = 0, dim = 1; i < depth; i++, dim *= 3); for (i = 0; i < dim; i++) { for (j = 0; j < dim; j++) { for (d = dim / 3; d; d /= 3) if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1) break; printf(d ? " " : "##"); } printf("\n"); } return 0; }
Write a version of this Java function in C with identical behavior.
public class BogoSort { public static void main(String[] args) { int[] arr={4,5,6,0,7,8,9,1,2,3}; BogoSort now=new BogoSort(); System.out.print("Unsorted: "); now.display1D(arr); now.bogo(arr); System.out.print("Sorted: "); now.display1D(arr); } void bogo(int[] arr) { int shuffle=1; for(;!isSorted(arr);shuffle++) shuffle(arr); System.out.println("This took "+shuffle+" shuffles."); } void shuffle(int[] arr) { int i=arr.length-1; while(i>0) swap(arr,i--,(int)(Math.random()*i)); } void swap(int[] arr,int i,int j) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } boolean isSorted(int[] arr) { for(int i=1;i<arr.length;i++) if(arr[i]<arr[i-1]) return false; return true; } void display1D(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> bool is_sorted(int *a, int n) { while ( --n >= 1 ) { if ( a[n] < a[n-1] ) return false; } return true; } void shuffle(int *a, int n) { int i, t, r; for(i=0; i < n; i++) { t = a[i]; r = rand() % n; a[i] = a[r]; a[r] = t; } } void bogosort(int *a, int n) { while ( !is_sorted(a, n) ) shuffle(a, n); } int main() { int numbers[] = { 1, 10, 9, 7, 3, 0 }; int i; bogosort(numbers, 6); for (i=0; i < 6; i++) printf("%d ", numbers[i]); printf("\n"); }
Write the same code in C as shown below in Java.
public class Euler { private static void euler (Callable f, double y0, int a, int b, int h) { int t = a; double y = y0; while (t < b) { System.out.println ("" + t + " " + y); t += h; y += h * f.compute (t, y); } System.out.println ("DONE"); } public static void main (String[] args) { Callable cooling = new Cooling (); int[] steps = {2, 5, 10}; for (int stepSize : steps) { System.out.println ("Step size: " + stepSize); euler (cooling, 100.0, 0, 100, stepSize); } } } interface Callable { public double compute (int time, double t); } class Cooling implements Callable { public double compute (int time, double t) { return -0.07 * (t - 20); } }
#include <stdio.h> #include <math.h> typedef double (*deriv_f)(double, double); #define FMT " %7.3f" void ivp_euler(deriv_f f, double y, int step, int end_t) { int t = 0; printf(" Step %2d: ", (int)step); do { if (t % 10 == 0) printf(FMT, y); y += step * f(t, y); } while ((t += step) <= end_t); printf("\n"); } void analytic() { double t; printf(" Time: "); for (t = 0; t <= 100; t += 10) printf(" %7g", t); printf("\nAnalytic: "); for (t = 0; t <= 100; t += 10) printf(FMT, 20 + 80 * exp(-0.07 * t)); printf("\n"); } double cooling(double t, double temp) { return -0.07 * (temp - 20); } int main() { analytic(); ivp_euler(cooling, 100, 2, 100); ivp_euler(cooling, 100, 5, 100); ivp_euler(cooling, 100, 10, 100); return 0; }
Generate an equivalent C version of this Java code.
public class SeqNonSquares { public static int nonsqr(int n) { return n + (int)Math.round(Math.sqrt(n)); } public static void main(String[] args) { for (int i = 1; i < 23; i++) System.out.print(nonsqr(i) + " "); System.out.println(); for (int i = 1; i < 1000000; i++) { double j = Math.sqrt(nonsqr(i)); assert j != Math.floor(j); } } }
#include <math.h> #include <stdio.h> #include <assert.h> int nonsqr(int n) { return n + (int)(0.5 + sqrt(n)); } int main() { int i; for (i = 1; i < 23; i++) printf("%d ", nonsqr(i)); printf("\n"); for (i = 1; i < 1000000; i++) { double j = sqrt(nonsqr(i)); assert(j != floor(j)); } return 0; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
public static String Substring(String str, int n, int m){ return str.substring(n, n+m); } public static String Substring(String str, int n){ return str.substring(n); } public static String Substring(String str){ return str.substring(0, str.length()-1); } public static String Substring(String str, char c, int m){ return str.substring(str.indexOf(c), str.indexOf(c)+m+1); } public static String Substring(String str, String sub, int m){ return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1); }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> void putm(char* string, size_t m) { while(*string && m--) putchar(*string++); } int main(void) { char string[] = "Programs for other encodings (such as 8-bit ASCII, or EUC-JP)." int n = 3; int m = 4; char knownCharacter = '('; char knownSubstring[] = "encodings"; putm(string+n-1, m ); putchar('\n'); puts(string+n+1); putchar('\n'); putm(string, strlen(string)-1); putchar('\n'); putm(strchr(string, knownCharacter), m ); putchar('\n'); putm(strstr(string, knownSubstring), m ); putchar('\n'); return EXIT_SUCCESS; }
Generate an equivalent C version of this Java code.
public static String Substring(String str, int n, int m){ return str.substring(n, n+m); } public static String Substring(String str, int n){ return str.substring(n); } public static String Substring(String str){ return str.substring(0, str.length()-1); } public static String Substring(String str, char c, int m){ return str.substring(str.indexOf(c), str.indexOf(c)+m+1); } public static String Substring(String str, String sub, int m){ return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1); }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> void putm(char* string, size_t m) { while(*string && m--) putchar(*string++); } int main(void) { char string[] = "Programs for other encodings (such as 8-bit ASCII, or EUC-JP)." int n = 3; int m = 4; char knownCharacter = '('; char knownSubstring[] = "encodings"; putm(string+n-1, m ); putchar('\n'); puts(string+n+1); putchar('\n'); putm(string, strlen(string)-1); putchar('\n'); putm(strchr(string, knownCharacter), m ); putchar('\n'); putm(strstr(string, knownSubstring), m ); putchar('\n'); return EXIT_SUCCESS; }
Convert this Java block to C, preserving its control flow and logic.
public class JortSort { public static void main(String[] args) { System.out.println(jortSort(new int[]{1, 2, 3})); } static boolean jortSort(int[] arr) { return true; } }
#include <stdio.h> #include <stdlib.h> int number_of_digits(int x){ int NumberOfDigits; for(NumberOfDigits=0;x!=0;NumberOfDigits++){ x=x/10; } return NumberOfDigits; } int* convert_array(char array[], int NumberOfElements) { int *convertedArray=malloc(NumberOfElements*sizeof(int)); int originalElement, convertedElement; for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++) { convertedArray[convertedElement]=atoi(&array[originalElement]); originalElement+=number_of_digits(convertedArray[convertedElement])+1; } return convertedArray; } int isSorted(int array[], int numberOfElements){ int sorted=1; for(int counter=0;counter<numberOfElements;counter++){ if(counter!=0 && array[counter-1]>array[counter]) sorted--; } return sorted; } int main(int argc, char* argv[]) { int* convertedArray; convertedArray=convert_array(*(argv+1), argc-1); if(isSorted(convertedArray, argc-1)==1) printf("Did you forgot to turn on your brain?! This array is already sorted!\n"); else if(argc-1<=10) printf("Am I really supposed to sort this? Sort it by yourself!\n"); else printf("Am I really supposed to sort this? Bhahahaha!\n"); free(convertedArray); return 0; }
Convert this Java block to C, preserving its control flow and logic.
import java.util.GregorianCalendar; import java.text.MessageFormat; public class Leapyear{ public static void main(String[] argv){ int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100}; GregorianCalendar cal = new GregorianCalendar(); for(int year : yrs){ System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.", year, cal.isLeapYear(year), isLeapYear(year))); } } public static boolean isLeapYear(int year){ return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0); } }
#include <stdio.h> int is_leap_year(unsigned year) { return !(year & (year % 100 ? 3 : 15)); } int main(void) { const unsigned test_case[] = { 1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100 }; const unsigned n = sizeof test_case / sizeof test_case[0]; for (unsigned i = 0; i != n; ++i) { unsigned year = test_case[i]; printf("%u is %sa leap year.\n", year, is_leap_year(year) ? "" : "not "); } return 0; }
Port the provided Java code into C while preserving the original functionality.
import java.math.BigInteger; public class CombinationsAndPermutations { public static void main(String[] args) { System.out.println(Double.MAX_VALUE); System.out.println("A sample of permutations from 1 to 12 with exact Integer arithmetic:"); for ( int n = 1 ; n <= 12 ; n++ ) { int k = n / 2; System.out.printf("%d P %d = %s%n", n, k, permutation(n, k)); } System.out.println(); System.out.println("A sample of combinations from 10 to 60 with exact Integer arithmetic:"); for ( int n = 10 ; n <= 60 ; n += 5 ) { int k = n / 2; System.out.printf("%d C %d = %s%n", n, k, combination(n, k)); } System.out.println(); System.out.println("A sample of permutations from 5 to 15000 displayed in floating point arithmetic:"); System.out.printf("%d P %d = %s%n", 5, 2, display(permutation(5, 2), 50)); for ( int n = 1000 ; n <= 15000 ; n += 1000 ) { int k = n / 2; System.out.printf("%d P %d = %s%n", n, k, display(permutation(n, k), 50)); } System.out.println(); System.out.println("A sample of combinations from 100 to 1000 displayed in floating point arithmetic:"); for ( int n = 100 ; n <= 1000 ; n += 100 ) { int k = n / 2; System.out.printf("%d C %d = %s%n", n, k, display(combination(n, k), 50)); } } private static String display(BigInteger val, int precision) { String s = val.toString(); precision = Math.min(precision, s.length()); StringBuilder sb = new StringBuilder(); sb.append(s.substring(0, 1)); sb.append("."); sb.append(s.substring(1, precision)); sb.append(" * 10^"); sb.append(s.length()-1); return sb.toString(); } public static BigInteger combination(int n, int k) { if ( n-k < k ) { k = n-k; } BigInteger result = permutation(n, k); while ( k > 0 ) { result = result.divide(BigInteger.valueOf(k)); k--; } return result; } public static BigInteger permutation(int n, int k) { BigInteger result = BigInteger.ONE; for ( int i = n ; i >= n-k+1 ; i-- ) { result = result.multiply(BigInteger.valueOf(i)); } return result; } }
#include <gmp.h> void perm(mpz_t out, int n, int k) { mpz_set_ui(out, 1); k = n - k; while (n > k) mpz_mul_ui(out, out, n--); } void comb(mpz_t out, int n, int k) { perm(out, n, k); while (k) mpz_divexact_ui(out, out, k--); } int main(void) { mpz_t x; mpz_init(x); perm(x, 1000, 969); gmp_printf("P(1000,969) = %Zd\n", x); comb(x, 1000, 969); gmp_printf("C(1000,969) = %Zd\n", x); return 0; }
Please provide an equivalent version of this Java code in C.
import java.util.List; import java.util.stream.*; public class LexicographicalNumbers { static List<Integer> lexOrder(int n) { int first = 1, last = n; if (n < 1) { first = n; last = 1; } return IntStream.rangeClosed(first, last) .mapToObj(Integer::toString) .sorted() .map(Integer::valueOf) .collect(Collectors.toList()); } public static void main(String[] args) { System.out.println("In lexicographical order:\n"); int[] ints = {0, 5, 13, 21, -22}; for (int n : ints) { System.out.printf("%3d: %s\n", n, lexOrder(n)); } } }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int compareStrings(const void *a, const void *b) { const char **aa = (const char **)a; const char **bb = (const char **)b; return strcmp(*aa, *bb); } void lexOrder(int n, int *ints) { char **strs; int i, first = 1, last = n, k = n, len; if (n < 1) { first = n; last = 1; k = 2 - n; } strs = malloc(k * sizeof(char *)); for (i = first; i <= last; ++i) { if (i >= 1) len = (int)log10(i) + 2; else if (i == 0) len = 2; else len = (int)log10(-i) + 3; strs[i-first] = malloc(len); sprintf(strs[i-first], "%d", i); } qsort(strs, k, sizeof(char *), compareStrings); for (i = 0; i < k; ++i) { ints[i] = atoi(strs[i]); free(strs[i]); } free(strs); } int main() { int i, j, k, n, *ints; int numbers[5] = {0, 5, 13, 21, -22}; printf("In lexicographical order:\n\n"); for (i = 0; i < 5; ++i) { k = n = numbers[i]; if (k < 1) k = 2 - k; ints = malloc(k * sizeof(int)); lexOrder(n, ints); printf("%3d: [", n); for (j = 0; j < k; ++j) { printf("%d ", ints[j]); } printf("\b]\n"); free(ints); } return 0; }
Produce a functionally identical C code for the snippet given in Java.
module NumberNames { void run() { @Inject Console console; Int[] tests = [0, 1, -1, 11, -17, 42, 99, 100, 101, -111, 1000, 1234, 10000, 100000, 123456789000, 0x123456789ABCDEF]; for (Int test : tests) { console.print($"{test} = {toEnglish(test)}"); } } static String[] digits = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]; static String[] teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; static String[] tens = ["zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; static String[] ten3rd = ["?", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion"]; static String toEnglish(Int n) { StringBuffer buf = new StringBuffer(); if (n < 0) { "negative ".appendTo(buf); n = -n; } format3digits(n, buf); return buf.toString(); } static void format3digits(Int n, StringBuffer buf, Int nested=0) { (Int left, Int right) = n /% 1000; if (left != 0) { format3digits(left, buf, nested+1); } if (right != 0 || (left == 0 && nested==0)) { if (right >= 100) { (left, right) = (right /% 100); digits[left].appendTo(buf); " hundred ".appendTo(buf); if (right != 0) { format2digits(right, buf); } } else { format2digits(right, buf); } if (nested > 0) { ten3rd[nested].appendTo(buf).add(' '); } } } static void format2digits(Int n, StringBuffer buf) { switch (n) { case 0..9: digits[n].appendTo(buf).add(' '); break; case 10..19: teens[n-10].appendTo(buf).add(' '); break; default: (Int left, Int right) = n /% 10; tens[left].appendTo(buf); if (right == 0) { buf.add(' '); } else { buf.add('-'); digits[right].appendTo(buf).add(' '); } break; } } }
#include <stdio.h> #include <string.h> const char *ones[] = { 0, "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char *tens[] = { 0, "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; const char *llions[] = { 0, "thousand", "million", "billion", "trillion", }; const int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3; int say_hundred(const char *s, int len, int depth, int has_lead) { int c[3], i; for (i = -3; i < 0; i++) { if (len + i >= 0) c[i + 3] = s[len + i] - '0'; else c[i + 3] = 0; } if (!(c[0] + c[1] + c[2])) return 0; if (c[0]) { printf("%s hundred", ones[c[0]]); has_lead = 1; } if (has_lead && (c[1] || c[2])) printf((!depth || c[0]) && (!c[0] || !c[1]) ? "and " : c[0] ? " " : ""); if (c[1] < 2) { if (c[1] || c[2]) printf("%s", ones[c[1] * 10 + c[2]]); } else { if (c[1]) { printf("%s", tens[c[1]]); if (c[2]) putchar('-'); } if (c[2]) printf("%s", ones[c[2]]); } return 1; } int say_maxillion(const char *s, int len, int depth, int has_lead) { int n = len / 3, r = len % 3; if (!r) { n--; r = 3; } const char *e = s + r; do { if (say_hundred(s, r, n, has_lead) && n) { has_lead = 1; printf(" %s", llions[n]); if (!depth) printf(", "); else printf(" "); } s = e; e += 3; } while (r = 3, n--); return 1; } void say_number(const char *s) { int len, i, got_sign = 0; while (*s == ' ') s++; if (*s < '0' || *s > '9') { if (*s == '-') got_sign = -1; else if (*s == '+') got_sign = 1; else goto nan; s++; } else got_sign = 1; while (*s == '0') { s++; if (*s == '\0') { printf("zero\n"); return; } } len = strlen(s); if (!len) goto nan; for (i = 0; i < len; i++) { if (s[i] < '0' || s[i] > '9') { printf("(not a number)"); return; } } if (got_sign == -1) printf("minus "); int n = len / maxillion; int r = len % maxillion; if (!r) { r = maxillion; n--; } const char *end = s + len - n * maxillion; int has_lead = 0; do { if ((has_lead = say_maxillion(s, r, n, has_lead))) { for (i = 0; i < n; i++) printf(" %s", llions[maxillion / 3]); if (n) printf(", "); } n--; r = maxillion; s = end; end += r; } while (n >= 0); printf("\n"); return; nan: printf("not a number\n"); return; } int main() { say_number("-42"); say_number("1984"); say_number("10000"); say_number("1024"); say_number("1001001001001"); say_number("123456789012345678901234567890123456789012345678900000001"); return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
package stringlensort; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; public class ReportStringLengths { public static void main(String[] args) { String[] list = {"abcd", "123456789", "abcdef", "1234567"}; String[] strings = args.length > 0 ? args : list; compareAndReportStringsLength(strings); } public static void compareAndReportStringsLength(String[] strings) { compareAndReportStringsLength(strings, System.out); } public static void compareAndReportStringsLength(String[] strings, PrintStream stream) { if (strings.length > 0) { strings = strings.clone(); final String QUOTE = "\""; Arrays.sort(strings, Comparator.comparing(String::length)); int min = strings[0].length(); int max = strings[strings.length - 1].length(); for (int i = strings.length - 1; i >= 0; i--) { int length = strings[i].length(); String predicate; if (length == max) { predicate = "is the longest string"; } else if (length == min) { predicate = "is the shortest string"; } else { predicate = "is neither the longest nor the shortest string"; } stream.println(QUOTE + strings[i] + QUOTE + " has length " + length + " and " + predicate); } } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> int cmp(const int* a, const int* b) { return *b - *a; } void compareAndReportStringsLength(const char* strings[], const int n) { if (n > 0) { char* has_length = "has length"; char* predicate_max = "and is the longest string"; char* predicate_min = "and is the shortest string"; char* predicate_ave = "and is neither the longest nor the shortest string"; int* si = malloc(2 * n * sizeof(int)); if (si != NULL) { for (int i = 0; i < n; i++) { si[2 * i] = strlen(strings[i]); si[2 * i + 1] = i; } qsort(si, n, 2 * sizeof(int), cmp); int max = si[0]; int min = si[2 * (n - 1)]; for (int i = 0; i < n; i++) { int length = si[2 * i]; char* string = strings[si[2 * i + 1]]; char* predicate; if (length == max) predicate = predicate_max; else if (length == min) predicate = predicate_min; else predicate = predicate_ave; printf("\"%s\" %s %d %s\n", string, has_length, length, predicate); } free(si); } else { fputs("unable allocate memory buffer", stderr); } } } int main(int argc, char* argv[]) { char* list[] = { "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(list, 4); return EXIT_SUCCESS; }
Change the following Java code into C without altering its purpose.
public static void shell(int[] a) { int increment = a.length / 2; while (increment > 0) { for (int i = increment; i < a.length; i++) { int j = i; int temp = a[i]; while (j >= increment && a[j - increment] > temp) { a[j] = a[j - increment]; j = j - increment; } a[j] = temp; } if (increment == 2) { increment = 1; } else { increment *= (5.0 / 11); } } }
#include <stdio.h> void shell_sort (int *a, int n) { int h, i, j, t; for (h = n; h /= 2;) { for (i = h; i < n; i++) { t = a[i]; for (j = i; j >= h && t < a[j - h]; j -= h) { a[j] = a[j - h]; } a[j] = t; } } } int main (int ac, char **av) { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); shell_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
Produce a functionally identical C code for the snippet given in Java.
import java.util.LinkedList; public class DoublyLinkedList { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.addFirst("Add First"); list.addLast("Add Last 1"); list.addLast("Add Last 2"); list.addLast("Add Last 1"); traverseList(list); list.removeFirstOccurrence("Add Last 1"); traverseList(list); } private static void traverseList(LinkedList<String> list) { System.out.println("Traverse List:"); for ( int i = 0 ; i < list.size() ; i++ ) { System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i)); } System.out.println(); } }
#include <stdio.h> #include <stdlib.h> struct List { struct MNode *head; struct MNode *tail; struct MNode *tail_pred; }; struct MNode { struct MNode *succ; struct MNode *pred; }; typedef struct MNode *NODE; typedef struct List *LIST; LIST newList(void); int isEmpty(LIST); NODE getTail(LIST); NODE getHead(LIST); NODE addTail(LIST, NODE); NODE addHead(LIST, NODE); NODE remHead(LIST); NODE remTail(LIST); NODE insertAfter(LIST, NODE, NODE); NODE removeNode(LIST, NODE); LIST newList(void) { LIST tl = malloc(sizeof(struct List)); if ( tl != NULL ) { tl->tail_pred = (NODE)&tl->head; tl->tail = NULL; tl->head = (NODE)&tl->tail; return tl; } return NULL; } int isEmpty(LIST l) { return (l->head->succ == 0); } NODE getHead(LIST l) { return l->head; } NODE getTail(LIST l) { return l->tail_pred; } NODE addTail(LIST l, NODE n) { n->succ = (NODE)&l->tail; n->pred = l->tail_pred; l->tail_pred->succ = n; l->tail_pred = n; return n; } NODE addHead(LIST l, NODE n) { n->succ = l->head; n->pred = (NODE)&l->head; l->head->pred = n; l->head = n; return n; } NODE remHead(LIST l) { NODE h; h = l->head; l->head = l->head->succ; l->head->pred = (NODE)&l->head; return h; } NODE remTail(LIST l) { NODE t; t = l->tail_pred; l->tail_pred = l->tail_pred->pred; l->tail_pred->succ = (NODE)&l->tail; return t; } NODE insertAfter(LIST l, NODE r, NODE n) { n->pred = r; n->succ = r->succ; n->succ->pred = n; r->succ = n; return n; } NODE removeNode(LIST l, NODE n) { n->pred->succ = n->succ; n->succ->pred = n->pred; return n; }
Translate this program into C but keep the logic exactly as in Java.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; public class LetterFreq { public static int[] countLetters(String filename) throws IOException{ int[] freqs = new int[26]; BufferedReader in = new BufferedReader(new FileReader(filename)); String line; while((line = in.readLine()) != null){ line = line.toUpperCase(); for(char ch:line.toCharArray()){ if(Character.isLetter(ch)){ freqs[ch - 'A']++; } } } in.close(); return freqs; } public static void main(String[] args) throws IOException{ System.out.println(Arrays.toString(countLetters("filename.txt"))); } }
int frequency[26]; int ch; FILE* txt_file = fopen ("a_text_file.txt", "rt"); for (ch = 0; ch < 26; ch++) frequency[ch] = 0; while (1) { ch = fgetc(txt_file); if (ch == EOF) break; if ('a' <= ch && ch <= 'z') frequency[ch-'a']++; else if ('A' <= ch && ch <= 'Z') frequency[ch-'A']++; }
Produce a language-to-language conversion: from Java to C, same semantics.
public class PermutationTest { private static final int[] data = new int[]{ 85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 }; private static int pick(int at, int remain, int accu, int treat) { if (remain == 0) return (accu > treat) ? 1 : 0; return pick(at - 1, remain - 1, accu + data[at - 1], treat) + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0); } public static void main(String[] args) { int treat = 0; double total = 1.0; for (int i = 0; i <= 8; ++i) { treat += data[i]; } for (int i = 19; i >= 11; --i) { total *= i; } for (int i = 9; i >= 1; --i) { total /= i; } int gt = pick(19, 9, 0, treat); int le = (int) (total - gt); System.out.printf("<= : %f%% %d\n", 100.0 * le / total, le); System.out.printf(" > : %f%% %d\n", 100.0 * gt / total, gt); } }
#include <stdio.h> int data[] = { 85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 }; int pick(int at, int remain, int accu, int treat) { if (!remain) return (accu > treat) ? 1 : 0; return pick(at - 1, remain - 1, accu + data[at - 1], treat) + ( at > remain ? pick(at - 1, remain, accu, treat) : 0 ); } int main() { int treat = 0, i; int le, gt; double total = 1; for (i = 0; i < 9; i++) treat += data[i]; for (i = 19; i > 10; i--) total *= i; for (i = 9; i > 0; i--) total /= i; gt = pick(19, 9, 0, treat); le = total - gt; printf("<= : %f%% %d\n > : %f%% %d\n", 100 * le / total, le, 100 * gt / total, gt); return 0; }
Please provide an equivalent version of this Java code in C.
public class MöbiusFunction { public static void main(String[] args) { System.out.printf("First 199 terms of the möbius function are as follows:%n "); for ( int n = 1 ; n < 200 ; n++ ) { System.out.printf("%2d ", möbiusFunction(n)); if ( (n+1) % 20 == 0 ) { System.out.printf("%n"); } } } private static int MU_MAX = 1_000_000; private static int[] MU = null; private static int möbiusFunction(int n) { if ( MU != null ) { return MU[n]; } MU = new int[MU_MAX+1]; int sqrt = (int) Math.sqrt(MU_MAX); for ( int i = 0 ; i < MU_MAX ; i++ ) { MU[i] = 1; } for ( int i = 2 ; i <= sqrt ; i++ ) { if ( MU[i] == 1 ) { for ( int j = i ; j <= MU_MAX ; j += i ) { MU[j] *= -i; } for ( int j = i*i ; j <= MU_MAX ; j += i*i ) { MU[j] = 0; } } } for ( int i = 2 ; i <= MU_MAX ; i++ ) { if ( MU[i] == i ) { MU[i] = 1; } else if ( MU[i] == -i ) { MU[i] = -1; } else if ( MU[i] < 0 ) { MU[i] = 1; } else if ( MU[i] > 0 ) { MU[i] = -1; } } return MU[n]; } }
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { const int MU_MAX = 1000000; int i, j; int *mu; int sqroot; sqroot = (int)sqrt(MU_MAX); mu = malloc((MU_MAX + 1) * sizeof(int)); for (i = 0; i < MU_MAX;i++) { mu[i] = 1; } for (i = 2; i <= sqroot; i++) { if (mu[i] == 1) { for (j = i; j <= MU_MAX; j += i) { mu[j] *= -i; } for (j = i * i; j <= MU_MAX; j += i * i) { mu[j] = 0; } } } for (i = 2; i <= MU_MAX; i++) { if (mu[i] == i) { mu[i] = 1; } else if (mu[i] == -i) { mu[i] = -1; } else if (mu[i] < 0) { mu[i] = 1; } else if (mu[i] > 0) { mu[i] = -1; } } printf("First 199 terms of the möbius function are as follows:\n "); for (i = 1; i < 200; i++) { printf("%2d ", mu[i]); if ((i + 1) % 20 == 0) { printf("\n"); } } free(mu); return 0; }
Generate an equivalent C version of this Java code.
String s = "12345"; IntLiteral lit1 = new IntLiteral(s); IntLiteral lit2 = 6789; ++lit1; ++lit2;
#include <stdio.h> #include <string.h> #include <stdlib.h> char * incr(char *s) { int i, begin, tail, len; int neg = (*s == '-'); char tgt = neg ? '0' : '9'; if (!strcmp(s, "-1")) { s[0] = '0', s[1] = '\0'; return s; } len = strlen(s); begin = (*s == '-' || *s == '+') ? 1 : 0; for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--); if (tail < begin && !neg) { if (!begin) s = realloc(s, len + 2); s[0] = '1'; for (i = 1; i <= len - begin; i++) s[i] = '0'; s[len + 1] = '\0'; } else if (tail == begin && neg && s[1] == '1') { for (i = 1; i < len - begin; i++) s[i] = '9'; s[len - 1] = '\0'; } else { for (i = len - 1; i > tail; i--) s[i] = neg ? '9' : '0'; s[tail] += neg ? -1 : 1; } return s; } void string_test(const char *s) { char *ret = malloc(strlen(s)); strcpy(ret, s); printf("text: %s\n", ret); printf(" ->: %s\n", ret = incr(ret)); free(ret); } int main() { string_test("+0"); string_test("-1"); string_test("-41"); string_test("+41"); string_test("999"); string_test("+999"); string_test("109999999999999999999999999999999999999999"); string_test("-100000000000000000000000000000000000000000000"); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
class StripChars { public static String stripChars(String inString, String toStrip) { return inString.replaceAll("[" + toStrip + "]", ""); } public static void main(String[] args) { String sentence = "She was a soul stripper. She took my heart!"; String chars = "aei"; System.out.println("sentence: " + sentence); System.out.println("to strip: " + chars); System.out.println("stripped: " + stripChars(sentence, chars)); } }
#include <string.h> #include <stdio.h> #include <stdlib.h> char *strip_chars(const char *string, const char *chars) { char * newstr = malloc(strlen(string) + 1); int counter = 0; for ( ; *string; string++) { if (!strchr(chars, *string)) { newstr[ counter ] = *string; ++ counter; } } newstr[counter] = 0; return newstr; } int main(void) { char *new = strip_chars("She was a soul stripper. She took my heart!", "aei"); printf("%s\n", new); free(new); return 0; }
Write the same code in C as shown below in Java.
import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class PermutationSort { public static void main(String[] args) { int[] a={3,2,1,8,9,4,6}; System.out.println("Unsorted: " + Arrays.toString(a)); a=pSort(a); System.out.println("Sorted: " + Arrays.toString(a)); } public static int[] pSort(int[] a) { List<int[]> list=new ArrayList<int[]>(); permute(a,a.length,list); for(int[] x : list) if(isSorted(x)) return x; return a; } private static void permute(int[] a, int n, List<int[]> list) { if (n == 1) { int[] b=new int[a.length]; System.arraycopy(a, 0, b, 0, a.length); list.add(b); return; } for (int i = 0; i < n; i++) { swap(a, i, n-1); permute(a, n-1, list); swap(a, i, n-1); } } private static boolean isSorted(int[] a) { for(int i=1;i<a.length;i++) if(a[i-1]>a[i]) return false; return true; } private static void swap(int[] arr,int i, int j) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int(*cmp_func)(const void*, const void*); void perm_sort(void *a, int n, size_t msize, cmp_func _cmp) { char *p, *q, *tmp = malloc(msize); # define A(i) ((char *)a + msize * (i)) # define swap(a, b) {\ memcpy(tmp, a, msize);\ memcpy(a, b, msize);\ memcpy(b, tmp, msize); } while (1) { for (p = A(n - 1); (void*)p > a; p = q) if (_cmp(q = p - msize, p) > 0) break; if ((void*)p <= a) break; for (p = A(n - 1); p > q; p-= msize) if (_cmp(q, p) > 0) break; swap(p, q); for (q += msize, p = A(n - 1); q < p; q += msize, p -= msize) swap(p, q); } free(tmp); } int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } int main() { int i; const char *strs[] = { "spqr", "abc", "giant squid", "stuff", "def" }; perm_sort(strs, 5, sizeof(*strs), scmp); for (i = 0; i < 5; i++) printf("%s\n", strs[i]); return 0; }
Write a version of this Java function in C with identical behavior.
public static double avg(double... arr) { double sum = 0.0; for (double x : arr) { sum += x; } return sum / arr.length; }
#include <stdio.h> double mean(double *v, int len) { double sum = 0; int i; for (i = 0; i < len; i++) sum += v[i]; return sum / len; } int main(void) { double v[] = {1, 2, 2.718, 3, 3.142}; int i, len; for (len = 5; len >= 0; len--) { printf("mean["); for (i = 0; i < len; i++) printf(i ? ", %g" : "%g", v[i]); printf("] = %g\n", mean(v, len)); } return 0; }
Write the same algorithm in C as shown in this Java implementation.
import java.util.*; public class Abbreviations { public static void main(String[] args) { CommandList commands = new CommandList(commandTable); String input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; System.out.println(" input: " + input); System.out.println("output: " + test(commands, input)); } private static String test(CommandList commands, String input) { StringBuilder output = new StringBuilder(); Scanner scanner = new Scanner(input); while (scanner.hasNext()) { String word = scanner.next(); if (output.length() > 0) output.append(' '); Command cmd = commands.findCommand(word); if (cmd != null) output.append(cmd.cmd); else output.append("*error*"); } return output.toString(); } private static String commandTable = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; private static class Command { private Command(String cmd, int minLength) { this.cmd = cmd; this.minLength = minLength; } private boolean match(String str) { int olen = str.length(); return olen >= minLength && olen <= cmd.length() && cmd.regionMatches(true, 0, str, 0, olen); } private String cmd; private int minLength; } private static Integer parseInteger(String word) { try { return Integer.valueOf(word); } catch (NumberFormatException ex) { return null; } } private static class CommandList { private CommandList(String table) { Scanner scanner = new Scanner(table); List<String> words = new ArrayList<>(); while (scanner.hasNext()) { String word = scanner.next(); words.add(word.toUpperCase()); } for (int i = 0, n = words.size(); i < n; ++i) { String word = words.get(i); int len = word.length(); if (i + 1 < n) { Integer number = parseInteger(words.get(i + 1)); if (number != null) { len = number.intValue(); ++i; } } commands.add(new Command(word, len)); } } private Command findCommand(String word) { for (Command command : commands) { if (command.match(word)) return command; } return null; } private List<Command> commands = new ArrayList<>(); } }
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = word_len; new_cmd->cmd = uppercase(word, word_len); if (i + 1 < count) { char* eptr = 0; unsigned long min_len = strtoul(words[i + 1], &eptr, 10); if (min_len > 0 && *eptr == 0) { free(words[i + 1]); new_cmd->min_len = min_len; ++i; } } new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Write a version of this Java function in C with identical behavior.
import java.util.*; public class Abbreviations { public static void main(String[] args) { CommandList commands = new CommandList(commandTable); String input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; System.out.println(" input: " + input); System.out.println("output: " + test(commands, input)); } private static String test(CommandList commands, String input) { StringBuilder output = new StringBuilder(); Scanner scanner = new Scanner(input); while (scanner.hasNext()) { String word = scanner.next(); if (output.length() > 0) output.append(' '); Command cmd = commands.findCommand(word); if (cmd != null) output.append(cmd.cmd); else output.append("*error*"); } return output.toString(); } private static String commandTable = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; private static class Command { private Command(String cmd, int minLength) { this.cmd = cmd; this.minLength = minLength; } private boolean match(String str) { int olen = str.length(); return olen >= minLength && olen <= cmd.length() && cmd.regionMatches(true, 0, str, 0, olen); } private String cmd; private int minLength; } private static Integer parseInteger(String word) { try { return Integer.valueOf(word); } catch (NumberFormatException ex) { return null; } } private static class CommandList { private CommandList(String table) { Scanner scanner = new Scanner(table); List<String> words = new ArrayList<>(); while (scanner.hasNext()) { String word = scanner.next(); words.add(word.toUpperCase()); } for (int i = 0, n = words.size(); i < n; ++i) { String word = words.get(i); int len = word.length(); if (i + 1 < n) { Integer number = parseInteger(words.get(i + 1)); if (number != null) { len = number.intValue(); ++i; } } commands.add(new Command(word, len)); } } private Command findCommand(String word) { for (Command command : commands) { if (command.match(word)) return command; } return null; } private List<Command> commands = new ArrayList<>(); } }
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = word_len; new_cmd->cmd = uppercase(word, word_len); if (i + 1 < count) { char* eptr = 0; unsigned long min_len = strtoul(words[i + 1], &eptr, 10); if (min_len > 0 && *eptr == 0) { free(words[i + 1]); new_cmd->min_len = min_len; ++i; } } new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Write the same algorithm in C as shown in this Java implementation.
import java.lang.Math; import java.util.Map; import java.util.HashMap; public class REntropy { @SuppressWarnings("boxing") public static double getShannonEntropy(String s) { int n = 0; Map<Character, Integer> occ = new HashMap<>(); for (int c_ = 0; c_ < s.length(); ++c_) { char cx = s.charAt(c_); if (occ.containsKey(cx)) { occ.put(cx, occ.get(cx) + 1); } else { occ.put(cx, 1); } ++n; } double e = 0.0; for (Map.Entry<Character, Integer> entry : occ.entrySet()) { char cx = entry.getKey(); double p = (double) entry.getValue() / n; e += p * log2(p); } return -e; } private static double log2(double a) { return Math.log(a) / Math.log(2); } public static void main(String[] args) { String[] sstr = { "1223334444", "1223334444555555555", "122333", "1227774444", "aaBBcccDDDD", "1234567890abcdefghijklmnopqrstuvwxyz", "Rosetta Code", }; for (String ss : sstr) { double entropy = REntropy.getShannonEntropy(ss); System.out.printf("Shannon entropy of %40s: %.12f%n", "\"" + ss + "\"", entropy); } return; } }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 100 int makehist(unsigned char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ unsigned char S[MAXLEN]; int len,*hist,histlen; double H; scanf("%[^\n]",S); len=strlen(S); hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
Translate the given Java code snippet into C without altering its behavior.
import java.util.*; public class TokenizeStringWithEscaping { public static void main(String[] args) { String sample = "one^|uno||three^^^^|four^^^|^cuatro|"; char separator = '|'; char escape = '^'; System.out.println(sample); try { System.out.println(tokenizeString(sample, separator, escape)); } catch (Exception e) { System.out.println(e); } } public static List<String> tokenizeString(String s, char sep, char escape) throws Exception { List<String> tokens = new ArrayList<>(); StringBuilder sb = new StringBuilder(); boolean inEscape = false; for (char c : s.toCharArray()) { if (inEscape) { inEscape = false; } else if (c == escape) { inEscape = true; continue; } else if (c == sep) { tokens.add(sb.toString()); sb.setLength(0); continue; } sb.append(c); } if (inEscape) throw new Exception("Invalid terminal escape"); tokens.add(sb.toString()); return tokens; } }
#include <stdlib.h> #include <stdio.h> #define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|" #define SEP '|' #define ESC '^' typedef char* Str; unsigned int ElQ( const char *s, char sep, char esc ); Str *Tokenize( char *s, char sep, char esc, unsigned int *q ); int main() { char s[] = STR_DEMO; unsigned int i, q; Str *list = Tokenize( s, SEP, ESC, &q ); if( list != NULL ) { printf( "\n Original string: %s\n\n", STR_DEMO ); printf( " %d tokens:\n\n", q ); for( i=0; i<q; ++i ) printf( " %4d. %s\n", i+1, list[i] ); free( list ); } return 0; } unsigned int ElQ( const char *s, char sep, char esc ) { unsigned int q, e; const char *p; for( e=0, q=1, p=s; *p; ++p ) { if( *p == esc ) e = !e; else if( *p == sep ) q += !e; else e = 0; } return q; } Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) { Str *list = NULL; *q = ElQ( s, sep, esc ); list = malloc( *q * sizeof(Str) ); if( list != NULL ) { unsigned int e, i; char *p; i = 0; list[i++] = s; for( e=0, p=s; *p; ++p ) { if( *p == esc ) { e = !e; } else if( *p == sep && !e ) { list[i++] = p+1; *p = '\0'; } else { e = 0; } } } return list; }
Port the provided Java code into C while preserving the original functionality.
module HelloWorld { void run() { @Inject Console console; console.print("Hello World!"); } }
const hello = "Hello world!\n" print(hello)
Port the provided Java code into C while preserving the original functionality.
import java.util.ArrayList; import java.util.List; public class SexyPrimes { public static void main(String[] args) { sieve(); int pairs = 0; List<String> pairList = new ArrayList<>(); int triples = 0; List<String> tripleList = new ArrayList<>(); int quadruplets = 0; List<String> quadrupletList = new ArrayList<>(); int unsexyCount = 1; List<String> unsexyList = new ArrayList<>(); for ( int i = 3 ; i < MAX ; i++ ) { if ( i-6 >= 3 && primes[i-6] && primes[i] ) { pairs++; pairList.add((i-6) + " " + i); if ( pairList.size() > 5 ) { pairList.remove(0); } } else if ( i < MAX-2 && primes[i] && ! (i+6<MAX && primes[i] && primes[i+6])) { unsexyCount++; unsexyList.add("" + i); if ( unsexyList.size() > 10 ) { unsexyList.remove(0); } } if ( i-12 >= 3 && primes[i-12] && primes[i-6] && primes[i] ) { triples++; tripleList.add((i-12) + " " + (i-6) + " " + i); if ( tripleList.size() > 5 ) { tripleList.remove(0); } } if ( i-16 >= 3 && primes[i-18] && primes[i-12] && primes[i-6] && primes[i] ) { quadruplets++; quadrupletList.add((i-18) + " " + (i-12) + " " + (i-6) + " " + i); if ( quadrupletList.size() > 5 ) { quadrupletList.remove(0); } } } System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, pairs); System.out.printf("The last 5 sexy pairs:%n %s%n%n", pairList.toString().replaceAll(", ", "], [")); System.out.printf("Count of sexy triples less than %,d = %,d%n", MAX, triples); System.out.printf("The last 5 sexy triples:%n %s%n%n", tripleList.toString().replaceAll(", ", "], [")); System.out.printf("Count of sexy quadruplets less than %,d = %,d%n", MAX, quadruplets); System.out.printf("The last 5 sexy quadruplets:%n %s%n%n", quadrupletList.toString().replaceAll(", ", "], [")); System.out.printf("Count of unsexy primes less than %,d = %,d%n", MAX, unsexyCount); System.out.printf("The last 10 unsexy primes:%n %s%n%n", unsexyList.toString().replaceAll(", ", "], [")); } private static int MAX = 1_000_035; private static boolean[] primes = new boolean[MAX]; private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #define TRUE 1 #define FALSE 0 typedef unsigned char bool; void sieve(bool *c, int limit) { int i, p = 3, p2; c[0] = TRUE; c[1] = TRUE; for (;;) { p2 = p * p; if (p2 >= limit) { break; } for (i = p2; i < limit; i += 2*p) { c[i] = TRUE; } for (;;) { p += 2; if (!c[p]) { break; } } } } void printHelper(const char *cat, int len, int lim, int n) { const char *sp = strcmp(cat, "unsexy primes") ? "sexy prime " : ""; const char *verb = (len == 1) ? "is" : "are"; printf("Number of %s%s less than %'d = %'d\n", sp, cat, lim, len); printf("The last %d %s:\n", n, verb); } void printArray(int *a, int len) { int i; printf("["); for (i = 0; i < len; ++i) printf("%d ", a[i]); printf("\b]"); } int main() { int i, ix, n, lim = 1000035; int pairs = 0, trips = 0, quads = 0, quins = 0, unsexy = 2; int pr = 0, tr = 0, qd = 0, qn = 0, un = 2; int lpr = 5, ltr = 5, lqd = 5, lqn = 5, lun = 10; int last_pr[5][2], last_tr[5][3], last_qd[5][4], last_qn[5][5]; int last_un[10]; bool *sv = calloc(lim - 1, sizeof(bool)); setlocale(LC_NUMERIC, ""); sieve(sv, lim); for (i = 3; i < lim; i += 2) { if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) { unsexy++; continue; } if (i < lim-6 && !sv[i] && !sv[i+6]) { pairs++; } else continue; if (i < lim-12 && !sv[i+12]) { trips++; } else continue; if (i < lim-18 && !sv[i+18]) { quads++; } else continue; if (i < lim-24 && !sv[i+24]) { quins++; } } if (pairs < lpr) lpr = pairs; if (trips < ltr) ltr = trips; if (quads < lqd) lqd = quads; if (quins < lqn) lqn = quins; if (unsexy < lun) lun = unsexy; for (i = 3; i < lim; i += 2) { if (i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6]) { un++; if (un > unsexy - lun) { last_un[un + lun - 1 - unsexy] = i; } continue; } if (i < lim-6 && !sv[i] && !sv[i+6]) { pr++; if (pr > pairs - lpr) { ix = pr + lpr - 1 - pairs; last_pr[ix][0] = i; last_pr[ix][1] = i + 6; } } else continue; if (i < lim-12 && !sv[i+12]) { tr++; if (tr > trips - ltr) { ix = tr + ltr - 1 - trips; last_tr[ix][0] = i; last_tr[ix][1] = i + 6; last_tr[ix][2] = i + 12; } } else continue; if (i < lim-18 && !sv[i+18]) { qd++; if (qd > quads - lqd) { ix = qd + lqd - 1 - quads; last_qd[ix][0] = i; last_qd[ix][1] = i + 6; last_qd[ix][2] = i + 12; last_qd[ix][3] = i + 18; } } else continue; if (i < lim-24 && !sv[i+24]) { qn++; if (qn > quins - lqn) { ix = qn + lqn - 1 - quins; last_qn[ix][0] = i; last_qn[ix][1] = i + 6; last_qn[ix][2] = i + 12; last_qn[ix][3] = i + 18; last_qn[ix][4] = i + 24; } } } printHelper("pairs", pairs, lim, lpr); printf(" ["); for (i = 0; i < lpr; ++i) { printArray(last_pr[i], 2); printf("\b] "); } printf("\b]\n\n"); printHelper("triplets", trips, lim, ltr); printf(" ["); for (i = 0; i < ltr; ++i) { printArray(last_tr[i], 3); printf("\b] "); } printf("\b]\n\n"); printHelper("quadruplets", quads, lim, lqd); printf(" ["); for (i = 0; i < lqd; ++i) { printArray(last_qd[i], 4); printf("\b] "); } printf("\b]\n\n"); printHelper("quintuplets", quins, lim, lqn); printf(" ["); for (i = 0; i < lqn; ++i) { printArray(last_qn[i], 5); printf("\b] "); } printf("\b]\n\n"); printHelper("unsexy primes", unsexy, lim, lun); printf(" ["); printArray(last_un, lun); printf("\b]\n"); free(sv); return 0; }
Please provide an equivalent version of this Java code in C.
import java.util.Arrays; public class FD { public static void main(String args[]) { double[] a = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; System.out.println(Arrays.toString(dif(a, 1))); System.out.println(Arrays.toString(dif(a, 2))); System.out.println(Arrays.toString(dif(a, 9))); System.out.println(Arrays.toString(dif(a, 10))); System.out.println(Arrays.toString(dif(a, 11))); System.out.println(Arrays.toString(dif(a, -1))); System.out.println(Arrays.toString(dif(a, 0))); } public static double[] dif(double[] a, int n) { if (n < 0) return null; for (int i = 0; i < n && a.length > 0; i++) { double[] b = new double[a.length - 1]; for (int j = 0; j < b.length; j++){ b[j] = a[j+1] - a[j]; } a = b; } return a; } }
#include <stdlib.h> #include <string.h> #include <stdio.h> double* fwd_diff(double* x, unsigned int len, unsigned int order) { unsigned int i, j; double* y; if (order >= len) return 0; y = malloc(sizeof(double) * len); if (!order) { memcpy(y, x, sizeof(double) * len); return y; } for (j = 0; j < order; j++, x = y) for (i = 0, len--; i < len; i++) y[i] = x[i + 1] - x[i]; y = realloc(y, sizeof(double) * len); return y; } int main(void) { double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; int i, len = sizeof(x) / sizeof(x[0]); y = fwd_diff(x, len, 1); for (i = 0; i < len - 1; i++) printf("%g ", y[i]); putchar('\n'); return 0; }
Convert the following code from Java to C, ensuring the logic remains intact.
public static boolean prime(long a){ if(a == 2){ return true; }else if(a <= 1 || a % 2 == 0){ return false; } long max = (long)Math.sqrt(a); for(long n= 3; n <= max; n+= 2){ if(a % n == 0){ return false; } } return true; }
int is_prime(unsigned int n) { unsigned int p; if (!(n & 1) || n < 2 ) return n == 2; for (p = 3; p <= n/p; p += 2) if (!(n % p)) return 0; return 1; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
public class Binomial { private static long binomialInt(int n, int k) { if (k > n - k) k = n - k; long binom = 1; for (int i = 1; i <= k; i++) binom = binom * (n + 1 - i) / i; return binom; } private static Object binomialIntReliable(int n, int k) { if (k > n - k) k = n - k; long binom = 1; for (int i = 1; i <= k; i++) { try { binom = Math.multiplyExact(binom, n + 1 - i) / i; } catch (ArithmeticException e) { return "overflow"; } } return binom; } private static double binomialFloat(int n, int k) { if (k > n - k) k = n - k; double binom = 1.0; for (int i = 1; i <= k; i++) binom = binom * (n + 1 - i) / i; return binom; } private static BigInteger binomialBigInt(int n, int k) { if (k > n - k) k = n - k; BigInteger binom = BigInteger.ONE; for (int i = 1; i <= k; i++) { binom = binom.multiply(BigInteger.valueOf(n + 1 - i)); binom = binom.divide(BigInteger.valueOf(i)); } return binom; } private static void demo(int n, int k) { List<Object> data = Arrays.asList( n, k, binomialInt(n, k), binomialIntReliable(n, k), binomialFloat(n, k), binomialBigInt(n, k)); System.out.println(data.stream().map(Object::toString).collect(Collectors.joining("\t"))); } public static void main(String[] args) { demo(5, 3); demo(1000, 300); } }
#include <stdio.h> #include <limits.h> static unsigned long gcd_ui(unsigned long x, unsigned long y) { unsigned long t; if (y < x) { t = x; x = y; y = t; } while (y > 0) { t = y; y = x % y; x = t; } return x; } unsigned long binomial(unsigned long n, unsigned long k) { unsigned long d, g, r = 1; if (k == 0) return 1; if (k == 1) return n; if (k >= n) return (k == n); if (k > n/2) k = n-k; for (d = 1; d <= k; d++) { if (r >= ULONG_MAX/n) { unsigned long nr, dr; g = gcd_ui(n, d); nr = n/g; dr = d/g; g = gcd_ui(r, dr); r = r/g; dr = dr/g; if (r >= ULONG_MAX/nr) return 0; r *= nr; r /= dr; n--; } else { r *= n--; r /= d; } } return r; } int main() { printf("%lu\n", binomial(5, 3)); printf("%lu\n", binomial(40, 19)); printf("%lu\n", binomial(67, 31)); return 0; }
Can you help me rewrite this code in C instead of Java, keeping it the same logically?
List arrayList = new ArrayList(); arrayList.add(new Integer(0)); arrayList.add(0); List<Integer> myarrlist = new ArrayList<Integer>(); int sum; for(int i = 0; i < 10; i++) { myarrlist.add(i); }
#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) int ar[10]; ar[0] = 1; ar[1] = 2; int* p; for (p=ar; p<(ar+cSize(ar)); p++) { printf("%d\n",*p); }
Convert this Java block to C, preserving its control flow and logic.
LinkedList<Type> list = new LinkedList<Type>(); for(Type i: list){ System.out.println(i); }
struct link *first; struct link *iter; for(iter = first; iter != NULL; iter = iter->next) { }
Convert this Java block to C, preserving its control flow and logic.
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class PPMWriter { public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException { file.delete(); try (var os = new FileOutputStream(file, true); var bw = new BufferedOutputStream(os)) { var header = String.format("P6\n%d %d\n255\n", bitmap.getWidth(), bitmap.getHeight()); bw.write(header.getBytes(StandardCharsets.US_ASCII)); for (var y = 0; y < bitmap.getHeight(); y++) { for (var x = 0; x < bitmap.getWidth(); x++) { var pixel = bitmap.getPixel(x, y); bw.write(pixel.getRed()); bw.write(pixel.getGreen()); bw.write(pixel.getBlue()); } } } } }
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
Generate a C translation of this Java snippet without changing its computational steps.
import java.io.File; public class FileDeleteTest { public static boolean deleteFile(String filename) { boolean exists = new File(filename).delete(); return exists; } public static void test(String type, String filename) { System.out.println("The following " + type + " called " + filename + (deleteFile(filename) ? " was deleted." : " could not be deleted.") ); } public static void main(String args[]) { test("file", "input.txt"); test("file", File.seperator + "input.txt"); test("directory", "docs"); test("directory", File.seperator + "docs" + File.seperator); } }
#include <stdio.h> int main() { remove("input.txt"); remove("/input.txt"); remove("docs"); remove("/docs"); return 0; }
Generate an equivalent C version of this Java code.
import java.util.Calendar; import java.util.GregorianCalendar; public class DiscordianDate { final static String[] seasons = {"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}; final static String[] weekday = {"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"}; final static String[] apostle = {"Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"}; final static String[] holiday = {"Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"}; public static String discordianDate(final GregorianCalendar date) { int y = date.get(Calendar.YEAR); int yold = y + 1166; int dayOfYear = date.get(Calendar.DAY_OF_YEAR); if (date.isLeapYear(y)) { if (dayOfYear == 60) return "St. Tib's Day, in the YOLD " + yold; else if (dayOfYear > 60) dayOfYear--; } dayOfYear--; int seasonDay = dayOfYear % 73 + 1; if (seasonDay == 5) return apostle[dayOfYear / 73] + ", in the YOLD " + yold; if (seasonDay == 50) return holiday[dayOfYear / 73] + ", in the YOLD " + yold; String season = seasons[dayOfYear / 73]; String dayOfWeek = weekday[dayOfYear % 5]; return String.format("%s, day %s of %s in the YOLD %s", dayOfWeek, seasonDay, season, yold); } public static void main(String[] args) { System.out.println(discordianDate(new GregorianCalendar())); test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176"); test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178"); test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178"); test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178"); test(2010, 0, 5, "Mungday, in the YOLD 3176"); test(2011, 4, 3, "Discoflux, in the YOLD 3177"); test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181"); } private static void test(int y, int m, int d, final String result) { assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result)); } }
#include <stdlib.h> #include <stdio.h> #include <time.h> #define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\ (x) == 2 ? "Boomtime" :\ (x) == 3 ? "Pungenday" :\ (x) == 4 ? "Prickle-Prickle" :\ "Setting Orange") #define season( x ) ((x) == 0 ? "Chaos" :\ (x) == 1 ? "Discord" :\ (x) == 2 ? "Confusion" :\ (x) == 3 ? "Bureaucracy" :\ "The Aftermath") #define date( x ) ((x)%73 == 0 ? 73 : (x)%73) #define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100)) char * ddate( int y, int d ){ int dyear = 1166 + y; char * result = malloc( 100 * sizeof( char ) ); if( leap_year( y ) ){ if( d == 60 ){ sprintf( result, "St. Tib's Day, YOLD %d", dyear ); return result; } else if( d >= 60 ){ -- d; } } sprintf( result, "%s, %s %d, YOLD %d", day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear ); return result; } int day_of_year( int y, int m, int d ){ int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; for( ; m > 1; m -- ){ d += month_lengths[ m - 2 ]; if( m == 3 && leap_year( y ) ){ ++ d; } } return d; } int main( int argc, char * argv[] ){ time_t now; struct tm * now_time; int year, doy; if( argc == 1 ){ now = time( NULL ); now_time = localtime( &now ); year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1; } else if( argc == 4 ){ year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) ); } char * result = ddate( year, doy ); puts( result ); free( result ); return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class FlippingBitsGame extends JPanel { final int maxLevel = 7; final int minLevel = 3; private Random rand = new Random(); private int[][] grid, target; private Rectangle box; private int n = maxLevel; private boolean solved = true; FlippingBitsGame() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); setFont(new Font("SansSerif", Font.PLAIN, 18)); box = new Rectangle(120, 90, 400, 400); startNewGame(); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (solved) { startNewGame(); } else { int x = e.getX(); int y = e.getY(); if (box.contains(x, y)) return; if (x > box.x && x < box.x + box.width) { flipCol((x - box.x) / (box.width / n)); } else if (y > box.y && y < box.y + box.height) flipRow((y - box.y) / (box.height / n)); if (solved(grid, target)) solved = true; printGrid(solved ? "Solved!" : "The board", grid); } repaint(); } }); } void startNewGame() { if (solved) { n = (n == maxLevel) ? minLevel : n + 1; grid = new int[n][n]; target = new int[n][n]; do { shuffle(); for (int i = 0; i < n; i++) target[i] = Arrays.copyOf(grid[i], n); shuffle(); } while (solved(grid, target)); solved = false; printGrid("The target", target); printGrid("The board", grid); } } void printGrid(String msg, int[][] g) { System.out.println(msg); for (int[] row : g) System.out.println(Arrays.toString(row)); System.out.println(); } boolean solved(int[][] a, int[][] b) { for (int i = 0; i < n; i++) if (!Arrays.equals(a[i], b[i])) return false; return true; } void shuffle() { for (int i = 0; i < n * n; i++) { if (rand.nextBoolean()) flipRow(rand.nextInt(n)); else flipCol(rand.nextInt(n)); } } void flipRow(int r) { for (int c = 0; c < n; c++) { grid[r][c] ^= 1; } } void flipCol(int c) { for (int[] row : grid) { row[c] ^= 1; } } void drawGrid(Graphics2D g) { g.setColor(getForeground()); if (solved) g.drawString("Solved! Click here to play again.", 180, 600); else g.drawString("Click next to a row or a column to flip.", 170, 600); int size = box.width / n; for (int r = 0; r < n; r++) for (int c = 0; c < n; c++) { g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange); g.fillRect(box.x + c * size, box.y + r * size, size, size); g.setColor(getBackground()); g.drawRect(box.x + c * size, box.y + r * size, size, size); g.setColor(target[r][c] == 1 ? Color.blue : Color.orange); g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10); } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawGrid(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Flipping Bits Game"); f.setResizable(false); f.add(new FlippingBitsGame(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include <stdio.h> #include <stdlib.h> int i, j; void fliprow(int **b, int sz, int n) { for(i = 0; i < sz; i++) b[n+1][i] = !b[n+1][i]; } void flipcol(int **b, int sz, int n) { for(i = 1; i <= sz; i++) b[i][n] = !b[i][n]; } void initt(int **t, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) t[i][j] = rand()%2; } void initb(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) b[i][j] = t[i][j]; for(i = 1; i <= sz; i++) fliprow(b, sz, rand()%sz+1); for(i = 0; i < sz; i++) flipcol(b, sz, rand()%sz); } void printb(int **b, int sz) { printf(" "); for(i = 0; i < sz; i++) printf(" %d", i); printf("\n"); for(i = 1; i <= sz; i++) { printf("%d", i-1); for(j = 0; j < sz; j++) printf(" %d", b[i][j]); printf("\n"); } printf("\n"); } int eq(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) if(b[i][j] != t[i][j]) return 0; return 1; } void main() { int sz = 3; int eql = 0; int mov = 0; int **t = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) t[i] = malloc(sz*sizeof(int)); int **b = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) b[i] = malloc(sz*sizeof(int)); char roc; int n; initt(t, sz); initb(t, b, sz); while(eq(t, b, sz)) initb(t, b, sz); while(!eql) { printf("Target: \n"); printb(t, sz); printf("Board: \n"); printb(b, sz); printf("What to flip: "); scanf(" %c", &roc); scanf(" %d", &n); switch(roc) { case 'r': fliprow(b, sz, n); break; case 'c': flipcol(b, sz, n); break; default: perror("Please specify r or c and an number"); break; } printf("Moves Taken: %d\n", ++mov); if(eq(t, b, sz)) { printf("You win!\n"); eql = 1; } } }
Keep all operations the same but rewrite the snippet in C.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class FlippingBitsGame extends JPanel { final int maxLevel = 7; final int minLevel = 3; private Random rand = new Random(); private int[][] grid, target; private Rectangle box; private int n = maxLevel; private boolean solved = true; FlippingBitsGame() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); setFont(new Font("SansSerif", Font.PLAIN, 18)); box = new Rectangle(120, 90, 400, 400); startNewGame(); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (solved) { startNewGame(); } else { int x = e.getX(); int y = e.getY(); if (box.contains(x, y)) return; if (x > box.x && x < box.x + box.width) { flipCol((x - box.x) / (box.width / n)); } else if (y > box.y && y < box.y + box.height) flipRow((y - box.y) / (box.height / n)); if (solved(grid, target)) solved = true; printGrid(solved ? "Solved!" : "The board", grid); } repaint(); } }); } void startNewGame() { if (solved) { n = (n == maxLevel) ? minLevel : n + 1; grid = new int[n][n]; target = new int[n][n]; do { shuffle(); for (int i = 0; i < n; i++) target[i] = Arrays.copyOf(grid[i], n); shuffle(); } while (solved(grid, target)); solved = false; printGrid("The target", target); printGrid("The board", grid); } } void printGrid(String msg, int[][] g) { System.out.println(msg); for (int[] row : g) System.out.println(Arrays.toString(row)); System.out.println(); } boolean solved(int[][] a, int[][] b) { for (int i = 0; i < n; i++) if (!Arrays.equals(a[i], b[i])) return false; return true; } void shuffle() { for (int i = 0; i < n * n; i++) { if (rand.nextBoolean()) flipRow(rand.nextInt(n)); else flipCol(rand.nextInt(n)); } } void flipRow(int r) { for (int c = 0; c < n; c++) { grid[r][c] ^= 1; } } void flipCol(int c) { for (int[] row : grid) { row[c] ^= 1; } } void drawGrid(Graphics2D g) { g.setColor(getForeground()); if (solved) g.drawString("Solved! Click here to play again.", 180, 600); else g.drawString("Click next to a row or a column to flip.", 170, 600); int size = box.width / n; for (int r = 0; r < n; r++) for (int c = 0; c < n; c++) { g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange); g.fillRect(box.x + c * size, box.y + r * size, size, size); g.setColor(getBackground()); g.drawRect(box.x + c * size, box.y + r * size, size, size); g.setColor(target[r][c] == 1 ? Color.blue : Color.orange); g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10); } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawGrid(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Flipping Bits Game"); f.setResizable(false); f.add(new FlippingBitsGame(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include <stdio.h> #include <stdlib.h> int i, j; void fliprow(int **b, int sz, int n) { for(i = 0; i < sz; i++) b[n+1][i] = !b[n+1][i]; } void flipcol(int **b, int sz, int n) { for(i = 1; i <= sz; i++) b[i][n] = !b[i][n]; } void initt(int **t, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) t[i][j] = rand()%2; } void initb(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) b[i][j] = t[i][j]; for(i = 1; i <= sz; i++) fliprow(b, sz, rand()%sz+1); for(i = 0; i < sz; i++) flipcol(b, sz, rand()%sz); } void printb(int **b, int sz) { printf(" "); for(i = 0; i < sz; i++) printf(" %d", i); printf("\n"); for(i = 1; i <= sz; i++) { printf("%d", i-1); for(j = 0; j < sz; j++) printf(" %d", b[i][j]); printf("\n"); } printf("\n"); } int eq(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) if(b[i][j] != t[i][j]) return 0; return 1; } void main() { int sz = 3; int eql = 0; int mov = 0; int **t = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) t[i] = malloc(sz*sizeof(int)); int **b = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) b[i] = malloc(sz*sizeof(int)); char roc; int n; initt(t, sz); initb(t, b, sz); while(eq(t, b, sz)) initb(t, b, sz); while(!eql) { printf("Target: \n"); printb(t, sz); printf("Board: \n"); printb(b, sz); printf("What to flip: "); scanf(" %c", &roc); scanf(" %d", &n); switch(roc) { case 'r': fliprow(b, sz, n); break; case 'c': flipcol(b, sz, n); break; default: perror("Please specify r or c and an number"); break; } printf("Moves Taken: %d\n", ++mov); if(eq(t, b, sz)) { printf("You win!\n"); eql = 1; } } }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class FlippingBitsGame extends JPanel { final int maxLevel = 7; final int minLevel = 3; private Random rand = new Random(); private int[][] grid, target; private Rectangle box; private int n = maxLevel; private boolean solved = true; FlippingBitsGame() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); setFont(new Font("SansSerif", Font.PLAIN, 18)); box = new Rectangle(120, 90, 400, 400); startNewGame(); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (solved) { startNewGame(); } else { int x = e.getX(); int y = e.getY(); if (box.contains(x, y)) return; if (x > box.x && x < box.x + box.width) { flipCol((x - box.x) / (box.width / n)); } else if (y > box.y && y < box.y + box.height) flipRow((y - box.y) / (box.height / n)); if (solved(grid, target)) solved = true; printGrid(solved ? "Solved!" : "The board", grid); } repaint(); } }); } void startNewGame() { if (solved) { n = (n == maxLevel) ? minLevel : n + 1; grid = new int[n][n]; target = new int[n][n]; do { shuffle(); for (int i = 0; i < n; i++) target[i] = Arrays.copyOf(grid[i], n); shuffle(); } while (solved(grid, target)); solved = false; printGrid("The target", target); printGrid("The board", grid); } } void printGrid(String msg, int[][] g) { System.out.println(msg); for (int[] row : g) System.out.println(Arrays.toString(row)); System.out.println(); } boolean solved(int[][] a, int[][] b) { for (int i = 0; i < n; i++) if (!Arrays.equals(a[i], b[i])) return false; return true; } void shuffle() { for (int i = 0; i < n * n; i++) { if (rand.nextBoolean()) flipRow(rand.nextInt(n)); else flipCol(rand.nextInt(n)); } } void flipRow(int r) { for (int c = 0; c < n; c++) { grid[r][c] ^= 1; } } void flipCol(int c) { for (int[] row : grid) { row[c] ^= 1; } } void drawGrid(Graphics2D g) { g.setColor(getForeground()); if (solved) g.drawString("Solved! Click here to play again.", 180, 600); else g.drawString("Click next to a row or a column to flip.", 170, 600); int size = box.width / n; for (int r = 0; r < n; r++) for (int c = 0; c < n; c++) { g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange); g.fillRect(box.x + c * size, box.y + r * size, size, size); g.setColor(getBackground()); g.drawRect(box.x + c * size, box.y + r * size, size, size); g.setColor(target[r][c] == 1 ? Color.blue : Color.orange); g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10); } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawGrid(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Flipping Bits Game"); f.setResizable(false); f.add(new FlippingBitsGame(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include <stdio.h> #include <stdlib.h> int i, j; void fliprow(int **b, int sz, int n) { for(i = 0; i < sz; i++) b[n+1][i] = !b[n+1][i]; } void flipcol(int **b, int sz, int n) { for(i = 1; i <= sz; i++) b[i][n] = !b[i][n]; } void initt(int **t, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) t[i][j] = rand()%2; } void initb(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) b[i][j] = t[i][j]; for(i = 1; i <= sz; i++) fliprow(b, sz, rand()%sz+1); for(i = 0; i < sz; i++) flipcol(b, sz, rand()%sz); } void printb(int **b, int sz) { printf(" "); for(i = 0; i < sz; i++) printf(" %d", i); printf("\n"); for(i = 1; i <= sz; i++) { printf("%d", i-1); for(j = 0; j < sz; j++) printf(" %d", b[i][j]); printf("\n"); } printf("\n"); } int eq(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) if(b[i][j] != t[i][j]) return 0; return 1; } void main() { int sz = 3; int eql = 0; int mov = 0; int **t = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) t[i] = malloc(sz*sizeof(int)); int **b = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) b[i] = malloc(sz*sizeof(int)); char roc; int n; initt(t, sz); initb(t, b, sz); while(eq(t, b, sz)) initb(t, b, sz); while(!eql) { printf("Target: \n"); printb(t, sz); printf("Board: \n"); printb(b, sz); printf("What to flip: "); scanf(" %c", &roc); scanf(" %d", &n); switch(roc) { case 'r': fliprow(b, sz, n); break; case 'c': flipcol(b, sz, n); break; default: perror("Please specify r or c and an number"); break; } printf("Moves Taken: %d\n", ++mov); if(eq(t, b, sz)) { printf("You win!\n"); eql = 1; } } }
Produce a language-to-language conversion: from Java to C, same semantics.
import java.math.*; public class Hickerson { final static String LN2 = "0.693147180559945309417232121458"; public static void main(String[] args) { for (int n = 1; n <= 17; n++) System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n)); } static boolean almostInteger(int n) { BigDecimal a = new BigDecimal(LN2); a = a.pow(n + 1).multiply(BigDecimal.valueOf(2)); long f = n; while (--n > 1) f *= n; BigDecimal b = new BigDecimal(f); b = b.divide(a, MathContext.DECIMAL128); BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN); return c.toString().matches("0|9"); } }
#include <stdio.h> #include <mpfr.h> void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_frac(b, a, MPFR_RNDD); mpfr_printf("%2d: %23.4Rf %c\n", n, a, mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N'); } int main(void) { int n; for (n = 1; n <= 17; n++) h(n); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
import java.math.*; public class Hickerson { final static String LN2 = "0.693147180559945309417232121458"; public static void main(String[] args) { for (int n = 1; n <= 17; n++) System.out.printf("%2s is almost integer: %s%n", n, almostInteger(n)); } static boolean almostInteger(int n) { BigDecimal a = new BigDecimal(LN2); a = a.pow(n + 1).multiply(BigDecimal.valueOf(2)); long f = n; while (--n > 1) f *= n; BigDecimal b = new BigDecimal(f); b = b.divide(a, MathContext.DECIMAL128); BigInteger c = b.movePointRight(1).toBigInteger().mod(BigInteger.TEN); return c.toString().matches("0|9"); } }
#include <stdio.h> #include <mpfr.h> void h(int n) { MPFR_DECL_INIT(a, 200); MPFR_DECL_INIT(b, 200); mpfr_fac_ui(a, n, MPFR_RNDD); mpfr_set_ui(b, 2, MPFR_RNDD); mpfr_log(b, b, MPFR_RNDD); mpfr_pow_ui(b, b, n + 1, MPFR_RNDD); mpfr_div(a, a, b, MPFR_RNDD); mpfr_div_ui(a, a, 2, MPFR_RNDD); mpfr_frac(b, a, MPFR_RNDD); mpfr_printf("%2d: %23.4Rf %c\n", n, a, mpfr_cmp_d(b, .1) * mpfr_cmp_d(b, .9) > 0 ? 'Y' : 'N'); } int main(void) { int n; for (n = 1; n <= 17; n++) h(n); return 0; }
Rewrite the snippet below in C so it works the same as the original Java code.
import java.util.HashSet; import java.util.Random; import java.util.Set; public class AverageLoopLength { private static final int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.nextInt(n); } Set<Integer> seen = new HashSet<>(n); int current = 0; int length = 0; while (seen.add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void main(String[] args) { System.out.println(" N average analytical (error)"); System.out.println("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { double avg = average(i); double ana = analytical(i); System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100))); } } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } return 0; }
Change the following Java code into C without altering its purpose.
import java.util.HashSet; import java.util.Random; import java.util.Set; public class AverageLoopLength { private static final int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.nextInt(n); } Set<Integer> seen = new HashSet<>(n); int current = 0; int length = 0; while (seen.add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void main(String[] args) { System.out.println(" N average analytical (error)"); System.out.println("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { double avg = average(i); double ana = analytical(i); System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100))); } } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } return 0; }
Write the same algorithm in C as shown in this Java implementation.
import java.util.HashSet; import java.util.Random; import java.util.Set; public class AverageLoopLength { private static final int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.nextInt(n); } Set<Integer> seen = new HashSet<>(n); int current = 0; int length = 0; while (seen.add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void main(String[] args) { System.out.println(" N average analytical (error)"); System.out.println("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { double avg = average(i); double ana = analytical(i); System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100))); } } }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } return 0; }
Produce a language-to-language conversion: from Java to C, same semantics.
String original = "Mary had a X lamb"; String little = "little"; String replaced = original.replace("X", little); System.out.println(replaced); System.out.printf("Mary had a %s lamb.", little); String formatted = String.format("Mary had a %s lamb.", little); System.out.println(formatted);
#include <stdio.h> int main() { const char *extra = "little"; printf("Mary had a %s lamb.\n", extra); return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
import java.util.*; public class PatienceSort { public static <E extends Comparable<? super E>> void sort (E[] n) { List<Pile<E>> piles = new ArrayList<Pile<E>>(); for (E x : n) { Pile<E> newPile = new Pile<E>(); newPile.push(x); int i = Collections.binarySearch(piles, newPile); if (i < 0) i = ~i; if (i != piles.size()) piles.get(i).push(x); else piles.add(newPile); } PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles); for (int c = 0; c < n.length; c++) { Pile<E> smallPile = heap.poll(); n[c] = smallPile.pop(); if (!smallPile.isEmpty()) heap.offer(smallPile); } assert(heap.isEmpty()); } private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> { public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); } } public static void main(String[] args) { Integer[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1}; sort(a); System.out.println(Arrays.toString(a)); } }
#include<stdlib.h> #include<stdio.h> int* patienceSort(int* arr,int size){ int decks[size][size],i,j,min,pickedRow; int *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int)); for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){ decks[j][count[j]] = arr[i]; count[j]++; break; } } } min = decks[0][count[0]-1]; pickedRow = 0; for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(count[j]>0 && decks[j][count[j]-1]<min){ min = decks[j][count[j]-1]; pickedRow = j; } } sortedArr[i] = min; count[pickedRow]--; for(j=0;j<size;j++) if(count[j]>0){ min = decks[j][count[j]-1]; pickedRow = j; break; } } free(count); free(decks); return sortedArr; } int main(int argC,char* argV[]) { int *arr, *sortedArr, i; if(argC==0) printf("Usage : %s <integers to be sorted separated by space>"); else{ arr = (int*)malloc((argC-1)*sizeof(int)); for(i=1;i<=argC;i++) arr[i-1] = atoi(argV[i]); sortedArr = patienceSort(arr,argC-1); for(i=0;i<argC-1;i++) printf("%d ",sortedArr[i]); } return 0; }
Ensure the translated C code behaves exactly like the original Java snippet.
import java.util.Arrays; import java.util.Random; public class SequenceMutation { public static void main(String[] args) { SequenceMutation sm = new SequenceMutation(); sm.setWeight(OP_CHANGE, 3); String sequence = sm.generateSequence(250); System.out.println("Initial sequence:"); printSequence(sequence); int count = 10; for (int i = 0; i < count; ++i) sequence = sm.mutateSequence(sequence); System.out.println("After " + count + " mutations:"); printSequence(sequence); } public SequenceMutation() { totalWeight_ = OP_COUNT; Arrays.fill(operationWeight_, 1); } public String generateSequence(int length) { char[] ch = new char[length]; for (int i = 0; i < length; ++i) ch[i] = getRandomBase(); return new String(ch); } public void setWeight(int operation, int weight) { totalWeight_ -= operationWeight_[operation]; operationWeight_[operation] = weight; totalWeight_ += weight; } public String mutateSequence(String sequence) { char[] ch = sequence.toCharArray(); int pos = random_.nextInt(ch.length); int operation = getRandomOperation(); if (operation == OP_CHANGE) { char b = getRandomBase(); System.out.println("Change base at position " + pos + " from " + ch[pos] + " to " + b); ch[pos] = b; } else if (operation == OP_ERASE) { System.out.println("Erase base " + ch[pos] + " at position " + pos); char[] newCh = new char[ch.length - 1]; System.arraycopy(ch, 0, newCh, 0, pos); System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1); ch = newCh; } else if (operation == OP_INSERT) { char b = getRandomBase(); System.out.println("Insert base " + b + " at position " + pos); char[] newCh = new char[ch.length + 1]; System.arraycopy(ch, 0, newCh, 0, pos); System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos); newCh[pos] = b; ch = newCh; } return new String(ch); } public static void printSequence(String sequence) { int[] count = new int[BASES.length]; for (int i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) System.out.println(); System.out.printf("%3d: ", i); } char ch = sequence.charAt(i); System.out.print(ch); for (int j = 0; j < BASES.length; ++j) { if (BASES[j] == ch) { ++count[j]; break; } } } System.out.println(); System.out.println("Base counts:"); int total = 0; for (int j = 0; j < BASES.length; ++j) { total += count[j]; System.out.print(BASES[j] + ": " + count[j] + ", "); } System.out.println("Total: " + total); } private char getRandomBase() { return BASES[random_.nextInt(BASES.length)]; } private int getRandomOperation() { int n = random_.nextInt(totalWeight_), op = 0; for (int weight = 0; op < OP_COUNT; ++op) { weight += operationWeight_[op]; if (n < weight) break; } return op; } private final Random random_ = new Random(); private int[] operationWeight_ = new int[OP_COUNT]; private int totalWeight_ = 0; private static final int OP_CHANGE = 0; private static final int OP_ERASE = 1; private static final int OP_INSERT = 2; private static final int OP_COUNT = 3; private static final char[] BASES = {'A', 'C', 'G', 'T'}; }
#include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct genome{ char base; struct genome *next; }genome; typedef struct{ char mutation; int position; }genomeChange; typedef struct{ int adenineCount,thymineCount,cytosineCount,guanineCount; }baseCounts; genome *strand; baseCounts baseData; int genomeLength = 100, lineLength = 50; int numDigits(int num){ int len = 1; while(num>10){ num /= 10; len++; } return len; } void generateStrand(){ int baseChoice = rand()%4, i; genome *strandIterator, *newStrand; baseData.adenineCount = 0; baseData.thymineCount = 0; baseData.cytosineCount = 0; baseData.guanineCount = 0; strand = (genome*)malloc(sizeof(genome)); strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); strand->next = NULL; strandIterator = strand; for(i=1;i<genomeLength;i++){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = NULL; strandIterator->next = newStrand; strandIterator = newStrand; } } genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){ int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight); genomeChange mutationCommand; mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D'); mutationCommand.position = rand()%genomeLength; return mutationCommand; } void printGenome(){ int rows, width = numDigits(genomeLength), len = 0,i,j; lineLength = (genomeLength<lineLength)?genomeLength:lineLength; rows = genomeLength/lineLength + (genomeLength%lineLength!=0); genome* strandIterator = strand; printf("\n\nGenome : \n--------\n"); for(i=0;i<rows;i++){ printf("\n%*d%3s",width,len,":"); for(j=0;j<lineLength && strandIterator!=NULL;j++){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } len += lineLength; } while(strandIterator!=NULL){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } printf("\n\nBase Counts\n-----------"); printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount); printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount); printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount); printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount); printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount); printf("\n"); } void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){ int i,j,width,baseChoice; genomeChange newMutation; genome *strandIterator, *strandFollower, *newStrand; for(i=0;i<numMutations;i++){ strandIterator = strand; strandFollower = strand; newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight); width = numDigits(genomeLength); for(j=0;j<newMutation.position;j++){ strandFollower = strandIterator; strandIterator = strandIterator->next; } if(newMutation.mutation=='S'){ if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='C'){ strandIterator->base='G'; printf("\nSwapping C at position : %*d with G",width,newMutation.position); } else{ strandIterator->base='C'; printf("\nSwapping G at position : %*d with C",width,newMutation.position); } } else if(newMutation.mutation=='I'){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = strandIterator; strandFollower->next = newStrand; genomeLength++; } else{ strandFollower->next = strandIterator->next; strandIterator->next = NULL; printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position); free(strandIterator); genomeLength--; } } } int main(int argc,char* argv[]) { int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10; if(argc==1||argc>6){ printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]); return 0; } switch(argc){ case 2: genomeLength = atoi(argv[1]); break; case 3: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); break; case 4: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); break; case 5: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); break; case 6: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); deleteWeight = atoi(argv[5]); break; }; srand(time(NULL)); generateStrand(); printf("\nOriginal:"); printGenome(); mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight); printf("\n\nMutated:"); printGenome(); return 0; }
Port the provided Java code into C while preserving the original functionality.
import java.util.Arrays; import java.util.Random; public class SequenceMutation { public static void main(String[] args) { SequenceMutation sm = new SequenceMutation(); sm.setWeight(OP_CHANGE, 3); String sequence = sm.generateSequence(250); System.out.println("Initial sequence:"); printSequence(sequence); int count = 10; for (int i = 0; i < count; ++i) sequence = sm.mutateSequence(sequence); System.out.println("After " + count + " mutations:"); printSequence(sequence); } public SequenceMutation() { totalWeight_ = OP_COUNT; Arrays.fill(operationWeight_, 1); } public String generateSequence(int length) { char[] ch = new char[length]; for (int i = 0; i < length; ++i) ch[i] = getRandomBase(); return new String(ch); } public void setWeight(int operation, int weight) { totalWeight_ -= operationWeight_[operation]; operationWeight_[operation] = weight; totalWeight_ += weight; } public String mutateSequence(String sequence) { char[] ch = sequence.toCharArray(); int pos = random_.nextInt(ch.length); int operation = getRandomOperation(); if (operation == OP_CHANGE) { char b = getRandomBase(); System.out.println("Change base at position " + pos + " from " + ch[pos] + " to " + b); ch[pos] = b; } else if (operation == OP_ERASE) { System.out.println("Erase base " + ch[pos] + " at position " + pos); char[] newCh = new char[ch.length - 1]; System.arraycopy(ch, 0, newCh, 0, pos); System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1); ch = newCh; } else if (operation == OP_INSERT) { char b = getRandomBase(); System.out.println("Insert base " + b + " at position " + pos); char[] newCh = new char[ch.length + 1]; System.arraycopy(ch, 0, newCh, 0, pos); System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos); newCh[pos] = b; ch = newCh; } return new String(ch); } public static void printSequence(String sequence) { int[] count = new int[BASES.length]; for (int i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) System.out.println(); System.out.printf("%3d: ", i); } char ch = sequence.charAt(i); System.out.print(ch); for (int j = 0; j < BASES.length; ++j) { if (BASES[j] == ch) { ++count[j]; break; } } } System.out.println(); System.out.println("Base counts:"); int total = 0; for (int j = 0; j < BASES.length; ++j) { total += count[j]; System.out.print(BASES[j] + ": " + count[j] + ", "); } System.out.println("Total: " + total); } private char getRandomBase() { return BASES[random_.nextInt(BASES.length)]; } private int getRandomOperation() { int n = random_.nextInt(totalWeight_), op = 0; for (int weight = 0; op < OP_COUNT; ++op) { weight += operationWeight_[op]; if (n < weight) break; } return op; } private final Random random_ = new Random(); private int[] operationWeight_ = new int[OP_COUNT]; private int totalWeight_ = 0; private static final int OP_CHANGE = 0; private static final int OP_ERASE = 1; private static final int OP_INSERT = 2; private static final int OP_COUNT = 3; private static final char[] BASES = {'A', 'C', 'G', 'T'}; }
#include<stdlib.h> #include<stdio.h> #include<time.h> typedef struct genome{ char base; struct genome *next; }genome; typedef struct{ char mutation; int position; }genomeChange; typedef struct{ int adenineCount,thymineCount,cytosineCount,guanineCount; }baseCounts; genome *strand; baseCounts baseData; int genomeLength = 100, lineLength = 50; int numDigits(int num){ int len = 1; while(num>10){ num /= 10; len++; } return len; } void generateStrand(){ int baseChoice = rand()%4, i; genome *strandIterator, *newStrand; baseData.adenineCount = 0; baseData.thymineCount = 0; baseData.cytosineCount = 0; baseData.guanineCount = 0; strand = (genome*)malloc(sizeof(genome)); strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); strand->next = NULL; strandIterator = strand; for(i=1;i<genomeLength;i++){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = NULL; strandIterator->next = newStrand; strandIterator = newStrand; } } genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){ int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight); genomeChange mutationCommand; mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D'); mutationCommand.position = rand()%genomeLength; return mutationCommand; } void printGenome(){ int rows, width = numDigits(genomeLength), len = 0,i,j; lineLength = (genomeLength<lineLength)?genomeLength:lineLength; rows = genomeLength/lineLength + (genomeLength%lineLength!=0); genome* strandIterator = strand; printf("\n\nGenome : \n--------\n"); for(i=0;i<rows;i++){ printf("\n%*d%3s",width,len,":"); for(j=0;j<lineLength && strandIterator!=NULL;j++){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } len += lineLength; } while(strandIterator!=NULL){ printf("%c",strandIterator->base); strandIterator = strandIterator->next; } printf("\n\nBase Counts\n-----------"); printf("\n%*c%3s%*d",width,'A',":",width,baseData.adenineCount); printf("\n%*c%3s%*d",width,'T',":",width,baseData.thymineCount); printf("\n%*c%3s%*d",width,'C',":",width,baseData.cytosineCount); printf("\n%*c%3s%*d",width,'G',":",width,baseData.guanineCount); printf("\n\nTotal:%*d",width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount); printf("\n"); } void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){ int i,j,width,baseChoice; genomeChange newMutation; genome *strandIterator, *strandFollower, *newStrand; for(i=0;i<numMutations;i++){ strandIterator = strand; strandFollower = strand; newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight); width = numDigits(genomeLength); for(j=0;j<newMutation.position;j++){ strandFollower = strandIterator; strandIterator = strandIterator->next; } if(newMutation.mutation=='S'){ if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='A'){ strandIterator->base='T'; printf("\nSwapping A at position : %*d with T",width,newMutation.position); } else if(strandIterator->base=='C'){ strandIterator->base='G'; printf("\nSwapping C at position : %*d with G",width,newMutation.position); } else{ strandIterator->base='C'; printf("\nSwapping G at position : %*d with C",width,newMutation.position); } } else if(newMutation.mutation=='I'){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); printf("\nInserting %c at position : %*d",newStrand->base,width,newMutation.position); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = strandIterator; strandFollower->next = newStrand; genomeLength++; } else{ strandFollower->next = strandIterator->next; strandIterator->next = NULL; printf("\nDeleting %c at position : %*d",strandIterator->base,width,newMutation.position); free(strandIterator); genomeLength--; } } } int main(int argc,char* argv[]) { int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10; if(argc==1||argc>6){ printf("Usage : %s <Genome Length> <Optional number of mutations> <Optional Swapping weight> <Optional Insertion weight> <Optional Deletion weight>\n",argv[0]); return 0; } switch(argc){ case 2: genomeLength = atoi(argv[1]); break; case 3: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); break; case 4: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); break; case 5: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); break; case 6: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); deleteWeight = atoi(argv[5]); break; }; srand(time(NULL)); generateStrand(); printf("\nOriginal:"); printGenome(); mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight); printf("\n\nMutated:"); printGenome(); return 0; }
Translate this program into C but keep the logic exactly as in Java.
public class Tau { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } public static void main(String[] args) { final long limit = 100; System.out.printf("The first %d tau numbers are:%n", limit); long count = 0; for (long n = 1; count < limit; ++n) { if (n % divisorCount(n) == 0) { System.out.printf("%6d", n); ++count; if (count % 10 == 0) { System.out.println(); } } } } }
#include <stdio.h> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p; for (; (n & 1) == 0; n >>= 1) { ++total; } for (p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } int main() { const unsigned int limit = 100; unsigned int count = 0; unsigned int n; printf("The first %d tau numbers are:\n", limit); for (n = 1; count < limit; ++n) { if (n % divisor_count(n) == 0) { printf("%6d", n); ++count; if (count % 10 == 0) { printf("\n"); } } } return 0; }
Change the programming language of this snippet from Java to C without modifying what it does.
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j<y){ result[i][j] = a[i+1][j]; }else if(i<x && j>=y){ result[i][j] = a[i][j+1]; }else{ result[i][j] = a[i+1][j+1]; } } return result; } public static double det(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ int sign = 1; double sum = 0; for(int i=0;i<a.length;i++){ sum += sign * a[0][i] * det(minor(a,0,i)); sign *= -1; } return sum; } } public static double perm(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ double sum = 0; for(int i=0;i<a.length;i++){ sum += a[0][i] * perm(minor(a,0,i)); } return sum; } } public static void main(String args[]){ Scanner sc = new Scanner(System.in); int size = sc.nextInt(); double[][] a = new double[size][size]; for(int i=0;i<size;i++) for(int j=0;j<size;j++){ a[i][j] = sc.nextDouble(); } sc.close(); System.out.println("Determinant: "+det(a)); System.out.println("Permanent: "+perm(a)); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) break; m[i] = in[i] + 1; if (!perm) sgn = -sgn; } return sum; } double det(double *in, int n, int perm) { double *m[n]; for (int i = 0; i < n; i++) m[i] = in + (n * i); return det_in(m, n, perm); } int main(void) { double x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; printf("det: %14.12g\n", det(x, 5, 0)); printf("perm: %14.12g\n", det(x, 5, 1)); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j<y){ result[i][j] = a[i+1][j]; }else if(i<x && j>=y){ result[i][j] = a[i][j+1]; }else{ result[i][j] = a[i+1][j+1]; } } return result; } public static double det(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ int sign = 1; double sum = 0; for(int i=0;i<a.length;i++){ sum += sign * a[0][i] * det(minor(a,0,i)); sign *= -1; } return sum; } } public static double perm(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ double sum = 0; for(int i=0;i<a.length;i++){ sum += a[0][i] * perm(minor(a,0,i)); } return sum; } } public static void main(String args[]){ Scanner sc = new Scanner(System.in); int size = sc.nextInt(); double[][] a = new double[size][size]; for(int i=0;i<size;i++) for(int j=0;j<size;j++){ a[i][j] = sc.nextDouble(); } sc.close(); System.out.println("Determinant: "+det(a)); System.out.println("Permanent: "+perm(a)); } }
#include <stdio.h> #include <stdlib.h> #include <string.h> double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0]; double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1; for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == n) break; m[i] = in[i] + 1; if (!perm) sgn = -sgn; } return sum; } double det(double *in, int n, int perm) { double *m[n]; for (int i = 0; i < n; i++) m[i] = in + (n * i); return det_in(m, n, perm); } int main(void) { double x[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; printf("det: %14.12g\n", det(x, 5, 0)); printf("perm: %14.12g\n", det(x, 5, 1)); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
import java.math.BigInteger; public class PartitionFunction { public static void main(String[] args) { long start = System.currentTimeMillis(); BigInteger result = partitions(6666); long end = System.currentTimeMillis(); System.out.println("P(6666) = " + result); System.out.printf("elapsed time: %d milliseconds\n", end - start); } private static BigInteger partitions(int n) { BigInteger[] p = new BigInteger[n + 1]; p[0] = BigInteger.ONE; for (int i = 1; i <= n; ++i) { p[i] = BigInteger.ZERO; for (int k = 1; ; ++k) { int j = (k * (3 * k - 1))/2; if (j > i) break; if ((k & 1) != 0) p[i] = p[i].add(p[i - j]); else p[i] = p[i].subtract(p[i - j]); j += k; if (j > i) break; if ((k & 1) != 0) p[i] = p[i].add(p[i - j]); else p[i] = p[i].subtract(p[i - j]); } } return p[n]; } }
#include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <gmp.h> mpz_t* partition(uint64_t n) { mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t)); mpz_init_set_ui(pn[0], 1); mpz_init_set_ui(pn[1], 1); for (uint64_t i = 2; i < n + 2; i ++) { mpz_init(pn[i]); for (uint64_t k = 1, penta; ; k++) { penta = k * (3 * k - 1) >> 1; if (penta >= i) break; if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]); else mpz_sub(pn[i], pn[i], pn[i - penta]); penta += k; if (penta >= i) break; if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]); else mpz_sub(pn[i], pn[i], pn[i - penta]); } } mpz_t *tmp = &pn[n + 1]; for (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]); free(pn); return tmp; } int main(int argc, char const *argv[]) { clock_t start = clock(); mpz_t *p = partition(6666); gmp_printf("%Zd\n", p); printf("Elapsed time: %.04f seconds\n", (double)(clock() - start) / (double)CLOCKS_PER_SEC); return 0; }
Preserve the algorithm and functionality while converting the code from C# to C++.
static void bitwise(int a, int b) { Console.WriteLine("a and b is {0}", a & b); Console.WriteLine("a or b is {0}", a | b); Console.WriteLine("a xor b is {0}", a ^ b); Console.WriteLine("not a is {0}", ~a); Console.WriteLine("a lshift b is {0}", a << b); Console.WriteLine("a arshift b is {0}", a >> b); uint c = (uint)a; Console.WriteLine("c rshift b is {0}", c >> b); }
#include <iostream> void bitwise(int a, int b) { std::cout << "a and b: " << (a & b) << '\n'; std::cout << "a or b: " << (a | b) << '\n'; std::cout << "a xor b: " << (a ^ b) << '\n'; std::cout << "not a: " << ~a << '\n'; std::cout << "a shl b: " << (a << b) << '\n'; std::cout << "a shr b: " << (a >> b) << '\n'; unsigned int ua = a; std::cout << "a lsr b: " << (ua >> b) << '\n'; std::cout << "a rol b: " << std::rotl(ua, b) << '\n'; std::cout << "a ror b: " << std::rotr(ua, b) << '\n'; }
Generate a C++ translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; public class DragonCurve : Form { private List<int> turns; private double startingAngle, side; public DragonCurve(int iter) { Size = new Size(800, 600); StartPosition = FormStartPosition.CenterScreen; DoubleBuffered = true; BackColor = Color.White; startingAngle = -iter * (Math.PI / 4); side = 400 / Math.Pow(2, iter / 2.0); turns = getSequence(iter); } private List<int> getSequence(int iter) { var turnSequence = new List<int>(); for (int i = 0; i < iter; i++) { var copy = new List<int>(turnSequence); copy.Reverse(); turnSequence.Add(1); foreach (int turn in copy) { turnSequence.Add(-turn); } } return turnSequence; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; double angle = startingAngle; int x1 = 230, y1 = 350; int x2 = x1 + (int)(Math.Cos(angle) * side); int y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; foreach (int turn in turns) { angle += turn * (Math.PI / 2); x2 = x1 + (int)(Math.Cos(angle) * side); y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; } } [STAThread] static void Main() { Application.Run(new DragonCurve(14)); } }
#include <windows.h> #include <iostream> using namespace std; const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class dragonC { public: dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; } void draw( int iterations ) { generate( iterations ); draw(); } private: void generate( int it ) { generator.push_back( 1 ); string temp; for( int y = 0; y < it - 1; y++ ) { temp = generator; temp.push_back( 1 ); for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ ) temp.push_back( !( *x ) ); generator = temp; } } void draw() { HDC dc = bmp.getDC(); unsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff }; int mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0; for( int t = 0; t < 4; t++ ) { int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++]; MoveToEx( dc, a, b, NULL ); bmp.setPenColor( clr[t] ); for( string::iterator x = generator.begin(); x < generator.end(); x++ ) { switch( dir ) { case NORTH: if( *x ) { a += LEN; dir = EAST; } else { a -= LEN; dir = WEST; } break; case EAST: if( *x ) { b += LEN; dir = SOUTH; } else { b -= LEN; dir = NORTH; } break; case SOUTH: if( *x ) { a -= LEN; dir = WEST; } else { a += LEN; dir = EAST; } break; case WEST: if( *x ) { b -= LEN; dir = NORTH; } else { b += LEN; dir = SOUTH; } } LineTo( dc, a, b ); } } bmp.saveBitmap( "f:/rc/dragonCpp.bmp" ); } int dir; myBitmap bmp; string generator; }; int main( int argc, char* argv[] ) { dragonC d; d.draw( 17 ); return system( "pause" ); }
Please provide an equivalent version of this C# code in C++.
foreach (string readLine in File.ReadLines("FileName")) DoSomething(readLine);
#include <fstream> #include <string> #include <iostream> int main( int argc , char** argv ) { int linecount = 0 ; std::string line ; std::ifstream infile( argv[ 1 ] ) ; if ( infile ) { while ( getline( infile , line ) ) { std::cout << linecount << ": " << line << '\n' ; linecount++ ; } } infile.close( ) ; return 0 ; }
Convert this C# snippet to C++ and keep its semantics consistent.
static void InsertAfter(Link prev, int i) { if (prev.next != null) { prev.next.prev = new Link() { item = i, prev = prev, next = prev.next }; prev.next = prev.next.prev; } else prev.next = new Link() { item = i, prev = prev }; }
template <typename T> void insert_after(Node<T>* N, T&& data) { auto node = new Node<T>{N, N->next, std::forward(data)}; if(N->next != nullptr) N->next->prev = node; N->next = node; }
Convert the following code from C# to C++, ensuring the logic remains intact.
using System; using System.Collections.Generic; using System.Linq; namespace QuickSelect { internal static class Program { #region Static Members private static void Main() { var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; Console.WriteLine( "Loop quick select 10 times." ); for( var i = 0 ; i < 10 ; i++ ) { Console.Write( inputArray.NthSmallestElement( i ) ); if( i < 9 ) Console.Write( ", " ); } Console.WriteLine(); Console.WriteLine( "Just sort 10 elements." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "Get 4 smallest and sort them." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "< Press any key >" ); Console.ReadKey(); } #endregion } internal static class ArrayExtension { #region Static Members public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T> { if( count < 0 ) throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." ); if( count == 0 ) return new T[0]; if( array.Length <= count ) return array; return QuickSelectSmallest( array, count - 1 ).Take( count ); } public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T> { if( n < 0 || n > array.Length - 1 ) throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) ); if( array.Length == 0 ) throw new ArgumentException( "Array is empty.", "array" ); if( array.Length == 1 ) return array[ 0 ]; return QuickSelectSmallest( array, n )[ n ]; } private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T> { var partiallySortedArray = (T[]) input.Clone(); var startIndex = 0; var endIndex = input.Length - 1; var pivotIndex = n; var r = new Random(); while( endIndex > startIndex ) { pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex ); if( pivotIndex == n ) break; if( pivotIndex > n ) endIndex = pivotIndex - 1; else startIndex = pivotIndex + 1; pivotIndex = r.Next( startIndex, endIndex ); } return partiallySortedArray; } private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T> { var pivotValue = array[ pivotIndex ]; array.Swap( pivotIndex, endIndex ); for( var i = startIndex ; i < endIndex ; i++ ) { if( array[ i ].CompareTo( pivotValue ) > 0 ) continue; array.Swap( i, startIndex ); startIndex++; } array.Swap( endIndex, startIndex ); return startIndex; } private static void Swap<T>( this T[] array, int index1, int index2 ) { if( index1 == index2 ) return; var temp = array[ index1 ]; array[ index1 ] = array[ index2 ]; array[ index2 ] = temp; } #endregion } }
#include <algorithm> #include <iostream> int main() { for (int i = 0; i < 10; i++) { int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a)); std::cout << a[i]; if (i < 9) std::cout << ", "; } std::cout << std::endl; return 0; }
Translate this program into C++ but keep the logic exactly as in C#.
public static class BaseConverter { public static long stringToLong(string s, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); checked { int slen = s.Length; long result = 0; bool isNegative = false; for ( int i = 0; i < slen; i++ ) { char c = s[i]; int num; if ( c == '-' ) { if ( i != 0 ) throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s"); isNegative = true; continue; } if ( c > 0x2F && c < 0x3A ) num = c - 0x30; else if ( c > 0x40 && c < 0x5B ) num = c - 0x37; else if ( c > 0x60 && c < 0x7B ) num = c - 0x57; else throw new ArgumentException("The string contains an invalid character '" + c + "'", "s"); if ( num >= b ) throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s"); result *= b; result += num; } if ( isNegative ) result = -result; return result; } } public static string longToString(long n, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); if ( b == 10 ) return n.ToString(); checked { long longBase = b; StringBuilder sb = new StringBuilder(); if ( n < 0 ) { n = -n; sb.Append('-'); } long div = 1; while ( n / div >= b ) div *= b; while ( true ) { byte digit = (byte) (n / div); if ( digit < 10 ) sb.Append((char) (digit + 0x30)); else sb.Append((char) (digit + 0x57)); if ( div == 1 ) break; n %= div; div /= b; } return sb.ToString(); } } }
#include <string> #include <cstdlib> #include <algorithm> #include <cassert> std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz"; std::string to_base(unsigned long num, int base) { if (num == 0) return "0"; std::string result; while (num > 0) { std::ldiv_t temp = std::div(num, (long)base); result += digits[temp.rem]; num = temp.quot; } std::reverse(result.begin(), result.end()); return result; } unsigned long from_base(std::string const& num_str, int base) { unsigned long result = 0; for (std::string::size_type pos = 0; pos < num_str.length(); ++pos) result = result * base + digits.find(num_str[pos]); return result; }
Rewrite the snippet below in C++ so it works the same as the original C# code.
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Write a version of this C# function in C++ with identical behavior.
public class Crc32 { #region Constants private const UInt32 s_generator = 0xEDB88320; #endregion #region Constructors public Crc32() { m_checksumTable = Enumerable.Range(0, 256).Select(i => { var tableEntry = (uint)i; for (var j = 0; j < 8; ++j) { tableEntry = ((tableEntry & 1) != 0) ? (s_generator ^ (tableEntry >> 1)) : (tableEntry >> 1); } return tableEntry; }).ToArray(); } #endregion #region Methods public UInt32 Get<T>(IEnumerable<T> byteStream) { try { return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8))); } catch (FormatException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (InvalidCastException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (OverflowException e) { throw new CrcException("Could not read the stream out as bytes.", e); } } #endregion #region Fields private readonly UInt32[] m_checksumTable; #endregion }
#include <algorithm> #include <array> #include <cstdint> #include <numeric> #include <iomanip> #include <iostream> #include <string> std::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept { auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL}; struct byte_checksum { std::uint_fast32_t operator()() noexcept { auto checksum = static_cast<std::uint_fast32_t>(n++); for (auto i = 0; i < 8; ++i) checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0); return checksum; } unsigned n = 0; }; auto table = std::array<std::uint_fast32_t, 256>{}; std::generate(table.begin(), table.end(), byte_checksum{}); return table; } template <typename InputIterator> std::uint_fast32_t crc(InputIterator first, InputIterator last) { static auto const table = generate_crc_lookup_table(); return std::uint_fast32_t{0xFFFFFFFFuL} & ~std::accumulate(first, last, ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL}, [](std::uint_fast32_t checksum, std::uint_fast8_t value) { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); }); } int main() { auto const s = std::string{"The quick brown fox jumps over the lazy dog"}; std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\n'; }
Produce a language-to-language conversion: from C# to C++, same semantics.
public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { MyClass instance = new MyClass(); instance.SomeMethod(); instance.Variable = 99; System.Console.WriteLine( "Variable=" + instance.Variable.ToString() ); } }
PRAGMA COMPILER g++ PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive OPTION PARSE FALSE '---The class does the declaring for you CLASS Books public: const char* title; const char* author; const char* subject; int book_id; END CLASS '---pointer to an object declaration (we use a class called Books) DECLARE Book1 TYPE Books '--- the correct syntax for class Book1 = Books() '--- initialize the strings const char* in c++ Book1.title = "C++ Programming to bacon " Book1.author = "anyone" Book1.subject ="RECORD Tutorial" Book1.book_id = 1234567 PRINT "Book title  : " ,Book1.title FORMAT "%s%s\n" PRINT "Book author  : ", Book1.author FORMAT "%s%s\n" PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n" PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"
Rewrite the snippet below in C# so it works the same as the original C++ code.
#include <vector> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <utility> long string2long( const std::string & s ) { long result ; std::istringstream( s ) >> result ; return result ; } bool isKaprekar( long number ) { long long squarenumber = ((long long)number) * number ; std::ostringstream numberbuf ; numberbuf << squarenumber ; std::string numberstring = numberbuf.str( ) ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) { std::string firstpart = numberstring.substr( 0 , i ) , secondpart = numberstring.substr( i ) ; if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) { return false ; } if ( string2long( firstpart ) + string2long( secondpart ) == number ) { return true ; } } return false ; } int main( ) { std::vector<long> kaprekarnumbers ; kaprekarnumbers.push_back( 1 ) ; for ( int i = 2 ; i < 1000001 ; i++ ) { if ( isKaprekar( i ) ) kaprekarnumbers.push_back( i ) ; } std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ; std::cout << "Kaprekar numbers up to 10000: \n" ; while ( *svi < 10000 ) { std::cout << *svi << " " ; svi++ ; } std::cout << '\n' ; std::cout << "All the Kaprekar numbers up to 1000000 :\n" ; std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) , std::ostream_iterator<long>( std::cout , "\n" ) ) ; std::cout << "There are " << kaprekarnumbers.size( ) << " Kaprekar numbers less than one million!\n" ; return 0 ; }
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
Write the same algorithm in C++ as shown in this C# implementation.
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
#include <vector> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <utility> long string2long( const std::string & s ) { long result ; std::istringstream( s ) >> result ; return result ; } bool isKaprekar( long number ) { long long squarenumber = ((long long)number) * number ; std::ostringstream numberbuf ; numberbuf << squarenumber ; std::string numberstring = numberbuf.str( ) ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) { std::string firstpart = numberstring.substr( 0 , i ) , secondpart = numberstring.substr( i ) ; if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) { return false ; } if ( string2long( firstpart ) + string2long( secondpart ) == number ) { return true ; } } return false ; } int main( ) { std::vector<long> kaprekarnumbers ; kaprekarnumbers.push_back( 1 ) ; for ( int i = 2 ; i < 1000001 ; i++ ) { if ( isKaprekar( i ) ) kaprekarnumbers.push_back( i ) ; } std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ; std::cout << "Kaprekar numbers up to 10000: \n" ; while ( *svi < 10000 ) { std::cout << *svi << " " ; svi++ ; } std::cout << '\n' ; std::cout << "All the Kaprekar numbers up to 1000000 :\n" ; std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) , std::ostream_iterator<long>( std::cout , "\n" ) ) ; std::cout << "There are " << kaprekarnumbers.size( ) << " Kaprekar numbers less than one million!\n" ; return 0 ; }
Please provide an equivalent version of this C# code in C++.
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
#include <iomanip> #include <iostream> #include <set> #include <vector> using namespace std; unsigned hofstadter(unsigned rlistSize, unsigned slistSize) { auto n = rlistSize > slistSize ? rlistSize : slistSize; auto rlist = new vector<unsigned> { 1, 3, 7 }; auto slist = new vector<unsigned> { 2, 4, 5, 6 }; auto list = rlistSize > 0 ? rlist : slist; auto target_size = rlistSize > 0 ? rlistSize : slistSize; while (list->size() > target_size) list->pop_back(); while (list->size() < target_size) { auto lastIndex = rlist->size() - 1; auto lastr = (*rlist)[lastIndex]; auto r = lastr + (*slist)[lastIndex]; rlist->push_back(r); for (auto s = lastr + 1; s < r && list->size() < target_size;) slist->push_back(s++); } auto v = (*list)[n - 1]; delete rlist; delete slist; return v; } ostream& operator<<(ostream& os, const set<unsigned>& s) { cout << '(' << s.size() << "):"; auto i = 0; for (auto c = s.begin(); c != s.end();) { if (i++ % 20 == 0) os << endl; os << setw(5) << *c++; } return os; } int main(int argc, const char* argv[]) { const auto v1 = atoi(argv[1]); const auto v2 = atoi(argv[2]); set<unsigned> r, s; for (auto n = 1; n <= v2; n++) { if (n <= v1) r.insert(hofstadter(n, 0)); s.insert(hofstadter(0, n)); } cout << "R" << r << endl; cout << "S" << s << endl; int m = max(*r.rbegin(), *s.rbegin()); for (auto n = 1; n <= m; n++) if (r.count(n) == s.count(n)) clog << "integer " << n << " either in both or neither set" << endl; return 0; }
Change the following C++ code into C# without altering its purpose.
#include <iomanip> #include <iostream> #include <set> #include <vector> using namespace std; unsigned hofstadter(unsigned rlistSize, unsigned slistSize) { auto n = rlistSize > slistSize ? rlistSize : slistSize; auto rlist = new vector<unsigned> { 1, 3, 7 }; auto slist = new vector<unsigned> { 2, 4, 5, 6 }; auto list = rlistSize > 0 ? rlist : slist; auto target_size = rlistSize > 0 ? rlistSize : slistSize; while (list->size() > target_size) list->pop_back(); while (list->size() < target_size) { auto lastIndex = rlist->size() - 1; auto lastr = (*rlist)[lastIndex]; auto r = lastr + (*slist)[lastIndex]; rlist->push_back(r); for (auto s = lastr + 1; s < r && list->size() < target_size;) slist->push_back(s++); } auto v = (*list)[n - 1]; delete rlist; delete slist; return v; } ostream& operator<<(ostream& os, const set<unsigned>& s) { cout << '(' << s.size() << "):"; auto i = 0; for (auto c = s.begin(); c != s.end();) { if (i++ % 20 == 0) os << endl; os << setw(5) << *c++; } return os; } int main(int argc, const char* argv[]) { const auto v1 = atoi(argv[1]); const auto v2 = atoi(argv[2]); set<unsigned> r, s; for (auto n = 1; n <= v2; n++) { if (n <= v1) r.insert(hofstadter(n, 0)); s.insert(hofstadter(0, n)); } cout << "R" << r << endl; cout << "S" << s << endl; int m = max(*r.rbegin(), *s.rbegin()); for (auto n = 1; n <= m; n++) if (r.count(n) == s.count(n)) clog << "integer " << n << " either in both or neither set" << endl; return 0; }
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
Generate an equivalent C++ version of this C# code.
static int Fib(int n) { if (n < 0) throw new ArgumentException("Must be non negativ", "n"); Func<int, int> fib = null; fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p; return fib(n); }
double fib(double n) { if(n < 0) { throw "Invalid argument passed to fib"; } else { struct actual_fib { static double calc(double n) { if(n < 2) { return n; } else { return calc(n-1) + calc(n-2); } } }; return actual_fib::calc(n); } }
Change the programming language of this snippet from C++ to C# without modifying what it does.
#include <vector> #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <iomanip> typedef unsigned int uint; using namespace std; const uint TAPE_MAX_LEN = 49152; struct action { char write, direction; }; class tape { public: tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); } void reset() { clear( '0' ); headPos = _sp; } char read(){ return _t[headPos]; } void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; } void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); } void action( const action* a ) { write( a->write ); move( a->direction ); } void print( int c = 10 ) { int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx; for( int x = st; x < ed; x++ ) { tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } cout << endl << setw( c + 1 ) << "^" << endl; } private: void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; } void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } } string _t; uint headPos, _sp; char blk; const uint MAX_LEN; }; class state { public: bool operator ==( const string o ) { return o == name; } string name, next; char symbol, write, direction; }; class actionTable { public: bool loadTable( string file ) { reset(); ifstream mf; mf.open( file.c_str() ); if( mf.is_open() ) { string str; state stt; while( mf.good() ) { getline( mf, str ); if( str[0] == '\'' ) break; parseState( str, stt ); states.push_back( stt ); } while( mf.good() ) { getline( mf, str ); if( str == "" ) continue; if( str[0] == '!' ) blank = str.erase( 0, 1 )[0]; if( str[0] == '^' ) curState = str.erase( 0, 1 ); if( str[0] == '>' ) input = str.erase( 0, 1 ); } mf.close(); return true; } cout << "Could not open " << file << endl; return false; } bool action( char symbol, action& a ) { vector<state>::iterator f = states.begin(); while( true ) { f = find( f, states.end(), curState ); if( f == states.end() ) return false; if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) ) { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; } f++; } return true; } void reset() { states.clear(); blank = '0'; curState = input = ""; } string getInput() { return input; } char getBlank() { return blank; } private: void parseState( string str, state& stt ) { string a[5]; int idx = 0; for( string::iterator si = str.begin(); si != str.end(); si++ ) { if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); } stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4]; } vector<state> states; char blank; string curState, input; }; class utm { public: utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; } void start() { while( true ) { reset(); int t = showMenu(); if( t == 0 ) return; if( !at.loadTable( files[t - 1] ) ) return; startMachine(); } } private: void simulate() { char r; action a; while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); } cout << endl << endl; system( "pause" ); } int showMenu() { int t = -1; while( t < 0 || t > 3 ) { system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit"; cout << endl << endl << "Choose an action "; cin >> t; } return t; } void reset() { tp.reset(); at.reset(); } void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); } tape tp; actionTable at; string files[7]; }; int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
Write a version of this C# function in C++ with identical behavior.
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
#include <vector> #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <iomanip> typedef unsigned int uint; using namespace std; const uint TAPE_MAX_LEN = 49152; struct action { char write, direction; }; class tape { public: tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); } void reset() { clear( '0' ); headPos = _sp; } char read(){ return _t[headPos]; } void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; } void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); } void action( const action* a ) { write( a->write ); move( a->direction ); } void print( int c = 10 ) { int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx; for( int x = st; x < ed; x++ ) { tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } cout << endl << setw( c + 1 ) << "^" << endl; } private: void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; } void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } } string _t; uint headPos, _sp; char blk; const uint MAX_LEN; }; class state { public: bool operator ==( const string o ) { return o == name; } string name, next; char symbol, write, direction; }; class actionTable { public: bool loadTable( string file ) { reset(); ifstream mf; mf.open( file.c_str() ); if( mf.is_open() ) { string str; state stt; while( mf.good() ) { getline( mf, str ); if( str[0] == '\'' ) break; parseState( str, stt ); states.push_back( stt ); } while( mf.good() ) { getline( mf, str ); if( str == "" ) continue; if( str[0] == '!' ) blank = str.erase( 0, 1 )[0]; if( str[0] == '^' ) curState = str.erase( 0, 1 ); if( str[0] == '>' ) input = str.erase( 0, 1 ); } mf.close(); return true; } cout << "Could not open " << file << endl; return false; } bool action( char symbol, action& a ) { vector<state>::iterator f = states.begin(); while( true ) { f = find( f, states.end(), curState ); if( f == states.end() ) return false; if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) ) { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; } f++; } return true; } void reset() { states.clear(); blank = '0'; curState = input = ""; } string getInput() { return input; } char getBlank() { return blank; } private: void parseState( string str, state& stt ) { string a[5]; int idx = 0; for( string::iterator si = str.begin(); si != str.end(); si++ ) { if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); } stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4]; } vector<state> states; char blank; string curState, input; }; class utm { public: utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; } void start() { while( true ) { reset(); int t = showMenu(); if( t == 0 ) return; if( !at.loadTable( files[t - 1] ) ) return; startMachine(); } } private: void simulate() { char r; action a; while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); } cout << endl << endl; system( "pause" ); } int showMenu() { int t = -1; while( t < 0 || t > 3 ) { system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit"; cout << endl << endl << "Choose an action "; cin >> t; } return t; } void reset() { tp.reset(); at.reset(); } void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); } tape tp; actionTable at; string files[7]; }; int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
Port the following code from C# to C++ with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
#include <vector> #include <string> #include <iostream> #include <algorithm> #include <fstream> #include <iomanip> typedef unsigned int uint; using namespace std; const uint TAPE_MAX_LEN = 49152; struct action { char write, direction; }; class tape { public: tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); } void reset() { clear( '0' ); headPos = _sp; } char read(){ return _t[headPos]; } void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; } void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); } void action( const action* a ) { write( a->write ); move( a->direction ); } void print( int c = 10 ) { int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx; for( int x = st; x < ed; x++ ) { tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; } cout << endl << setw( c + 1 ) << "^" << endl; } private: void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; } void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } } string _t; uint headPos, _sp; char blk; const uint MAX_LEN; }; class state { public: bool operator ==( const string o ) { return o == name; } string name, next; char symbol, write, direction; }; class actionTable { public: bool loadTable( string file ) { reset(); ifstream mf; mf.open( file.c_str() ); if( mf.is_open() ) { string str; state stt; while( mf.good() ) { getline( mf, str ); if( str[0] == '\'' ) break; parseState( str, stt ); states.push_back( stt ); } while( mf.good() ) { getline( mf, str ); if( str == "" ) continue; if( str[0] == '!' ) blank = str.erase( 0, 1 )[0]; if( str[0] == '^' ) curState = str.erase( 0, 1 ); if( str[0] == '>' ) input = str.erase( 0, 1 ); } mf.close(); return true; } cout << "Could not open " << file << endl; return false; } bool action( char symbol, action& a ) { vector<state>::iterator f = states.begin(); while( true ) { f = find( f, states.end(), curState ); if( f == states.end() ) return false; if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) ) { a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; } f++; } return true; } void reset() { states.clear(); blank = '0'; curState = input = ""; } string getInput() { return input; } char getBlank() { return blank; } private: void parseState( string str, state& stt ) { string a[5]; int idx = 0; for( string::iterator si = str.begin(); si != str.end(); si++ ) { if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); } stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4]; } vector<state> states; char blank; string curState, input; }; class utm { public: utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; } void start() { while( true ) { reset(); int t = showMenu(); if( t == 0 ) return; if( !at.loadTable( files[t - 1] ) ) return; startMachine(); } } private: void simulate() { char r; action a; while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); } cout << endl << endl; system( "pause" ); } int showMenu() { int t = -1; while( t < 0 || t > 3 ) { system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit"; cout << endl << endl << "Choose an action "; cin >> t; } return t; } void reset() { tp.reset(); at.reset(); } void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); } tape tp; actionTable at; string files[7]; }; int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the C# version.
using System; using System.IO; class Program { static void Main(string[] args) { File.Create("output.txt"); File.Create(@"\output.txt"); Directory.CreateDirectory("docs"); Directory.CreateDirectory(@"\docs"); } }
#include <direct.h> #include <fstream> int main() { std::fstream f("output.txt", std::ios::out); f.close(); f.open("/output.txt", std::ios::out); f.close(); _mkdir("docs"); _mkdir("/docs"); return 0; }
Ensure the translated C++ code behaves exactly like the original C# snippet.
using System; interface IOperable { string Operate(); } class Inoperable { } class Operable : IOperable { public string Operate() { return "Delegate implementation."; } } class Delegator : IOperable { object Delegate; public string Operate() { var operable = Delegate as IOperable; return operable != null ? operable.Operate() : "Default implementation."; } static void Main() { var delegator = new Delegator(); foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() }) { delegator.Delegate = @delegate; Console.WriteLine(delegator.Operate()); } } }
#include <tr1/memory> #include <string> #include <iostream> #include <tr1/functional> using namespace std; using namespace std::tr1; using std::tr1::function; class IDelegate { public: virtual ~IDelegate() {} }; class IThing { public: virtual ~IThing() {} virtual std::string Thing() = 0; }; class DelegateA : virtual public IDelegate { }; class DelegateB : public IThing, public IDelegate { std::string Thing() { return "delegate implementation"; } }; class Delegator { public: std::string Operation() { if(Delegate) if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get())) return pThing->Thing(); return "default implementation"; } shared_ptr<IDelegate> Delegate; }; int main() { shared_ptr<DelegateA> delegateA(new DelegateA()); shared_ptr<DelegateB> delegateB(new DelegateB()); Delegator delegator; std::cout << delegator.Operation() << std::endl; delegator.Delegate = delegateA; std::cout << delegator.Operation() << std::endl; delegator.Delegate = delegateB; std::cout << delegator.Operation() << std::endl; }
Produce a functionally identical C++ code for the snippet given in C#.
using System; interface IOperable { string Operate(); } class Inoperable { } class Operable : IOperable { public string Operate() { return "Delegate implementation."; } } class Delegator : IOperable { object Delegate; public string Operate() { var operable = Delegate as IOperable; return operable != null ? operable.Operate() : "Default implementation."; } static void Main() { var delegator = new Delegator(); foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() }) { delegator.Delegate = @delegate; Console.WriteLine(delegator.Operate()); } } }
#include <tr1/memory> #include <string> #include <iostream> #include <tr1/functional> using namespace std; using namespace std::tr1; using std::tr1::function; class IDelegate { public: virtual ~IDelegate() {} }; class IThing { public: virtual ~IThing() {} virtual std::string Thing() = 0; }; class DelegateA : virtual public IDelegate { }; class DelegateB : public IThing, public IDelegate { std::string Thing() { return "delegate implementation"; } }; class Delegator { public: std::string Operation() { if(Delegate) if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get())) return pThing->Thing(); return "default implementation"; } shared_ptr<IDelegate> Delegate; }; int main() { shared_ptr<DelegateA> delegateA(new DelegateA()); shared_ptr<DelegateB> delegateB(new DelegateB()); Delegator delegator; std::cout << delegator.Operation() << std::endl; delegator.Delegate = delegateA; std::cout << delegator.Operation() << std::endl; delegator.Delegate = delegateB; std::cout << delegator.Operation() << std::endl; }
Transform the following C# implementation into C++, maintaining the same output and logic.
readonly DateTime now = DateTime.Now;
#include <iostream> class MyOtherClass { public: const int m_x; MyOtherClass(const int initX = 0) : m_x(initX) { } }; int main() { MyOtherClass mocA, mocB(7); std::cout << mocA.m_x << std::endl; std::cout << mocB.m_x << std::endl; return 0; }
Write a version of this C# function in C++ with identical behavior.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaconCipher { class Program { private static Dictionary<char, string> codes = new Dictionary<char, string> { {'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" }, {'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" }, {'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" }, {'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" }, {'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" }, {'z', "BBAAB" }, {' ', "BBBAA" }, }; private static string Encode(string plainText, string message) { string pt = plainText.ToLower(); StringBuilder sb = new StringBuilder(); foreach (char c in pt) { if ('a' <= c && c <= 'z') sb.Append(codes[c]); else sb.Append(codes[' ']); } string et = sb.ToString(); string mg = message.ToLower(); sb.Length = 0; int count = 0; foreach (char c in mg) { if ('a' <= c && c <= 'z') { if (et[count] == 'A') sb.Append(c); else sb.Append((char)(c - 32)); count++; if (count == et.Length) break; } else sb.Append(c); } return sb.ToString(); } private static string Decode(string message) { StringBuilder sb = new StringBuilder(); foreach (char c in message) { if ('a' <= c && c <= 'z') sb.Append('A'); else if ('A' <= c && c <= 'Z') sb.Append('B'); } string et = sb.ToString(); sb.Length = 0; for (int i = 0; i < et.Length; i += 5) { string quintet = et.Substring(i, 5); char key = codes.Where(a => a.Value == quintet).First().Key; sb.Append(key); } return sb.ToString(); } static void Main(string[] args) { string plainText = "the quick brown fox jumps over the lazy dog"; string message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; string cipherText = Encode(plainText, message); Console.WriteLine("Cipher text ->\n{0}", cipherText); string decodedText = Decode(cipherText); Console.WriteLine("\nHidden text ->\n{0}", decodedText); } } }
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Ensure the translated C++ code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaconCipher { class Program { private static Dictionary<char, string> codes = new Dictionary<char, string> { {'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" }, {'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" }, {'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" }, {'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" }, {'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" }, {'z', "BBAAB" }, {' ', "BBBAA" }, }; private static string Encode(string plainText, string message) { string pt = plainText.ToLower(); StringBuilder sb = new StringBuilder(); foreach (char c in pt) { if ('a' <= c && c <= 'z') sb.Append(codes[c]); else sb.Append(codes[' ']); } string et = sb.ToString(); string mg = message.ToLower(); sb.Length = 0; int count = 0; foreach (char c in mg) { if ('a' <= c && c <= 'z') { if (et[count] == 'A') sb.Append(c); else sb.Append((char)(c - 32)); count++; if (count == et.Length) break; } else sb.Append(c); } return sb.ToString(); } private static string Decode(string message) { StringBuilder sb = new StringBuilder(); foreach (char c in message) { if ('a' <= c && c <= 'z') sb.Append('A'); else if ('A' <= c && c <= 'Z') sb.Append('B'); } string et = sb.ToString(); sb.Length = 0; for (int i = 0; i < et.Length; i += 5) { string quintet = et.Substring(i, 5); char key = codes.Where(a => a.Value == quintet).First().Key; sb.Append(key); } return sb.ToString(); } static void Main(string[] args) { string plainText = "the quick brown fox jumps over the lazy dog"; string message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; string cipherText = Encode(plainText, message); Console.WriteLine("Cipher text ->\n{0}", cipherText); string decodedText = Decode(cipherText); Console.WriteLine("\nHidden text ->\n{0}", decodedText); } } }
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Convert this C# snippet to C++ and keep its semantics consistent.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaconCipher { class Program { private static Dictionary<char, string> codes = new Dictionary<char, string> { {'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" }, {'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" }, {'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" }, {'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" }, {'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" }, {'z', "BBAAB" }, {' ', "BBBAA" }, }; private static string Encode(string plainText, string message) { string pt = plainText.ToLower(); StringBuilder sb = new StringBuilder(); foreach (char c in pt) { if ('a' <= c && c <= 'z') sb.Append(codes[c]); else sb.Append(codes[' ']); } string et = sb.ToString(); string mg = message.ToLower(); sb.Length = 0; int count = 0; foreach (char c in mg) { if ('a' <= c && c <= 'z') { if (et[count] == 'A') sb.Append(c); else sb.Append((char)(c - 32)); count++; if (count == et.Length) break; } else sb.Append(c); } return sb.ToString(); } private static string Decode(string message) { StringBuilder sb = new StringBuilder(); foreach (char c in message) { if ('a' <= c && c <= 'z') sb.Append('A'); else if ('A' <= c && c <= 'Z') sb.Append('B'); } string et = sb.ToString(); sb.Length = 0; for (int i = 0; i < et.Length; i += 5) { string quintet = et.Substring(i, 5); char key = codes.Where(a => a.Value == quintet).First().Key; sb.Append(key); } return sb.ToString(); } static void Main(string[] args) { string plainText = "the quick brown fox jumps over the lazy dog"; string message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; string cipherText = Encode(plainText, message); Console.WriteLine("Cipher text ->\n{0}", cipherText); string decodedText = Decode(cipherText); Console.WriteLine("\nHidden text ->\n{0}", decodedText); } } }
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Write a version of this C# function in C++ with identical behavior.
public int[,] Spiral(int n) { int[,] result = new int[n, n]; int pos = 0; int count = n; int value = -n; int sum = -1; do { value = -1 * value / n; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } value *= n; count--; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } } while (count > 0); return result; } public void PrintArray(int[,] array) { int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1; for (int i = 0; i < array.GetLength(0); i++) { for (int j = 0; j < array.GetLength(1); j++) { Console.Write(array[i, j].ToString().PadLeft(n, ' ')); } Console.WriteLine(); } }
#include <vector> #include <memory> #include <cmath> #include <iostream> #include <iomanip> using namespace std; typedef vector< int > IntRow; typedef vector< IntRow > IntTable; auto_ptr< IntTable > getSpiralArray( int dimension ) { auto_ptr< IntTable > spiralArrayPtr( new IntTable( dimension, IntRow( dimension ) ) ); int numConcentricSquares = static_cast< int >( ceil( static_cast< double >( dimension ) / 2.0 ) ); int j; int sideLen = dimension; int currNum = 0; for ( int i = 0; i < numConcentricSquares; i++ ) { for ( j = 0; j < sideLen; j++ ) ( *spiralArrayPtr )[ i ][ i + j ] = currNum++; for ( j = 1; j < sideLen; j++ ) ( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++; for ( j = sideLen - 2; j > -1; j-- ) ( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++; for ( j = sideLen - 2; j > 0; j-- ) ( *spiralArrayPtr )[ i + j ][ i ] = currNum++; sideLen -= 2; } return spiralArrayPtr; } void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr ) { size_t dimension = spiralArrayPtr->size(); int fieldWidth = static_cast< int >( floor( log10( static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; size_t col; for ( size_t row = 0; row < dimension; row++ ) { for ( col = 0; col < dimension; col++ ) cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ]; cout << endl; } } int main() { printSpiralArray( getSpiralArray( 5 ) ); }
Translate the given C# code snippet into C++ without altering its behavior.
using System; namespace FaulhabersTriangle { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { throw new ArgumentException("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.Abs(Gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } private static long Gcd(long a, long b) { if (b == 0) { return a; } return Gcd(b, a % b); } public static Frac operator -(Frac self) { return new Frac(-self.num, self.denom); } public static Frac operator +(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom); } public static Frac operator -(Frac lhs, Frac rhs) { return lhs + -rhs; } public static Frac operator *(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom); } public static bool operator <(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x < y; } public static bool operator >(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x > y; } public static bool operator ==(Frac lhs, Frac rhs) { return lhs.num == rhs.num && lhs.denom == rhs.denom; } public static bool operator !=(Frac lhs, Frac rhs) { return lhs.num != rhs.num || lhs.denom != rhs.denom; } public override string ToString() { if (denom == 1) { return num.ToString(); } return string.Format("{0}/{1}", num, denom); } public override bool Equals(object obj) { var frac = obj as Frac; return frac != null && num == frac.num && denom == frac.denom; } public override int GetHashCode() { var hashCode = 1317992671; hashCode = hashCode * -1521134295 + num.GetHashCode(); hashCode = hashCode * -1521134295 + denom.GetHashCode(); return hashCode; } } class Program { static Frac Bernoulli(int n) { if (n < 0) { throw new ArgumentException("n may not be negative or zero"); } Frac[] a = new Frac[n + 1]; for (int m = 0; m <= n; m++) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1); } } if (n != 1) return a[0]; return -a[0]; } static int Binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw new ArgumentException(); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num = num * i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom = denom * i; } return num / denom; } static Frac[] FaulhaberTriangle(int p) { Frac[] coeffs = new Frac[p + 1]; for (int i = 0; i < p + 1; i++) { coeffs[i] = Frac.ZERO; } Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j); } return coeffs; } static void Main(string[] args) { for (int i = 0; i < 10; i++) { Frac[] coeffs = FaulhaberTriangle(i); foreach (Frac coeff in coeffs) { Console.Write("{0,5} ", coeff); } Console.WriteLine(); } } } }
#include <exception> #include <iomanip> #include <iostream> #include <numeric> #include <sstream> #include <vector> class Frac { public: Frac() : num(0), denom(1) {} Frac(int n, int d) { if (d == 0) { throw std::runtime_error("d must not be zero"); } int sign_of_d = d < 0 ? -1 : 1; int g = std::gcd(n, d); num = sign_of_d * n / g; denom = sign_of_d * d / g; } Frac operator-() const { return Frac(-num, denom); } Frac operator+(const Frac& rhs) const { return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom); } Frac operator-(const Frac& rhs) const { return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom); } Frac operator*(const Frac& rhs) const { return Frac(num*rhs.num, denom*rhs.denom); } Frac operator*(int rhs) const { return Frac(num * rhs, denom); } friend std::ostream& operator<<(std::ostream&, const Frac&); private: int num; int denom; }; std::ostream & operator<<(std::ostream & os, const Frac &f) { if (f.num == 0 || f.denom == 1) { return os << f.num; } std::stringstream ss; ss << f.num << "/" << f.denom; return os << ss.str(); } Frac bernoulli(int n) { if (n < 0) { throw std::runtime_error("n may not be negative or zero"); } std::vector<Frac> a; for (int m = 0; m <= n; m++) { a.push_back(Frac(1, m + 1)); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * j; } } if (n != 1) return a[0]; return -a[0]; } int binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw std::runtime_error("parameters are invalid"); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num *= i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom *= i; } return num / denom; } std::vector<Frac> faulhaberTraingle(int p) { std::vector<Frac> coeffs(p + 1); Frac q{ 1, p + 1 }; int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j); } return coeffs; } int main() { for (int i = 0; i < 10; i++) { std::vector<Frac> coeffs = faulhaberTraingle(i); for (auto frac : coeffs) { std::cout << std::right << std::setw(5) << frac << " "; } std::cout << std::endl; } return 0; }
Produce a functionally identical C++ code for the snippet given in C#.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl; return 0; }
Write a version of this C++ function in C# with identical behavior.
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl; return 0; }
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
Keep all operations the same but rewrite the snippet in C++.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { int[] a = { 1, 2, 3 }; int[] b = { 4, 5, 6 }; int[] c = new int[a.Length + b.Length]; a.CopyTo(c, 0); b.CopyTo(c, a.Length); foreach(int n in c) { Console.WriteLine(n.ToString()); } } } }
#include <vector> #include <iostream> int main() { std::vector<int> a(3), b(4); a[0] = 11; a[1] = 12; a[2] = 13; b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24; a.insert(a.end(), b.begin(), b.end()); for (int i = 0; i < a.size(); ++i) std::cout << "a[" << i << "] = " << a[i] << "\n"; }
Generate an equivalent C++ version of this C# code.
using System; namespace C_Sharp_Console { class example { static void Main() { string word; int num; Console.Write("Enter an integer: "); num = Console.Read(); Console.Write("Enter a String: "); word = Console.ReadLine(); } } }
#include <iostream> #include <string> using namespace std; int main() { long int integer_input; string string_input; cout << "Enter an integer: "; cin >> integer_input; cout << "Enter a string: "; cin >> string_input; return 0; }
Change the programming language of this snippet from C# to C++ without modifying what it does.
using System; using System.Collections.Generic; namespace Tests_With_Framework_4 { class Bag : IEnumerable<Bag.Item> { List<Item> items; const int MaxWeightAllowed = 400; public Bag() { items = new List<Item>(); } void AddItem(Item i) { if ((TotalWeight + i.Weight) <= MaxWeightAllowed) items.Add(i); } public void Calculate(List<Item> items) { foreach (Item i in Sorte(items)) { AddItem(i); } } List<Item> Sorte(List<Item> inputItems) { List<Item> choosenItems = new List<Item>(); for (int i = 0; i < inputItems.Count; i++) { int j = -1; if (i == 0) { choosenItems.Add(inputItems[i]); } if (i > 0) { if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j)) { choosenItems.Add(inputItems[i]); } } } return choosenItems; } bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd) { if (!(lastBound < 0)) { if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV ) { indxToAdd = lastBound; } return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd); } if (indxToAdd > -1) { choosenItems.Insert(indxToAdd, knapsackItems[i]); return true; } return false; } #region IEnumerable<Item> Members IEnumerator<Item> IEnumerable<Item>.GetEnumerator() { foreach (Item i in items) yield return i; } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return items.GetEnumerator(); } #endregion public int TotalWeight { get { var sum = 0; foreach (Item i in this) { sum += i.Weight; } return sum; } } public class Item { public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return Weight-Value; } } public override string ToString() { return "Name : " + Name + " Wieght : " + Weight + " Value : " + Value + " ResultWV : " + ResultWV; } } } class Program { static void Main(string[] args) {List<Bag.Item> knapsackItems = new List<Bag.Item>(); knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 }); knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 }); knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 }); knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 }); knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 }); knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 }); knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 }); knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 }); knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 }); knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 }); knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 }); Bag b = new Bag(); b.Calculate(knapsackItems); b.All(x => { Console.WriteLine(x); return true; }); Console.WriteLine(b.Sum(x => x.Weight)); Console.ReadKey(); } } }
#include <vector> #include <string> #include <iostream> #include <boost/tuple/tuple.hpp> #include <set> int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , std::set<int> & , const int ) ; int main( ) { std::vector<boost::tuple<std::string , int , int> > items ; items.push_back( boost::make_tuple( "" , 0 , 0 ) ) ; items.push_back( boost::make_tuple( "map" , 9 , 150 ) ) ; items.push_back( boost::make_tuple( "compass" , 13 , 35 ) ) ; items.push_back( boost::make_tuple( "water" , 153 , 200 ) ) ; items.push_back( boost::make_tuple( "sandwich", 50 , 160 ) ) ; items.push_back( boost::make_tuple( "glucose" , 15 , 60 ) ) ; items.push_back( boost::make_tuple( "tin", 68 , 45 ) ) ; items.push_back( boost::make_tuple( "banana", 27 , 60 ) ) ; items.push_back( boost::make_tuple( "apple" , 39 , 40 ) ) ; items.push_back( boost::make_tuple( "cheese" , 23 , 30 ) ) ; items.push_back( boost::make_tuple( "beer" , 52 , 10 ) ) ; items.push_back( boost::make_tuple( "suntan creme" , 11 , 70 ) ) ; items.push_back( boost::make_tuple( "camera" , 32 , 30 ) ) ; items.push_back( boost::make_tuple( "T-shirt" , 24 , 15 ) ) ; items.push_back( boost::make_tuple( "trousers" , 48 , 10 ) ) ; items.push_back( boost::make_tuple( "umbrella" , 73 , 40 ) ) ; items.push_back( boost::make_tuple( "waterproof trousers" , 42 , 70 ) ) ; items.push_back( boost::make_tuple( "waterproof overclothes" , 43 , 75 ) ) ; items.push_back( boost::make_tuple( "note-case" , 22 , 80 ) ) ; items.push_back( boost::make_tuple( "sunglasses" , 7 , 20 ) ) ; items.push_back( boost::make_tuple( "towel" , 18 , 12 ) ) ; items.push_back( boost::make_tuple( "socks" , 4 , 50 ) ) ; items.push_back( boost::make_tuple( "book" , 30 , 10 ) ) ; const int maximumWeight = 400 ; std::set<int> bestItems ; int bestValue = findBestPack( items , bestItems , maximumWeight ) ; std::cout << "The best value that can be packed in the given knapsack is " << bestValue << " !\n" ; int totalweight = 0 ; std::cout << "The following items should be packed in the knapsack:\n" ; for ( std::set<int>::const_iterator si = bestItems.begin( ) ; si != bestItems.end( ) ; si++ ) { std::cout << (items.begin( ) + *si)->get<0>( ) << "\n" ; totalweight += (items.begin( ) + *si)->get<1>( ) ; } std::cout << "The total weight of all items is " << totalweight << " !\n" ; return 0 ; } int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) { const int n = items.size( ) ; int bestValues [ n ][ weightlimit ] ; std::set<int> solutionSets[ n ][ weightlimit ] ; std::set<int> emptyset ; for ( int i = 0 ; i < n ; i++ ) { for ( int j = 0 ; j < weightlimit ; j++ ) { bestValues[ i ][ j ] = 0 ; solutionSets[ i ][ j ] = emptyset ; } } for ( int i = 0 ; i < n ; i++ ) { for ( int weight = 0 ; weight < weightlimit ; weight++ ) { if ( i == 0 ) bestValues[ i ][ weight ] = 0 ; else { int itemweight = (items.begin( ) + i)->get<1>( ) ; if ( weight < itemweight ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } else { if ( bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) > bestValues[ i - 1 ][ weight ] ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight - itemweight ] ; solutionSets[ i ][ weight ].insert( i ) ; } else { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } } } } } bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ; return bestValues[ n - 1 ][ weightlimit - 1 ] ; }
Rewrite this program in C# while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <vector> #include <algorithm> void print(const std::vector<std::vector<int>>& v) { std::cout << "{ "; for (const auto& p : v) { std::cout << "("; for (const auto& e : p) { std::cout << e << " "; } std::cout << ") "; } std::cout << "}" << std::endl; } auto product(const std::vector<std::vector<int>>& lists) { std::vector<std::vector<int>> result; if (std::find_if(std::begin(lists), std::end(lists), [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) { return result; } for (auto& e : lists[0]) { result.push_back({ e }); } for (size_t i = 1; i < lists.size(); ++i) { std::vector<std::vector<int>> temp; for (auto& e : result) { for (auto f : lists[i]) { auto e_tmp = e; e_tmp.push_back(f); temp.push_back(e_tmp); } } result = temp; } return result; } int main() { std::vector<std::vector<int>> prods[] = { { { 1, 2 }, { 3, 4 } }, { { 3, 4 }, { 1, 2} }, { { 1, 2 }, { } }, { { }, { 1, 2 } }, { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } }, { { 1, 2, 3 }, { 30 }, { 500, 100 } }, { { 1, 2, 3 }, { }, { 500, 100 } } }; for (const auto& p : prods) { print(product(p)); } std::cin.ignore(); std::cin.get(); return 0; }
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
Produce a language-to-language conversion: from C# to C++, same semantics.
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
#include <iostream> #include <vector> #include <algorithm> void print(const std::vector<std::vector<int>>& v) { std::cout << "{ "; for (const auto& p : v) { std::cout << "("; for (const auto& e : p) { std::cout << e << " "; } std::cout << ") "; } std::cout << "}" << std::endl; } auto product(const std::vector<std::vector<int>>& lists) { std::vector<std::vector<int>> result; if (std::find_if(std::begin(lists), std::end(lists), [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) { return result; } for (auto& e : lists[0]) { result.push_back({ e }); } for (size_t i = 1; i < lists.size(); ++i) { std::vector<std::vector<int>> temp; for (auto& e : result) { for (auto f : lists[i]) { auto e_tmp = e; e_tmp.push_back(f); temp.push_back(e_tmp); } } result = temp; } return result; } int main() { std::vector<std::vector<int>> prods[] = { { { 1, 2 }, { 3, 4 } }, { { 3, 4 }, { 1, 2} }, { { 1, 2 }, { } }, { { }, { 1, 2 } }, { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } }, { { 1, 2, 3 }, { 30 }, { 500, 100 } }, { { 1, 2, 3 }, { }, { 500, 100 } } }; for (const auto& p : prods) { print(product(p)); } std::cin.ignore(); std::cin.get(); return 0; }