Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate the given Java code snippet into C without altering its behavior.
System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { printf("%d\n", mul_inv(42, 2017)); return 0; }
Transform the following Java implementation into C, maintaining the same output and logic.
Point p = component.getLocation(); Robot robot = new Robot(); robot.mouseMove(p.getX(), p.getY()); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK);
#define WINVER 0x500 #include<windows.h> int main() { int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN); int x = maxX/2, y = maxY/2; double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY; INPUT ip; ZeroMemory(&ip,sizeof(ip)); ip.type = INPUT_MOUSE; while(x > 5 || y < maxY-5){ ip.mi.mouseData = 0; ip.mi.dx = x * factorX; ip.mi.dy = y * factorY; ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; SendInput(1,&ip,sizeof(ip)); Sleep(1); if(x>3) x-=1; if(y<maxY-3) y+=1; } ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP; SendInput(1,&ip,sizeof(ip)); return 0; }
Generate a C translation of this Java snippet without changing its computational steps.
import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class HelloWorld{ public static void main(String[] args) throws IOException{ ServerSocket listener = new ServerSocket(8080); while(true){ Socket sock = listener.accept(); new PrintWriter(sock.getOutputStream(), true). println("Goodbye, World!"); sock.close(); } } }
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <err.h> char response[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n" "<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>" "<style>body { background-color: #111 }" "h1 { font-size:4cm; text-align: center; color: black;" " text-shadow: 0 0 2mm red}</style></head>" "<body><h1>Goodbye, world!</h1></body></html>\r\n"; int main() { int one = 1, client_fd; struct sockaddr_in svr_addr, cli_addr; socklen_t sin_len = sizeof(cli_addr); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) err(1, "can't open socket"); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); int port = 8080; svr_addr.sin_family = AF_INET; svr_addr.sin_addr.s_addr = INADDR_ANY; svr_addr.sin_port = htons(port); if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { close(sock); err(1, "Can't bind"); } listen(sock, 5); while (1) { client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); printf("got connection\n"); if (client_fd == -1) { perror("Can't accept"); continue; } write(client_fd, response, sizeof(response) - 1); close(client_fd); } }
Port the following code from Java to C with equivalent syntax and logic.
public class Clear { public static void main (String[] args) { System.out.print("\033[2J"); } }
void cls(void) { printf("\33[2J"); }
Ensure the translated C code behaves exactly like the original Java snippet.
size(1000,1000); surface.setTitle("Sunflower..."); int iter = 3000; float factor = .5 + sqrt(1.25),r,theta,diskRatio=0.5; float x = width/2.0, y = height/2.0; double maxRad = pow(iter,factor)/iter; int i; background(#add8e6); for(i=0;i<=iter;i++){ r = pow(i,factor)/iter; if(r/maxRad < diskRatio){ stroke(#000000); } else stroke(#ffff00); theta = 2*PI*factor*i; ellipse(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter),10 * i/(1.0*iter)); }
#include<graphics.h> #include<math.h> #define pi M_PI void sunflower(int winWidth, int winHeight, double diskRatio, int iter){ double factor = .5 + sqrt(1.25),r,theta; double x = winWidth/2.0, y = winHeight/2.0; double maxRad = pow(iter,factor)/iter; int i; setbkcolor(LIGHTBLUE); for(i=0;i<=iter;i++){ r = pow(i,factor)/iter; r/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW); theta = 2*pi*factor*i; circle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter)); } } int main() { initwindow(1000,1000,"Sunflower..."); sunflower(1000,1000,0.5,3000); getch(); closegraph(); return 0; }
Change the following Java code into C without altering its purpose.
import java.util.Arrays; import static java.util.Arrays.stream; import java.util.concurrent.*; public class VogelsApproximationMethod { final static int[] demand = {30, 20, 70, 30, 60}; final static int[] supply = {50, 60, 50, 50}; final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}}; final static int nRows = supply.length; final static int nCols = demand.length; static boolean[] rowDone = new boolean[nRows]; static boolean[] colDone = new boolean[nCols]; static int[][] result = new int[nRows][nCols]; static ExecutorService es = Executors.newFixedThreadPool(2); public static void main(String[] args) throws Exception { int supplyLeft = stream(supply).sum(); int totalCost = 0; while (supplyLeft > 0) { int[] cell = nextCell(); int r = cell[0]; int c = cell[1]; int quantity = Math.min(demand[c], supply[r]); demand[c] -= quantity; if (demand[c] == 0) colDone[c] = true; supply[r] -= quantity; if (supply[r] == 0) rowDone[r] = true; result[r][c] = quantity; supplyLeft -= quantity; totalCost += quantity * costs[r][c]; } stream(result).forEach(a -> System.out.println(Arrays.toString(a))); System.out.println("Total cost: " + totalCost); es.shutdown(); } static int[] nextCell() throws Exception { Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true)); Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false)); int[] res1 = f1.get(); int[] res2 = f2.get(); if (res1[3] == res2[3]) return res1[2] < res2[2] ? res1 : res2; return (res1[3] > res2[3]) ? res2 : res1; } static int[] diff(int j, int len, boolean isRow) { int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; int minP = -1; for (int i = 0; i < len; i++) { if (isRow ? colDone[i] : rowDone[i]) continue; int c = isRow ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; minP = i; } else if (c < min2) min2 = c; } return new int[]{min2 - min1, min1, minP}; } static int[] maxPenalty(int len1, int len2, boolean isRow) { int md = Integer.MIN_VALUE; int pc = -1, pm = -1, mc = -1; for (int i = 0; i < len1; i++) { if (isRow ? rowDone[i] : colDone[i]) continue; int[] res = diff(i, len2, isRow); if (res[0] > md) { md = res[0]; pm = i; mc = res[1]; pc = res[2]; } } return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md}; } }
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 4 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 50, 60, 50, 50 }; int demand[N_COLS] = { 30, 20, 70, 30, 60 }; int costs[N_ROWS][N_COLS] = { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 }, { 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } }; bool row_done[N_ROWS] = { FALSE }; bool col_done[N_COLS] = { FALSE }; void diff(int j, int len, bool is_row, int res[3]) { int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; for (i = 0; i < len; ++i) { if((is_row) ? col_done[i] : row_done[i]) continue; c = (is_row) ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; min_p = i; } else if (c < min2) min2 = c; } res[0] = min2 - min1; res[1] = min1; res[2] = min_p; } void max_penalty(int len1, int len2, bool is_row, int res[4]) { int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; int res2[3]; for (i = 0; i < len1; ++i) { if((is_row) ? row_done[i] : col_done[i]) continue; diff(i, len2, is_row, res2); if (res2[0] > md) { md = res2[0]; pm = i; mc = res2[1]; pc = res2[2]; } } if (is_row) { res[0] = pm; res[1] = pc; } else { res[0] = pc; res[1] = pm; } res[2] = mc; res[3] = md; } void next_cell(int res[4]) { int i, res1[4], res2[4]; max_penalty(N_ROWS, N_COLS, TRUE, res1); max_penalty(N_COLS, N_ROWS, FALSE, res2); if (res1[3] == res2[3]) { if (res1[2] < res2[2]) for (i = 0; i < 4; ++i) res[i] = res1[i]; else for (i = 0; i < 4; ++i) res[i] = res2[i]; return; } if (res1[3] > res2[3]) for (i = 0; i < 4; ++i) res[i] = res2[i]; else for (i = 0; i < 4; ++i) res[i] = res1[i]; } int main() { int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; int results[N_ROWS][N_COLS] = { 0 }; for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; while (supply_left > 0) { next_cell(cell); r = cell[0]; c = cell[1]; q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; demand[c] -= q; if (!demand[c]) col_done[c] = TRUE; supply[r] -= q; if (!supply[r]) row_done[r] = TRUE; results[r][c] = q; supply_left -= q; total_cost += q * costs[r][c]; } printf(" A B C D E\n"); for (i = 0; i < N_ROWS; ++i) { printf("%c", 'W' + i); for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]); printf("\n"); } printf("\nTotal cost = %d\n", total_cost); return 0; }
Port the following code from Java to C with equivalent syntax and logic.
public class AirMass { public static void main(String[] args) { System.out.println("Angle 0 m 13700 m"); System.out.println("------------------------------------"); for (double z = 0; z <= 90; z+= 5) { System.out.printf("%2.0f %11.8f %11.8f\n", z, airmass(0.0, z), airmass(13700.0, z)); } } private static double rho(double a) { return Math.exp(-a / 8500.0); } private static double height(double a, double z, double d) { double aa = RE + a; double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z))); return hh - RE; } private static double columnDensity(double a, double z) { double sum = 0.0, d = 0.0; while (d < FIN) { double delta = Math.max(DD * d, DD); sum += rho(height(a, z, d + 0.5 * delta)) * delta; d += delta; } return sum; } private static double airmass(double a, double z) { return columnDensity(a, z) / columnDensity(a, 0.0); } private static final double RE = 6371000.0; private static final double DD = 0.001; private static final double FIN = 10000000.0; }
#include <math.h> #include <stdio.h> #define DEG 0.017453292519943295769236907684886127134 #define RE 6371000.0 #define DD 0.001 #define FIN 10000000.0 static double rho(double a) { return exp(-a / 8500.0); } static double height(double a, double z, double d) { double aa = RE + a; double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG)); return hh - RE; } static double column_density(double a, double z) { double sum = 0.0, d = 0.0; while (d < FIN) { double delta = DD * d; if (delta < DD) delta = DD; sum += rho(height(a, z, d + 0.5 * delta)) * delta; d += delta; } return sum; } static double airmass(double a, double z) { return column_density(a, z) / column_density(a, 0.0); } int main() { puts("Angle 0 m 13700 m"); puts("------------------------------------"); for (double z = 0; z <= 90; z+= 5) { printf("%2.0f %11.8f %11.8f\n", z, airmass(0.0, z), airmass(13700.0, z)); } }
Convert this Java snippet to C and keep its semantics consistent.
public class PancakeSort { int[] heap; public String toString() { String info = ""; for (int x: heap) info += x + " "; return info; } public void flip(int n) { for (int i = 0; i < (n+1) / 2; ++i) { int tmp = heap[i]; heap[i] = heap[n-i]; heap[n-i] = tmp; } System.out.println("flip(0.." + n + "): " + toString()); } public int[] minmax(int n) { int xm, xM; xm = xM = heap[0]; int posm = 0, posM = 0; for (int i = 1; i < n; ++i) { if (heap[i] < xm) { xm = heap[i]; posm = i; } else if (heap[i] > xM) { xM = heap[i]; posM = i; } } return new int[] {posm, posM}; } public void sort(int n, int dir) { if (n == 0) return; int[] mM = minmax(n); int bestXPos = mM[dir]; int altXPos = mM[1-dir]; boolean flipped = false; if (bestXPos == n-1) { --n; } else if (bestXPos == 0) { flip(n-1); --n; } else if (altXPos == n-1) { dir = 1-dir; --n; flipped = true; } else { flip(bestXPos); } sort(n, dir); if (flipped) { flip(n); } } PancakeSort(int[] numbers) { heap = numbers; sort(numbers.length, 1); } public static void main(String[] args) { int[] numbers = new int[args.length]; for (int i = 0; i < args.length; ++i) numbers[i] = Integer.valueOf(args[i]); PancakeSort pancakes = new PancakeSort(numbers); System.out.println(pancakes); } }
int pancake_sort(int *list, unsigned int length) { if(length<2) return 0; int i,a,max_num_pos,moves; moves=0; for(i=length;i>1;i--) { max_num_pos=0; for(a=0;a<i;a++) { if(list[a]>list[max_num_pos]) max_num_pos=a; } if(max_num_pos==i-1) continue; if(max_num_pos) { moves++; do_flip(list, length, max_num_pos+1); } moves++; do_flip(list, length, i); } return moves; }
Translate this program into C but keep the logic exactly as in Java.
public class PancakeSort { int[] heap; public String toString() { String info = ""; for (int x: heap) info += x + " "; return info; } public void flip(int n) { for (int i = 0; i < (n+1) / 2; ++i) { int tmp = heap[i]; heap[i] = heap[n-i]; heap[n-i] = tmp; } System.out.println("flip(0.." + n + "): " + toString()); } public int[] minmax(int n) { int xm, xM; xm = xM = heap[0]; int posm = 0, posM = 0; for (int i = 1; i < n; ++i) { if (heap[i] < xm) { xm = heap[i]; posm = i; } else if (heap[i] > xM) { xM = heap[i]; posM = i; } } return new int[] {posm, posM}; } public void sort(int n, int dir) { if (n == 0) return; int[] mM = minmax(n); int bestXPos = mM[dir]; int altXPos = mM[1-dir]; boolean flipped = false; if (bestXPos == n-1) { --n; } else if (bestXPos == 0) { flip(n-1); --n; } else if (altXPos == n-1) { dir = 1-dir; --n; flipped = true; } else { flip(bestXPos); } sort(n, dir); if (flipped) { flip(n); } } PancakeSort(int[] numbers) { heap = numbers; sort(numbers.length, 1); } public static void main(String[] args) { int[] numbers = new int[args.length]; for (int i = 0; i < args.length; ++i) numbers[i] = Integer.valueOf(args[i]); PancakeSort pancakes = new PancakeSort(numbers); System.out.println(pancakes); } }
int pancake_sort(int *list, unsigned int length) { if(length<2) return 0; int i,a,max_num_pos,moves; moves=0; for(i=length;i>1;i--) { max_num_pos=0; for(a=0;a<i;a++) { if(list[a]>list[max_num_pos]) max_num_pos=a; } if(max_num_pos==i-1) continue; if(max_num_pos) { moves++; do_flip(list, length, max_num_pos+1); } moves++; do_flip(list, length, i); } return moves; }
Please provide an equivalent version of this Java code in C.
import java.io.IOException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection; public class LdapConnectionDemo { public static void main(String[] args) throws LdapException, IOException { try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) { connection.bind(); connection.unBind(); } } }
#include <ldap.h> ... char *name, *password; ... LDAP *ld = ldap_init("ldap.somewhere.com", 389); ldap_simple_bind_s(ld, name, password); ... after done with it... ldap_unbind(ld);
Port the provided Java code into C while preserving the original functionality.
package org.rosettacode.java; import java.util.Arrays; import java.util.stream.IntStream; public class HeapsAlgorithm { public static void main(String[] args) { Object[] array = IntStream.range(0, 4) .boxed() .toArray(); HeapsAlgorithm algorithm = new HeapsAlgorithm(); algorithm.recursive(array); System.out.println(); algorithm.loop(array); } void recursive(Object[] array) { recursive(array, array.length, true); } void recursive(Object[] array, int n, boolean plus) { if (n == 1) { output(array, plus); } else { for (int i = 0; i < n; i++) { recursive(array, n - 1, i == 0); swap(array, n % 2 == 0 ? i : 0, n - 1); } } } void output(Object[] array, boolean plus) { System.out.println(Arrays.toString(array) + (plus ? " +1" : " -1")); } void swap(Object[] array, int a, int b) { Object o = array[a]; array[a] = array[b]; array[b] = o; } void loop(Object[] array) { loop(array, array.length); } void loop(Object[] array, int n) { int[] c = new int[n]; output(array, true); boolean plus = false; for (int i = 0; i < n; ) { if (c[i] < i) { if (i % 2 == 0) { swap(array, 0, i); } else { swap(array, c[i], i); } output(array, plus); plus = !plus; c[i]++; i = 0; } else { c[i] = 0; i++; } } } }
#include<stdlib.h> #include<string.h> #include<stdio.h> int flag = 1; void heapPermute(int n, int arr[],int arrLen){ int temp; int i; if(n==1){ printf("\n["); for(i=0;i<arrLen;i++) printf("%d,",arr[i]); printf("\b] Sign : %d",flag); flag*=-1; } else{ for(i=0;i<n-1;i++){ heapPermute(n-1,arr,arrLen); if(n%2==0){ temp = arr[i]; arr[i] = arr[n-1]; arr[n-1] = temp; } else{ temp = arr[0]; arr[0] = arr[n-1]; arr[n-1] = temp; } } heapPermute(n-1,arr,arrLen); } } int main(int argC,char* argV[0]) { int *arr, i=0, count = 1; char* token; if(argC==1) printf("Usage : %s <comma separated list of integers>",argV[0]); else{ while(argV[1][i]!=00){ if(argV[1][i++]==',') count++; } arr = (int*)malloc(count*sizeof(int)); i = 0; token = strtok(argV[1],","); while(token!=NULL){ arr[i++] = atoi(token); token = strtok(NULL,","); } heapPermute(i,arr,count); } return 0; }
Write a version of this Java function in C with identical behavior.
import java.util.ArrayList; import java.util.List; public class PythagoreanQuadruples { public static void main(String[] args) { long d = 2200; System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d)); } private static List<Long> getPythagoreanQuadruples(long max) { List<Long> list = new ArrayList<>(); long n = -1; long m = -1; while ( true ) { long nTest = (long) Math.pow(2, n+1); long mTest = (long) (5L * Math.pow(2, m+1)); long test = 0; if ( nTest > mTest ) { test = mTest; m++; } else { test = nTest; n++; } if ( test < max ) { list.add(test); } else { break; } } return list; } }
#include <stdio.h> #include <math.h> #include <string.h> #define N 2200 int main(int argc, char **argv){ int a,b,c,d; int r[N+1]; memset(r,0,sizeof(r)); for(a=1; a<=N; a++){ for(b=a; b<=N; b++){ int aabb; if(a&1 && b&1) continue; aabb=a*a + b*b; for(c=b; c<=N; c++){ int aabbcc=aabb + c*c; d=(int)sqrt((float)aabbcc); if(aabbcc == d*d && d<=N) r[d]=1; } } } for(a=1; a<=N; a++) if(!r[a]) printf("%d ",a); printf("\n"); }
Ensure the translated C code behaves exactly like the original Java snippet.
import java.util.ArrayList; import java.util.List; public class PythagoreanQuadruples { public static void main(String[] args) { long d = 2200; System.out.printf("Values of d < %d where a, b, and c are non-zero and a^2 + b^2 + c^2 = d^2 has no solutions:%n%s%n", d, getPythagoreanQuadruples(d)); } private static List<Long> getPythagoreanQuadruples(long max) { List<Long> list = new ArrayList<>(); long n = -1; long m = -1; while ( true ) { long nTest = (long) Math.pow(2, n+1); long mTest = (long) (5L * Math.pow(2, m+1)); long test = 0; if ( nTest > mTest ) { test = mTest; m++; } else { test = nTest; n++; } if ( test < max ) { list.add(test); } else { break; } } return list; } }
#include <stdio.h> #include <math.h> #include <string.h> #define N 2200 int main(int argc, char **argv){ int a,b,c,d; int r[N+1]; memset(r,0,sizeof(r)); for(a=1; a<=N; a++){ for(b=a; b<=N; b++){ int aabb; if(a&1 && b&1) continue; aabb=a*a + b*b; for(c=b; c<=N; c++){ int aabbcc=aabb + c*c; d=(int)sqrt((float)aabbcc); if(aabbcc == d*d && d<=N) r[d]=1; } } } for(a=1; a<=N; a++) if(!r[a]) printf("%d ",a); printf("\n"); }
Transform the following Java implementation into C, maintaining the same output and logic.
import java.io.*; import java.util.*; import java.util.regex.*; public class UpdateConfig { public static void main(String[] args) { if (args[0] == null) { System.out.println("filename required"); } else if (readConfig(args[0])) { enableOption("seedsremoved"); disableOption("needspeeling"); setOption("numberofbananas", "1024"); addOption("numberofstrawberries", "62000"); store(); } } private enum EntryType { EMPTY, ENABLED, DISABLED, COMMENT } private static class Entry { EntryType type; String name, value; Entry(EntryType t, String n, String v) { type = t; name = n; value = v; } } private static Map<String, Entry> entries = new LinkedHashMap<>(); private static String path; private static boolean readConfig(String p) { path = p; File f = new File(path); if (!f.exists() || f.isDirectory()) return false; String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)"; Pattern regex = Pattern.compile(regexString); try (Scanner sc = new Scanner(new FileReader(f))){ int emptyLines = 0; String line; while (sc.hasNext()) { line = sc.nextLine().trim(); if (line.isEmpty()) { addOption("" + emptyLines++, null, EntryType.EMPTY); } else if (line.charAt(0) == '#') { entries.put(line, new Entry(EntryType.COMMENT, line, null)); } else { line = line.replaceAll("[^a-zA-Z0-9\\x20;]", ""); Matcher m = regex.matcher(line); if (m.find() && !m.group(2).isEmpty()) { EntryType t = EntryType.ENABLED; if (!m.group(1).isEmpty()) t = EntryType.DISABLED; addOption(m.group(2), m.group(3), t); } } } } catch (IOException e) { System.out.println(e); } return true; } private static void addOption(String name, String value) { addOption(name, value, EntryType.ENABLED); } private static void addOption(String name, String value, EntryType t) { name = name.toUpperCase(); entries.put(name, new Entry(t, name, value)); } private static void enableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.ENABLED; } private static void disableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.DISABLED; } private static void setOption(String name, String value) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.value = value; } private static void store() { try (PrintWriter pw = new PrintWriter(path)) { for (Entry e : entries.values()) { switch (e.type) { case EMPTY: pw.println(); break; case ENABLED: pw.format("%s %s%n", e.name, e.value); break; case DISABLED: pw.format("; %s %s%n", e.name, e.value); break; case COMMENT: pw.println(e.name); break; default: break; } } if (pw.checkError()) { throw new IOException("writing to file failed"); } } catch (IOException e) { System.out.println(e); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define strcomp(X, Y) strcasecmp(X, Y) struct option { const char *name, *value; int flag; }; struct option updlist[] = { { "NEEDSPEELING", NULL }, { "SEEDSREMOVED", "" }, { "NUMBEROFBANANAS", "1024" }, { "NUMBEROFSTRAWBERRIES", "62000" }, { NULL, NULL } }; int output_opt(FILE *to, struct option *opt) { if (opt->value == NULL) return fprintf(to, "; %s\n", opt->name); else if (opt->value[0] == 0) return fprintf(to, "%s\n", opt->name); else return fprintf(to, "%s %s\n", opt->name, opt->value); } int update(FILE *from, FILE *to, struct option *updlist) { char line_buf[256], opt_name[128]; int i; for (;;) { size_t len, space_span, span_to_hash; if (fgets(line_buf, sizeof line_buf, from) == NULL) break; len = strlen(line_buf); space_span = strspn(line_buf, "\t "); span_to_hash = strcspn(line_buf, "#"); if (space_span == span_to_hash) goto line_out; if (space_span == len) goto line_out; if ((sscanf(line_buf, "; %127s", opt_name) == 1) || (sscanf(line_buf, "%127s", opt_name) == 1)) { int flag = 0; for (i = 0; updlist[i].name; i++) { if (strcomp(updlist[i].name, opt_name) == 0) { if (output_opt(to, &updlist[i]) < 0) return -1; updlist[i].flag = 1; flag = 1; } } if (flag == 0) goto line_out; } else line_out: if (fprintf(to, "%s", line_buf) < 0) return -1; continue; } { for (i = 0; updlist[i].name; i++) { if (!updlist[i].flag) if (output_opt(to, &updlist[i]) < 0) return -1; } } return feof(from) ? 0 : -1; } int main(void) { if (update(stdin, stdout, updlist) < 0) { fprintf(stderr, "failed\n"); return (EXIT_FAILURE); } return 0; }
Generate a C translation of this Java snippet without changing its computational steps.
import java.io.*; import java.util.*; import java.util.regex.*; public class UpdateConfig { public static void main(String[] args) { if (args[0] == null) { System.out.println("filename required"); } else if (readConfig(args[0])) { enableOption("seedsremoved"); disableOption("needspeeling"); setOption("numberofbananas", "1024"); addOption("numberofstrawberries", "62000"); store(); } } private enum EntryType { EMPTY, ENABLED, DISABLED, COMMENT } private static class Entry { EntryType type; String name, value; Entry(EntryType t, String n, String v) { type = t; name = n; value = v; } } private static Map<String, Entry> entries = new LinkedHashMap<>(); private static String path; private static boolean readConfig(String p) { path = p; File f = new File(path); if (!f.exists() || f.isDirectory()) return false; String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)"; Pattern regex = Pattern.compile(regexString); try (Scanner sc = new Scanner(new FileReader(f))){ int emptyLines = 0; String line; while (sc.hasNext()) { line = sc.nextLine().trim(); if (line.isEmpty()) { addOption("" + emptyLines++, null, EntryType.EMPTY); } else if (line.charAt(0) == '#') { entries.put(line, new Entry(EntryType.COMMENT, line, null)); } else { line = line.replaceAll("[^a-zA-Z0-9\\x20;]", ""); Matcher m = regex.matcher(line); if (m.find() && !m.group(2).isEmpty()) { EntryType t = EntryType.ENABLED; if (!m.group(1).isEmpty()) t = EntryType.DISABLED; addOption(m.group(2), m.group(3), t); } } } } catch (IOException e) { System.out.println(e); } return true; } private static void addOption(String name, String value) { addOption(name, value, EntryType.ENABLED); } private static void addOption(String name, String value, EntryType t) { name = name.toUpperCase(); entries.put(name, new Entry(t, name, value)); } private static void enableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.ENABLED; } private static void disableOption(String name) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.type = EntryType.DISABLED; } private static void setOption(String name, String value) { Entry e = entries.get(name.toUpperCase()); if (e != null) e.value = value; } private static void store() { try (PrintWriter pw = new PrintWriter(path)) { for (Entry e : entries.values()) { switch (e.type) { case EMPTY: pw.println(); break; case ENABLED: pw.format("%s %s%n", e.name, e.value); break; case DISABLED: pw.format("; %s %s%n", e.name, e.value); break; case COMMENT: pw.println(e.name); break; default: break; } } if (pw.checkError()) { throw new IOException("writing to file failed"); } } catch (IOException e) { System.out.println(e); } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #define strcomp(X, Y) strcasecmp(X, Y) struct option { const char *name, *value; int flag; }; struct option updlist[] = { { "NEEDSPEELING", NULL }, { "SEEDSREMOVED", "" }, { "NUMBEROFBANANAS", "1024" }, { "NUMBEROFSTRAWBERRIES", "62000" }, { NULL, NULL } }; int output_opt(FILE *to, struct option *opt) { if (opt->value == NULL) return fprintf(to, "; %s\n", opt->name); else if (opt->value[0] == 0) return fprintf(to, "%s\n", opt->name); else return fprintf(to, "%s %s\n", opt->name, opt->value); } int update(FILE *from, FILE *to, struct option *updlist) { char line_buf[256], opt_name[128]; int i; for (;;) { size_t len, space_span, span_to_hash; if (fgets(line_buf, sizeof line_buf, from) == NULL) break; len = strlen(line_buf); space_span = strspn(line_buf, "\t "); span_to_hash = strcspn(line_buf, "#"); if (space_span == span_to_hash) goto line_out; if (space_span == len) goto line_out; if ((sscanf(line_buf, "; %127s", opt_name) == 1) || (sscanf(line_buf, "%127s", opt_name) == 1)) { int flag = 0; for (i = 0; updlist[i].name; i++) { if (strcomp(updlist[i].name, opt_name) == 0) { if (output_opt(to, &updlist[i]) < 0) return -1; updlist[i].flag = 1; flag = 1; } } if (flag == 0) goto line_out; } else line_out: if (fprintf(to, "%s", line_buf) < 0) return -1; continue; } { for (i = 0; updlist[i].name; i++) { if (!updlist[i].flag) if (output_opt(to, &updlist[i]) < 0) return -1; } } return feof(from) ? 0 : -1; } int main(void) { if (update(stdin, stdout, updlist) < 0) { fprintf(stderr, "failed\n"); return (EXIT_FAILURE); } return 0; }
Port the provided Java code into C while preserving the original functionality.
import java.awt.image.*; import java.io.File; import java.io.IOException; import javax.imageio.*; public class ImageConvolution { public static class ArrayData { public final int[] dataArray; public final int width; public final int height; public ArrayData(int width, int height) { this(new int[width * height], width, height); } public ArrayData(int[] dataArray, int width, int height) { this.dataArray = dataArray; this.width = width; this.height = height; } public int get(int x, int y) { return dataArray[y * width + x]; } public void set(int x, int y, int value) { dataArray[y * width + x] = value; } } private static int bound(int value, int endIndex) { if (value < 0) return 0; if (value < endIndex) return value; return endIndex - 1; } public static ArrayData convolute(ArrayData inputData, ArrayData kernel, int kernelDivisor) { int inputWidth = inputData.width; int inputHeight = inputData.height; int kernelWidth = kernel.width; int kernelHeight = kernel.height; if ((kernelWidth <= 0) || ((kernelWidth & 1) != 1)) throw new IllegalArgumentException("Kernel must have odd width"); if ((kernelHeight <= 0) || ((kernelHeight & 1) != 1)) throw new IllegalArgumentException("Kernel must have odd height"); int kernelWidthRadius = kernelWidth >>> 1; int kernelHeightRadius = kernelHeight >>> 1; ArrayData outputData = new ArrayData(inputWidth, inputHeight); for (int i = inputWidth - 1; i >= 0; i--) { for (int j = inputHeight - 1; j >= 0; j--) { double newValue = 0.0; for (int kw = kernelWidth - 1; kw >= 0; kw--) for (int kh = kernelHeight - 1; kh >= 0; kh--) newValue += kernel.get(kw, kh) * inputData.get( bound(i + kw - kernelWidthRadius, inputWidth), bound(j + kh - kernelHeightRadius, inputHeight)); outputData.set(i, j, (int)Math.round(newValue / kernelDivisor)); } } return outputData; } public static ArrayData[] getArrayDatasFromImage(String filename) throws IOException { BufferedImage inputImage = ImageIO.read(new File(filename)); int width = inputImage.getWidth(); int height = inputImage.getHeight(); int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width); ArrayData reds = new ArrayData(width, height); ArrayData greens = new ArrayData(width, height); ArrayData blues = new ArrayData(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int rgbValue = rgbData[y * width + x]; reds.set(x, y, (rgbValue >>> 16) & 0xFF); greens.set(x, y, (rgbValue >>> 8) & 0xFF); blues.set(x, y, rgbValue & 0xFF); } } return new ArrayData[] { reds, greens, blues }; } public static void writeOutputImage(String filename, ArrayData[] redGreenBlue) throws IOException { ArrayData reds = redGreenBlue[0]; ArrayData greens = redGreenBlue[1]; ArrayData blues = redGreenBlue[2]; BufferedImage outputImage = new BufferedImage(reds.width, reds.height, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < reds.height; y++) { for (int x = 0; x < reds.width; x++) { int red = bound(reds.get(x, y), 256); int green = bound(greens.get(x, y), 256); int blue = bound(blues.get(x, y), 256); outputImage.setRGB(x, y, (red << 16) | (green << 8) | blue | -0x01000000); } } ImageIO.write(outputImage, "PNG", new File(filename)); return; } public static void main(String[] args) throws IOException { int kernelWidth = Integer.parseInt(args[2]); int kernelHeight = Integer.parseInt(args[3]); int kernelDivisor = Integer.parseInt(args[4]); System.out.println("Kernel size: " + kernelWidth + "x" + kernelHeight + ", divisor=" + kernelDivisor); int y = 5; ArrayData kernel = new ArrayData(kernelWidth, kernelHeight); for (int i = 0; i < kernelHeight; i++) { System.out.print("["); for (int j = 0; j < kernelWidth; j++) { kernel.set(j, i, Integer.parseInt(args[y++])); System.out.print(" " + kernel.get(j, i) + " "); } System.out.println("]"); } ArrayData[] dataArrays = getArrayDatasFromImage(args[0]); for (int i = 0; i < dataArrays.length; i++) dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor); writeOutputImage(args[1], dataArrays); return; } }
image filter(image img, double *K, int Ks, double, double);
Change the programming language of this snippet from Java to C without modifying what it does.
import java.util.Random; public class Dice{ private static int roll(int nDice, int nSides){ int sum = 0; Random rand = new Random(); for(int i = 0; i < nDice; i++){ sum += rand.nextInt(nSides) + 1; } return sum; } private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){ int p1Wins = 0; for(int i = 0; i < rolls; i++){ int p1Roll = roll(p1Dice, p1Sides); int p2Roll = roll(p2Dice, p2Sides); if(p1Roll > p2Roll) p1Wins++; } return p1Wins; } public static void main(String[] args){ int p1Dice = 9; int p1Sides = 4; int p2Dice = 6; int p2Sides = 6; int rolls = 10000; int p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); System.out.println(); p1Dice = 5; p1Sides = 10; p2Dice = 6; p2Sides = 7; rolls = 10000; p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); System.out.println(); p1Dice = 9; p1Sides = 4; p2Dice = 6; p2Sides = 6; rolls = 1000000; p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); System.out.println(); p1Dice = 5; p1Sides = 10; p2Dice = 6; p2Sides = 7; rolls = 1000000; p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls); System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides); System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time"); } }
#include <stdio.h> #include <stdint.h> typedef uint32_t uint; typedef uint64_t ulong; ulong ipow(const uint x, const uint y) { ulong result = 1; for (uint i = 1; i <= y; i++) result *= x; return result; } uint min(const uint x, const uint y) { return (x < y) ? x : y; } void throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) { if (n_dice == 0) { counts[s]++; return; } for (uint i = 1; i < n_sides + 1; i++) throw_die(n_sides, n_dice - 1, s + i, counts); } double beating_probability(const uint n_sides1, const uint n_dice1, const uint n_sides2, const uint n_dice2) { const uint len1 = (n_sides1 + 1) * n_dice1; uint C1[len1]; for (uint i = 0; i < len1; i++) C1[i] = 0; throw_die(n_sides1, n_dice1, 0, C1); const uint len2 = (n_sides2 + 1) * n_dice2; uint C2[len2]; for (uint j = 0; j < len2; j++) C2[j] = 0; throw_die(n_sides2, n_dice2, 0, C2); const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2)); double tot = 0; for (uint i = 0; i < len1; i++) for (uint j = 0; j < min(i, len2); j++) tot += (double)C1[i] * C2[j] / p12; return tot; } int main() { printf("%1.16f\n", beating_probability(4, 9, 6, 6)); printf("%1.16f\n", beating_probability(10, 5, 7, 6)); return 0; }
Convert this Java snippet to C and keep its semantics consistent.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import static java.awt.image.BufferedImage.*; import static java.lang.Math.*; import javax.swing.*; public class PlasmaEffect extends JPanel { float[][] plasma; float hueShift = 0; BufferedImage img; public PlasmaEffect() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white); img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB); plasma = createPlasma(dim.height, dim.width); new Timer(42, (ActionEvent e) -> { hueShift = (hueShift + 0.02f) % 1; repaint(); }).start(); } float[][] createPlasma(int w, int h) { float[][] buffer = new float[h][w]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { double value = sin(x / 16.0); value += sin(y / 8.0); value += sin((x + y) / 16.0); value += sin(sqrt(x * x + y * y) / 8.0); value += 4; value /= 8; assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds"; buffer[y][x] = (float) value; } return buffer; } void drawPlasma(Graphics2D g) { int h = plasma.length; int w = plasma[0].length; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { float hue = hueShift + plasma[y][x] % 1; img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1)); } g.drawImage(img, 0, 0, null); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawPlasma(g); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Plasma Effect"); f.setResizable(false); f.add(new PlasmaEffect(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include<windows.h> #include<stdlib.h> #include<stdio.h> #include<time.h> #include<math.h> #define pi M_PI int main() { CONSOLE_SCREEN_BUFFER_INFO info; int cols, rows; time_t t; int i,j; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info); cols = info.srWindow.Right - info.srWindow.Left + 1; rows = info.srWindow.Bottom - info.srWindow.Top + 1; HANDLE console; console = GetStdHandle(STD_OUTPUT_HANDLE); system("@clear||cls"); srand((unsigned)time(&t)); for(i=0;i<rows;i++) for(j=0;j<cols;j++){ SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254); printf("%c",219); } getchar(); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.SAXException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationException; import java.util.regex.Pattern; import java.util.regex.Matcher; class MyHandler extends DefaultHandler { private static final String TITLE = "title"; private static final String TEXT = "text"; private String lastTag = ""; private String title = ""; @Override public void characters(char[] ch, int start, int length) throws SAXException { String regex = ".*==French==.*"; Pattern pat = Pattern.compile(regex, Pattern.DOTALL); switch (lastTag) { case TITLE: title = new String(ch, start, length); break; case TEXT: String text = new String(ch, start, length); Matcher mat = pat.matcher(text); if (mat.matches()) { System.out.println(title); } break; } } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { lastTag = qName; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { lastTag = ""; } } public class WiktoWords { public static void main(java.lang.String[] args) { try { SAXParserFactory spFactory = SAXParserFactory.newInstance(); SAXParser saxParser = spFactory.newSAXParser(); MyHandler handler = new MyHandler(); saxParser.parse(new InputSource(System.in), handler); } catch(Exception e) { System.exit(1); } } }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <unistd.h> #include <expat.h> #include <pcre.h> #ifdef XML_LARGE_SIZE # define XML_FMT_INT_MOD "ll" #else # define XML_FMT_INT_MOD "l" #endif #ifdef XML_UNICODE_WCHAR_T # define XML_FMT_STR "ls" #else # define XML_FMT_STR "s" #endif void reset_char_data_buffer(); void process_char_data_buffer(); static bool last_tag_is_title; static bool last_tag_is_text; static pcre *reCompiled; static pcre_extra *pcreExtra; void start_element(void *data, const char *element, const char **attribute) { process_char_data_buffer(); reset_char_data_buffer(); if (strcmp("title", element) == 0) { last_tag_is_title = true; } if (strcmp("text", element) == 0) { last_tag_is_text = true; } } void end_element(void *data, const char *el) { process_char_data_buffer(); reset_char_data_buffer(); } #define TITLE_BUF_SIZE (1024 * 8) static char char_data_buffer[1024 * 64 * 8]; static char title_buffer[TITLE_BUF_SIZE]; static size_t offs; static bool overflow; void reset_char_data_buffer(void) { offs = 0; overflow = false; } void char_data(void *userData, const XML_Char *s, int len) { if (!overflow) { if (len + offs >= sizeof(char_data_buffer)) { overflow = true; fprintf(stderr, "Warning: buffer overflow\n"); fflush(stderr); } else { memcpy(char_data_buffer + offs, s, len); offs += len; } } } void try_match(); void process_char_data_buffer(void) { if (offs > 0) { char_data_buffer[offs] = '\0'; if (last_tag_is_title) { unsigned int n = (offs+1 > TITLE_BUF_SIZE) ? TITLE_BUF_SIZE : (offs+1); memcpy(title_buffer, char_data_buffer, n); last_tag_is_title = false; } if (last_tag_is_text) { try_match(); last_tag_is_text = false; } } } void try_match() { int subStrVec[80]; int subStrVecLen; int pcreExecRet; subStrVecLen = sizeof(subStrVec) / sizeof(int); pcreExecRet = pcre_exec( reCompiled, pcreExtra, char_data_buffer, strlen(char_data_buffer), 0, 0, subStrVec, subStrVecLen); if (pcreExecRet < 0) { switch (pcreExecRet) { case PCRE_ERROR_NOMATCH : break; case PCRE_ERROR_NULL : fprintf(stderr, "Something was null\n"); break; case PCRE_ERROR_BADOPTION : fprintf(stderr, "A bad option was passed\n"); break; case PCRE_ERROR_BADMAGIC : fprintf(stderr, "Magic number bad (compiled re corrupt?)\n"); break; case PCRE_ERROR_UNKNOWN_NODE : fprintf(stderr, "Something kooky in the compiled re\n"); break; case PCRE_ERROR_NOMEMORY : fprintf(stderr, "Ran out of memory\n"); break; default : fprintf(stderr, "Unknown error\n"); break; } } else { puts(title_buffer); } } #define BUF_SIZE 1024 int main(int argc, char *argv[]) { char buffer[BUF_SIZE]; int n; const char *pcreErrorStr; int pcreErrorOffset; char *aStrRegex; char **aLineToMatch; aStrRegex = "(.*)(==French==)(.*)"; reCompiled = pcre_compile(aStrRegex, PCRE_DOTALL | PCRE_UTF8, &pcreErrorStr, &pcreErrorOffset, NULL); if (reCompiled == NULL) { fprintf(stderr, "ERROR: Could not compile regex '%s': %s\n", aStrRegex, pcreErrorStr); exit(1); } pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr); if (pcreErrorStr != NULL) { fprintf(stderr, "ERROR: Could not study regex '%s': %s\n", aStrRegex, pcreErrorStr); exit(1); } XML_Parser parser = XML_ParserCreate(NULL); XML_SetElementHandler(parser, start_element, end_element); XML_SetCharacterDataHandler(parser, char_data); reset_char_data_buffer(); while (1) { int done; int len; len = (int)fread(buffer, 1, BUF_SIZE, stdin); if (ferror(stdin)) { fprintf(stderr, "Read error\n"); exit(1); } done = feof(stdin); if (XML_Parse(parser, buffer, len, done) == XML_STATUS_ERROR) { fprintf(stderr, "Parse error at line %" XML_FMT_INT_MOD "u:\n%" XML_FMT_STR "\n", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); exit(1); } if (done) break; } XML_ParserFree(parser); pcre_free(reCompiled); if (pcreExtra != NULL) { #ifdef PCRE_CONFIG_JIT pcre_free_study(pcreExtra); #else pcre_free(pcreExtra); #endif } return 0; }
Translate this program into C but keep the logic exactly as in Java.
import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.SAXException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationException; import java.util.regex.Pattern; import java.util.regex.Matcher; class MyHandler extends DefaultHandler { private static final String TITLE = "title"; private static final String TEXT = "text"; private String lastTag = ""; private String title = ""; @Override public void characters(char[] ch, int start, int length) throws SAXException { String regex = ".*==French==.*"; Pattern pat = Pattern.compile(regex, Pattern.DOTALL); switch (lastTag) { case TITLE: title = new String(ch, start, length); break; case TEXT: String text = new String(ch, start, length); Matcher mat = pat.matcher(text); if (mat.matches()) { System.out.println(title); } break; } } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { lastTag = qName; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { lastTag = ""; } } public class WiktoWords { public static void main(java.lang.String[] args) { try { SAXParserFactory spFactory = SAXParserFactory.newInstance(); SAXParser saxParser = spFactory.newSAXParser(); MyHandler handler = new MyHandler(); saxParser.parse(new InputSource(System.in), handler); } catch(Exception e) { System.exit(1); } } }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <unistd.h> #include <expat.h> #include <pcre.h> #ifdef XML_LARGE_SIZE # define XML_FMT_INT_MOD "ll" #else # define XML_FMT_INT_MOD "l" #endif #ifdef XML_UNICODE_WCHAR_T # define XML_FMT_STR "ls" #else # define XML_FMT_STR "s" #endif void reset_char_data_buffer(); void process_char_data_buffer(); static bool last_tag_is_title; static bool last_tag_is_text; static pcre *reCompiled; static pcre_extra *pcreExtra; void start_element(void *data, const char *element, const char **attribute) { process_char_data_buffer(); reset_char_data_buffer(); if (strcmp("title", element) == 0) { last_tag_is_title = true; } if (strcmp("text", element) == 0) { last_tag_is_text = true; } } void end_element(void *data, const char *el) { process_char_data_buffer(); reset_char_data_buffer(); } #define TITLE_BUF_SIZE (1024 * 8) static char char_data_buffer[1024 * 64 * 8]; static char title_buffer[TITLE_BUF_SIZE]; static size_t offs; static bool overflow; void reset_char_data_buffer(void) { offs = 0; overflow = false; } void char_data(void *userData, const XML_Char *s, int len) { if (!overflow) { if (len + offs >= sizeof(char_data_buffer)) { overflow = true; fprintf(stderr, "Warning: buffer overflow\n"); fflush(stderr); } else { memcpy(char_data_buffer + offs, s, len); offs += len; } } } void try_match(); void process_char_data_buffer(void) { if (offs > 0) { char_data_buffer[offs] = '\0'; if (last_tag_is_title) { unsigned int n = (offs+1 > TITLE_BUF_SIZE) ? TITLE_BUF_SIZE : (offs+1); memcpy(title_buffer, char_data_buffer, n); last_tag_is_title = false; } if (last_tag_is_text) { try_match(); last_tag_is_text = false; } } } void try_match() { int subStrVec[80]; int subStrVecLen; int pcreExecRet; subStrVecLen = sizeof(subStrVec) / sizeof(int); pcreExecRet = pcre_exec( reCompiled, pcreExtra, char_data_buffer, strlen(char_data_buffer), 0, 0, subStrVec, subStrVecLen); if (pcreExecRet < 0) { switch (pcreExecRet) { case PCRE_ERROR_NOMATCH : break; case PCRE_ERROR_NULL : fprintf(stderr, "Something was null\n"); break; case PCRE_ERROR_BADOPTION : fprintf(stderr, "A bad option was passed\n"); break; case PCRE_ERROR_BADMAGIC : fprintf(stderr, "Magic number bad (compiled re corrupt?)\n"); break; case PCRE_ERROR_UNKNOWN_NODE : fprintf(stderr, "Something kooky in the compiled re\n"); break; case PCRE_ERROR_NOMEMORY : fprintf(stderr, "Ran out of memory\n"); break; default : fprintf(stderr, "Unknown error\n"); break; } } else { puts(title_buffer); } } #define BUF_SIZE 1024 int main(int argc, char *argv[]) { char buffer[BUF_SIZE]; int n; const char *pcreErrorStr; int pcreErrorOffset; char *aStrRegex; char **aLineToMatch; aStrRegex = "(.*)(==French==)(.*)"; reCompiled = pcre_compile(aStrRegex, PCRE_DOTALL | PCRE_UTF8, &pcreErrorStr, &pcreErrorOffset, NULL); if (reCompiled == NULL) { fprintf(stderr, "ERROR: Could not compile regex '%s': %s\n", aStrRegex, pcreErrorStr); exit(1); } pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr); if (pcreErrorStr != NULL) { fprintf(stderr, "ERROR: Could not study regex '%s': %s\n", aStrRegex, pcreErrorStr); exit(1); } XML_Parser parser = XML_ParserCreate(NULL); XML_SetElementHandler(parser, start_element, end_element); XML_SetCharacterDataHandler(parser, char_data); reset_char_data_buffer(); while (1) { int done; int len; len = (int)fread(buffer, 1, BUF_SIZE, stdin); if (ferror(stdin)) { fprintf(stderr, "Read error\n"); exit(1); } done = feof(stdin); if (XML_Parse(parser, buffer, len, done) == XML_STATUS_ERROR) { fprintf(stderr, "Parse error at line %" XML_FMT_INT_MOD "u:\n%" XML_FMT_STR "\n", XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); exit(1); } if (done) break; } XML_ParserFree(parser); pcre_free(reCompiled); if (pcreExtra != NULL) { #ifdef PCRE_CONFIG_JIT pcre_free_study(pcreExtra); #else pcre_free(pcreExtra); #endif } return 0; }
Ensure the translated C++ code behaves exactly like the original C# snippet.
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
Port the following code from C# to C++ with equivalent syntax and logic.
using System; using System.IO; using System.Text; namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT"; private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt); } else { var sb = new StringBuilder(); sb.Append(DateTime.Now).Append("\n\t"); foreach (string s in args) sb.Append(s).Append(" "); sb.Append("\n"); if (File.Exists(FileName)) File.AppendAllText(FileName, sb.ToString()); else File.WriteAllText(FileName, sb.ToString()); } } } }
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
Preserve the algorithm and functionality while converting the code from C# to C++.
using System; public static class Angles { public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000); public static void Print(params double[] angles) { string[] names = { "Degrees", "Gradians", "Mils", "Radians" }; Func<double, double> rnd = a => Math.Round(a, 4); Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad }; Func<double, double>[,] convert = { { a => a, DegToGrad, DegToMil, DegToRad }, { GradToDeg, a => a, GradToMil, GradToRad }, { MilToDeg, MilToGrad, a => a, MilToRad }, { RadToDeg, RadToGrad, RadToMil, a => a } }; Console.WriteLine($@"{"Angle",-12}{"Normalized",-12}{"Unit",-12}{ "Degrees",-12}{"Gradians",-12}{"Mils",-12}{"Radians",-12}"); foreach (double angle in angles) { for (int i = 0; i < 4; i++) { double nAngle = normal[i](angle); Console.WriteLine($@"{ rnd(angle),-12}{ rnd(nAngle),-12}{ names[i],-12}{ rnd(convert[i, 0](nAngle)),-12}{ rnd(convert[i, 1](nAngle)),-12}{ rnd(convert[i, 2](nAngle)),-12}{ rnd(convert[i, 3](nAngle)),-12}"); } } } public static double NormalizeDeg(double angle) => Normalize(angle, 360); public static double NormalizeGrad(double angle) => Normalize(angle, 400); public static double NormalizeMil(double angle) => Normalize(angle, 6400); public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI); private static double Normalize(double angle, double N) { while (angle <= -N) angle += N; while (angle >= N) angle -= N; return angle; } public static double DegToGrad(double angle) => angle * 10 / 9; public static double DegToMil(double angle) => angle * 160 / 9; public static double DegToRad(double angle) => angle * Math.PI / 180; public static double GradToDeg(double angle) => angle * 9 / 10; public static double GradToMil(double angle) => angle * 16; public static double GradToRad(double angle) => angle * Math.PI / 200; public static double MilToDeg(double angle) => angle * 9 / 160; public static double MilToGrad(double angle) => angle / 16; public static double MilToRad(double angle) => angle * Math.PI / 3200; public static double RadToDeg(double angle) => angle * 180 / Math.PI; public static double RadToGrad(double angle) => angle * 200 / Math.PI; public static double RadToMil(double angle) => angle * 3200 / Math.PI; }
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(double a) { return normalize<double>(a, 400); } inline double m2m(double a) { return normalize<double>(a, 6400); } inline double r2r(double a) { return normalize<double>(a, 2*M_PI); } double d2g(double a) { return g2g(a * 10 / 9); } double d2m(double a) { return m2m(a * 160 / 9); } double d2r(double a) { return r2r(a * M_PI / 180); } double g2d(double a) { return d2d(a * 9 / 10); } double g2m(double a) { return m2m(a * 16); } double g2r(double a) { return r2r(a * M_PI / 200); } double m2d(double a) { return d2d(a * 9 / 160); } double m2g(double a) { return g2g(a / 16); } double m2r(double a) { return r2r(a * M_PI / 3200); } double r2d(double a) { return d2d(a * 180 / M_PI); } double r2g(double a) { return g2g(a * 200 / M_PI); } double r2m(double a) { return m2m(a * 3200 / M_PI); } void print(const std::vector<double> &values, const char *s, std::function<double(double)> f) { using namespace std; ostringstream out; out << " ┌───────────────────┐\n"; out << " │ " << setw(17) << s << " │\n"; out << "┌─────────────────┼───────────────────┤\n"; for (double i : values) out << "│ " << setw(15) << fixed << i << defaultfloat << " │ " << setw(17) << fixed << f(i) << defaultfloat << " │\n"; out << "└─────────────────┴───────────────────┘\n"; auto str = out.str(); boost::algorithm::replace_all(str, ".000000", " "); cout << str; } int main() { std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 }; print(values, "normalized (deg)", d2d); print(values, "normalized (grad)", g2g); print(values, "normalized (mil)", m2m); print(values, "normalized (rad)", r2r); print(values, "deg -> grad ", d2g); print(values, "deg -> mil ", d2m); print(values, "deg -> rad ", d2r); print(values, "grad -> deg ", g2d); print(values, "grad -> mil ", g2m); print(values, "grad -> rad ", g2r); print(values, "mil -> deg ", m2d); print(values, "mil -> grad ", m2g); print(values, "mil -> rad ", m2r); print(values, "rad -> deg ", r2d); print(values, "rad -> grad ", r2g); print(values, "rad -> mil ", r2m); return 0; }
Change the programming language of this snippet from C# to C++ without modifying what it does.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks { class Program { static void Main ( string[ ] args ) { FindCommonDirectoryPath.Test ( ); } } class FindCommonDirectoryPath { public static void Test ( ) { Console.WriteLine ( "Find Common Directory Path" ); Console.WriteLine ( ); List<string> PathSet1 = new List<string> ( ); PathSet1.Add ( "/home/user1/tmp/coverage/test" ); PathSet1.Add ( "/home/user1/tmp/covert/operator" ); PathSet1.Add ( "/home/user1/tmp/coven/members" ); Console.WriteLine("Path Set 1 (All Absolute Paths):"); foreach ( string path in PathSet1 ) { Console.WriteLine ( path ); } Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) ); } public static string FindCommonPath ( string Separator, List<string> Paths ) { string CommonPath = String.Empty; List<string> SeparatedPath = Paths .First ( str => str.Length == Paths.Max ( st2 => st2.Length ) ) .Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries ) .ToList ( ); foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) ) { if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) ) { CommonPath = PathSegment; } else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) ) { CommonPath += Separator + PathSegment; } else { break; } } return CommonPath; } } }
#include <algorithm> #include <iostream> #include <string> #include <vector> std::string longestPath( const std::vector<std::string> & , char ) ; int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std::vector<std::string> myDirs ( dirs , dirs + 3 ) ; std::cout << "The longest common path of the given directories is " << longestPath( myDirs , '/' ) << "!\n" ; return 0 ; } std::string longestPath( const std::vector<std::string> & dirs , char separator ) { std::vector<std::string>::const_iterator vsi = dirs.begin( ) ; int maxCharactersCommon = vsi->length( ) ; std::string compareString = *vsi ; for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) { std::pair<std::string::const_iterator , std::string::const_iterator> p = std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ; if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) maxCharactersCommon = p.first - compareString.begin( ) ; } std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ; return compareString.substr( 0 , found ) ; }
Change the programming language of this snippet from C++ to C# without modifying what it does.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
Translate the given C# code snippet into C++ without altering its behavior.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
Change the following C# code into C++ without altering its purpose.
using System; using System.Runtime.InteropServices; public unsafe class Program { public static unsafe void HeapMemory() { const int HEAP_ZERO_MEMORY = 0x00000008; const int size = 1000; int ph = GetProcessHeap(); void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size); if (pointer == null) throw new OutOfMemoryException(); Console.WriteLine(HeapSize(ph, 0, pointer)); HeapFree(ph, 0, pointer); } public static unsafe void StackMemory() { byte* buffer = stackalloc byte[1000]; } public static void Main(string[] args) { HeapMemory(); StackMemory(); } [DllImport("kernel32")] static extern void* HeapAlloc(int hHeap, int flags, int size); [DllImport("kernel32")] static extern bool HeapFree(int hHeap, int flags, void* block); [DllImport("kernel32")] static extern int GetProcessHeap(); [DllImport("kernel32")] static extern int HeapSize(int hHeap, int flags, void* block); }
#include <string> int main() { int* p; p = new int; delete p; p = new int(2); delete p; std::string* p2; p2 = new std::string; delete p2; p = new int[10]; delete[] p; p2 = new std::string[10]; delete[] p2; }
Write a version of this C# function in C++ with identical behavior.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaTicTacToe { class Program { static string[][] Players = new string[][] { new string[] { "COMPUTER", "X" }, new string[] { "HUMAN", "O" } }; const int Unplayed = -1; const int Computer = 0; const int Human = 1; static int[] GameBoard = new int[9]; static int[] corners = new int[] { 0, 2, 6, 8 }; static int[][] wins = new int[][] { new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } }; static void Main(string[] args) { while (true) { Console.Clear(); Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#."); initializeGameBoard(); displayGameBoard(); int currentPlayer = rnd.Next(0, 2); Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer)); while (true) { int thisMove = getMoveFor(currentPlayer); if (thisMove == Unplayed) { Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer)); break; } playMove(thisMove, currentPlayer); displayGameBoard(); if (isGameWon()) { Console.WriteLine("{0} has won the game!", playerName(currentPlayer)); break; } else if (isGameTied()) { Console.WriteLine("Cat game ... we have a tie."); break; } currentPlayer = getNextPlayer(currentPlayer); } if (!playAgain()) return; } } static int getMoveFor(int player) { if (player == Human) return getManualMove(player); else { int selectedMove = getSemiRandomMove(player); Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1); return selectedMove; } } static int getManualMove(int player) { while (true) { Console.Write("{0}, enter you move (number): ", playerName(player)); ConsoleKeyInfo keyInfo = Console.ReadKey(); Console.WriteLine(); if (keyInfo.Key == ConsoleKey.Escape) return Unplayed; if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9) { int move = keyInfo.KeyChar - '1'; if (GameBoard[move] == Unplayed) return move; else Console.WriteLine("Spot {0} is already taken, please select again.", move + 1); } else Console.WriteLine("Illegal move, please select again.\n"); } } static int getRandomMove(int player) { int movesLeft = GameBoard.Count(position => position == Unplayed); int x = rnd.Next(0, movesLeft); for (int i = 0; i < GameBoard.Length; i++) { if (GameBoard[i] == Unplayed && x < 0) return i; x--; } return Unplayed; } static int getSemiRandomMove(int player) { int posToPlay; if (checkForWinningMove(player, out posToPlay)) return posToPlay; if (checkForBlockingMove(player, out posToPlay)) return posToPlay; return getRandomMove(player); } static int getBestMove(int player) { return -1; } static bool checkForWinningMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(player, line, out posToPlay)) return true; return false; } static bool checkForBlockingMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay)) return true; return false; } static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay) { int cnt = 0; posToPlay = int.MinValue; foreach (int pos in line) { if (GameBoard[pos] == player) cnt++; else if (GameBoard[pos] == Unplayed) posToPlay = pos; } return cnt == 2 && posToPlay >= 0; } static void playMove(int boardPosition, int player) { GameBoard[boardPosition] = player; } static bool isGameWon() { return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2])); } static bool takenBySamePlayer(int a, int b, int c) { return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c]; } static bool isGameTied() { return !GameBoard.Any(spot => spot == Unplayed); } static Random rnd = new Random(); static void initializeGameBoard() { for (int i = 0; i < GameBoard.Length; i++) GameBoard[i] = Unplayed; } static string playerName(int player) { return Players[player][0]; } static string playerToken(int player) { return Players[player][1]; } static int getNextPlayer(int player) { return (player + 1) % 2; } static void displayGameBoard() { Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8)); Console.WriteLine(); } static string pieceAt(int boardPosition) { if (GameBoard[boardPosition] == Unplayed) return (boardPosition + 1).ToString(); return playerToken(GameBoard[boardPosition]); } private static bool playAgain() { Console.WriteLine("\nDo you want to play again?"); return Console.ReadKey(false).Key == ConsoleKey.Y; } } }
#include <windows.h> #include <iostream> #include <string> using namespace std; enum players { Computer, Human, Draw, None }; const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } }; class ttt { public: ttt() { _p = rand() % 2; reset(); } void play() { int res = Draw; while( true ) { drawGrid(); while( true ) { if( _p ) getHumanMove(); else getComputerMove(); drawGrid(); res = checkVictory(); if( res != None ) break; ++_p %= 2; } if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!"; else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!"; else cout << "It's a draw!"; cout << endl << endl; string r; cout << "Play again( Y / N )? "; cin >> r; if( r != "Y" && r != "y" ) return; ++_p %= 2; reset(); } } private: void reset() { for( int x = 0; x < 9; x++ ) _field[x] = None; } void drawGrid() { system( "cls" ); COORD c = { 0, 2 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); cout << " 1 | 2 | 3 " << endl; cout << "---+---+---" << endl; cout << " 4 | 5 | 6 " << endl; cout << "---+---+---" << endl; cout << " 7 | 8 | 9 " << endl << endl << endl; int f = 0; for( int y = 0; y < 5; y += 2 ) for( int x = 1; x < 11; x += 4 ) { if( _field[f] != None ) { COORD c = { x, 2 + y }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); string o = _field[f] == Computer ? "X" : "O"; cout << o; } f++; } c.Y = 9; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); } int checkVictory() { for( int i = 0; i < 8; i++ ) { if( _field[iWin[i][0]] != None && _field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] ) { return _field[iWin[i][0]]; } } int i = 0; for( int f = 0; f < 9; f++ ) { if( _field[f] != None ) i++; } if( i == 9 ) return Draw; return None; } void getHumanMove() { int m; cout << "Enter your move ( 1 - 9 ) "; while( true ) { m = 0; do { cin >> m; } while( m < 1 && m > 9 ); if( _field[m - 1] != None ) cout << "Invalid move. Try again!" << endl; else break; } _field[m - 1] = Human; } void getComputerMove() { int move = 0; do{ move = rand() % 9; } while( _field[move] != None ); for( int i = 0; i < 8; i++ ) { int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2]; if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None ) { move = try3; if( _field[try1] == Computer ) break; } if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) { move = try2; if( _field[try1] == Computer ) break; } if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None ) { move = try1; if( _field[try2] == Computer ) break; } } _field[move] = Computer; } int _p; int _field[9]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); ttt tic; tic.play(); return 0; }
Write a version of this C# function in C++ with identical behavior.
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
Maintain the same structure and functionality when rewriting this code in C#.
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
Ensure the translated C++ code behaves exactly like the original C# snippet.
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Preserve the algorithm and functionality while converting the code from C# to C++.
using System; public class SevenSidedDice { Random random = new Random(); static void Main(string[] args) { SevenSidedDice sevenDice = new SevenSidedDice(); Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven()); Console.Read(); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1 + random.Next(5); } }
template<typename F> class fivetoseven { public: fivetoseven(F f): d5(f), rem(0), max(1) {} int operator()(); private: F d5; int rem, max; }; template<typename F> int fivetoseven<F>::operator()() { while (rem/7 == max/7) { while (max < 7) { int rand5 = d5()-1; max *= 5; rem = 5*rem + rand5; } int groups = max / 7; if (rem >= 7*groups) { rem -= 7*groups; max -= 7*groups; } } int result = rem % 7; rem /= 7; max /= 7; return result+1; } int d5() { return 5.0*std::rand()/(RAND_MAX + 1.0) + 1; } fivetoseven<int(*)()> d7(d5); int main() { srand(time(0)); test_distribution(d5, 1000000, 0.001); test_distribution(d7, 1000000, 0.001); }
Produce a functionally identical C++ code for the snippet given in C#.
using System; using static System.Console; class Program { static bool[] np; static void ms(long lmt) { np = new bool[lmt]; np[0] = np[1] = true; for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n]) for (long k = n * n; k < lmt; k += n) np[k] = true; } static bool is_Mag(long n) { long res, rem; for (long p = 10; n >= p; p *= 10) { res = Math.DivRem (n, p, out rem); if (np[res + rem]) return false; } return true; } static void Main(string[] args) { ms(100_009); string mn; WriteLine("First 45{0}", mn = " magnanimous numbers:"); for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) { if (c++ < 45 || (c > 240 && c <= 250) || c > 390) Write(c <= 45 ? "{0,4} " : "{0,8:n0} ", l); if (c < 45 && c % 15 == 0) WriteLine(); if (c == 240) WriteLine ("\n\n241st through 250th{0}", mn); if (c == 390) WriteLine ("\n\n391st through 400th{0}", mn); } } }
#include <iomanip> #include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } bool is_magnanimous(unsigned int n) { for (unsigned int p = 10; n >= p; p *= 10) { if (!is_prime(n % p + n / p)) return false; } return true; } int main() { unsigned int count = 0, n = 0; std::cout << "First 45 magnanimous numbers:\n"; for (; count < 45; ++n) { if (is_magnanimous(n)) { if (count > 0) std::cout << (count % 15 == 0 ? "\n" : ", "); std::cout << std::setw(3) << n; ++count; } } std::cout << "\n\n241st through 250th magnanimous numbers:\n"; for (unsigned int i = 0; count < 250; ++n) { if (is_magnanimous(n)) { if (count++ >= 240) { if (i++ > 0) std::cout << ", "; std::cout << n; } } } std::cout << "\n\n391st through 400th magnanimous numbers:\n"; for (unsigned int i = 0; count < 400; ++n) { if (is_magnanimous(n)) { if (count++ >= 390) { if (i++ > 0) std::cout << ", "; std::cout << n; } } } std::cout << '\n'; return 0; }
Translate the given C# code snippet into C++ without altering its behavior.
class Program { static void Main(string[] args) { Console.WriteLine("Enter two integers. Space delimited please: "); string s = Console.ReadLine(); int[,] myArray=new int[(int)s[0],(int)s[2]]; myArray[0, 0] = 2; Console.WriteLine(myArray[0, 0]); Console.ReadLine(); } }
#include <iostream> int main() { int dim1, dim2; std::cin >> dim1 >> dim2; double* array_data = new double[dim1*dim2]; double** array = new double*[dim1]; for (int i = 0; i < dim1; ++i) array[i] = array_data + dim2*i; array[0][0] = 3.5; std::cout << array[0][0] << std::endl; delete[] array; delete[] array_data; return 0; }
Convert this C# snippet to C++ and keep its semantics consistent.
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Write the same code in C# as shown below in C++.
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Maintain the same structure and functionality when rewriting this code in C++.
using System; using System.Numerics; namespace PiCalc { internal class Program { private readonly BigInteger FOUR = new BigInteger(4); private readonly BigInteger SEVEN = new BigInteger(7); private readonly BigInteger TEN = new BigInteger(10); private readonly BigInteger THREE = new BigInteger(3); private readonly BigInteger TWO = new BigInteger(2); private BigInteger k = BigInteger.One; private BigInteger l = new BigInteger(3); private BigInteger n = new BigInteger(3); private BigInteger q = BigInteger.One; private BigInteger r = BigInteger.Zero; private BigInteger t = BigInteger.One; public void CalcPiDigits() { BigInteger nn, nr; bool first = true; while (true) { if ((FOUR*q + r - t).CompareTo(n*t) == -1) { Console.Write(n); if (first) { Console.Write("."); first = false; } nr = TEN*(r - (n*t)); n = TEN*(THREE*q + r)/t - (TEN*n); q *= TEN; r = nr; } else { nr = (TWO*q + r)*l; nn = (q*(SEVEN*k) + TWO + r*l)/(t*l); q *= k; t *= l; l += TWO; k += BigInteger.One; n = nn; r = nr; } } } private static void Main(string[] args) { new Program().CalcPiDigits(); } } }
#include <iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; class Gospers { cpp_int q, r, t, i, n; public: Gospers() : q{1}, r{0}, t{1}, i{1} { ++*this; } Gospers& operator++() { n = (q*(27*i-12)+5*r) / (5*t); while(n != (q*(675*i-216)+125*r)/(125*t)) { r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r); q = i*(2*i-1)*q; t = 3*(3*i+1)*(3*i+2)*t; i++; n = (q*(27*i-12)+5*r) / (5*t); } q = 10*q; r = 10*r-10*n*t; return *this; } int operator*() { return (int)n; } }; int main() { Gospers g; std::cout << *g << "."; for(;;) { std::cout << *++g; } }
Transform the following C# implementation into C++, maintaining the same output and logic.
using System; static class YCombinator<T, TResult> { private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r); public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } = f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x))); } static class Program { static void Main() { var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1)); var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2)); Console.WriteLine(fac(10)); Console.WriteLine(fib(10)); } }
#include <iostream> #include <functional> template <typename F> struct RecursiveFunc { std::function<F(RecursiveFunc)> o; }; template <typename A, typename B> std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) { RecursiveFunc<std::function<B(A)>> r = { std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) { return f(std::function<B(A)>([w](A x) { return w.o(w)(x); })); }) }; return r.o(r); } typedef std::function<int(int)> Func; typedef std::function<Func(Func)> FuncFunc; FuncFunc almost_fac = [](Func f) { return Func([f](int n) { if (n <= 1) return 1; return n * f(n - 1); }); }; FuncFunc almost_fib = [](Func f) { return Func([f](int n) { if (n <= 2) return 1; return f(n - 1) + f(n - 2); }); }; int main() { auto fib = Y(almost_fib); auto fac = Y(almost_fac); std::cout << "fib(10) = " << fib(10) << std::endl; std::cout << "fac(10) = " << fac(10) << std::endl; return 0; }
Preserve the algorithm and functionality while converting the code from C++ to C#.
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(string.Join(" ", h.Skip(i).Take(10))); } sho(0); sho(990); } }
Port the provided C# code into C++ while preserving the original functionality.
using System.Linq; class Program { static void Main() { int a, b, c, d, e, f, g; int[] h = new int[g = 1000]; for (a = 0, b = 1, c = 2; c < g; a = b, b = c++) for (d = a, e = b - d, f = h[b]; e <= b; e++) if (f == h[d--]) { h[c] = e; break; } void sho(int i) { System.Console.WriteLine(string.Join(" ", h.Skip(i).Take(10))); } sho(0); sho(990); } }
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
Transform the following C# implementation into C++, maintaining the same output and logic.
using System; class Program { static void Main(string[] args) { for (int i = 1; i <= 10; i++) { Console.Write(i); if (i % 5 == 0) { Console.WriteLine(); continue; } Console.Write(", "); } } }
for(int i = 1;i <= 10; i++){ cout << i; if(i % 5 == 0){ cout << endl; continue; } cout << ", "; }
Maintain the same structure and functionality when rewriting this code in C++.
using System; public class GeneralFizzBuzz { public static void Main() { int i; int j; int k; int limit; string iString; string jString; string kString; Console.WriteLine("First integer:"); i = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("First string:"); iString = Console.ReadLine(); Console.WriteLine("Second integer:"); j = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Second string:"); jString = Console.ReadLine(); Console.WriteLine("Third integer:"); k = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Third string:"); kString = Console.ReadLine(); Console.WriteLine("Limit (inclusive):"); limit = Convert.ToInt32(Console.ReadLine()); for(int n = 1; n<= limit; n++) { bool flag = true; if(n%i == 0) { Console.Write(iString); flag = false; } if(n%j == 0) { Console.Write(jString); flag = false; } if(n%k == 0) { Console.Write(kString); flag = false; } if(flag) Console.Write(n); Console.WriteLine(); } } }
#include <algorithm> #include <iostream> #include <vector> #include <string> class pair { public: pair( int s, std::string z ) { p = std::make_pair( s, z ); } bool operator < ( const pair& o ) const { return i() < o.i(); } int i() const { return p.first; } std::string s() const { return p.second; } private: std::pair<int, std::string> p; }; void gFizzBuzz( int c, std::vector<pair>& v ) { bool output; for( int x = 1; x <= c; x++ ) { output = false; for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) { if( !( x % ( *i ).i() ) ) { std::cout << ( *i ).s(); output = true; } } if( !output ) std::cout << x; std::cout << "\n"; } } int main( int argc, char* argv[] ) { std::vector<pair> v; v.push_back( pair( 7, "Baxx" ) ); v.push_back( pair( 3, "Fizz" ) ); v.push_back( pair( 5, "Buzz" ) ); std::sort( v.begin(), v.end() ); gFizzBuzz( 20, v ); return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the C# version.
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Rosetta.CheckPointSync; public class Program { public async Task Main() { RobotBuilder robotBuilder = new RobotBuilder(); Task work = robotBuilder.BuildRobots( "Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin", "Bender", "Number Six", "C3-PO", "Dolores"); await work; } public class RobotBuilder { static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" }; static readonly Random rng = new Random(); static readonly object key = new object(); public Task BuildRobots(params string[] robots) { int r = 0; Barrier checkpoint = new Barrier(parts.Length, b => { Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!"); Console.WriteLine(); r++; }); var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray(); return Task.WhenAll(tasks); } private static int GetTime() { lock (key) { return rng.Next(100, 1000); } } private async Task BuildPart(Barrier barrier, string part, string[] robots) { foreach (var robot in robots) { int time = GetTime(); Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms."); await Task.Delay(time); Console.WriteLine($"{part} for {robot} finished."); barrier.SignalAndWait(); } } } }
#include <iostream> #include <chrono> #include <atomic> #include <mutex> #include <random> #include <thread> std::mutex cout_lock; class Latch { std::atomic<int> semafor; public: Latch(int limit) : semafor(limit) {} void wait() { semafor.fetch_sub(1); while(semafor.load() > 0) std::this_thread::yield(); } }; struct Worker { static void do_work(int how_long, Latch& barrier, std::string name) { std::this_thread::sleep_for(std::chrono::milliseconds(how_long)); { std::lock_guard<std::mutex> lock(cout_lock); std::cout << "Worker " << name << " finished work\n"; } barrier.wait(); { std::lock_guard<std::mutex> lock(cout_lock); std::cout << "Worker " << name << " finished assembly\n"; } } }; int main() { Latch latch(5); std::mt19937 rng(std::random_device{}()); std::uniform_int_distribution<> dist(300, 3000); std::thread threads[] { std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"), std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"}, }; for(auto& t: threads) t.join(); std::cout << "Assembly is finished"; }
Translate this program into C++ but keep the logic exactly as in C#.
namespace Vlq { using System; using System.Collections.Generic; using System.Linq; public static class VarLenQuantity { public static ulong ToVlq(ulong integer) { var array = new byte[8]; var buffer = ToVlqCollection(integer) .SkipWhile(b => b == 0) .Reverse() .ToArray(); Array.Copy(buffer, array, buffer.Length); return BitConverter.ToUInt64(array, 0); } public static ulong FromVlq(ulong integer) { var collection = BitConverter.GetBytes(integer).Reverse(); return FromVlqCollection(collection); } public static IEnumerable<byte> ToVlqCollection(ulong integer) { if (integer > Math.Pow(2, 56)) throw new OverflowException("Integer exceeds max value."); var index = 7; var significantBitReached = false; var mask = 0x7fUL << (index * 7); while (index >= 0) { var buffer = (mask & integer); if (buffer > 0 || significantBitReached) { significantBitReached = true; buffer >>= index * 7; if (index > 0) buffer |= 0x80; yield return (byte)buffer; } mask >>= 7; index--; } } public static ulong FromVlqCollection(IEnumerable<byte> vlq) { ulong integer = 0; var significantBitReached = false; using (var enumerator = vlq.GetEnumerator()) { int index = 0; while (enumerator.MoveNext()) { var buffer = enumerator.Current; if (buffer > 0 || significantBitReached) { significantBitReached = true; integer <<= 7; integer |= (buffer & 0x7fUL); } if (++index == 8 || (significantBitReached && (buffer & 0x80) != 0x80)) break; } } return integer; } public static void Main() { var integers = new ulong[] { 0x7fUL << 7 * 7, 0x80, 0x2000, 0x3FFF, 0x4000, 0x200000, 0x1fffff }; foreach (var original in integers) { Console.WriteLine("Original: 0x{0:X}", original); var seq = ToVlqCollection(original); Console.WriteLine("Sequence: 0x{0}", seq.Select(b => b.ToString("X2")).Aggregate(string.Concat)); var decoded = FromVlqCollection(seq); Console.WriteLine("Decoded: 0x{0:X}", decoded); var encoded = ToVlq(original); Console.WriteLine("Encoded: 0x{0:X}", encoded); decoded = FromVlq(encoded); Console.WriteLine("Decoded: 0x{0:X}", decoded); Console.WriteLine(); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }
#include <iomanip> #include <iostream> #include <vector> std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) { auto it = v.cbegin(); auto end = v.cend(); os << "[ "; if (it != end) { os << std::setfill('0') << std::setw(2) << (uint32_t)*it; it = std::next(it); } while (it != end) { os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it; it = std::next(it); } return os << " ]"; } std::vector<uint8_t> to_seq(uint64_t x) { int i; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) { break; } } std::vector<uint8_t> out; for (int j = 0; j <= i; j++) { out.push_back(((x >> ((i - j) * 7)) & 127) | 128); } out[i] ^= 128; return out; } uint64_t from_seq(const std::vector<uint8_t> &seq) { uint64_t r = 0; for (auto b : seq) { r = (r << 7) | (b & 127); } return r; } int main() { std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL }; for (auto x : src) { auto s = to_seq(x); std::cout << std::hex; std::cout << "seq from " << x << ' ' << s << " back: " << from_seq(s) << '\n'; std::cout << std::dec; } return 0; }
Keep all operations the same but rewrite the snippet in C++.
using System; namespace StringCase { class Program { public static void Main() { String input = scope .("alphaBETA"); input.ToUpper(); Console.WriteLine(input); input.ToLower(); Console.WriteLine(input); } } }
#include <algorithm> #include <string> #include <cctype> void str_toupper(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::toupper); } void str_tolower(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::tolower); }
Keep all operations the same but rewrite the snippet in C++.
using System.Text; using System.Security.Cryptography; byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back"); byte[] hash = MD5.Create().ComputeHash(data); Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());
#include <string> #include <iostream> #include "Poco/MD5Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::MD5Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ; MD5Engine md5 ; DigestOutputStream outstr( md5 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = md5.digest( ) ; std::cout << myphrase << " as a MD5 digest :\n" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
Convert the following code from C# to C++, ensuring the logic remains intact.
class Program { static void Main(string[] args) { CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US"); string dateString = "March 7 2009 7:30pm EST"; string format = "MMMM d yyyy h:mmtt z"; DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ; DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ; Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST")); Console.ReadLine(); } }
#include <string> #include <iostream> #include <boost/date_time/local_time/local_time.hpp> #include <sstream> #include <boost/date_time/gregorian/gregorian.hpp> #include <vector> #include <boost/algorithm/string.hpp> #include <cstdlib> #include <locale> int main( ) { std::string datestring ("March 7 2009 7:30pm EST" ) ; std::vector<std::string> elements ; boost::split( elements , datestring , boost::is_any_of( " " ) ) ; std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " + elements[ 2 ] ; std::string timepart = elements[ 3 ] ; std::string timezone = elements[ 4 ] ; const char meridians[ ] = { 'a' , 'p' } ; std::string::size_type found = timepart.find_first_of( meridians, 0 ) ; std::string twelve_hour ( timepart.substr( found , 1 ) ) ; timepart = timepart.substr( 0 , found ) ; elements.clear( ) ; boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ; long hour = std::atol( (elements.begin( ))->c_str( ) ) ; if ( twelve_hour == "p" ) hour += 12 ; long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; boost::local_time::tz_database tz_db ; tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ; boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ; boost::gregorian::date_input_facet *f = new boost::gregorian::date_input_facet( "%B %d %Y" ) ; std::stringstream ss ; ss << datepart ; ss.imbue( std::locale( std::locale::classic( ) , f ) ) ; boost::gregorian::date d ; ss >> d ; boost::posix_time::time_duration td ( hour , minute , 0 ) ; boost::local_time::local_date_time lt ( d , td , dyc , boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ; std::cout << "local time: " << lt << '\n' ; ss.str( "" ) ; ss << lt ; boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ; boost::local_time::local_date_time ltlater = lt + td2 ; boost::gregorian::date_facet *f2 = new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ; std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ; std::cout << "12 hours after " << ss.str( ) << " it is " << ltlater << " !\n" ; boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ; std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ; std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ; return 0 ; }
Translate this program into C++ but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using System.Linq; using System.Threading; class Program { static void ThreadStart(object item) { Thread.Sleep(1000 * (int)item); Console.WriteLine(item); } static void SleepSort(IEnumerable<int> items) { foreach (var item in items) { new Thread(ThreadStart).Start(item); } } static void Main(string[] arguments) { SleepSort(arguments.Select(int.Parse)); } }
#include <chrono> #include <iostream> #include <thread> #include <vector> int main(int argc, char* argv[]) { std::vector<std::thread> threads; for (int i = 1; i < argc; ++i) { threads.emplace_back([i, &argv]() { int arg = std::stoi(argv[i]); std::this_thread::sleep_for(std::chrono::seconds(arg)); std::cout << argv[i] << std::endl; }); } for (auto& thread : threads) { thread.join(); } }
Translate this program into C++ but keep the logic exactly as in C#.
using System; class Program { static void Main(string[] args) { int[,] a = new int[10, 10]; Random r = new Random(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { a[i, j] = r.Next(0, 21) + 1; } } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { Console.Write(" {0}", a[i, j]); if (a[i, j] == 20) { goto Done; } } Console.WriteLine(); } Done: Console.WriteLine(); } }
#include<cstdlib> #include<ctime> #include<iostream> using namespace std; int main() { int arr[10][10]; srand(time(NULL)); for(auto& row: arr) for(auto& col: row) col = rand() % 20 + 1; ([&](){ for(auto& row : arr) for(auto& col: row) { cout << col << endl; if(col == 20)return; } })(); return 0; }
Write a version of this C# function in C++ with identical behavior.
int[] nums = { 1, 1, 2, 3, 4, 4 }; List<int> unique = new List<int>(); foreach (int n in nums) if (!unique.Contains(n)) unique.Add(n);
#include <set> #include <iostream> using namespace std; int main() { typedef set<int> TySet; int data[] = {1, 2, 3, 2, 3, 4}; TySet unique_set(data, data + 6); cout << "Set items:" << endl; for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++) cout << *iter << " "; cout << endl; }
Write the same code in C++ as shown below in C#.
using System; using System.Text; using System.Linq; class Program { static string lookandsay(string number) { StringBuilder result = new StringBuilder(); char repeat = number[0]; number = number.Substring(1, number.Length-1)+" "; int times = 1; foreach (char actual in number) { if (actual != repeat) { result.Append(Convert.ToString(times)+repeat); times = 1; repeat = actual; } else { times += 1; } } return result.ToString(); } static void Main(string[] args) { string num = "1"; foreach (int i in Enumerable.Range(1, 10)) { Console.WriteLine(num); num = lookandsay(num); } } }
#include <iostream> #include <sstream> #include <string> std::string lookandsay(const std::string& s) { std::ostringstream r; for (std::size_t i = 0; i != s.length();) { auto new_i = s.find_first_not_of(s[i], i + 1); if (new_i == std::string::npos) new_i = s.length(); r << new_i - i << s[i]; i = new_i; } return r.str(); } int main() { std::string laf = "1"; std::cout << laf << '\n'; for (int i = 0; i < 10; ++i) { laf = lookandsay(laf); std::cout << laf << '\n'; } }
Maintain the same structure and functionality when rewriting this code in C++.
System.Collections.Stack stack = new System.Collections.Stack(); stack.Push( obj ); bool isEmpty = stack.Count == 0; object top = stack.Peek(); top = stack.Pop(); System.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>(); stack.Push(new Foo()); bool isEmpty = stack.Count == 0; Foo top = stack.Peek(); top = stack.Pop();
#include <stack>
Write the same algorithm in C++ as shown in this C# implementation.
using static System.Console; using static System.Linq.Enumerable; public class Program { static void Main() { for (int i = 1; i <= 25; i++) { int t = Totient(i); WriteLine(i + "\t" + t + (t == i - 1 ? "\tprime" : "")); } WriteLine(); for (int i = 100; i <= 100_000; i *= 10) { WriteLine($"{Range(1, i).Count(x => Totient(x) + 1 == x):n0} primes below {i:n0}"); } } static int Totient(int n) { if (n < 3) return 1; if (n == 3) return 2; int totient = n; if ((n & 1) == 0) { totient >>= 1; while (((n >>= 1) & 1) == 0) ; } for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { totient -= totient / i; while ((n /= i) % i == 0) ; } } if (n > 1) totient -= totient / n; return totient; } }
#include <cassert> #include <iomanip> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) continue; for (int j = i; j <= max; j += i) totient_[j] -= totient_[j] / i; } } int totient(int n) const { assert (n >= 1 && n < totient_.size()); return totient_[n]; } bool is_prime(int n) const { return totient(n) == n - 1; } private: std::vector<int> totient_; }; int count_primes(const totient_calculator& tc, int min, int max) { int count = 0; for (int i = min; i <= max; ++i) { if (tc.is_prime(i)) ++count; } return count; } int main() { const int max = 10000000; totient_calculator tc(max); std::cout << " n totient prime?\n"; for (int i = 1; i <= 25; ++i) { std::cout << std::setw(2) << i << std::setw(9) << tc.totient(i) << std::setw(8) << (tc.is_prime(i) ? "yes" : "no") << '\n'; } for (int n = 100; n <= max; n *= 10) { std::cout << "Count of primes up to " << n << ": " << count_primes(tc, 1, n) << '\n'; } return 0; }
Port the provided C# code into C++ while preserving the original functionality.
if (condition) { } if (condition) { } else if (condition2) { } else { }
template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse; template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType> { typedef ThenType type; }; template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType> { typedef ElseType type; }; ifthenelse<INT_MAX == 32767, long int, int> ::type myvar;
Convert this C# snippet to C++ and keep its semantics consistent.
using System; using System.Collections.Generic; namespace RosettaCode { class SortCustomComparator { public void CustomSort() { String[] items = { "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; List<String> list = new List<string>(items); DisplayList("Unsorted", list); list.Sort(CustomCompare); DisplayList("Descending Length", list); list.Sort(); DisplayList("Ascending order", list); } public int CustomCompare(String x, String y) { int result = -x.Length.CompareTo(y.Length); if (result == 0) { result = x.ToLower().CompareTo(y.ToLower()); } return result; } public void DisplayList(String header, List<String> theList) { Console.WriteLine(header); Console.WriteLine("".PadLeft(header.Length, '*')); foreach (String str in theList) { Console.WriteLine(str); } Console.WriteLine(); } } }
#include <algorithm> #include <string> #include <cctype> struct icompare_char { bool operator()(char c1, char c2) { return std::toupper(c1) < std::toupper(c2); } }; struct compare { bool operator()(std::string const& s1, std::string const& s2) { if (s1.length() > s2.length()) return true; if (s1.length() < s2.length()) return false; return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), icompare_char()); } }; int main() { std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; std::sort(strings, strings+8, compare()); return 0; }
Port the following code from C# to C++ with equivalent syntax and logic.
using System; using System.Drawing; using System.Windows.Forms; namespace BasicAnimation { class BasicAnimationForm : Form { bool isReverseDirection; Label textLabel; Timer timer; internal BasicAnimationForm() { this.Size = new Size(150, 75); this.Text = "Basic Animation"; textLabel = new Label(); textLabel.Text = "Hello World! "; textLabel.Location = new Point(3,3); textLabel.AutoSize = true; textLabel.Click += new EventHandler(textLabel_OnClick); this.Controls.Add(textLabel); timer = new Timer(); timer.Interval = 500; timer.Tick += new EventHandler(timer_OnTick); timer.Enabled = true; isReverseDirection = false; } private void timer_OnTick(object sender, EventArgs e) { string oldText = textLabel.Text, newText; if(isReverseDirection) newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1); else newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1); textLabel.Text = newText; } private void textLabel_OnClick(object sender, EventArgs e) { isReverseDirection = !isReverseDirection; } } class Program { static void Main() { Application.Run(new BasicAnimationForm()); } } }
#include "animationwidget.h" #include <QLabel> #include <QTimer> #include <QVBoxLayout> #include <algorithm> AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) { setWindowTitle(tr("Animation")); QFont font("Courier", 24); QLabel* label = new QLabel("Hello World! "); label->setFont(font); QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(label); QTimer* timer = new QTimer(this); connect(timer, &QTimer::timeout, this, [label,this]() { QString text = label->text(); std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end()); label->setText(text); }); timer->start(200); } void AnimationWidget::mousePressEvent(QMouseEvent*) { right_ = !right_; }
Convert the following code from C# to C++, ensuring the logic remains intact.
using System; namespace RadixSort { class Program { static void Sort(int[] old) { int i, j; int[] tmp = new int[old.Length]; for (int shift = 31; shift > -1; --shift) { j = 0; for (i = 0; i < old.Length; ++i) { bool move = (old[i] << shift) >= 0; if (shift == 0 ? !move : move) old[i-j] = old[i]; else tmp[j++] = old[i]; } Array.Copy(tmp, 0, old, old.Length-j, j); } } static void Main(string[] args) { int[] old = new int[] { 2, 5, 1, -3, 4 }; Console.WriteLine(string.Join(", ", old)); Sort(old); Console.WriteLine(string.Join(", ", old)); Console.Read(); } } }
#include <algorithm> #include <iostream> #include <iterator> class radix_test { const int bit; public: radix_test(int offset) : bit(offset) {} bool operator()(int value) const { if (bit == 31) return value < 0; else return !(value & (1 << bit)); } }; void lsd_radix_sort(int *first, int *last) { for (int lsb = 0; lsb < 32; ++lsb) { std::stable_partition(first, last, radix_test(lsb)); } } void msd_radix_sort(int *first, int *last, int msb = 31) { if (first != last && msb >= 0) { int *mid = std::partition(first, last, radix_test(msb)); msb--; msd_radix_sort(first, mid, msb); msd_radix_sort(mid, last, msb); } } int main() { int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 }; lsd_radix_sort(data, data + 8); std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, " ")); return 0; }
Convert this C# block to C++, preserving its control flow and logic.
using System.Linq; static class Program { static void Main() { var ts = from a in Enumerable.Range(1, 20) from b in Enumerable.Range(a, 21 - a) from c in Enumerable.Range(b, 21 - b) where a * a + b * b == c * c select new { a, b, c }; foreach (var t in ts) System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c); } }
#include <vector> #include <cmath> #include <iostream> #include <algorithm> #include <iterator> void list_comprehension( std::vector<int> & , int ) ; int main( ) { std::vector<int> triangles ; list_comprehension( triangles , 20 ) ; std::copy( triangles.begin( ) , triangles.end( ) , std::ostream_iterator<int>( std::cout , " " ) ) ; std::cout << std::endl ; return 0 ; } void list_comprehension( std::vector<int> & numbers , int upper_border ) { for ( int a = 1 ; a < upper_border ; a++ ) { for ( int b = a + 1 ; b < upper_border ; b++ ) { double c = pow( a * a + b * b , 0.5 ) ; if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) { if ( c == floor( c ) ) { numbers.push_back( a ) ; numbers.push_back( b ) ; numbers.push_back( static_cast<int>( c ) ) ; } } } } }
Maintain the same structure and functionality when rewriting this code in C++.
class SelectionSort<T> where T : IComparable { public T[] Sort(T[] list) { int k; T temp; for (int i = 0; i < list.Length; i++) { k = i; for (int j=i + 1; j < list.Length; j++) { if (list[j].CompareTo(list[k]) < 0) { k = j; } } temp = list[i]; list[i] = list[k]; list[k] = temp; } return list; } }
#include <algorithm> #include <iterator> #include <iostream> template<typename ForwardIterator> void selection_sort(ForwardIterator begin, ForwardIterator end) { for(auto i = begin; i != end; ++i) { std::iter_swap(i, std::min_element(i, end)); } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; selection_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
Preserve the algorithm and functionality while converting the code from C# to C++.
int[] intArray = { 1, 2, 3, 4, 5 }; int[] squares1 = intArray.Select(x => x * x).ToArray(); int[] squares2 = (from x in intArray select x * x).ToArray(); foreach (var i in intArray) Console.WriteLine(i * i);
#include <iostream> #include <algorithm> void print_square(int i) { std::cout << i*i << " "; } int main() { int ary[]={1,2,3,4,5}; std::for_each(ary,ary+5,print_square); return 0; }
Rewrite the snippet below in C++ so it works the same as the original C# code.
public sealed class Singleton1 { private static Singleton1 instance; private static readonly object lockObj = new object(); public static Singleton1 Instance { get { lock(lockObj) { if (instance == null) { instance = new Singleton1(); } } return instance; } } }
#include <stdexcept> template <typename Self> class singleton { protected: static Self* sentry; public: static Self& instance() { return *sentry; } singleton() { if(sentry) throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!"); sentry = (Self*)this; } virtual ~singleton() { if(sentry == this) sentry = 0; } }; template <typename Self> Self* singleton<Self>::sentry = 0; #include <iostream> #include <string> using namespace std; class controller : public singleton<controller> { public: controller(string const& name) : name(name) { trace("begin"); } ~controller() { trace("end"); } void work() { trace("doing stuff"); } void trace(string const& message) { cout << name << ": " << message << endl; } string name; }; int main() { controller* first = new controller("first"); controller::instance().work(); delete first; controller second("second"); controller::instance().work(); try { controller goner("goner"); controller::instance().work(); } catch(exception const& error) { cout << error.what() << endl; } controller::instance().work(); controller goner("goner"); controller::instance().work(); }
Ensure the translated C++ code behaves exactly like the original C# snippet.
using System; namespace SafeAddition { class Program { static float NextUp(float d) { if (d == 0.0) return float.Epsilon; if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d; byte[] bytes = BitConverter.GetBytes(d); int dl = BitConverter.ToInt32(bytes, 0); dl++; bytes = BitConverter.GetBytes(dl); return BitConverter.ToSingle(bytes, 0); } static float NextDown(float d) { if (d == 0.0) return -float.Epsilon; if (float.IsNaN(d) || float.IsNegativeInfinity(d) || float.IsPositiveInfinity(d)) return d; byte[] bytes = BitConverter.GetBytes(d); int dl = BitConverter.ToInt32(bytes, 0); dl--; bytes = BitConverter.GetBytes(dl); return BitConverter.ToSingle(bytes, 0); } static Tuple<float, float> SafeAdd(float a, float b) { return new Tuple<float, float>(NextDown(a + b), NextUp(a + b)); } static void Main(string[] args) { float a = 1.20f; float b = 0.03f; Console.WriteLine("({0} + {1}) is in the range {2}", a, b, SafeAdd(a, b)); } } }
#include <iostream> #include <tuple> union conv { int i; float f; }; float nextUp(float d) { if (isnan(d) || d == -INFINITY || d == INFINITY) return d; if (d == 0.0) return FLT_EPSILON; conv c; c.f = d; c.i++; return c.f; } float nextDown(float d) { if (isnan(d) || d == -INFINITY || d == INFINITY) return d; if (d == 0.0) return -FLT_EPSILON; conv c; c.f = d; c.i--; return c.f; } auto safeAdd(float a, float b) { return std::make_tuple(nextDown(a + b), nextUp(a + b)); } int main() { float a = 1.20f; float b = 0.03f; auto result = safeAdd(a, b); printf("(%f + %f) is in the range (%0.16f, %0.16f)\n", a, b, std::get<0>(result), std::get<1>(result)); return 0; }
Rewrite the snippet below in C++ so it works the same as the original C# code.
for (int i = 10; i >= 0; i--) { Console.WriteLine(i); }
for(int i = 10; i >= 0; --i) std::cout << i << "\n";
Please provide an equivalent version of this C# code in C++.
System.IO.File.WriteAllText("filename.txt", "This file contains a string.");
#include <fstream> using namespace std; int main() { ofstream file("new.txt"); file << "this is a string"; file.close(); return 0; }
Generate an equivalent C++ version of this C# code.
using System; class Program { static void Main(string[] args) { for (int i = 0; i < 5; i++) { for (int j = 0; j <= i; j++) { Console.Write("*"); } Console.WriteLine(); } } }
for(int i = 0; i < 5; ++i) { for(int j = 0; j < i; ++j) std::cout.put('*'); std::cout.put('\n'); }
Change the following C# code into C++ without altering its purpose.
using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { var sequence = new[] { "A", "B", "C", "D" }; foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) { Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i]))); } } static IEnumerable<List<int>> Subsets(int length) { int[] values = Enumerable.Range(0, length).ToArray(); var stack = new Stack<int>(length); for (int i = 0; stack.Count > 0 || i < length; ) { if (i < length) { stack.Push(i++); yield return (from index in stack.Reverse() select values[index]).ToList(); } else { i = stack.Pop() + 1; if (stack.Count > 0) i = stack.Pop() + 1; } } } static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count; }
class N{ uint n,i,g,e,l; public: N(uint n): n(n-1),i{},g{},e(1),l(n-1){} bool hasNext(){ g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i; if (l==2) {l=--n; e=1; return true;} if (e<((1<<(l-1))-1)) {++e; return true;} e=1; --l; return (l>0); } uint next() {return g;} };
Rewrite the snippet below in C++ so it works the same as the original C# code.
using System; class Program { static uint[] res = new uint[10]; static uint ri = 1, p = 10, count = 0; static void TabulateTwinPrimes(uint bound) { if (bound < 5) return; count++; uint cl = (bound - 1) >> 1, i = 1, j, limit = (uint)(Math.Sqrt(bound) - 1) >> 1; var comp = new bool[cl]; bool lp; for (j = 3; j < cl; j += 3) comp[j] = true; while (i < limit) { if (lp = !comp[i]) { uint pr = (i << 1) + 3; for (j = (pr * pr - 2) >> 1; j < cl; j += pr) comp[j] = true; } if (!comp[++i]) { uint pr = (i << 1) + 3; if (lp) { if (pr > p) { res[ri++] = count; p *= 10; } count++; i++; } for (j = (pr * pr - 2) >> 1; j < cl; j += pr) comp[j] = true; } } cl--; while (i < cl) { lp = !comp[i++]; if (!comp[i] && lp) { if ((i++ << 1) + 3 > p) { res[ri++] = count; p *= 10; } count++; } } res[ri] = count; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); string fmt = "{0,9:n0} twin primes below {1,-13:n0}"; TabulateTwinPrimes(1_000_000_000); sw.Stop(); p = 1; for (var j = 1; j <= ri; j++) Console.WriteLine(fmt, res[j], p *= 10); Console.Write("{0} sec", sw.Elapsed.TotalSeconds); } }
#include <cstdint> #include <iostream> #include <string> #include <primesieve.hpp> void print_twin_prime_count(long long limit) { std::cout << "Number of twin prime pairs less than " << limit << " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n'; } int main(int argc, char** argv) { std::cout.imbue(std::locale("")); if (argc > 1) { for (int i = 1; i < argc; ++i) { try { print_twin_prime_count(std::stoll(argv[i])); } catch (const std::exception& ex) { std::cerr << "Cannot parse limit from '" << argv[i] << "'\n"; } } } else { uint64_t limit = 10; for (int power = 1; power < 12; ++power, limit *= 10) print_twin_prime_count(limit); } return 0; }
Rewrite the snippet below in C++ so it works the same as the original C# code.
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; class Program { static IEnumerable<Complex> RootsOfUnity(int degree) { return Enumerable .Range(0, degree) .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree)); } static void Main() { var degree = 3; foreach (var root in RootsOfUnity(degree)) { Console.WriteLine(root); } } }
#include <complex> #include <cmath> #include <iostream> double const pi = 4 * std::atan(1); int main() { for (int n = 2; n <= 10; ++n) { std::cout << n << ": "; for (int k = 0; k < n; ++k) std::cout << std::polar(1, 2*pi*k/n) << " "; std::cout << std::endl; } }
Generate an equivalent C++ version of this C# code.
using System; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static decimal mx = 1E28M, hm = 1E14M, a; struct bi { public decimal hi, lo; } static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; } static string toStr(bi a, bool comma = false) { string r = a.hi == 0 ? string.Format("{0:0}", a.lo) : string.Format("{0:0}{1:" + new string('0', 28) + "}", a.hi, a.lo); if (!comma) return r; string rc = ""; for (int i = r.Length - 3; i > 0; i -= 3) rc = "," + r.Substring(i, 3) + rc; return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; } static decimal Pow_dec(decimal bas, uint exp) { if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp; if ((exp & 1) == 0) return tmp; return tmp * bas; } static void Main(string[] args) { for (uint p = 64; p < 95; p += 30) { bi x = set4sq(a = Pow_dec(2M, p)), y; WriteLine("The square of (2^{0}): {1,38:n0}", p, a); BI BS = BI.Pow((BI)a, 2); y.lo = x.lo * x.lo; y.hi = x.hi * x.hi; a = x.hi * x.lo * 2M; y.hi += Math.Floor(a / hm); y.lo += (a % hm) * hm; while (y.lo > mx) { y.lo -= mx; y.hi++; } WriteLine(" is {0,75} (which {1} match the BigInteger computation)\n", toStr(y, true), BS.ToString() == toStr(y) ? "does" : "fails to"); } } }
#include <iostream> #include <sstream> typedef long long bigInt; using namespace std; class number { public: number() { s = "0"; neg = false; } number( bigInt a ) { set( a ); } number( string a ) { set( a ); } void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); } void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); } number operator * ( const number& b ) { return this->mul( b ); } number& operator *= ( const number& b ) { *this = *this * b; return *this; } number& operator = ( const number& b ) { s = b.s; return *this; } friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; } friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; } private: number mul( const number& b ) { number a; bool neg = false; string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' ); int xx, ss, rr, t, c, stp = 0; string::reverse_iterator xi = bs.rbegin(), si, ri; for( ; xi != bs.rend(); xi++ ) { c = 0; ri = r.rbegin() + stp; for( si = s.rbegin(); si != s.rend(); si++ ) { xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48; ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10; ( *ri++ ) = t + 48; } if( c > 0 ) ( *ri ) = c + 48; stp++; } trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0; if( t & 1 ) a.s = "-" + r; else a.s = r; return a; } void trimLeft( string& r ) { if( r.length() < 2 ) return; for( string::iterator x = r.begin(); x != ( r.end() - 1 ); ) { if( ( *x ) != '0' ) return; x = r.erase( x ); } } void clearStr() { for( string::iterator x = s.begin(); x != s.end(); ) { if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x ); else x++; } } string s; bool neg; }; int main( int argc, char* argv[] ) { number a, b; a.set( "18446744073709551616" ); b.set( "18446744073709551616" ); cout << a * b << endl << endl; cout << "Factor 1 = "; cin >> a; cout << "Factor 2 = "; cin >> b; cout << "Product: = " << a * b << endl << endl; return system( "pause" ); }
Change the programming language of this snippet from C# to C++ without modifying what it does.
using System; using System.Numerics; static class Program { static void Fun(ref BigInteger a, ref BigInteger b, int c) { BigInteger t = a; a = b; b = b * c + t; } static void SolvePell(int n, ref BigInteger a, ref BigInteger b) { int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1; BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x); if (a * a - n * b * b == 1) return; } } static void Main() { BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 }) { SolvePell(n, ref x, ref y); Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y); } } }
#include <iomanip> #include <iostream> #include <tuple> std::tuple<uint64_t, uint64_t> solvePell(int n) { int x = (int)sqrt(n); if (x * x == n) { return std::make_pair(1, 0); } int y = x; int z = 1; int r = 2 * x; std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0); std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e)); f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f)); a = std::get<1>(e) + x * std::get<1>(f); b = std::get<1>(f); if (a * a - n * b * b == 1) { break; } } return std::make_pair(a, b); } void test(int n) { auto r = solvePell(n); std::cout << "x^2 - " << std::setw(3) << n << " * y^2 = 1 for x = " << std::setw(21) << std::get<0>(r) << " and y = " << std::setw(21) << std::get<1>(r) << '\n'; } int main() { test(61); test(109); test(181); test(277); return 0; }
Produce a functionally identical C++ code for the snippet given in C#.
using System; namespace BullsnCows { class Program { static void Main(string[] args) { int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; KnuthShuffle<int>(ref nums); int[] chosenNum = new int[4]; Array.Copy(nums, chosenNum, 4); Console.WriteLine("Your Guess ?"); while (!game(Console.ReadLine(), chosenNum)) { Console.WriteLine("Your next Guess ?"); } Console.ReadKey(); } public static void KnuthShuffle<T>(ref T[] array) { System.Random random = new System.Random(); for (int i = 0; i < array.Length; i++) { int j = random.Next(array.Length); T temp = array[i]; array[i] = array[j]; array[j] = temp; } } public static bool game(string guess, int[] num) { char[] guessed = guess.ToCharArray(); int bullsCount = 0, cowsCount = 0; if (guessed.Length != 4) { Console.WriteLine("Not a valid guess."); return false; } for (int i = 0; i < 4; i++) { int curguess = (int) char.GetNumericValue(guessed[i]); if (curguess < 1 || curguess > 9) { Console.WriteLine("Digit must be ge greater 0 and lower 10."); return false; } if (curguess == num[i]) { bullsCount++; } else { for (int j = 0; j < 4; j++) { if (curguess == num[j]) cowsCount++; } } } if (bullsCount == 4) { Console.WriteLine("Congratulations! You have won!"); return true; } else { Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount); return false; } } } }
#include <iostream> #include <string> #include <algorithm> #include <cstdlib> bool contains_duplicates(std::string s) { std::sort(s.begin(), s.end()); return std::adjacent_find(s.begin(), s.end()) != s.end(); } void game() { typedef std::string::size_type index; std::string symbols = "0123456789"; unsigned int const selection_length = 4; std::random_shuffle(symbols.begin(), symbols.end()); std::string selection = symbols.substr(0, selection_length); std::string guess; while (std::cout << "Your guess? ", std::getline(std::cin, guess)) { if (guess.length() != selection_length || guess.find_first_not_of(symbols) != std::string::npos || contains_duplicates(guess)) { std::cout << guess << " is not a valid guess!"; continue; } unsigned int bulls = 0; unsigned int cows = 0; for (index i = 0; i != selection_length; ++i) { index pos = selection.find(guess[i]); if (pos == i) ++bulls; else if (pos != std::string::npos) ++cows; } std::cout << bulls << " bulls, " << cows << " cows.\n"; if (bulls == selection_length) { std::cout << "Congratulations! You have won!\n"; return; } } std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n"; std::exit(EXIT_FAILURE); } int main() { std::cout << "Welcome to bulls and cows!\nDo you want to play? "; std::string answer; while (true) { while (true) { if (!std::getline(std::cin, answer)) { std::cout << "I can't get an answer. Exiting.\n"; return EXIT_FAILURE; } if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y") break; if (answer == "no" || answer == "No" || answer == "n" || answer == "N") { std::cout << "Ok. Goodbye.\n"; return EXIT_SUCCESS; } std::cout << "Please answer yes or no: "; } game(); std::cout << "Another game? "; } }
Port the following code from C# to C++ with equivalent syntax and logic.
using System; using System.Collections.Generic; namespace RosettaCode.BubbleSort { public static class BubbleSortMethods { public static void BubbleSort<T>(this List<T> list) where T : IComparable { bool madeChanges; int itemCount = list.Count; do { madeChanges = false; itemCount--; for (int i = 0; i < itemCount; i++) { if (list[i].CompareTo(list[i + 1]) > 0) { T temp = list[i + 1]; list[i + 1] = list[i]; list[i] = temp; madeChanges = true; } } } while (madeChanges); } } class Program { static void Main() { List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 }; testList.BubbleSort(); foreach (var t in testList) Console.Write(t + " "); } } }
#include <algorithm> #include <iostream> #include <iterator> template <typename RandomAccessIterator> void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) { bool swapped = true; while (begin != end-- && swapped) { swapped = false; for (auto i = begin; i != end; ++i) { if (*(i + 1) < *i) { std::iter_swap(i, i + 1); swapped = true; } } } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bubble_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
Translate this program into C++ but keep the logic exactly as in C#.
using System; using System.Collections.Generic; namespace RosettaCode.BubbleSort { public static class BubbleSortMethods { public static void BubbleSort<T>(this List<T> list) where T : IComparable { bool madeChanges; int itemCount = list.Count; do { madeChanges = false; itemCount--; for (int i = 0; i < itemCount; i++) { if (list[i].CompareTo(list[i + 1]) > 0) { T temp = list[i + 1]; list[i + 1] = list[i]; list[i] = temp; madeChanges = true; } } } while (madeChanges); } } class Program { static void Main() { List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 }; testList.BubbleSort(); foreach (var t in testList) Console.Write(t + " "); } } }
#include <algorithm> #include <iostream> #include <iterator> template <typename RandomAccessIterator> void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) { bool swapped = true; while (begin != end-- && swapped) { swapped = false; for (auto i = begin; i != end; ++i) { if (*(i + 1) < *i) { std::iter_swap(i, i + 1); swapped = true; } } } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bubble_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
Produce a functionally identical C++ code for the snippet given in C#.
using System; using System.IO; namespace FileIO { class Program { static void Main() { String s = scope .(); File.ReadAllText("input.txt", s); File.WriteAllText("output.txt", s); } } }
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream input ( "input.txt" ); ofstream output ("output.txt"); if (output.is_open()) { if (input.is_open()){ while (getline (input,line)) { output << line << endl; } input.close(); } else { cout << "input.txt cannot be opened!\n"; } output.close(); } else { cout << "output.txt cannot be written to!\n"; } return 0; }
Rewrite the snippet below in C++ so it works the same as the original C# code.
using System; class Program { static void Main(string[] args) { int a = Convert.ToInt32(args[0]); int b = Convert.ToInt32(args[1]); Console.WriteLine("{0} + {1} = {2}", a, b, a + b); Console.WriteLine("{0} - {1} = {2}", a, b, a - b); Console.WriteLine("{0} * {1} = {2}", a, b, a * b); Console.WriteLine("{0} / {1} = {2}", a, b, a / b); Console.WriteLine("{0} % {1} = {2}", a, b, a % b); Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b)); } }
#include <iostream> int main() { int a, b; std::cin >> a >> b; std::cout << "a+b = " << a+b << "\n"; std::cout << "a-b = " << a-b << "\n"; std::cout << "a*b = " << a*b << "\n"; std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n"; return 0; }
Ensure the translated C++ code behaves exactly like the original C# snippet.
using System; using System.Text; namespace prog { class MainClass { public static void Main (string[] args) { double[,] m = { {1,2,3},{4,5,6},{7,8,9} }; double[,] t = Transpose( m ); for( int i=0; i<t.GetLength(0); i++ ) { for( int j=0; j<t.GetLength(1); j++ ) Console.Write( t[i,j] + " " ); Console.WriteLine(""); } } public static double[,] Transpose( double[,] m ) { double[,] t = new double[m.GetLength(1),m.GetLength(0)]; for( int i=0; i<m.GetLength(0); i++ ) for( int j=0; j<m.GetLength(1); j++ ) t[j,i] = m[i,j]; return t; } } }
#include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> int main() { using namespace boost::numeric::ublas; matrix<double> m(3,3); for(int i=0; i!=m.size1(); ++i) for(int j=0; j!=m.size2(); ++j) m(i,j)=3*i+j; std::cout << trans(m) << std::endl; }
Generate an equivalent C++ version of this C# code.
using System; delegate T Func<T>(); class ManOrBoy { static void Main() { Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0))); } static Func<int> C(int i) { return delegate { return i; }; } static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5) { Func<int> b = null; b = delegate { k--; return A(k, b, x1, x2, x3, x4); }; return k <= 0 ? x4() + x5() : b(); } }
#include <iostream> #include <tr1/memory> using std::tr1::shared_ptr; using std::tr1::enable_shared_from_this; struct Arg { virtual int run() = 0; virtual ~Arg() { }; }; int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>); class B : public Arg, public enable_shared_from_this<B> { private: int k; const shared_ptr<Arg> x1, x2, x3, x4; public: B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3, shared_ptr<Arg> _x4) : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { } int run() { return A(--k, shared_from_this(), x1, x2, x3, x4); } }; class Const : public Arg { private: const int x; public: Const(int _x) : x(_x) { } int run () { return x; } }; int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3, shared_ptr<Arg> x4, shared_ptr<Arg> x5) { if (k <= 0) return x4->run() + x5->run(); else { shared_ptr<Arg> b(new B(k, x1, x2, x3, x4)); return b->run(); } } int main() { std::cout << A(10, shared_ptr<Arg>(new Const(1)), shared_ptr<Arg>(new Const(-1)), shared_ptr<Arg>(new Const(-1)), shared_ptr<Arg>(new Const(1)), shared_ptr<Arg>(new Const(0))) << std::endl; return 0; }
Convert this C# block to C++, preserving its control flow and logic.
using System; class Program { static bool a(bool value) { Console.WriteLine("a"); return value; } static bool b(bool value) { Console.WriteLine("b"); return value; } static void Main() { foreach (var i in new[] { false, true }) { foreach (var j in new[] { false, true }) { Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j)); Console.WriteLine(); Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j)); Console.WriteLine(); } } } }
#include <iostream> bool a(bool in) { std::cout << "a" << std::endl; return in; } bool b(bool in) { std::cout << "b" << std::endl; return in; } void test(bool i, bool j) { std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl; std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl; } int main() { test(false, false); test(false, true); test(true, false); test(true, true); return 0; }
Generate a C++ translation of this C# snippet without changing its computational steps.
using System; class RecursionLimit { static void Main(string[] args) { Recur(0); } private static void Recur(int i) { Console.WriteLine(i); Recur(i + 1); } }
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
Please provide an equivalent version of this C++ code in C#.
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
using System; class RecursionLimit { static void Main(string[] args) { Recur(0); } private static void Recur(int i) { Console.WriteLine(i); Recur(i + 1); } }
Rewrite the snippet below in C++ so it works the same as the original C# code.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; class Program { static Size size = new Size(320, 240); static Rectangle rectsize = new Rectangle(new Point(0, 0), size); static int numpixels = size.Width * size.Height; static int numbytes = numpixels * 3; static PictureBox pb; static BackgroundWorker worker; static double time = 0; static double frames = 0; static Random rand = new Random(); static byte tmp; static byte white = 255; static byte black = 0; static int halfmax = int.MaxValue / 2; static IEnumerable<byte> YieldVodoo() { for (int i = 0; i < numpixels; i++) { tmp = rand.Next() < halfmax ? black : white; yield return tmp; yield return tmp; yield return tmp; } } static Image Randimg() { var bitmap = new Bitmap(size.Width, size.Height); var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); Marshal.Copy( YieldVodoo().ToArray<byte>(), 0, data.Scan0, numbytes); bitmap.UnlockBits(data); return bitmap; } [STAThread] static void Main() { var form = new Form(); form.AutoSize = true; form.Size = new Size(0, 0); form.Text = "Test"; form.FormClosed += delegate { Application.Exit(); }; worker = new BackgroundWorker(); worker.DoWork += delegate { System.Threading.Thread.Sleep(500); while (true) { var a = DateTime.Now; pb.Image = Randimg(); var b = DateTime.Now; time += (b - a).TotalSeconds; frames += 1; if (frames == 30) { Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time); time = 0; frames = 0; } } }; worker.RunWorkerAsync(); FlowLayoutPanel flp = new FlowLayoutPanel(); form.Controls.Add(flp); pb = new PictureBox(); pb.Size = size; flp.AutoSize = true; flp.Controls.Add(pb); form.Show(); Application.Run(); } }
#include <windows.h> #include <sstream> #include <tchar.h> using namespace std; const unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } void* getBits( void ) const { return pBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void* pBits; int width, height, wid; DWORD clr; }; class bmpNoise { public: bmpNoise() { QueryPerformanceFrequency( &_frequency ); _bmp.create( BMP_WID, BMP_HEI ); _frameTime = _fps = 0; _start = getTime(); _frames = 0; } void mainLoop() { float now = getTime(); if( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; } HDC wdc, dc = _bmp.getDC(); unsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() ); for( int y = 0; y < BMP_HEI; y++ ) { for( int x = 0; x < BMP_WID; x++ ) { if( rand() % 10 < 5 ) memset( bits, 255, 3 ); else memset( bits, 0, 3 ); bits++; } } ostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() ); wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); _frames++; _frameTime = getTime() - now; if( _frameTime > 1.0f ) _frameTime = 1.0f; } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: float getTime() { LARGE_INTEGER liTime; QueryPerformanceCounter( &liTime ); return liTime.QuadPart / ( float )_frequency.QuadPart; } myBitmap _bmp; HWND _hwnd; float _start, _fps, _frameTime; unsigned int _frames; LARGE_INTEGER _frequency; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _noise.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { _noise.mainLoop(); } } return UnregisterClass( "_MY_NOISE_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_NOISE_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_WID, BMP_HEI }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_NOISE_", ".: Noise image -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; bmpNoise _noise; }; wnd* wnd::_inst = 0; int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
Please provide an equivalent version of this C# code in C++.
static void Main(string[] args) { Console.WriteLine("Perfect numbers from 1 to 33550337:"); for (int x = 0; x < 33550337; x++) { if (IsPerfect(x)) Console.WriteLine(x + " is perfect."); } Console.ReadLine(); } static bool IsPerfect(int num) { int sum = 0; for (int i = 1; i < num; i++) { if (num % i == 0) sum += i; } return sum == num ; }
#include <iostream> using namespace std ; int divisor_sum( int number ) { int sum = 0 ; for ( int i = 1 ; i < number ; i++ ) if ( number % i == 0 ) sum += i ; return sum; } int main( ) { cout << "Perfect numbers from 1 to 33550337:\n" ; for ( int num = 1 ; num < 33550337 ; num++ ) { if (divisor_sum(num) == num) cout << num << '\n' ; } return 0 ; }
Keep all operations the same but rewrite the snippet in C++.
using System; using System.Diagnostics; using System.Linq; using System.Numerics; static class Program { static void Main() { BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2))); string result = n.ToString(); Debug.Assert(result.Length == 183231); Debug.Assert(result.StartsWith("62060698786608744707")); Debug.Assert(result.EndsWith("92256259918212890625")); Console.WriteLine("n = 5^4^3^2"); Console.WriteLine("n = {0}...{1}", result.Substring(0, 20), result.Substring(result.Length - 20, 20) ); Console.WriteLine("n digits = {0}", result.Length); } }
#include <iostream> #include <boost/multiprecision/gmp.hpp> #include <string> namespace mp = boost::multiprecision; int main(int argc, char const *argv[]) { uint64_t tmpres = mp::pow(mp::mpz_int(4) , mp::pow(mp::mpz_int(3) , 2).convert_to<uint64_t>() ).convert_to<uint64_t>(); mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres); std::string s = res.str(); std::cout << s.substr(0, 20) << "..." << s.substr(s.length() - 20, 20) << std::endl; return 0; }
Produce a language-to-language conversion: from C# to C++, same semantics.
using System; using System.Collections.Generic; using System.IO; using System.Linq; class InvertedIndex { static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary) { return dictionary .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key))) .GroupBy(keyValuePair => keyValuePair.Key) .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value)); } static void Main() { Console.Write("files: "); var files = Console.ReadLine(); Console.Write("find: "); var find = Console.ReadLine(); var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable()); Console.WriteLine("{0} found in: {1}", find, string.Join(" ", Invert(dictionary)[find])); } }
#include <algorithm> #include <fstream> #include <iostream> #include <vector> #include <string> const std::string _CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.:-_/"; const size_t MAX_NODES = 41; class node { public: node() { clear(); } node( char z ) { clear(); } ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; } void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; } bool isWord; std::vector<std::string> files; node* next[MAX_NODES]; }; class index { public: void add( std::string s, std::string fileName ) { std::transform( s.begin(), s.end(), s.begin(), tolower ); std::string h; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { if( *i == 32 ) { pushFileName( addWord( h ), fileName ); h.clear(); continue; } h.append( 1, *i ); } if( h.length() ) pushFileName( addWord( h ), fileName ); } void findWord( std::string s ) { std::vector<std::string> v = find( s ); if( !v.size() ) { std::cout << s + " was not found!\n"; return; } std::cout << s << " found in:\n"; for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) { std::cout << *i << "\n"; } std::cout << "\n"; } private: void pushFileName( node* n, std::string fn ) { std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn ); if( i == n->files.end() ) n->files.push_back( fn ); } const std::vector<std::string>& find( std::string s ) { size_t idx; std::transform( s.begin(), s.end(), s.begin(), tolower ); node* rt = &root; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { idx = _CHARS.find( *i ); if( idx < MAX_NODES ) { if( !rt->next[idx] ) return std::vector<std::string>(); rt = rt->next[idx]; } } if( rt->isWord ) return rt->files; return std::vector<std::string>(); } node* addWord( std::string s ) { size_t idx; node* rt = &root, *n; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { idx = _CHARS.find( *i ); if( idx < MAX_NODES ) { n = rt->next[idx]; if( n ){ rt = n; continue; } n = new node( *i ); rt->next[idx] = n; rt = n; } } rt->isWord = true; return rt; } node root; }; int main( int argc, char* argv[] ) { index t; std::string s; std::string files[] = { "file1.txt", "f_text.txt", "text_1b.txt" }; for( int x = 0; x < 3; x++ ) { std::ifstream f; f.open( files[x].c_str(), std::ios::in ); if( f.good() ) { while( !f.eof() ) { f >> s; t.add( s, files[x] ); s.clear(); } f.close(); } } while( true ) { std::cout << "Enter one word to search for, return to exit: "; std::getline( std::cin, s ); if( !s.length() ) break; t.findWord( s ); } return 0; }
Ensure the translated C# code behaves exactly like the original C++ snippet.
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
Using System; class Program { static int gcd(int m, int n) { return n == 0 ? Math.Abs(m) : gcd(n, n % m); } static int lcm(int m, int n) { return Math.Abs(m * n) / gcd(m, n); } static void Main() { Console.WriteLine("lcm(12,18)=" + lcm(12,18)); } }
Port the following code from C# to C++ with equivalent syntax and logic.
Using System; class Program { static int gcd(int m, int n) { return n == 0 ? Math.Abs(m) : gcd(n, n % m); } static int lcm(int m, int n) { return Math.Abs(m * n) / gcd(m, n); } static void Main() { Console.WriteLine("lcm(12,18)=" + lcm(12,18)); } }
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
Translate the given C# code snippet into C++ without altering its behavior.
class Program { static void Main(string[] args) { Random random = new Random(); while (true) { int a = random.Next(20); Console.WriteLine(a); if (a == 10) break; int b = random.Next(20) Console.WriteLine(b); } Console.ReadLine(); } }
#include <iostream> #include <ctime> #include <cstdlib> int main(){ srand(time(NULL)); while(true){ const int a = rand() % 20; std::cout << a << std::endl; if(a == 10) break; const int b = rand() % 20; std::cout << b << std::endl; } return 0; }
Convert this C++ snippet to C# and keep its semantics consistent.
#include <iostream> #include <vector> #include <algorithm> enum { EMPTY, WALL, WATER }; auto fill(const std::vector<int> b) { auto water = 0; const auto rows = *std::max_element(std::begin(b), std::end(b)); const auto cols = std::size(b); std::vector<std::vector<int>> g(rows); for (auto& r : g) { for (auto i = 0; i < cols; ++i) { r.push_back(EMPTY); } } for (auto c = 0; c < cols; ++c) { for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) { g[r][c] = WALL; } } for (auto c = 0; c < cols - 1; ++c) { auto start_row = rows - b[c]; while (start_row < rows) { if (g[start_row][c] == EMPTY) break; auto c2 = c + 1; bool hitWall = false; while (c2 < cols) { if (g[start_row][c2] == WALL) { hitWall = true; break; } ++c2; } if (hitWall) { for (auto i = c + 1; i < c2; ++i) { g[start_row][i] = WATER; ++water; } } ++start_row; } } return water; } int main() { std::vector<std::vector<int>> b = { { 1, 5, 3, 7, 2 }, { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, { 5, 5, 5, 5 }, { 5, 6, 7, 8 }, { 8, 7, 7, 6 }, { 6, 7, 10, 7, 6 } }; for (const auto v : b) { auto water = fill(v); std::cout << water << " water drops." << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
class Program { static void Main(string[] args) { int[][] wta = { new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 }, new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }}; string blk, lf = "\n", tb = "██", wr = "≈≈", mt = " "; for (int i = 0; i < wta.Length; i++) { int bpf; blk = ""; do { string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++) { if (wta[i][j] > 0) { floor += tb; wta[i][j] -= 1; bpf += 1; } else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt); } if (bpf > 0) blk = floor + lf + blk; } while (bpf > 0); while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt); while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt); if (args.Length > 0) System.Console.Write("\n{0}", blk); System.Console.WriteLine("Block {0} retains {1,2} water units.", i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2); } } }
Keep all operations the same but rewrite the snippet in C#.
#include <iostream> bool ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128]; while (true) { nc = 0; for (i = 0; i < pc; i++) { if (ispr(a = ps[i])) printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " "); for (b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i]; else break; } printf("\n%d descending primes found", c); }
using System; class Program { static bool ispr(uint n) { if ((n & 1) == 0 || n < 2) return n == 2; for (uint j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } static void Main(string[] args) { uint c = 0; int nc; var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var nxt = new uint[128]; while (true) { nc = 0; foreach (var a in ps) { if (ispr(a)) Console.Write("{0,8}{1}", a, ++c % 5 == 0 ? "\n" : " "); for (uint b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) { Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); } else break; } Console.WriteLine("\n{0} descending primes found", c); } }
Change the programming language of this snippet from C++ to C# without modifying what it does.
#include <iostream> bool ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128]; while (true) { nc = 0; for (i = 0; i < pc; i++) { if (ispr(a = ps[i])) printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " "); for (b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i]; else break; } printf("\n%d descending primes found", c); }
using System; class Program { static bool ispr(uint n) { if ((n & 1) == 0 || n < 2) return n == 2; for (uint j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } static void Main(string[] args) { uint c = 0; int nc; var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var nxt = new uint[128]; while (true) { nc = 0; foreach (var a in ps) { if (ispr(a)) Console.Write("{0,8}{1}", a, ++c % 5 == 0 ? "\n" : " "); for (uint b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) { Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); } else break; } Console.WriteLine("\n{0} descending primes found", c); } }
Port the following code from C++ to C# with equivalent syntax and logic.
#include <algorithm> #include <iostream> #include <map> #include <vector> std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) { for (auto &p : v) { auto sum = p.first + p.second; auto prod = p.first * p.second; os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod; } return os << '\n'; } void print_count(const std::vector<std::pair<int, int>> &candidates) { auto c = candidates.size(); if (c == 0) { std::cout << "no candidates\n"; } else if (c == 1) { std::cout << "one candidate\n"; } else { std::cout << c << " candidates\n"; } } auto setup() { std::vector<std::pair<int, int>> candidates; for (int x = 2; x <= 98; x++) { for (int y = x + 1; y <= 98; y++) { if (x + y <= 100) { candidates.push_back(std::make_pair(x, y)); } } } return candidates; } void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [sum](const std::pair<int, int> &pair) { auto s = pair.first + pair.second; return s == sum; } ), candidates.end()); } void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [prod](const std::pair<int, int> &pair) { auto p = pair.first * pair.second; return p == prod; } ), candidates.end()); } void statement1(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] == 1) { auto sum = pair.first + pair.second; remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } void statement2(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] > 1) { remove_by_prod(candidates, prod); loop = true; break; } } } while (loop); } void statement3(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto sum = pair.first + pair.second; uniqueMap[sum]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto sum = pair.first + pair.second; if (uniqueMap[sum] > 1) { remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } int main() { auto candidates = setup(); print_count(candidates); statement1(candidates); print_count(candidates); statement2(candidates); print_count(candidates); statement3(candidates); print_count(candidates); std::cout << candidates; return 0; }
using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { const int maxSum = 100; var pairs = ( from X in 2.To(maxSum / 2 - 1) from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum) select new { X, Y, S = X + Y, P = X * Y } ).ToHashSet(); Console.WriteLine(pairs.Count); var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet(); pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g)); Console.WriteLine(pairs.Count); pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g)); Console.WriteLine(pairs.Count); pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g)); Console.WriteLine(pairs.Count); foreach (var pair in pairs) Console.WriteLine(pair); } } public static class Extensions { public static IEnumerable<int> To(this int start, int end) { for (int i = start; i <= end; i++) yield return i; } public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source); }
Convert this C++ block to C#, preserving its control flow and logic.
#include <ciso646> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> using std::vector; using std::string; #include <exception> #include <stdexcept> template <typename...Args> std::runtime_error error( Args...args ) { return std::runtime_error( (std::ostringstream{} << ... << args).str() ); }; template <typename T> struct stack : public std::vector <T> { using base_type = std::vector <T> ; T push ( const T& x ) { base_type::push_back( x ); return x; } const T& top () { return base_type::back(); } T pop () { T x = std::move( top() ); base_type::pop_back(); return x; } bool empty() { return base_type::empty(); } }; using Number = double; using Operator_Name = string; using Precedence = int; enum class Associates { none, left_to_right, right_to_left }; struct Operator_Info { Precedence precedence; Associates associativity; }; std::unordered_map <Operator_Name, Operator_Info> Operators = { { "^", { 4, Associates::right_to_left } }, { "*", { 3, Associates::left_to_right } }, { "/", { 3, Associates::left_to_right } }, { "+", { 2, Associates::left_to_right } }, { "-", { 2, Associates::left_to_right } }, }; Precedence precedence ( const Operator_Name& op ) { return Operators[ op ].precedence; } Associates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; } using Token = string; bool is_number ( const Token& t ) { return regex_match( t, std::regex{ R"z((\d+(\.\d*)?|\.\d+)([Ee][\+\-]?\d+)?)z" } ); } bool is_operator ( const Token& t ) { return Operators.count( t ); } bool is_open_parenthesis ( const Token& t ) { return t == "("; } bool is_close_parenthesis( const Token& t ) { return t == ")"; } bool is_parenthesis ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); } template <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs ) { std::size_t n = 0; for (auto x : xs) outs << (n++ ? " " : "") << x; return outs; } #include <iomanip> struct Progressive_Display { string token_name; string token_type; Progressive_Display() { std::cout << "\n" " INPUT │ TYPE │ ACTION │ STACK │ OUTPUT\n" "────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\n"; } Progressive_Display& operator () ( const Token& token ) { token_name = token; token_type = is_operator ( token ) ? "op" : is_parenthesis( token ) ? "()" : is_number ( token ) ? "num" : ""; return *this; } Progressive_Display& operator () ( const string & description, const stack <Token> & stack, const vector <Token> & output ) { std::cout << std::right << std::setw( 7 ) << token_name << " │ " << std::left << std::setw( 4 ) << token_type << " │ " << std::setw( 16 ) << description << " │ " << std::setw( 12 ) << (std::ostringstream{} << stack).str() << " │ " << output << "\n"; return operator () ( "" ); } }; vector <Token> parse( const vector <Token> & tokens ) { vector <Token> output; stack <Token> stack; Progressive_Display display; for (auto token : tokens) if (is_number( token )) { output.push_back( token ); display( token )( "num --> output", stack, output ); } else if (is_operator( token ) or is_parenthesis( token )) { display( token ); if (!is_open_parenthesis( token )) { while (!stack.empty() and ( (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() )) or (precedence( stack.top() ) > precedence( token )) or ( (precedence( stack.top() ) == precedence( token )) and (associativity( token ) == Associates::left_to_right)))) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } if (is_close_parenthesis( token )) { stack.pop(); display( "pop", stack, output ); } } if (!is_close_parenthesis( token )) { stack.push( token ); display( "push op", stack, output ); } } else throw error( "unexpected token: ", token ); display( "END" ); while (!stack.empty()) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } return output; } int main( int argc, char** argv ) try { auto tokens = vector <Token> ( argv+1, argv+argc ); auto rpn_expr = parse( tokens ); std::cout << "\nInfix = " << tokens << "\nRPN = " << rpn_expr << "\n"; } catch (std::exception e) { std::cerr << "error: " << e.what() << "\n"; return 1; }
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; Console.WriteLine(infix.ToPostfix()); } } public static class ShuntingYard { private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators = new (string symbol, int precedence, bool rightAssociative) [] { ("^", 4, true), ("*", 3, false), ("/", 3, false), ("+", 2, false), ("-", 2, false) }.ToDictionary(op => op.symbol); public static string ToPostfix(this string infix) { string[] tokens = infix.Split(' '); var stack = new Stack<string>(); var output = new List<string>(); foreach (string token in tokens) { if (int.TryParse(token, out _)) { output.Add(token); Print(token); } else if (operators.TryGetValue(token, out var op1)) { while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) { int c = op1.precedence.CompareTo(op2.precedence); if (c < 0 || !op1.rightAssociative && c <= 0) { output.Add(stack.Pop()); } else { break; } } stack.Push(token); Print(token); } else if (token == "(") { stack.Push(token); Print(token); } else if (token == ")") { string top = ""; while (stack.Count > 0 && (top = stack.Pop()) != "(") { output.Add(top); } if (top != "(") throw new ArgumentException("No matching left parenthesis."); Print(token); } } while (stack.Count > 0) { var top = stack.Pop(); if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis."); output.Add(top); } Print("pop"); return string.Join(" ", output); void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}"); void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]"); } }
Can you help me rewrite this code in C# instead of C++, keeping it the same logically?
#include <iostream> std::string middleThreeDigits(int n) { auto number = std::to_string(std::abs(n)); auto length = number.size(); if (length < 3) { return "less than three digits"; } else if (length % 2 == 0) { return "even number of digits"; } else { return number.substr(length / 2 - 1, 3); } } int main() { auto values {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}; for (auto&& v : values) { std::cout << "middleThreeDigits(" << v << "): " << middleThreeDigits(v) << "\n"; } }
using System; namespace RosettaCode { class Program { static void Main(string[] args) { string text = Math.Abs(int.Parse(Console.ReadLine())).ToString(); Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3)); } } }
Keep all operations the same but rewrite the snippet in C#.
#include <iostream> #include <iomanip> #include <algorithm> #include <vector> unsigned gcd( unsigned i, unsigned j ) { return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j; } void createSequence( std::vector<unsigned>& seq, int c ) { if( 1500 == seq.size() ) return; unsigned t = seq.at( c ) + seq.at( c + 1 ); seq.push_back( t ); seq.push_back( seq.at( c + 1 ) ); createSequence( seq, c + 1 ); } int main( int argc, char* argv[] ) { std::vector<unsigned> seq( 2, 1 ); createSequence( seq, 0 ); std::cout << "First fifteen members of the sequence:\n "; for( unsigned x = 0; x < 15; x++ ) { std::cout << seq[x] << " "; } std::cout << "\n\n"; for( unsigned x = 1; x < 11; x++ ) { std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x ); if( i != seq.end() ) { std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } } std::cout << "\n"; std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 ); if( i != seq.end() ) { std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } std::cout << "\n"; unsigned g; bool f = false; for( int x = 0, y = 1; x < 1000; x++, y++ ) { g = gcd( seq[x], seq[y] ); if( g != 1 ) f = true; std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", " << seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" ); } std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n"; return 0; }
using System; using System.Collections.Generic; using System.Linq; static class Program { static List<int> l = new List<int>() { 1, 1 }; static int gcd(int a, int b) { return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; } static void Main(string[] args) { int max = 1000; int take = 15; int i = 1; int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 }; do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; } while (l.Count < max || l[l.Count - 2] != selection.Last()); Console.Write("The first {0} items In the Stern-Brocot sequence: ", take); Console.WriteLine("{0}\n", string.Join(", ", l.Take(take))); Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:"); foreach (int ii in selection) { int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); } Console.WriteLine(); bool good = true; for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } } Console.WriteLine("The greatest common divisor of all the two consecutive items of the" + " series up to the {0}th item is {1}always one.", max, good ? "" : "not "); } }
Maintain the same structure and functionality when rewriting this code in C#.
#include <iostream> #include <fstream> int main( int argc, char **argv ){ if( argc <= 1 ){ std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl; return -1; } std::ifstream input(argv[1]); if(!input.good()){ std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << std::endl; return -1; } std::string line, name, content; while( std::getline( input, line ).good() ){ if( line.empty() || line[0] == '>' ){ if( !name.empty() ){ std::cout << name << " : " << content << std::endl; name.clear(); } if( !line.empty() ){ name = line.substr(1); } content.clear(); } else if( !name.empty() ){ if( line.find(' ') != std::string::npos ){ name.clear(); content.clear(); } else { content += line; } } } if( !name.empty() ){ std::cout << name << " : " << content << std::endl; } return 0; }
using System; using System.Collections.Generic; using System.IO; using System.Text; class Program { public class FastaEntry { public string Name { get; set; } public StringBuilder Sequence { get; set; } } static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile) { FastaEntry f = null; string line; while ((line = fastaFile.ReadLine()) != null) { if (line.StartsWith(";")) continue; if (line.StartsWith(">")) { if (f != null) yield return f; f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() }; } else if (f != null) f.Sequence.Append(line); } yield return f; } static void Main(string[] args) { try { using (var fastaFile = new StreamReader("fasta.txt")) { foreach (FastaEntry f in ParseFasta(fastaFile)) Console.WriteLine("{0}: {1}", f.Name, f.Sequence); } } catch (FileNotFoundException e) { Console.WriteLine(e); } Console.ReadLine(); } }
Convert this C# block to C++, preserving its control flow and logic.
string path = @"C:\Windows\System32"; string multiline = @"Line 1. Line 2. Line 3.";
auto strA = R"(this is a newline-separated raw string)";
Can you help me rewrite this code in C++ instead of C#, keeping it the same logically?
enum fruits { apple, banana, cherry } enum fruits { apple = 0, banana = 1, cherry = 2 } enum fruits : int { apple = 0, banana = 1, cherry = 2 } [FlagsAttribute] enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
Ensure the translated C++ code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordinates(int row, int col) { this.row = row; this.col = col; } public Boolean Equals(Coordinates c) { if (this.row == c.row && this.col == c.col) return true; else return false; } } public class Cell { public int cost; public int g; public int f; public Coordinates parent; } public class Astar { public Cell[,] cells = new Cell[8, 8]; public List<Coordinates> path = new List<Coordinates>(); public List<Coordinates> opened = new List<Coordinates>(); public List<Coordinates> closed = new List<Coordinates>(); public Coordinates startCell = new Coordinates(0, 0); public Coordinates finishCell = new Coordinates(7, 7); public Astar() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cells[i, j] = new Cell(); cells[i, j].parent = new Coordinates(); if (IsAWall(i, j)) cells[i, j].cost = 100; else cells[i, j].cost = 1; } opened.Add(startCell); Boolean pathFound = false; do { List<Coordinates> neighbors = new List<Coordinates>(); Coordinates currentCell = ShorterExpectedPath(); neighbors = neighborsCells(currentCell); foreach (Coordinates newCell in neighbors) { if (newCell.row == finishCell.row && newCell.col == finishCell.col) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; pathFound = true; break; } else if (!opened.Contains(newCell) && !closed.Contains(newCell)) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); } else if (cells[newCell.row, newCell.col].g > cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); ResetCell(newCell, closed); } } SetCell(currentCell, closed); ResetCell(currentCell, opened); } while (opened.Count > 0 && pathFound == false); if (pathFound) { path.Add(finishCell); Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col); while (cells[currentCell.row, currentCell.col].parent.row >= 0) { path.Add(cells[currentCell.row, currentCell.col].parent); int tmp_row = cells[currentCell.row, currentCell.col].parent.row; currentCell.col = cells[currentCell.row, currentCell.col].parent.col; currentCell.row = tmp_row; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { char gr = '.'; if (path.Contains(new Coordinates(i, j))) { gr = 'X'; } else if (cells[i, j].cost > 1) { gr = '\u2588'; } System.Console.Write(gr); } System.Console.WriteLine(); } System.Console.Write("\nPath: "); for (int i = path.Count - 1; i >= 0; i--) { System.Console.Write("({0},{1})", path[i].row, path[i].col); } System.Console.WriteLine("\nPath cost: {0}", path.Count - 1); String wt = System.Console.ReadLine(); } } public Coordinates ShorterExpectedPath() { int sep = 0; if (opened.Count > 1) { for (int i = 1; i < opened.Count; i++) { if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row, opened[sep].col].f) { sep = i; } } } return opened[sep]; } public List<Coordinates> neighborsCells(Coordinates c) { List<Coordinates> lc = new List<Coordinates>(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 && (i != 0 || j != 0)) { lc.Add(new Coordinates(c.row + i, c.col + j)); } return lc; } public bool IsAWall(int row, int col) { int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 }, { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } }; bool found = false; for (int i = 0; i < walls.GetLength(0); i++) if (walls[i,0] == row && walls[i,1] == col) found = true; return found; } public int Heuristic(Coordinates cell) { int dRow = Math.Abs(finishCell.row - cell.row); int dCol = Math.Abs(finishCell.col - cell.col); return Math.Max(dRow, dCol); } public void SetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell) == false) { coordinatesList.Add(cell); } } public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell)) { coordinatesList.Remove(cell); } } } static void Main(string[] args) { Astar astar = new Astar(); } } }
#include <list> #include <algorithm> #include <iostream> class point { public: point( int a = 0, int b = 0 ) { x = a; y = b; } bool operator ==( const point& o ) { return o.x == x && o.y == y; } point operator +( const point& o ) { return point( o.x + x, o.y + y ); } int x, y; }; class map { public: map() { char t[8][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0} }; w = h = 8; for( int r = 0; r < h; r++ ) for( int s = 0; s < w; s++ ) m[s][r] = t[r][s]; } int operator() ( int x, int y ) { return m[x][y]; } char m[8][8]; int w, h; }; class node { public: bool operator == (const node& o ) { return pos == o.pos; } bool operator == (const point& o ) { return pos == o; } bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; } point pos, parent; int dist, cost; }; class aStar { public: aStar() { neighbours[0] = point( -1, -1 ); neighbours[1] = point( 1, -1 ); neighbours[2] = point( -1, 1 ); neighbours[3] = point( 1, 1 ); neighbours[4] = point( 0, -1 ); neighbours[5] = point( -1, 0 ); neighbours[6] = point( 0, 1 ); neighbours[7] = point( 1, 0 ); } int calcDist( point& p ){ int x = end.x - p.x, y = end.y - p.y; return( x * x + y * y ); } bool isValid( point& p ) { return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h ); } bool existPoint( point& p, int cost ) { std::list<node>::iterator i; i = std::find( closed.begin(), closed.end(), p ); if( i != closed.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { closed.erase( i ); return false; } } i = std::find( open.begin(), open.end(), p ); if( i != open.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { open.erase( i ); return false; } } return false; } bool fillOpen( node& n ) { int stepCost, nc, dist; point neighbour; for( int x = 0; x < 8; x++ ) { stepCost = x < 4 ? 1 : 1; neighbour = n.pos + neighbours[x]; if( neighbour == end ) return true; if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) { nc = stepCost + n.cost; dist = calcDist( neighbour ); if( !existPoint( neighbour, nc + dist ) ) { node m; m.cost = nc; m.dist = dist; m.pos = neighbour; m.parent = n.pos; open.push_back( m ); } } } return false; } bool search( point& s, point& e, map& mp ) { node n; end = e; start = s; m = mp; n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s ); open.push_back( n ); while( !open.empty() ) { node n = open.front(); open.pop_front(); closed.push_back( n ); if( fillOpen( n ) ) return true; } return false; } int path( std::list<point>& path ) { path.push_front( end ); int cost = 1 + closed.back().cost; path.push_front( closed.back().pos ); point parent = closed.back().parent; for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) { if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) { path.push_front( ( *i ).pos ); parent = ( *i ).parent; } } path.push_front( start ); return cost; } map m; point end, start; point neighbours[8]; std::list<node> open; std::list<node> closed; }; int main( int argc, char* argv[] ) { map m; point s, e( 7, 7 ); aStar as; if( as.search( s, e, m ) ) { std::list<point> path; int c = as.path( path ); for( int y = -1; y < 9; y++ ) { for( int x = -1; x < 9; x++ ) { if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 ) std::cout << char(0xdb); else { if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() ) std::cout << "x"; else std::cout << "."; } } std::cout << "\n"; } std::cout << "\nPath cost " << c << ": "; for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) { std::cout<< "(" << ( *i ).x << ", " << ( *i ).y << ") "; } } std::cout << "\n\n"; return 0; }
Produce a functionally identical C++ code for the snippet given in C#.
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordinates(int row, int col) { this.row = row; this.col = col; } public Boolean Equals(Coordinates c) { if (this.row == c.row && this.col == c.col) return true; else return false; } } public class Cell { public int cost; public int g; public int f; public Coordinates parent; } public class Astar { public Cell[,] cells = new Cell[8, 8]; public List<Coordinates> path = new List<Coordinates>(); public List<Coordinates> opened = new List<Coordinates>(); public List<Coordinates> closed = new List<Coordinates>(); public Coordinates startCell = new Coordinates(0, 0); public Coordinates finishCell = new Coordinates(7, 7); public Astar() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cells[i, j] = new Cell(); cells[i, j].parent = new Coordinates(); if (IsAWall(i, j)) cells[i, j].cost = 100; else cells[i, j].cost = 1; } opened.Add(startCell); Boolean pathFound = false; do { List<Coordinates> neighbors = new List<Coordinates>(); Coordinates currentCell = ShorterExpectedPath(); neighbors = neighborsCells(currentCell); foreach (Coordinates newCell in neighbors) { if (newCell.row == finishCell.row && newCell.col == finishCell.col) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; pathFound = true; break; } else if (!opened.Contains(newCell) && !closed.Contains(newCell)) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); } else if (cells[newCell.row, newCell.col].g > cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); ResetCell(newCell, closed); } } SetCell(currentCell, closed); ResetCell(currentCell, opened); } while (opened.Count > 0 && pathFound == false); if (pathFound) { path.Add(finishCell); Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col); while (cells[currentCell.row, currentCell.col].parent.row >= 0) { path.Add(cells[currentCell.row, currentCell.col].parent); int tmp_row = cells[currentCell.row, currentCell.col].parent.row; currentCell.col = cells[currentCell.row, currentCell.col].parent.col; currentCell.row = tmp_row; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { char gr = '.'; if (path.Contains(new Coordinates(i, j))) { gr = 'X'; } else if (cells[i, j].cost > 1) { gr = '\u2588'; } System.Console.Write(gr); } System.Console.WriteLine(); } System.Console.Write("\nPath: "); for (int i = path.Count - 1; i >= 0; i--) { System.Console.Write("({0},{1})", path[i].row, path[i].col); } System.Console.WriteLine("\nPath cost: {0}", path.Count - 1); String wt = System.Console.ReadLine(); } } public Coordinates ShorterExpectedPath() { int sep = 0; if (opened.Count > 1) { for (int i = 1; i < opened.Count; i++) { if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row, opened[sep].col].f) { sep = i; } } } return opened[sep]; } public List<Coordinates> neighborsCells(Coordinates c) { List<Coordinates> lc = new List<Coordinates>(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 && (i != 0 || j != 0)) { lc.Add(new Coordinates(c.row + i, c.col + j)); } return lc; } public bool IsAWall(int row, int col) { int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 }, { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } }; bool found = false; for (int i = 0; i < walls.GetLength(0); i++) if (walls[i,0] == row && walls[i,1] == col) found = true; return found; } public int Heuristic(Coordinates cell) { int dRow = Math.Abs(finishCell.row - cell.row); int dCol = Math.Abs(finishCell.col - cell.col); return Math.Max(dRow, dCol); } public void SetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell) == false) { coordinatesList.Add(cell); } } public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell)) { coordinatesList.Remove(cell); } } } static void Main(string[] args) { Astar astar = new Astar(); } } }
#include <list> #include <algorithm> #include <iostream> class point { public: point( int a = 0, int b = 0 ) { x = a; y = b; } bool operator ==( const point& o ) { return o.x == x && o.y == y; } point operator +( const point& o ) { return point( o.x + x, o.y + y ); } int x, y; }; class map { public: map() { char t[8][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0} }; w = h = 8; for( int r = 0; r < h; r++ ) for( int s = 0; s < w; s++ ) m[s][r] = t[r][s]; } int operator() ( int x, int y ) { return m[x][y]; } char m[8][8]; int w, h; }; class node { public: bool operator == (const node& o ) { return pos == o.pos; } bool operator == (const point& o ) { return pos == o; } bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; } point pos, parent; int dist, cost; }; class aStar { public: aStar() { neighbours[0] = point( -1, -1 ); neighbours[1] = point( 1, -1 ); neighbours[2] = point( -1, 1 ); neighbours[3] = point( 1, 1 ); neighbours[4] = point( 0, -1 ); neighbours[5] = point( -1, 0 ); neighbours[6] = point( 0, 1 ); neighbours[7] = point( 1, 0 ); } int calcDist( point& p ){ int x = end.x - p.x, y = end.y - p.y; return( x * x + y * y ); } bool isValid( point& p ) { return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h ); } bool existPoint( point& p, int cost ) { std::list<node>::iterator i; i = std::find( closed.begin(), closed.end(), p ); if( i != closed.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { closed.erase( i ); return false; } } i = std::find( open.begin(), open.end(), p ); if( i != open.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { open.erase( i ); return false; } } return false; } bool fillOpen( node& n ) { int stepCost, nc, dist; point neighbour; for( int x = 0; x < 8; x++ ) { stepCost = x < 4 ? 1 : 1; neighbour = n.pos + neighbours[x]; if( neighbour == end ) return true; if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) { nc = stepCost + n.cost; dist = calcDist( neighbour ); if( !existPoint( neighbour, nc + dist ) ) { node m; m.cost = nc; m.dist = dist; m.pos = neighbour; m.parent = n.pos; open.push_back( m ); } } } return false; } bool search( point& s, point& e, map& mp ) { node n; end = e; start = s; m = mp; n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s ); open.push_back( n ); while( !open.empty() ) { node n = open.front(); open.pop_front(); closed.push_back( n ); if( fillOpen( n ) ) return true; } return false; } int path( std::list<point>& path ) { path.push_front( end ); int cost = 1 + closed.back().cost; path.push_front( closed.back().pos ); point parent = closed.back().parent; for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) { if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) { path.push_front( ( *i ).pos ); parent = ( *i ).parent; } } path.push_front( start ); return cost; } map m; point end, start; point neighbours[8]; std::list<node> open; std::list<node> closed; }; int main( int argc, char* argv[] ) { map m; point s, e( 7, 7 ); aStar as; if( as.search( s, e, m ) ) { std::list<point> path; int c = as.path( path ); for( int y = -1; y < 9; y++ ) { for( int x = -1; x < 9; x++ ) { if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 ) std::cout << char(0xdb); else { if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() ) std::cout << "x"; else std::cout << "."; } } std::cout << "\n"; } std::cout << "\nPath cost " << c << ": "; for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) { std::cout<< "(" << ( *i ).x << ", " << ( *i ).y << ") "; } } std::cout << "\n\n"; 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 A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordinates(int row, int col) { this.row = row; this.col = col; } public Boolean Equals(Coordinates c) { if (this.row == c.row && this.col == c.col) return true; else return false; } } public class Cell { public int cost; public int g; public int f; public Coordinates parent; } public class Astar { public Cell[,] cells = new Cell[8, 8]; public List<Coordinates> path = new List<Coordinates>(); public List<Coordinates> opened = new List<Coordinates>(); public List<Coordinates> closed = new List<Coordinates>(); public Coordinates startCell = new Coordinates(0, 0); public Coordinates finishCell = new Coordinates(7, 7); public Astar() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cells[i, j] = new Cell(); cells[i, j].parent = new Coordinates(); if (IsAWall(i, j)) cells[i, j].cost = 100; else cells[i, j].cost = 1; } opened.Add(startCell); Boolean pathFound = false; do { List<Coordinates> neighbors = new List<Coordinates>(); Coordinates currentCell = ShorterExpectedPath(); neighbors = neighborsCells(currentCell); foreach (Coordinates newCell in neighbors) { if (newCell.row == finishCell.row && newCell.col == finishCell.col) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; pathFound = true; break; } else if (!opened.Contains(newCell) && !closed.Contains(newCell)) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); } else if (cells[newCell.row, newCell.col].g > cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); ResetCell(newCell, closed); } } SetCell(currentCell, closed); ResetCell(currentCell, opened); } while (opened.Count > 0 && pathFound == false); if (pathFound) { path.Add(finishCell); Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col); while (cells[currentCell.row, currentCell.col].parent.row >= 0) { path.Add(cells[currentCell.row, currentCell.col].parent); int tmp_row = cells[currentCell.row, currentCell.col].parent.row; currentCell.col = cells[currentCell.row, currentCell.col].parent.col; currentCell.row = tmp_row; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { char gr = '.'; if (path.Contains(new Coordinates(i, j))) { gr = 'X'; } else if (cells[i, j].cost > 1) { gr = '\u2588'; } System.Console.Write(gr); } System.Console.WriteLine(); } System.Console.Write("\nPath: "); for (int i = path.Count - 1; i >= 0; i--) { System.Console.Write("({0},{1})", path[i].row, path[i].col); } System.Console.WriteLine("\nPath cost: {0}", path.Count - 1); String wt = System.Console.ReadLine(); } } public Coordinates ShorterExpectedPath() { int sep = 0; if (opened.Count > 1) { for (int i = 1; i < opened.Count; i++) { if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row, opened[sep].col].f) { sep = i; } } } return opened[sep]; } public List<Coordinates> neighborsCells(Coordinates c) { List<Coordinates> lc = new List<Coordinates>(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 && (i != 0 || j != 0)) { lc.Add(new Coordinates(c.row + i, c.col + j)); } return lc; } public bool IsAWall(int row, int col) { int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 }, { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } }; bool found = false; for (int i = 0; i < walls.GetLength(0); i++) if (walls[i,0] == row && walls[i,1] == col) found = true; return found; } public int Heuristic(Coordinates cell) { int dRow = Math.Abs(finishCell.row - cell.row); int dCol = Math.Abs(finishCell.col - cell.col); return Math.Max(dRow, dCol); } public void SetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell) == false) { coordinatesList.Add(cell); } } public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell)) { coordinatesList.Remove(cell); } } } static void Main(string[] args) { Astar astar = new Astar(); } } }
#include <list> #include <algorithm> #include <iostream> class point { public: point( int a = 0, int b = 0 ) { x = a; y = b; } bool operator ==( const point& o ) { return o.x == x && o.y == y; } point operator +( const point& o ) { return point( o.x + x, o.y + y ); } int x, y; }; class map { public: map() { char t[8][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0} }; w = h = 8; for( int r = 0; r < h; r++ ) for( int s = 0; s < w; s++ ) m[s][r] = t[r][s]; } int operator() ( int x, int y ) { return m[x][y]; } char m[8][8]; int w, h; }; class node { public: bool operator == (const node& o ) { return pos == o.pos; } bool operator == (const point& o ) { return pos == o; } bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; } point pos, parent; int dist, cost; }; class aStar { public: aStar() { neighbours[0] = point( -1, -1 ); neighbours[1] = point( 1, -1 ); neighbours[2] = point( -1, 1 ); neighbours[3] = point( 1, 1 ); neighbours[4] = point( 0, -1 ); neighbours[5] = point( -1, 0 ); neighbours[6] = point( 0, 1 ); neighbours[7] = point( 1, 0 ); } int calcDist( point& p ){ int x = end.x - p.x, y = end.y - p.y; return( x * x + y * y ); } bool isValid( point& p ) { return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h ); } bool existPoint( point& p, int cost ) { std::list<node>::iterator i; i = std::find( closed.begin(), closed.end(), p ); if( i != closed.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { closed.erase( i ); return false; } } i = std::find( open.begin(), open.end(), p ); if( i != open.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { open.erase( i ); return false; } } return false; } bool fillOpen( node& n ) { int stepCost, nc, dist; point neighbour; for( int x = 0; x < 8; x++ ) { stepCost = x < 4 ? 1 : 1; neighbour = n.pos + neighbours[x]; if( neighbour == end ) return true; if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) { nc = stepCost + n.cost; dist = calcDist( neighbour ); if( !existPoint( neighbour, nc + dist ) ) { node m; m.cost = nc; m.dist = dist; m.pos = neighbour; m.parent = n.pos; open.push_back( m ); } } } return false; } bool search( point& s, point& e, map& mp ) { node n; end = e; start = s; m = mp; n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s ); open.push_back( n ); while( !open.empty() ) { node n = open.front(); open.pop_front(); closed.push_back( n ); if( fillOpen( n ) ) return true; } return false; } int path( std::list<point>& path ) { path.push_front( end ); int cost = 1 + closed.back().cost; path.push_front( closed.back().pos ); point parent = closed.back().parent; for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) { if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) { path.push_front( ( *i ).pos ); parent = ( *i ).parent; } } path.push_front( start ); return cost; } map m; point end, start; point neighbours[8]; std::list<node> open; std::list<node> closed; }; int main( int argc, char* argv[] ) { map m; point s, e( 7, 7 ); aStar as; if( as.search( s, e, m ) ) { std::list<point> path; int c = as.path( path ); for( int y = -1; y < 9; y++ ) { for( int x = -1; x < 9; x++ ) { if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 ) std::cout << char(0xdb); else { if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() ) std::cout << "x"; else std::cout << "."; } } std::cout << "\n"; } std::cout << "\nPath cost " << c << ": "; for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) { std::cout<< "(" << ( *i ).x << ", " << ( *i ).y << ") "; } } std::cout << "\n\n"; return 0; }