Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in C while keeping its functionality equivalent to the VB version.
Option Explicit Dim seed As Long Sub Main() Dim i As Integer seed = 675248 For i = 1 To 5 Debug.Print Rand Next i End Sub Function Rand() As Variant Dim s As String s = CStr(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End Function
#include<stdio.h> long long seed; long long random(){ seed = seed * seed / 1000 % 1000000; return seed; } int main(){ seed = 675248; for(int i=1;i<=5;i++) printf("%lld\n",random()); return 0; }
Translate the given VB code snippet into C without altering its behavior.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objParamLookup = CreateObject("Scripting.Dictionary") With objParamLookup .Add "FAVOURITEFRUIT", "banana" .Add "NEEDSPEELING", "" .Add "SEEDSREMOVED", "" .Add "NUMBEROFBANANAS", "1024" .Add "NUMBEROFSTRAWBERRIES", "62000" End With Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\IN_config.txt",1) Output = "" Isnumberofstrawberries = False With objInFile Do Until .AtEndOfStream line = .ReadLine If Left(line,1) = "#" Or line = "" Then Output = Output & line & vbCrLf ElseIf Left(line,1) = " " And InStr(line,"#") Then Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf ElseIf Replace(Replace(line,";","")," ","") <> "" Then If InStr(1,line,"FAVOURITEFRUIT",1) Then Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf ElseIf InStr(1,line,"NEEDSPEELING",1) Then Output = Output & "; " & "NEEDSPEELING" & vbCrLf ElseIf InStr(1,line,"SEEDSREMOVED",1) Then Output = Output & "SEEDSREMOVED" & vbCrLf ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If End If Loop If Isnumberofstrawberries = False Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If .Close End With Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\OUT_config.txt",2,True) With objOutFile .Write Output .Close End With Set objFSO = Nothing Set objParamLookup = Nothing
#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; }
Write the same algorithm in C as shown in this VB implementation.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objParamLookup = CreateObject("Scripting.Dictionary") With objParamLookup .Add "FAVOURITEFRUIT", "banana" .Add "NEEDSPEELING", "" .Add "SEEDSREMOVED", "" .Add "NUMBEROFBANANAS", "1024" .Add "NUMBEROFSTRAWBERRIES", "62000" End With Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\IN_config.txt",1) Output = "" Isnumberofstrawberries = False With objInFile Do Until .AtEndOfStream line = .ReadLine If Left(line,1) = "#" Or line = "" Then Output = Output & line & vbCrLf ElseIf Left(line,1) = " " And InStr(line,"#") Then Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf ElseIf Replace(Replace(line,";","")," ","") <> "" Then If InStr(1,line,"FAVOURITEFRUIT",1) Then Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf ElseIf InStr(1,line,"NEEDSPEELING",1) Then Output = Output & "; " & "NEEDSPEELING" & vbCrLf ElseIf InStr(1,line,"SEEDSREMOVED",1) Then Output = Output & "SEEDSREMOVED" & vbCrLf ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If End If Loop If Isnumberofstrawberries = False Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If .Close End With Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\OUT_config.txt",2,True) With objOutFile .Write Output .Close End With Set objFSO = Nothing Set objParamLookup = Nothing
#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; }
Change the programming language of this snippet from VB to C without modifying what it does.
Set http= CreateObject("WinHttp.WinHttpRequest.5.1") Set oDic = WScript.CreateObject("scripting.dictionary") start="https://rosettacode.org" Const lang="VBScript" Dim oHF gettaskslist "about:/wiki/Category:Programming_Tasks" ,True print odic.Count gettaskslist "about:/wiki/Category:Draft_Programming_Tasks",True print "total tasks " & odic.Count gettaskslist "about:/wiki/Category:"&lang,False print "total tasks not in " & lang & " " &odic.Count & vbcrlf For Each d In odic.keys print d &vbTab & Replace(odic(d),"about:", start) next WScript.Quit(1) Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.echo " Please run this script with CScript": WScript.quit End Sub Function getpage(name) Set oHF=Nothing Set oHF = CreateObject("HTMLFILE") http.open "GET",name,False http.send oHF.write "<html><body></body></html>" oHF.body.innerHTML = http.responsetext Set getpage=Nothing End Function Sub gettaskslist(b,build) nextpage=b While nextpage <>"" nextpage=Replace(nextpage,"about:", start) WScript.Echo nextpage getpage(nextpage) Set xtoc = oHF.getElementbyId("mw-pages") nextpage="" For Each ch In xtoc.children If ch.innertext= "next page" Then nextpage=ch.attributes("href").value ElseIf ch.attributes("class").value="mw-content-ltr" Then Set ytoc=ch.children(0) Exit For End If Next For Each ch1 In ytoc.children For Each ch2 In ch1.children(1).children Set ch=ch2.children(0) If build Then odic.Add ch.innertext , ch.attributes("href").value else odic.Remove ch.innertext End if Next Next Wend End Sub
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "wren.h" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; char *ptr = realloc(mem->memory, mem->size + realsize + 1); if(!ptr) { printf("not enough memory (realloc returned NULL)\n"); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } void C_bufferAllocate(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); ms->memory = malloc(1); ms->size = 0; } void C_bufferFinalize(void* data) { struct MemoryStruct *ms = (struct MemoryStruct *)data; free(ms->memory); } void C_curlAllocate(WrenVM* vm) { CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); *pcurl = curl_easy_init(); } void C_value(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); wrenSetSlotString(vm, 0, ms->memory); } void C_easyPerform(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_perform(curl); } void C_easyCleanup(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_cleanup(curl); } void C_easySetOpt(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); if (opt < 10000) { long lparam = (long)wrenGetSlotDouble(vm, 2); curl_easy_setopt(curl, opt, lparam); } else if (opt < 20000) { if (opt == CURLOPT_WRITEDATA) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); curl_easy_setopt(curl, opt, (void *)ms); } else if (opt == CURLOPT_URL) { const char *url = wrenGetSlotString(vm, 2); curl_easy_setopt(curl, opt, url); } } else if (opt < 30000) { if (opt == CURLOPT_WRITEFUNCTION) { curl_easy_setopt(curl, opt, &WriteMemoryCallback); } } } WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { WrenForeignClassMethods methods; methods.allocate = NULL; methods.finalize = NULL; if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { methods.allocate = C_bufferAllocate; methods.finalize = C_bufferFinalize; } else if (strcmp(className, "Curl") == 0) { methods.allocate = C_curlAllocate; } } return methods; } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { if (!isStatic && strcmp(signature, "value") == 0) return C_value; } else if (strcmp(className, "Curl") == 0) { if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { switch (errorType) { case WREN_ERROR_COMPILE: printf("[%s line %d] [Error] %s\n", module, line, msg); break; case WREN_ERROR_STACK_TRACE: printf("[%s line %d] in %s\n", module, line, msg); break; case WREN_ERROR_RUNTIME: printf("[Runtime Error] %s\n", msg); break; } } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { if( result.source) free((void*)result.source); } WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { WrenLoadModuleResult result = {0}; if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { result.onComplete = loadModuleComplete; char fullName[strlen(name) + 6]; strcpy(fullName, name); strcat(fullName, ".wren"); result.source = readFile(fullName); } return result; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.errorFn = &errorFn; config.bindForeignClassFn = &bindForeignClass; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "rc_find_unimplemented_tasks.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { case WREN_RESULT_COMPILE_ERROR: printf("Compile Error!\n"); break; case WREN_RESULT_RUNTIME_ERROR: printf("Runtime Error!\n"); break; case WREN_RESULT_SUCCESS: break; } wrenFreeVM(vm); free(script); return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
public class PrimeDigits { private static boolean primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; if (r != 2 && r != 3 && r != 5 && r != 7) { return false; } n /= 10; sum += r; } return sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
#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; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
public class Compare { public static void compare (String A, String B) { if (A.equals(B)) System.debug(A + ' and ' + B + ' are lexically equal.'); else System.debug(A + ' and ' + B + ' are not lexically equal.'); if (A.equalsIgnoreCase(B)) System.debug(A + ' and ' + B + ' are case-insensitive lexically equal.'); else System.debug(A + ' and ' + B + ' are not case-insensitive lexically equal.'); if (A.compareTo(B) < 0) System.debug(A + ' is lexically before ' + B); else if (A.compareTo(B) > 0) System.debug(A + ' is lexically after ' + B); if (A.compareTo(B) >= 0) System.debug(A + ' is not lexically before ' + B); if (A.compareTo(B) <= 0) System.debug(A + ' is not lexically after ' + B); System.debug('The lexical relationship is: ' + A.compareTo(B)); } }
#include <algorithm> #include <iostream> #include <sstream> #include <string> template <typename T> void demo_compare(const T &a, const T &b, const std::string &semantically) { std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ") << "exactly " << semantically << " equal." << std::endl; std::cout << a << " and " << b << " are " << ((a != b) ? "" : "not ") << semantically << "inequal." << std::endl; std::cout << a << " is " << ((a < b) ? "" : "not ") << semantically << " ordered before " << b << '.' << std::endl; std::cout << a << " is " << ((a > b) ? "" : "not ") << semantically << " ordered after " << b << '.' << std::endl; } int main(int argc, char *argv[]) { std::string a((argc > 1) ? argv[1] : "1.2.Foo"); std::string b((argc > 2) ? argv[2] : "1.3.Bar"); demo_compare<std::string>(a, b, "lexically"); std::transform(a.begin(), a.end(), a.begin(), ::tolower); std::transform(b.begin(), b.end(), b.begin(), ::tolower); demo_compare<std::string>(a, b, "lexically"); double numA, numB; std::istringstream(a) >> numA; std::istringstream(b) >> numB; demo_compare<double>(numA, numB, "numerically"); return (a == b); }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.io.*; import java.nio.channels.*; import java.util.Date; public class TakeNotes { public static void main(String[] args) throws IOException { if (args.length > 0) { PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true)); ps.println(new Date()); ps.print("\t" + args[0]); for (int i = 1; i < args.length; i++) ps.print(" " + args[i]); ps.println(); ps.close(); } else { FileChannel fc = new FileInputStream("notes.txt").getChannel(); fc.transferTo(0, fc.size(), Channels.newChannel(System.out)); fc.close(); } } }
#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(); } } }
Write the same algorithm in C++ as shown in this Java implementation.
import static java.lang.Math.*; public class Test { final static int N = 32; final static int N2 = (N * (N - 1) / 2); final static double STEP = 0.05; static double[] xval = new double[N]; static double[] t_sin = new double[N]; static double[] t_cos = new double[N]; static double[] t_tan = new double[N]; static double[] r_sin = new double[N2]; static double[] r_cos = new double[N2]; static double[] r_tan = new double[N2]; static double rho(double[] x, double[] y, double[] r, int i, int n) { if (n < 0) return 0; if (n == 0) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } static double thiele(double[] x, double[] y, double[] r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } public static void main(String[] args) { for (int i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (int i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN; System.out.printf("%16.14f%n", 6 * thiele(t_sin, xval, r_sin, 0.5, 0)); System.out.printf("%16.14f%n", 3 * thiele(t_cos, xval, r_cos, 0.5, 0)); System.out.printf("%16.14f%n", 4 * thiele(t_tan, xval, r_tan, 1.0, 0)); } }
#include <cmath> #include <iostream> #include <iomanip> #include <string.h> constexpr unsigned int N = 32u; double xval[N], t_sin[N], t_cos[N], t_tan[N]; constexpr unsigned int N2 = N * (N - 1u) / 2u; double r_sin[N2], r_cos[N2], r_tan[N2]; double ρ(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; unsigned int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, unsigned int n) { return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } inline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); } inline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); } inline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); } int main() { constexpr double step = .05; for (auto i = 0u; i < N; i++) { xval[i] = i * step; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (auto i = 0u; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = NAN; std::cout << std::setw(16) << std::setprecision(25) << 6 * i_sin(.5) << std::endl << 3 * i_cos(.5) << std::endl << 4 * i_tan(1.) << std::endl; return 0; }
Preserve the algorithm and functionality while converting the code from Java to C++.
import static java.lang.Math.*; public class Test { final static int N = 32; final static int N2 = (N * (N - 1) / 2); final static double STEP = 0.05; static double[] xval = new double[N]; static double[] t_sin = new double[N]; static double[] t_cos = new double[N]; static double[] t_tan = new double[N]; static double[] r_sin = new double[N2]; static double[] r_cos = new double[N2]; static double[] r_tan = new double[N2]; static double rho(double[] x, double[] y, double[] r, int i, int n) { if (n < 0) return 0; if (n == 0) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } static double thiele(double[] x, double[] y, double[] r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } public static void main(String[] args) { for (int i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (int i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN; System.out.printf("%16.14f%n", 6 * thiele(t_sin, xval, r_sin, 0.5, 0)); System.out.printf("%16.14f%n", 3 * thiele(t_cos, xval, r_cos, 0.5, 0)); System.out.printf("%16.14f%n", 4 * thiele(t_tan, xval, r_tan, 1.0, 0)); } }
#include <cmath> #include <iostream> #include <iomanip> #include <string.h> constexpr unsigned int N = 32u; double xval[N], t_sin[N], t_cos[N], t_tan[N]; constexpr unsigned int N2 = N * (N - 1u) / 2u; double r_sin[N2], r_cos[N2], r_tan[N2]; double ρ(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; unsigned int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, unsigned int n) { return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } inline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); } inline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); } inline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); } int main() { constexpr double step = .05; for (auto i = 0u; i < N; i++) { xval[i] = i * step; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (auto i = 0u; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = NAN; std::cout << std::setw(16) << std::setprecision(25) << 6 * i_sin(.5) << std::endl << 3 * i_cos(.5) << std::endl << 4 * i_tan(1.) << std::endl; return 0; }
Convert the following code from Java to C++, ensuring the logic remains intact.
import java.util.*; public class FWord { private String fWord0 = ""; private String fWord1 = ""; private String nextFWord () { final String result; if ( "".equals ( fWord1 ) ) result = "1"; else if ( "".equals ( fWord0 ) ) result = "0"; else result = fWord1 + fWord0; fWord0 = fWord1; fWord1 = result; return result; } public static double entropy ( final String source ) { final int length = source.length (); final Map < Character, Integer > counts = new HashMap < Character, Integer > (); double result = 0.0; for ( int i = 0; i < length; i++ ) { final char c = source.charAt ( i ); if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); else counts.put ( c, 1 ); } for ( final int count : counts.values () ) { final double proportion = ( double ) count / length; result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); } return result; } public static void main ( final String [] args ) { final FWord fWord = new FWord (); for ( int i = 0; i < 37; ) { final String word = fWord.nextFWord (); System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) ); } } }
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
Convert the following code from Java to C++, ensuring the logic remains intact.
import java.util.*; public class FWord { private String fWord0 = ""; private String fWord1 = ""; private String nextFWord () { final String result; if ( "".equals ( fWord1 ) ) result = "1"; else if ( "".equals ( fWord0 ) ) result = "0"; else result = fWord1 + fWord0; fWord0 = fWord1; fWord1 = result; return result; } public static double entropy ( final String source ) { final int length = source.length (); final Map < Character, Integer > counts = new HashMap < Character, Integer > (); double result = 0.0; for ( int i = 0; i < length; i++ ) { final char c = source.charAt ( i ); if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); else counts.put ( c, 1 ); } for ( final int count : counts.values () ) { final double proportion = ( double ) count / length; result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); } return result; } public static void main ( final String [] args ) { final FWord fWord = new FWord (); for ( int i = 0; i < 37; ) { final String word = fWord.nextFWord (); System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) ); } } }
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.text.DecimalFormat; public class AnglesNormalizationAndConversion { public static void main(String[] args) { DecimalFormat formatAngle = new DecimalFormat("######0.000000"); DecimalFormat formatConv = new DecimalFormat("###0.0000"); System.out.printf(" degrees gradiens mils radians%n"); for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) { for ( String units : new String[] {"degrees", "gradiens", "mils", "radians"}) { double d = 0, g = 0, m = 0, r = 0; switch (units) { case "degrees": d = d2d(angle); g = d2g(d); m = d2m(d); r = d2r(d); break; case "gradiens": g = g2g(angle); d = g2d(g); m = g2m(g); r = g2r(g); break; case "mils": m = m2m(angle); d = m2d(m); g = m2g(m); r = m2r(m); break; case "radians": r = r2r(angle); d = r2d(r); g = r2g(r); m = r2m(r); break; } System.out.printf("%15s %8s = %10s %10s %10s %10s%n", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r)); } } } private static final double DEGREE = 360D; private static final double GRADIAN = 400D; private static final double MIL = 6400D; private static final double RADIAN = (2 * Math.PI); private static double d2d(double a) { return a % DEGREE; } private static double d2g(double a) { return a * (GRADIAN / DEGREE); } private static double d2m(double a) { return a * (MIL / DEGREE); } private static double d2r(double a) { return a * (RADIAN / 360); } private static double g2d(double a) { return a * (DEGREE / GRADIAN); } private static double g2g(double a) { return a % GRADIAN; } private static double g2m(double a) { return a * (MIL / GRADIAN); } private static double g2r(double a) { return a * (RADIAN / GRADIAN); } private static double m2d(double a) { return a * (DEGREE / MIL); } private static double m2g(double a) { return a * (GRADIAN / MIL); } private static double m2m(double a) { return a % MIL; } private static double m2r(double a) { return a * (RADIAN / MIL); } private static double r2d(double a) { return a * (DEGREE / RADIAN); } private static double r2g(double a) { return a * (GRADIAN / RADIAN); } private static double r2m(double a) { return a * (MIL / RADIAN); } private static double r2r(double a) { return a % RADIAN; } }
#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; }
Port the following code from Java to C++ with equivalent syntax and logic.
public class CommonPath { public static String commonPath(String... paths){ String commonPath = ""; String[][] folders = new String[paths.length][]; for(int i = 0; i < paths.length; i++){ folders[i] = paths[i].split("/"); } for(int j = 0; j < folders[0].length; j++){ String thisFolder = folders[0][j]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
#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 ) ; }
Transform the following Java implementation into C++, maintaining the same output and logic.
public class CommonPath { public static String commonPath(String... paths){ String commonPath = ""; String[][] folders = new String[paths.length][]; for(int i = 0; i < paths.length; i++){ folders[i] = paths[i].split("/"); } for(int j = 0; j < folders[0].length; j++){ String thisFolder = folders[0][j]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
#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 ) ; }
Translate the given Java code snippet into C++ without altering its behavior.
import static java.lang.Math.abs; import java.util.*; import java.util.function.IntSupplier; public class Test { static void distCheck(IntSupplier f, int nRepeats, double delta) { Map<Integer, Integer> counts = new HashMap<>(); for (int i = 0; i < nRepeats; i++) counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1); double target = nRepeats / (double) counts.size(); int deltaCount = (int) (delta / 100.0 * target); counts.forEach((k, v) -> { if (abs(target - v) >= deltaCount) System.out.printf("distribution potentially skewed " + "for '%s': '%d'%n", k, v); }); counts.keySet().stream().sorted().forEach(k -> System.out.printf("%d %d%n", k, counts.get(k))); } public static void main(String[] a) { distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1); } }
#include <map> #include <iostream> #include <cmath> template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist; for (int i = 0; i < calls; ++i) ++dist[f()]; double mean = 1.0/dist.size(); bool good = true; for (distmap::iterator i = dist.begin(); i != dist.end(); ++i) { if (std::abs((1.0 * i->second)/calls - mean) > delta) { std::cout << "Relative frequency " << i->second/(1.0*calls) << " of result " << i->first << " deviates by more than " << delta << " from the expected value " << mean << "\n"; good = false; } } return good; }
Write the same algorithm in C++ as shown in this Java implementation.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
Change the programming language of this snippet from Java to C++ without modifying what it does.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Java version.
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence areΒ : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", 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; }
Convert the following code from Java to C++, ensuring the logic remains intact.
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence areΒ : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", 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; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence areΒ : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", 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; }
Please provide an equivalent version of this Java code in C++.
Object foo = new Object(); int[] fooArray = new int[size]; int x = 0;
#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; }
Rewrite this program in C++ while keeping its functionality equivalent to the Java version.
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(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'; }
Write the same algorithm in C++ as shown in this Java implementation.
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(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'; }
Produce a functionally identical C++ code for the snippet given in Java.
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(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'; }
Write the same algorithm in C++ as shown in this Java implementation.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" =Β %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
#include <iostream> #include <fstream> #include <cmath> using namespace std; string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; } double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; } int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" =Β %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
#include <iostream> #include <fstream> #include <cmath> using namespace std; string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; } double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; } int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
Port the provided Java code into C++ while preserving the original functionality.
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4Β : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6Β : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
#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) ; }
Translate this program into C++ but keep the logic exactly as in Java.
import java.io.*; public class PeanoCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) { PeanoCurve s = new PeanoCurve(writer); final int length = 8; s.currentAngle = 90; s.currentX = length; s.currentY = length; s.lineLength = length; s.begin(656); s.execute(rewrite(4)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private PeanoCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY += length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = "L"; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'L') sb.append("LFRFL-F-RFLFR+F+LFRFL"); else if (ch == 'R') sb.append("RFLFR+F+LFRFL-F-RFLFR"); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final int ANGLE = 90; }
#include <cmath> #include <fstream> #include <iostream> #include <string> class peano_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::string& s); double x_; double y_; int angle_; int length_; }; void peano_curve::write(std::ostream& out, int size, int length, int order) { length_ = length; x_ = length; y_ = length; angle_ = 90; out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; std::string s = "L"; for (int i = 0; i < order; ++i) s = rewrite(s); execute(out, s); out << "'/>\n</svg>\n"; } std::string peano_curve::rewrite(const std::string& s) { std::string t; for (char c : s) { switch (c) { case 'L': t += "LFRFL-F-RFLFR+F+LFRFL"; break; case 'R': t += "RFLFR+F+LFRFL-F-RFLFR"; break; default: t += c; break; } } return t; } void peano_curve::line(std::ostream& out) { double theta = (3.14159265359 * angle_)/180.0; x_ += length_ * std::cos(theta); y_ += length_ * std::sin(theta); out << " L" << x_ << ',' << y_; } void peano_curve::execute(std::ostream& out, const std::string& s) { out << 'M' << x_ << ',' << y_; for (char c : s) { switch (c) { case 'F': line(out); break; case '+': angle_ = (angle_ + 90) % 360; break; case '-': angle_ = (angle_ - 90) % 360; break; } } } int main() { std::ofstream out("peano_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return 1; } peano_curve pc; pc.write(out, 656, 8, 4); return 0; }
Write the same code in C++ as shown below in Java.
import java.util.Random; public class SevenSidedDice { private static final Random rnd = new Random(); public static void main(String[] args) { SevenSidedDice now=new SevenSidedDice(); System.out.println("Random number from 1 to 7: "+now.seven()); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1+rnd.nextInt(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); }
Transform the following Java implementation into C++, maintaining the same output and logic.
import static java.lang.Math.abs; import java.util.*; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public class NoConnection { static int[][] links = { {2, 3, 4}, {3, 4, 5}, {2, 4}, {5}, {2, 3, 4}, {3, 4, 5}, }; static int[] pegs = new int[8]; public static void main(String[] args) { List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList()); do { Collections.shuffle(vals); for (int i = 0; i < pegs.length; i++) pegs[i] = vals.get(i); } while (!solved()); printResult(); } static boolean solved() { for (int i = 0; i < links.length; i++) for (int peg : links[i]) if (abs(pegs[i] - peg) == 1) return false; return true; } static void printResult() { System.out.printf(" %s %s%n", pegs[0], pegs[1]); System.out.printf("%s %s %s %s%n", pegs[2], pegs[3], pegs[4], pegs[5]); System.out.printf(" %s %s%n", pegs[6], pegs[7]); } }
#include <array> #include <iostream> #include <vector> std::vector<std::pair<int, int>> connections = { {0, 2}, {0, 3}, {0, 4}, {1, 3}, {1, 4}, {1, 5}, {6, 2}, {6, 3}, {6, 4}, {7, 3}, {7, 4}, {7, 5}, {2, 3}, {3, 4}, {4, 5}, }; std::array<int, 8> pegs; int num = 0; void printSolution() { std::cout << "----- " << num++ << " -----\n"; std::cout << " " << pegs[0] << ' ' << pegs[1] << '\n'; std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\n'; std::cout << " " << pegs[6] << ' ' << pegs[7] << '\n'; std::cout << '\n'; } bool valid() { for (size_t i = 0; i < connections.size(); i++) { if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) { return false; } } return true; } void solution(int le, int ri) { if (le == ri) { if (valid()) { printSolution(); } } else { for (size_t i = le; i <= ri; i++) { std::swap(pegs[le], pegs[i]); solution(le + 1, ri); std::swap(pegs[le], pegs[i]); } } } int main() { pegs = { 1, 2, 3, 4, 5, 6, 7, 8 }; solution(0, pegs.size() - 1); return 0; }
Change the programming language of this snippet from Java to C++ without modifying what it does.
import java.util.ArrayList; import java.util.List; public class MagnanimousNumbers { public static void main(String[] args) { runTask("Find and display the first 45 magnanimous numbers.", 1, 45); runTask("241st through 250th magnanimous numbers.", 241, 250); runTask("391st through 400th magnanimous numbers.", 391, 400); } private static void runTask(String message, int startN, int endN) { int count = 0; List<Integer> nums = new ArrayList<>(); for ( int n = 0 ; count < endN ; n++ ) { if ( isMagnanimous(n) ) { nums.add(n); count++; } } System.out.printf("%s%n", message); System.out.printf("%s%n%n", nums.subList(startN-1, endN)); } private static boolean isMagnanimous(long n) { if ( n >= 0 && n <= 9 ) { return true; } long q = 11; for ( long div = 10 ; q >= 10 ; div *= 10 ) { q = n / div; long r = n % div; if ( ! isPrime(q+r) ) { return false; } } return true; } private static final int MAX = 100_000; private static final boolean[] primes = new boolean[MAX]; private static boolean SIEVE_COMPLETE = false; private static final boolean isPrimeTrivial(long test) { if ( ! SIEVE_COMPLETE ) { sieve(); SIEVE_COMPLETE = true; } return primes[(int) test]; } private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } public static final boolean isPrime(long testValue) { if ( testValue == 2 ) return true; if ( testValue % 2 == 0 ) return false; if ( testValue <= MAX ) return isPrimeTrivial(testValue); long d = testValue-1; int s = 0; while ( d % 2 == 0 ) { s += 1; d /= 2; } if ( testValue < 1373565L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(3, s, d, testValue) ) { return false; } return true; } if ( testValue < 4759123141L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(7, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } return true; } if ( testValue < 10000000000000000L ) { if ( ! aSrp(3, s, d, testValue) ) { return false; } if ( ! aSrp(24251, s, d, testValue) ) { return false; } return true; } if ( ! aSrp(37, s, d, testValue) ) { return false; } if ( ! aSrp(47, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } if ( ! aSrp(73, s, d, testValue) ) { return false; } if ( ! aSrp(83, s, d, testValue) ) { return false; } return true; } private static final boolean aSrp(int a, int s, long d, long n) { long modPow = modPow(a, d, n); if ( modPow == 1 ) { return true; } int twoExpR = 1; for ( int r = 0 ; r < s ; r++ ) { if ( modPow(modPow, twoExpR, n) == n-1 ) { return true; } twoExpR *= 2; } return false; } private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE); public static final long modPow(long base, long exponent, long modulus) { long result = 1; while ( exponent > 0 ) { if ( exponent % 2 == 1 ) { if ( result > SQRT || base > SQRT ) { result = multiply(result, base, modulus); } else { result = (result * base) % modulus; } } exponent >>= 1; if ( base > SQRT ) { base = multiply(base, base, modulus); } else { base = (base * base) % modulus; } } return result; } public static final long multiply(long a, long b, long modulus) { long x = 0; long y = a % modulus; long t; while ( b > 0 ) { if ( b % 2 == 1 ) { t = x + y; x = (t > modulus ? t-modulus : t); } t = y << 1; y = (t > modulus ? t-modulus : t); b >>= 1; } return x % modulus; } }
#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; }
Port the provided Java code into C++ while preserving the original functionality.
import java.util.*; public class PrimeGenerator { private int limit_; private int index_ = 0; private int increment_; private int count_ = 0; private List<Integer> primes_ = new ArrayList<>(); private BitSet sieve_ = new BitSet(); private int sieveLimit_ = 0; public PrimeGenerator(int initialLimit, int increment) { limit_ = nextOddNumber(initialLimit); increment_ = increment; primes_.add(2); findPrimes(3); } public int nextPrime() { if (index_ == primes_.size()) { if (Integer.MAX_VALUE - increment_ < limit_) return 0; int start = limit_ + 2; limit_ = nextOddNumber(limit_ + increment_); primes_.clear(); findPrimes(start); } ++count_; return primes_.get(index_++); } public int count() { return count_; } private void findPrimes(int start) { index_ = 0; int newLimit = sqrt(limit_); for (int p = 3; p * p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p)); for (; q <= newLimit; q += 2*p) sieve_.set(q/2 - 1, true); } sieveLimit_ = newLimit; int count = (limit_ - start)/2 + 1; BitSet composite = new BitSet(count); for (int p = 3; p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start; q /= 2; for (; q >= 0 && q < count; q += p) composite.set(q, true); } for (int p = 0; p < count; ++p) { if (!composite.get(p)) primes_.add(p * 2 + start); } } private static int sqrt(int n) { return nextOddNumber((int)Math.sqrt(n)); } private static int nextOddNumber(int n) { return 1 + 2 * (n/2); } public static void main(String[] args) { PrimeGenerator pgen = new PrimeGenerator(20, 200000); System.out.println("First 20 primes:"); for (int i = 0; i < 20; ++i) { if (i > 0) System.out.print(", "); System.out.print(pgen.nextPrime()); } System.out.println(); System.out.println("Primes between 100 and 150:"); for (int i = 0; ; ) { int prime = pgen.nextPrime(); if (prime > 150) break; if (prime >= 100) { if (i++ != 0) System.out.print(", "); System.out.print(prime); } } System.out.println(); int count = 0; for (;;) { int prime = pgen.nextPrime(); if (prime > 8000) break; if (prime >= 7700) ++count; } System.out.println("Number of primes between 7700 and 8000: " + count); int n = 10000; for (;;) { int prime = pgen.nextPrime(); if (prime == 0) { System.out.println("Can't generate any more primes."); break; } if (pgen.count() == n) { System.out.println(n + "th prime: " + prime); n *= 10; } } } }
#include <iostream> #include <cstdint> #include <queue> #include <utility> #include <vector> #include <limits> template<typename integer> class prime_generator { public: integer next_prime(); integer count() const { return count_; } private: struct queue_item { queue_item(integer prime, integer multiple, unsigned int wheel_index) : prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {} integer prime_; integer multiple_; unsigned int wheel_index_; }; struct cmp { bool operator()(const queue_item& a, const queue_item& b) const { return a.multiple_ > b.multiple_; } }; static integer wheel_next(unsigned int& index) { integer offset = wheel_[index]; ++index; if (index == std::size(wheel_)) index = 0; return offset; } typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue; integer next_ = 11; integer count_ = 0; queue queue_; unsigned int wheel_index_ = 0; static const unsigned int wheel_[]; static const integer primes_[]; }; template<typename integer> const unsigned int prime_generator<integer>::wheel_[] = { 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10 }; template<typename integer> const integer prime_generator<integer>::primes_[] = { 2, 3, 5, 7 }; template<typename integer> integer prime_generator<integer>::next_prime() { if (count_ < std::size(primes_)) return primes_[count_++]; integer n = next_; integer prev = 0; while (!queue_.empty()) { queue_item item = queue_.top(); if (prev != 0 && prev != item.multiple_) n += wheel_next(wheel_index_); if (item.multiple_ > n) break; else if (item.multiple_ == n) { queue_.pop(); queue_item new_item(item); new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_); queue_.push(new_item); } else throw std::overflow_error("prime_generator: overflow!"); prev = item.multiple_; } if (std::numeric_limits<integer>::max()/n > n) queue_.emplace(n, n * n, wheel_index_); next_ = n + wheel_next(wheel_index_); ++count_; return n; } int main() { typedef uint32_t integer; prime_generator<integer> pgen; std::cout << "First 20 primes:\n"; for (int i = 0; i < 20; ++i) { integer p = pgen.next_prime(); if (i != 0) std::cout << ", "; std::cout << p; } std::cout << "\nPrimes between 100 and 150:\n"; for (int n = 0; ; ) { integer p = pgen.next_prime(); if (p > 150) break; if (p >= 100) { if (n != 0) std::cout << ", "; std::cout << p; ++n; } } int count = 0; for (;;) { integer p = pgen.next_prime(); if (p > 8000) break; if (p >= 7700) ++count; } std::cout << "\nNumber of primes between 7700 and 8000: " << count << '\n'; for (integer n = 10000; n <= 10000000; n *= 10) { integer prime; while (pgen.count() != n) prime = pgen.next_prime(); std::cout << n << "th prime: " << prime << '\n'; } return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Random; public class RPS { public enum Item{ ROCK, PAPER, SCISSORS, ; public List<Item> losesToList; public boolean losesTo(Item other) { return losesToList.contains(other); } static { SCISSORS.losesToList = Arrays.asList(ROCK); ROCK.losesToList = Arrays.asList(PAPER); PAPER.losesToList = Arrays.asList(SCISSORS); } } public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{ for(Item item:Item.values()) put(item, 1); }}; private int totalThrows = Item.values().length; public static void main(String[] args){ RPS rps = new RPS(); rps.run(); } public void run() { Scanner in = new Scanner(System.in); System.out.print("Make your choice: "); while(in.hasNextLine()){ Item aiChoice = getAIChoice(); String input = in.nextLine(); Item choice; try{ choice = Item.valueOf(input.toUpperCase()); }catch (IllegalArgumentException ex){ System.out.println("Invalid choice"); continue; } counts.put(choice, counts.get(choice) + 1); totalThrows++; System.out.println("Computer chose: " + aiChoice); if(aiChoice == choice){ System.out.println("Tie!"); }else if(aiChoice.losesTo(choice)){ System.out.println("You chose...wisely. You win!"); }else{ System.out.println("You chose...poorly. You lose!"); } System.out.print("Make your choice: "); } } private static final Random rng = new Random(); private Item getAIChoice() { int rand = rng.nextInt(totalThrows); for(Map.Entry<Item, Integer> entry:counts.entrySet()){ Item item = entry.getKey(); int count = entry.getValue(); if(rand < count){ List<Item> losesTo = item.losesToList; return losesTo.get(rng.nextInt(losesTo.size())); } rand -= count; } return null; } }
#include <windows.h> #include <iostream> #include <string> using namespace std; enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C }; enum indexes { PLAYER, COMPUTER, DRAW }; class stats { public: stats() : _draw( 0 ) { ZeroMemory( _moves, sizeof( _moves ) ); ZeroMemory( _win, sizeof( _win ) ); } void draw() { _draw++; } void win( int p ) { _win[p]++; } void move( int p, int m ) { _moves[p][m]++; } int getMove( int p, int m ) { return _moves[p][m]; } string format( int a ) { char t[32]; wsprintf( t, "%.3d", a ); string d( t ); return d; } void print() { string d = format( _draw ), pw = format( _win[PLAYER] ), cw = format( _win[COMPUTER] ), pr = format( _moves[PLAYER][ROCK] ), cr = format( _moves[COMPUTER][ROCK] ), pp = format( _moves[PLAYER][PAPER] ), cp = format( _moves[COMPUTER][PAPER] ), ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ), pl = format( _moves[PLAYER][LIZARD] ), cl = format( _moves[COMPUTER][LIZARD] ), pk = format( _moves[PLAYER][SPOCK] ), ck = format( _moves[COMPUTER][SPOCK] ); system( "cls" ); cout << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |" << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << "| PLAYER | " << pw << " | | " << pr << " | " << pp << " | " << ps << " | " << pl << " | " << pk << " |" << endl; cout << "+----------+-------+ " << d << " +--------+---------+----------+--------+---------+" << endl; cout << "| COMPUTER | " << cw << " | | " << cr << " | " << cp << " | " << cs << " | " << cl << " | " << ck << " |" << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << endl << endl; system( "pause" ); } private: int _moves[2][MX_C], _win[2], _draw; }; class rps { private: int makeMove() { int total = 0, r, s; for( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) ); r = rand() % total; for( int i = ROCK; i < SCISSORS; i++ ) { s = statistics.getMove( PLAYER, i ); if( r < s ) return ( i + 1 ); r -= s; } return ROCK; } void printMove( int p, int m ) { if( p == COMPUTER ) cout << "My move: "; else cout << "Your move: "; switch( m ) { case ROCK: cout << "ROCK\n"; break; case PAPER: cout << "PAPER\n"; break; case SCISSORS: cout << "SCISSORS\n"; break; case LIZARD: cout << "LIZARD\n"; break; case SPOCK: cout << "SPOCK\n"; } } public: rps() { checker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1; checker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0; checker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1; checker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0; checker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2; } void play() { int p, r, m; while( true ) { cout << "What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)QuitΒ ? "; cin >> p; if( !p || p < 0 ) break; if( p > 0 && p < 6 ) { p--; cout << endl; printMove( PLAYER, p ); statistics.move( PLAYER, p ); m = makeMove(); statistics.move( COMPUTER, m ); printMove( COMPUTER, m ); r = checker[p][m]; switch( r ) { case DRAW: cout << endl << "DRAW!" << endl << endl; statistics.draw(); break; case COMPUTER: cout << endl << "I WIN!" << endl << endl; statistics.win( COMPUTER ); break; case PLAYER: cout << endl << "YOU WIN!" << endl << endl; statistics.win( PLAYER ); } system( "pause" ); } system( "cls" ); } statistics.print(); } private: stats statistics; int checker[MX_C][MX_C]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); rps game; game.play(); return 0; }
Port the following code from Java to C++ with equivalent syntax and logic.
import java.util.Scanner; public class twoDimArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int nbr1 = in.nextInt(); int nbr2 = in.nextInt(); double[][] array = new double[nbr1][nbr2]; array[0][0] = 42.0; System.out.println("The number at place [0 0] is " + array[0][0]); } }
#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; }
Generate a C++ translation of this Java snippet without changing its computational steps.
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
#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 a version of this Java function in C++ with identical behavior.
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
#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; }
Preserve the algorithm and functionality while converting the code from Java to C++.
public class Vig{ static String encodedMessage = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; final static double freq[] = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 }; public static void main(String[] args) { int lenghtOfEncodedMessage = encodedMessage.length(); char[] encoded = new char [lenghtOfEncodedMessage] ; char[] key = new char [lenghtOfEncodedMessage] ; encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0); int txt[] = new int[lenghtOfEncodedMessage]; int len = 0, j; double fit, best_fit = 1e100; for (j = 0; j < lenghtOfEncodedMessage; j++) if (Character.isUpperCase(encoded[j])) txt[len++] = encoded[j] - 'A'; for (j = 1; j < 30; j++) { fit = freq_every_nth(txt, len, j, key); System.out.printf("%f, key length: %2d ", fit, j); System.out.print(key); if (fit < best_fit) { best_fit = fit; System.out.print(" <--- best so far"); } System.out.print("\n"); } } static String decrypt(String text, final String key) { String res = ""; text = text.toUpperCase(); for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < 'A' || c > 'Z') continue; res += (char)((c - key.charAt(j) + 26) % 26 + 'A'); j = ++j % key.length(); } return res; } static int best_match(final double []a, final double []b) { double sum = 0, fit, d, best_fit = 1e100; int i, rotate, best_rotate = 0; for (i = 0; i < 26; i++) sum += a[i]; for (rotate = 0; rotate < 26; rotate++) { fit = 0; for (i = 0; i < 26; i++) { d = a[(i + rotate) % 26] / sum - b[i]; fit += d * d / b[i]; } if (fit < best_fit) { best_fit = fit; best_rotate = rotate; } } return best_rotate; } static double freq_every_nth(final int []msg, int len, int interval, char[] key) { double sum, d, ret; double [] accu = new double [26]; double [] out = new double [26]; int i, j, rot; for (j = 0; j < interval; j++) { for (i = 0; i < 26; i++) out[i] = 0; for (i = j; i < len; i += interval) out[msg[i]]++; rot = best_match(out, freq); try{ key[j] = (char)(rot + 'A'); } catch (Exception e) { System.out.print(e.getMessage()); } for (i = 0; i < 26; i++) accu[i] += out[(i + rot) % 26]; } for (i = 0, sum = 0; i < 26; i++) sum += accu[i]; for (i = 0, ret = 0; i < 26; i++) { d = accu[i] / sum - freq[i]; ret += d * d / freq[i]; } key[interval] = '\0'; return ret; } }
#include <iostream> #include <string> #include <vector> #include <map> #include <algorithm> #include <array> using namespace std; typedef array<pair<char, double>, 26> FreqArray; class VigenereAnalyser { private: array<double, 26> targets; array<double, 26> sortedTargets; FreqArray freq; FreqArray& frequency(const string& input) { for (char c = 'A'; c <= 'Z'; ++c) freq[c - 'A'] = make_pair(c, 0); for (size_t i = 0; i < input.size(); ++i) freq[input[i] - 'A'].second++; return freq; } double correlation(const string& input) { double result = 0.0; frequency(input); sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool { return u.second < v.second; }); for (size_t i = 0; i < 26; ++i) result += freq[i].second * sortedTargets[i]; return result; } public: VigenereAnalyser(const array<double, 26>& targetFreqs) { targets = targetFreqs; sortedTargets = targets; sort(sortedTargets.begin(), sortedTargets.end()); } pair<string, string> analyze(string input) { string cleaned; for (size_t i = 0; i < input.size(); ++i) { if (input[i] >= 'A' && input[i] <= 'Z') cleaned += input[i]; else if (input[i] >= 'a' && input[i] <= 'z') cleaned += input[i] + 'A' - 'a'; } size_t bestLength = 0; double bestCorr = -100.0; for (size_t i = 2; i < cleaned.size() / 20; ++i) { vector<string> pieces(i); for (size_t j = 0; j < cleaned.size(); ++j) pieces[j % i] += cleaned[j]; double corr = -0.5*i; for (size_t j = 0; j < i; ++j) corr += correlation(pieces[j]); if (corr > bestCorr) { bestLength = i; bestCorr = corr; } } if (bestLength == 0) return make_pair("Text is too short to analyze", ""); vector<string> pieces(bestLength); for (size_t i = 0; i < cleaned.size(); ++i) pieces[i % bestLength] += cleaned[i]; vector<FreqArray> freqs; for (size_t i = 0; i < bestLength; ++i) freqs.push_back(frequency(pieces[i])); string key = ""; for (size_t i = 0; i < bestLength; ++i) { sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool { return u.second > v.second; }); size_t m = 0; double mCorr = 0.0; for (size_t j = 0; j < 26; ++j) { double corr = 0.0; char c = 'A' + j; for (size_t k = 0; k < 26; ++k) { int d = (freqs[i][k].first - c + 26) % 26; corr += freqs[i][k].second * targets[d]; } if (corr > mCorr) { m = j; mCorr = corr; } } key += m + 'A'; } string result = ""; for (size_t i = 0; i < cleaned.size(); ++i) result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A'; return make_pair(result, key); } }; int main() { string input = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; array<double, 26> english = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074}; VigenereAnalyser va(english); pair<string, string> output = va.analyze(input); cout << "Key: " << output.second << endl << endl; cout << "Text: " << output.first << endl; }
Transform the following Java implementation into C++, maintaining the same output and logic.
import java.math.BigInteger ; public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ; BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ; public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } } public static void main(String[] args) { Pi p = new Pi() ; p.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; } }
Write the same algorithm in C++ as shown in this Java implementation.
import java.math.BigInteger ; public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ; BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ; public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } } public static void main(String[] args) { Pi p = new Pi() ; p.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; } }
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << "Β !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }
Convert this Java snippet to C++ and keep its semantics consistent.
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << "Β !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(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; }
Convert the following code from Java to C++, ensuring the logic remains intact.
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class RReturnMultipleVals { public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; public static final Long K_1024 = 1024L; public static final String L = "L"; public static final String R = "R"; public static void main(String[] args) throws NumberFormatException{ Long nv_; String sv_; switch (args.length) { case 0: nv_ = K_1024; sv_ = K_lipsum; break; case 1: nv_ = Long.parseLong(args[0]); sv_ = K_lipsum; break; case 2: nv_ = Long.parseLong(args[0]); sv_ = args[1]; break; default: nv_ = Long.parseLong(args[0]); sv_ = args[1]; for (int ix = 2; ix < args.length; ++ix) { sv_ = sv_ + " " + args[ix]; } break; } RReturnMultipleVals lcl = new RReturnMultipleVals(); Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); System.out.println("Results extracted from a composite object:"); System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal()); List<Object> rvl = lcl.getPairFromList(nv_, sv_); System.out.println("Results extracted from a Java Colections \"List\" object:"); System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1)); Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); System.out.println("Results extracted from a Java Colections \"Map\" object:"); System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R)); } public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) { return new Pair<T, U>(vl_, vr_); } public List<Object> getPairFromList(Object nv_, Object sv_) { List<Object> rset = new ArrayList<Object>(); rset.add(nv_); rset.add(sv_); return rset; } public Map<String, Object> getPairFromMap(Object nv_, Object sv_) { Map<String, Object> rset = new HashMap<String, Object>(); rset.put(L, nv_); rset.put(R, sv_); return rset; } private static class Pair<L, R> { private L leftVal; private R rightVal; public Pair(L nv_, R sv_) { setLeftVal(nv_); setRightVal(sv_); } public void setLeftVal(L nv_) { leftVal = nv_; } public L getLeftVal() { return leftVal; } public void setRightVal(R sv_) { rightVal = sv_; } public R getRightVal() { return rightVal; } } }
#include <algorithm> #include <array> #include <cstdint> #include <iostream> #include <tuple> std::tuple<int, int> minmax(const int * numbers, const std::size_t num) { const auto maximum = std::max_element(numbers, numbers + num); const auto minimum = std::min_element(numbers, numbers + num); return std::make_tuple(*minimum, *maximum) ; } int main( ) { const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}}; int min{}; int max{}; std::tie(min, max) = minmax(numbers.data(), numbers.size()); std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ; }
Write a version of this Java function in C++ with identical behavior.
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
#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; }
Preserve the algorithm and functionality while converting the code from Java to C++.
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
#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; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
#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; }
Convert this Java block to C++, preserving its control flow and logic.
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
#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; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPconn { public static void main(String[] args) throws IOException { String server = "ftp.hq.nasa.gov"; int port = 21; String user = "anonymous"; String pass = "ftptest@example.com"; OutputStream output = null; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); serverReply(ftpClient); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Failure. Server reply code: " + replyCode); return; } serverReply(ftpClient); if (!ftpClient.login(user, pass)) { System.out.println("Could not login to the server."); return; } String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/"; if (!ftpClient.changeWorkingDirectory(dir)) { System.out.println("Change directory failed."); return; } ftpClient.enterLocalPassiveMode(); for (FTPFile file : ftpClient.listFiles()) System.out.println(file); String filename = "Can People go to Mars.mp3"; output = new FileOutputStream(filename); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!ftpClient.retrieveFile(filename, output)) { System.out.println("Retrieving file failed"); return; } serverReply(ftpClient); ftpClient.logout(); } finally { if (output != null) output.close(); } } private static void serverReply(FTPClient ftpClient) { for (String reply : ftpClient.getReplyStrings()) { System.out.println(reply); } } }
#include <iostream> #include <string> #include <cstring> #include <fstream> #include <sys/stat.h> #include <ftplib.h> #include <ftp++.hpp> int stat(const char *pathname, struct stat *buf); char *strerror(int errnum); char *basename(char *path); namespace stl { using std::cout; using std::cerr; using std::string; using std::ifstream; using std::remove; }; using namespace stl; using Mode = ftp::Connection::Mode; Mode PASV = Mode::PASSIVE; Mode PORT = Mode::PORT; using TransferMode = ftp::Connection::TransferMode; TransferMode BINARY = TransferMode::BINARY; TransferMode TEXT = TransferMode::TEXT; struct session { const string server; const string port; const string user; const string pass; Mode mode; TransferMode txmode; string dir; }; ftp::Connection connect_ftp( const session& sess); size_t get_ftp( ftp::Connection& conn, string const& path); string readFile( const string& filename); string login_ftp(ftp::Connection& conn, const session& sess); string dir_listing( ftp::Connection& conn, const string& path); string readFile( const string& filename) { struct stat stat_buf; string contents; errno = 0; if (stat(filename.c_str() , &stat_buf) != -1) { size_t len = stat_buf.st_size; string bytes(len+1, '\0'); ifstream ifs(filename); ifs.read(&bytes[0], len); if (! ifs.fail() ) contents.swap(bytes); ifs.close(); } else { cerr << "stat error: " << strerror(errno); } return contents; } ftp::Connection connect_ftp( const session& sess) try { string constr = sess.server + ":" + sess.port; cerr << "connecting to " << constr << " ...\n"; ftp::Connection conn{ constr.c_str() }; cerr << "connected to " << constr << "\n"; conn.setConnectionMode(sess.mode); return conn; } catch (ftp::ConnectException e) { cerr << "FTP error: could not connect to server" << "\n"; } string login_ftp(ftp::Connection& conn, const session& sess) { conn.login(sess.user.c_str() , sess.pass.c_str() ); return conn.getLastResponse(); } string dir_listing( ftp::Connection& conn, const string& path) try { const char* dirdata = "/dev/shm/dirdata"; conn.getList(dirdata, path.c_str() ); string dir_string = readFile(dirdata); cerr << conn.getLastResponse() << "\n"; errno = 0; if ( remove(dirdata) != 0 ) { cerr << "error: " << strerror(errno) << "\n"; } return dir_string; } catch (...) { cerr << "error: getting dir contents: \n" << strerror(errno) << "\n"; } size_t get_ftp( ftp::Connection& conn, const string& r_path) { size_t received = 0; const char* path = r_path.c_str(); unsigned remotefile_size = conn.size(path , BINARY); const char* localfile = basename(path); conn.get(localfile, path, BINARY); cerr << conn.getLastResponse() << "\n"; struct stat stat_buf; errno = 0; if (stat(localfile, &stat_buf) != -1) received = stat_buf.st_size; else cerr << strerror(errno); return received; } const session sonic { "mirrors.sonic.net", "21" , "anonymous", "xxxx@nohost.org", PASV, BINARY, "/pub/OpenBSD" }; int main(int argc, char* argv[], char * env[] ) { const session remote = sonic; try { ftp::Connection conn = connect_ftp(remote); cerr << login_ftp(conn, remote); cout << "System type: " << conn.getSystemType() << "\n"; cerr << conn.getLastResponse() << "\n"; conn.cd(remote.dir.c_str()); cerr << conn.getLastResponse() << "\n"; string pwdstr = conn.getDirectory(); cout << "PWD: " << pwdstr << "\n"; cerr << conn.getLastResponse() << "\n"; string dirlist = dir_listing(conn, pwdstr.c_str() ); cout << dirlist << "\n"; string filename = "ftplist"; auto pos = dirlist.find(filename); auto notfound = string::npos; if (pos != notfound) { size_t received = get_ftp(conn, filename.c_str() ); if (received == 0) cerr << "got 0 bytes\n"; else cerr << "got " << filename << " (" << received << " bytes)\n"; } else { cerr << "file " << filename << "not found on server. \n"; } } catch (ftp::ConnectException e) { cerr << "FTP error: could not connect to server" << "\n"; } catch (ftp::Exception e) { cerr << "FTP error: " << e << "\n"; } catch (...) { cerr << "error: " << strerror(errno) << "\n"; } return 0; }
Ensure the translated C++ code behaves exactly like the original Java snippet.
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FTPconn { public static void main(String[] args) throws IOException { String server = "ftp.hq.nasa.gov"; int port = 21; String user = "anonymous"; String pass = "ftptest@example.com"; OutputStream output = null; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); serverReply(ftpClient); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("Failure. Server reply code: " + replyCode); return; } serverReply(ftpClient); if (!ftpClient.login(user, pass)) { System.out.println("Could not login to the server."); return; } String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/"; if (!ftpClient.changeWorkingDirectory(dir)) { System.out.println("Change directory failed."); return; } ftpClient.enterLocalPassiveMode(); for (FTPFile file : ftpClient.listFiles()) System.out.println(file); String filename = "Can People go to Mars.mp3"; output = new FileOutputStream(filename); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!ftpClient.retrieveFile(filename, output)) { System.out.println("Retrieving file failed"); return; } serverReply(ftpClient); ftpClient.logout(); } finally { if (output != null) output.close(); } } private static void serverReply(FTPClient ftpClient) { for (String reply : ftpClient.getReplyStrings()) { System.out.println(reply); } } }
#include <iostream> #include <string> #include <cstring> #include <fstream> #include <sys/stat.h> #include <ftplib.h> #include <ftp++.hpp> int stat(const char *pathname, struct stat *buf); char *strerror(int errnum); char *basename(char *path); namespace stl { using std::cout; using std::cerr; using std::string; using std::ifstream; using std::remove; }; using namespace stl; using Mode = ftp::Connection::Mode; Mode PASV = Mode::PASSIVE; Mode PORT = Mode::PORT; using TransferMode = ftp::Connection::TransferMode; TransferMode BINARY = TransferMode::BINARY; TransferMode TEXT = TransferMode::TEXT; struct session { const string server; const string port; const string user; const string pass; Mode mode; TransferMode txmode; string dir; }; ftp::Connection connect_ftp( const session& sess); size_t get_ftp( ftp::Connection& conn, string const& path); string readFile( const string& filename); string login_ftp(ftp::Connection& conn, const session& sess); string dir_listing( ftp::Connection& conn, const string& path); string readFile( const string& filename) { struct stat stat_buf; string contents; errno = 0; if (stat(filename.c_str() , &stat_buf) != -1) { size_t len = stat_buf.st_size; string bytes(len+1, '\0'); ifstream ifs(filename); ifs.read(&bytes[0], len); if (! ifs.fail() ) contents.swap(bytes); ifs.close(); } else { cerr << "stat error: " << strerror(errno); } return contents; } ftp::Connection connect_ftp( const session& sess) try { string constr = sess.server + ":" + sess.port; cerr << "connecting to " << constr << " ...\n"; ftp::Connection conn{ constr.c_str() }; cerr << "connected to " << constr << "\n"; conn.setConnectionMode(sess.mode); return conn; } catch (ftp::ConnectException e) { cerr << "FTP error: could not connect to server" << "\n"; } string login_ftp(ftp::Connection& conn, const session& sess) { conn.login(sess.user.c_str() , sess.pass.c_str() ); return conn.getLastResponse(); } string dir_listing( ftp::Connection& conn, const string& path) try { const char* dirdata = "/dev/shm/dirdata"; conn.getList(dirdata, path.c_str() ); string dir_string = readFile(dirdata); cerr << conn.getLastResponse() << "\n"; errno = 0; if ( remove(dirdata) != 0 ) { cerr << "error: " << strerror(errno) << "\n"; } return dir_string; } catch (...) { cerr << "error: getting dir contents: \n" << strerror(errno) << "\n"; } size_t get_ftp( ftp::Connection& conn, const string& r_path) { size_t received = 0; const char* path = r_path.c_str(); unsigned remotefile_size = conn.size(path , BINARY); const char* localfile = basename(path); conn.get(localfile, path, BINARY); cerr << conn.getLastResponse() << "\n"; struct stat stat_buf; errno = 0; if (stat(localfile, &stat_buf) != -1) received = stat_buf.st_size; else cerr << strerror(errno); return received; } const session sonic { "mirrors.sonic.net", "21" , "anonymous", "xxxx@nohost.org", PASV, BINARY, "/pub/OpenBSD" }; int main(int argc, char* argv[], char * env[] ) { const session remote = sonic; try { ftp::Connection conn = connect_ftp(remote); cerr << login_ftp(conn, remote); cout << "System type: " << conn.getSystemType() << "\n"; cerr << conn.getLastResponse() << "\n"; conn.cd(remote.dir.c_str()); cerr << conn.getLastResponse() << "\n"; string pwdstr = conn.getDirectory(); cout << "PWD: " << pwdstr << "\n"; cerr << conn.getLastResponse() << "\n"; string dirlist = dir_listing(conn, pwdstr.c_str() ); cout << dirlist << "\n"; string filename = "ftplist"; auto pos = dirlist.find(filename); auto notfound = string::npos; if (pos != notfound) { size_t received = get_ftp(conn, filename.c_str() ); if (received == 0) cerr << "got 0 bytes\n"; else cerr << "got " << filename << " (" << received << " bytes)\n"; } else { cerr << "file " << filename << "not found on server. \n"; } } catch (ftp::ConnectException e) { cerr << "FTP error: could not connect to server" << "\n"; } catch (ftp::Exception e) { cerr << "FTP error: " << e << "\n"; } catch (...) { cerr << "error: " << strerror(errno) << "\n"; } return 0; }
Preserve the algorithm and functionality while converting the code from Java to C++.
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); stk.push(f(a, b)); } void parse(char c) { if(c >= '0' && c <= '9') { stk.push(c - '0'); digits.insert(c - '0'); } else if(c == '+') op([](double a, double b) {return a+b;}); else if(c == '-') op([](double a, double b) {return a-b;}); else if(c == '*') op([](double a, double b) {return a*b;}); else if(c == '/') op([](double a, double b) {return a/b;}); } void parse(string s) { for(int i = 0; i < s.size(); ++i) parse(s[i]); } double getResult() { if(stk.size() != 1) throw "Improperly written expression"; return stk.top(); } }; int main() { random_device seed; mt19937 engine(seed()); uniform_int_distribution<> distribution(1, 9); auto rnd = bind(distribution, engine); multiset<int> digits; cout << "Make 24 with the digits: "; for(int i = 0; i < 4; ++i) { int n = rnd(); cout << " " << n; digits.insert(n); } cout << endl; RPNParse parser; try { string input; getline(cin, input); parser.parse(input); if(digits != parser.digits) cout << "Error: Not using the given digits" << endl; else { double r = parser.getResult(); cout << "Result: " << r << endl; if(r > 23.999 && r < 24.001) cout << "Good job!" << endl; else cout << "Try again." << endl; } } catch(char* e) { cout << "Error: " << e << endl; } return 0; }
Generate an equivalent C++ version of this Java code.
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); stk.push(f(a, b)); } void parse(char c) { if(c >= '0' && c <= '9') { stk.push(c - '0'); digits.insert(c - '0'); } else if(c == '+') op([](double a, double b) {return a+b;}); else if(c == '-') op([](double a, double b) {return a-b;}); else if(c == '*') op([](double a, double b) {return a*b;}); else if(c == '/') op([](double a, double b) {return a/b;}); } void parse(string s) { for(int i = 0; i < s.size(); ++i) parse(s[i]); } double getResult() { if(stk.size() != 1) throw "Improperly written expression"; return stk.top(); } }; int main() { random_device seed; mt19937 engine(seed()); uniform_int_distribution<> distribution(1, 9); auto rnd = bind(distribution, engine); multiset<int> digits; cout << "Make 24 with the digits: "; for(int i = 0; i < 4; ++i) { int n = rnd(); cout << " " << n; digits.insert(n); } cout << endl; RPNParse parser; try { string input; getline(cin, input); parser.parse(input); if(digits != parser.digits) cout << "Error: Not using the given digits" << endl; else { double r = parser.getResult(); cout << "Result: " << r << endl; if(r > 23.999 && r < 24.001) cout << "Good job!" << endl; else cout << "Try again." << endl; } } catch(char* e) { cout << "Error: " << e << endl; } return 0; }
Preserve the algorithm and functionality while converting the code from Java to C++.
for(int i = 1;i <= 10; i++){ System.out.print(i); if(i % 5 == 0){ System.out.println(); continue; } System.out.print(", "); }
for(int i = 1;i <= 10; i++){ cout << i; if(i % 5 == 0){ cout << endl; continue; } cout << ", "; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class ColorFrame extends JFrame { public ColorFrame(int width, int height) { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(width, height); this.setVisible(true); } @Override public void paint(Graphics g) { Color[] colors = { Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.CYAN, Color.yellow, Color.white }; for (int i = 0; i < colors.length; i++) { g.setColor(colors[i]); g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth() / colors.length, this.getHeight()); } } public static void main(String args[]) { new ColorFrame(200, 200); } }
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> class QPaintEvent ; class MyWidget : public QWidget { public : MyWidget( ) ; protected : void paintEvent( QPaintEvent * ) ; private : int width ; int height ; const int colornumber ; } ; #endif
Ensure the translated C++ code behaves exactly like the original Java snippet.
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class ColorFrame extends JFrame { public ColorFrame(int width, int height) { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(width, height); this.setVisible(true); } @Override public void paint(Graphics g) { Color[] colors = { Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.CYAN, Color.yellow, Color.white }; for (int i = 0; i < colors.length; i++) { g.setColor(colors[i]); g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth() / colors.length, this.getHeight()); } } public static void main(String args[]) { new ColorFrame(200, 200); } }
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> class QPaintEvent ; class MyWidget : public QWidget { public : MyWidget( ) ; protected : void paintEvent( QPaintEvent * ) ; private : int width ; int height ; const int colornumber ; } ; #endif
Write the same code in C++ as shown below in Java.
import static java.util.Arrays.stream; import java.util.Locale; import static java.util.stream.IntStream.range; public class Test { static double dotProduct(double[] a, double[] b) { return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum(); } static double[][] matrixMul(double[][] A, double[][] B) { double[][] result = new double[A.length][B[0].length]; double[] aux = new double[B.length]; for (int j = 0; j < B[0].length; j++) { for (int k = 0; k < B.length; k++) aux[k] = B[k][j]; for (int i = 0; i < A.length; i++) result[i][j] = dotProduct(A[i], aux); } return result; } static double[][] pivotize(double[][] m) { int n = m.length; double[][] id = range(0, n).mapToObj(j -> range(0, n) .mapToDouble(i -> i == j ? 1 : 0).toArray()) .toArray(double[][]::new); for (int i = 0; i < n; i++) { double maxm = m[i][i]; int row = i; for (int j = i; j < n; j++) if (m[j][i] > maxm) { maxm = m[j][i]; row = j; } if (i != row) { double[] tmp = id[i]; id[i] = id[row]; id[row] = tmp; } } return id; } static double[][][] lu(double[][] A) { int n = A.length; double[][] L = new double[n][n]; double[][] U = new double[n][n]; double[][] P = pivotize(A); double[][] A2 = matrixMul(P, A); for (int j = 0; j < n; j++) { L[j][j] = 1; for (int i = 0; i < j + 1; i++) { double s1 = 0; for (int k = 0; k < i; k++) s1 += U[k][j] * L[i][k]; U[i][j] = A2[i][j] - s1; } for (int i = j; i < n; i++) { double s2 = 0; for (int k = 0; k < j; k++) s2 += U[k][j] * L[i][k]; L[i][j] = (A2[i][j] - s2) / U[j][j]; } } return new double[][][]{L, U, P}; } static void print(double[][] m) { stream(m).forEach(a -> { stream(a).forEach(n -> System.out.printf(Locale.US, "%5.1f ", n)); System.out.println(); }); System.out.println(); } public static void main(String[] args) { double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}}; double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1}, {2.0, 5, 7, 1}}; for (double[][] m : lu(a)) print(m); System.out.println(); for (double[][] m : lu(b)) print(m); } }
#include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <limits> #include <numeric> #include <sstream> #include <vector> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, scalar_type value) : rows_(rows), columns_(columns), elements_(rows * columns, value) {} matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<scalar_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[i]); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const scalar_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } scalar_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } private: size_t rows_; size_t columns_; std::vector<scalar_type> elements_; }; template <typename scalar_type> void print(std::wostream& out, const matrix<scalar_type>& a) { const wchar_t* box_top_left = L"\x23a1"; const wchar_t* box_top_right = L"\x23a4"; const wchar_t* box_left = L"\x23a2"; const wchar_t* box_right = L"\x23a5"; const wchar_t* box_bottom_left = L"\x23a3"; const wchar_t* box_bottom_right = L"\x23a6"; const int precision = 5; size_t rows = a.rows(), columns = a.columns(); std::vector<size_t> width(columns); for (size_t column = 0; column < columns; ++column) { size_t max_width = 0; for (size_t row = 0; row < rows; ++row) { std::ostringstream str; str << std::fixed << std::setprecision(precision) << a(row, column); max_width = std::max(max_width, str.str().length()); } width[column] = max_width; } out << std::fixed << std::setprecision(precision); for (size_t row = 0; row < rows; ++row) { const bool top(row == 0), bottom(row + 1 == rows); out << (top ? box_top_left : (bottom ? box_bottom_left : box_left)); for (size_t column = 0; column < columns; ++column) { if (column > 0) out << L' '; out << std::setw(width[column]) << a(row, column); } out << (top ? box_top_right : (bottom ? box_bottom_right : box_right)); out << L'\n'; } } template <typename scalar_type> auto lu_decompose(const matrix<scalar_type>& input) { assert(input.rows() == input.columns()); size_t n = input.rows(); std::vector<size_t> perm(n); std::iota(perm.begin(), perm.end(), 0); matrix<scalar_type> lower(n, n); matrix<scalar_type> upper(n, n); matrix<scalar_type> input1(input); for (size_t j = 0; j < n; ++j) { size_t max_index = j; scalar_type max_value = 0; for (size_t i = j; i < n; ++i) { scalar_type value = std::abs(input1(perm[i], j)); if (value > max_value) { max_index = i; max_value = value; } } if (max_value <= std::numeric_limits<scalar_type>::epsilon()) throw std::runtime_error("matrix is singular"); if (j != max_index) std::swap(perm[j], perm[max_index]); size_t jj = perm[j]; for (size_t i = j + 1; i < n; ++i) { size_t ii = perm[i]; input1(ii, j) /= input1(jj, j); for (size_t k = j + 1; k < n; ++k) input1(ii, k) -= input1(ii, j) * input1(jj, k); } } for (size_t j = 0; j < n; ++j) { lower(j, j) = 1; for (size_t i = j + 1; i < n; ++i) lower(i, j) = input1(perm[i], j); for (size_t i = 0; i <= j; ++i) upper(i, j) = input1(perm[i], j); } matrix<scalar_type> pivot(n, n); for (size_t i = 0; i < n; ++i) pivot(i, perm[i]) = 1; return std::make_tuple(lower, upper, pivot); } template <typename scalar_type> void show_lu_decomposition(const matrix<scalar_type>& input) { try { std::wcout << L"A\n"; print(std::wcout, input); auto result(lu_decompose(input)); std::wcout << L"\nL\n"; print(std::wcout, std::get<0>(result)); std::wcout << L"\nU\n"; print(std::wcout, std::get<1>(result)); std::wcout << L"\nP\n"; print(std::wcout, std::get<2>(result)); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; } } int main() { std::wcout.imbue(std::locale("")); std::wcout << L"Example 1:\n"; matrix<double> matrix1(3, 3, {{1, 3, 5}, {2, 4, 7}, {1, 1, 0}}); show_lu_decomposition(matrix1); std::wcout << '\n'; std::wcout << L"Example 2:\n"; matrix<double> matrix2(4, 4, {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}}); show_lu_decomposition(matrix2); std::wcout << '\n'; std::wcout << L"Example 3:\n"; matrix<double> matrix3(3, 3, {{-5, -6, -3}, {-1, 0, -2}, {-3, -4, -7}}); show_lu_decomposition(matrix3); std::wcout << '\n'; std::wcout << L"Example 4:\n"; matrix<double> matrix4(3, 3, {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}); show_lu_decomposition(matrix4); return 0; }
Translate the given Java code snippet into C++ without altering its behavior.
public class FizzBuzz { public static void main(String[] args) { Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")}; for (int i = 1; i <= 20; i++) { StringBuilder sb = new StringBuilder(); for (Sound sound : sounds) { sb.append(sound.generate(i)); } System.out.println(sb.length() == 0 ? i : sb.toString()); } } private static class Sound { private final int trigger; private final String onomatopoeia; public Sound(int trigger, String onomatopoeia) { this.trigger = trigger; this.onomatopoeia = onomatopoeia; } public String generate(int i) { return i % trigger == 0 ? onomatopoeia : ""; } } }
#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; }
Port the provided Java code into C++ while preserving the original functionality.
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look atΒ ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you want to seeΒ ? ( Give a number > 0 )Β ?\n" ; std::getline( std::cin , input ) ; int linenumber = std::stoi( input ) ; int lines_read = 0 ; std::string line ; if ( infile.is_open( ) ) { while ( infile ) { getline( infile , line ) ; lines_read++ ; if ( lines_read == linenumber ) { std::cout << line << std::endl ; break ; } } infile.close( ) ; if ( lines_read < linenumber ) std::cout << "No " << linenumber << " lines in " << file << "Β !\n" ; return 0 ; } else { std::cerr << "Could not find file " << file << "Β !\n" ; return 1 ; } }
Port the following code from Java to C++ with equivalent syntax and logic.
package linenbr7; import java.io.*; public class LineNbr7 { public static void main(String[] args) throws Exception { File f = new File(args[0]); if (!f.isFile() || !f.canRead()) throw new IOException("can't read " + args[0]); BufferedReader br = new BufferedReader(new FileReader(f)); try (LineNumberReader lnr = new LineNumberReader(br)) { String line = null; int lnum = 0; while ((line = lnr.readLine()) != null && (lnum = lnr.getLineNumber()) < 7) { } switch (lnum) { case 0: System.out.println("the file has zero length"); break; case 7: boolean empty = "".equals(line); System.out.println("line 7: " + (empty ? "empty" : line)); break; default: System.out.println("the file has only " + lnum + " line(s)"); } } } }
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look atΒ ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you want to seeΒ ? ( Give a number > 0 )Β ?\n" ; std::getline( std::cin , input ) ; int linenumber = std::stoi( input ) ; int lines_read = 0 ; std::string line ; if ( infile.is_open( ) ) { while ( infile ) { getline( infile , line ) ; lines_read++ ; if ( lines_read == linenumber ) { std::cout << line << std::endl ; break ; } } infile.close( ) ; if ( lines_read < linenumber ) std::cout << "No " << linenumber << " lines in " << file << "Β !\n" ; return 0 ; } else { std::cerr << "Could not find file " << file << "Β !\n" ; return 1 ; } }
Generate an equivalent C++ version of this Java code.
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
#include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <vector> bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) { const size_t n1 = str.length(); const size_t n2 = suffix.length(); if (n1 < n2) return false; return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(), [](char c1, char c2) { return std::tolower(static_cast<unsigned char>(c1)) == std::tolower(static_cast<unsigned char>(c2)); }); } bool filenameHasExtension(const std::string& filename, const std::vector<std::string>& extensions) { return std::any_of(extensions.begin(), extensions.end(), [&filename](const std::string& extension) { return endsWithIgnoreCase(filename, "." + extension); }); } void test(const std::string& filename, const std::vector<std::string>& extensions) { std::cout << std::setw(20) << std::left << filename << ": " << std::boolalpha << filenameHasExtension(filename, extensions) << '\n'; } int main() { const std::vector<std::string> extensions{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}; test("MyData.a##", extensions); test("MyData.tar.Gz", extensions); test("MyData.gzip", extensions); test("MyData.7z.backup", extensions); test("MyData...", extensions); test("MyData", extensions); test("MyData_v1.0.tar.bz2", extensions); test("MyData_v1.0.bz2", extensions); return 0; }
Convert this Java snippet to C++ and keep its semantics consistent.
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
#include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <vector> bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) { const size_t n1 = str.length(); const size_t n2 = suffix.length(); if (n1 < n2) return false; return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(), [](char c1, char c2) { return std::tolower(static_cast<unsigned char>(c1)) == std::tolower(static_cast<unsigned char>(c2)); }); } bool filenameHasExtension(const std::string& filename, const std::vector<std::string>& extensions) { return std::any_of(extensions.begin(), extensions.end(), [&filename](const std::string& extension) { return endsWithIgnoreCase(filename, "." + extension); }); } void test(const std::string& filename, const std::vector<std::string>& extensions) { std::cout << std::setw(20) << std::left << filename << ": " << std::boolalpha << filenameHasExtension(filename, extensions) << '\n'; } int main() { const std::vector<std::string> extensions{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}; test("MyData.a##", extensions); test("MyData.tar.Gz", extensions); test("MyData.gzip", extensions); test("MyData.7z.backup", extensions); test("MyData...", extensions); test("MyData", extensions); test("MyData_v1.0.tar.bz2", extensions); test("MyData_v1.0.bz2", extensions); return 0; }
Transform the following Java implementation into C++, maintaining the same output and logic.
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\')); String filename = test.substring(lastSlash + 1); int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.'); String ext = filename.substring(lastDot); Arrays.sort(exts); return Arrays.binarySearch(exts, ext, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }) >= 0; } }
#include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <vector> bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) { const size_t n1 = str.length(); const size_t n2 = suffix.length(); if (n1 < n2) return false; return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(), [](char c1, char c2) { return std::tolower(static_cast<unsigned char>(c1)) == std::tolower(static_cast<unsigned char>(c2)); }); } bool filenameHasExtension(const std::string& filename, const std::vector<std::string>& extensions) { return std::any_of(extensions.begin(), extensions.end(), [&filename](const std::string& extension) { return endsWithIgnoreCase(filename, "." + extension); }); } void test(const std::string& filename, const std::vector<std::string>& extensions) { std::cout << std::setw(20) << std::left << filename << ": " << std::boolalpha << filenameHasExtension(filename, extensions) << '\n'; } int main() { const std::vector<std::string> extensions{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}; test("MyData.a##", extensions); test("MyData.tar.Gz", extensions); test("MyData.gzip", extensions); test("MyData.7z.backup", extensions); test("MyData...", extensions); test("MyData", extensions); test("MyData_v1.0.tar.bz2", extensions); test("MyData_v1.0.bz2", extensions); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
import java.util.*; public class Game24Player { final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo"}; final String ops = "+-*/^"; String solution; List<Integer> digits; public static void main(String[] args) { new Game24Player().play(); } void play() { digits = getSolvableDigits(); Scanner in = new Scanner(System.in); while (true) { System.out.print("Make 24 using these digits: "); System.out.println(digits); System.out.println("(Enter 'q' to quit, 's' for a solution)"); System.out.print("> "); String line = in.nextLine(); if (line.equalsIgnoreCase("q")) { System.out.println("\nThanks for playing"); return; } if (line.equalsIgnoreCase("s")) { System.out.println(solution); digits = getSolvableDigits(); continue; } char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray(); try { validate(entry); if (evaluate(infixToPostfix(entry))) { System.out.println("\nCorrect! Want to try another? "); digits = getSolvableDigits(); } else { System.out.println("\nNot correct."); } } catch (Exception e) { System.out.printf("%n%s Try again.%n", e.getMessage()); } } } void validate(char[] input) throws Exception { int total1 = 0, parens = 0, opsCount = 0; for (char c : input) { if (Character.isDigit(c)) total1 += 1 << (c - '0') * 4; else if (c == '(') parens++; else if (c == ')') parens--; else if (ops.indexOf(c) != -1) opsCount++; if (parens < 0) throw new Exception("Parentheses mismatch."); } if (parens != 0) throw new Exception("Parentheses mismatch."); if (opsCount != 3) throw new Exception("Wrong number of operators."); int total2 = 0; for (int d : digits) total2 += 1 << d * 4; if (total1 != total2) throw new Exception("Not the same digits."); } boolean evaluate(char[] line) throws Exception { Stack<Float> s = new Stack<>(); try { for (char c : line) { if ('0' <= c && c <= '9') s.push((float) c - '0'); else s.push(applyOperator(s.pop(), s.pop(), c)); } } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return (Math.abs(24 - s.peek()) < 0.001F); } float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } List<Integer> randomDigits() { Random r = new Random(); List<Integer> result = new ArrayList<>(4); for (int i = 0; i < 4; i++) result.add(r.nextInt(9) + 1); return result; } List<Integer> getSolvableDigits() { List<Integer> result; do { result = randomDigits(); } while (!isSolvable(result)); return result; } boolean isSolvable(List<Integer> digits) { Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2); permute(digits, dPerms, 0); int total = 4 * 4 * 4; List<List<Integer>> oPerms = new ArrayList<>(total); permuteOperators(oPerms, 4, total); StringBuilder sb = new StringBuilder(4 + 3); for (String pattern : patterns) { char[] patternChars = pattern.toCharArray(); for (List<Integer> dig : dPerms) { for (List<Integer> opr : oPerms) { int i = 0, j = 0; for (char c : patternChars) { if (c == 'n') sb.append(dig.get(i++)); else sb.append(ops.charAt(opr.get(j++))); } String candidate = sb.toString(); try { if (evaluate(candidate.toCharArray())) { solution = postfixToInfix(candidate); return true; } } catch (Exception ignored) { } sb.setLength(0); } } } return false; } String postfixToInfix(String postfix) { class Expression { String op, ex; int prec = 3; Expression(String e) { ex = e; } Expression(String e1, String e2, String o) { ex = String.format("%s %s %s", e1, o, e2); op = o; prec = ops.indexOf(o) / 2; } } Stack<Expression> expr = new Stack<>(); for (char c : postfix.toCharArray()) { int idx = ops.indexOf(c); if (idx != -1) { Expression r = expr.pop(); Expression l = expr.pop(); int opPrec = idx / 2; if (l.prec < opPrec) l.ex = '(' + l.ex + ')'; if (r.prec <= opPrec) r.ex = '(' + r.ex + ')'; expr.push(new Expression(l.ex, r.ex, "" + c)); } else { expr.push(new Expression("" + c)); } } return expr.peek().ex; } char[] infixToPostfix(char[] infix) throws Exception { StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); try { for (char c : infix) { int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 >= prec1) sb.append(ops.charAt(s.pop())); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())); s.pop(); } else { sb.append(c); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())); } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return sb.toString().toCharArray(); } void permute(List<Integer> lst, Set<List<Integer>> res, int k) { for (int i = k; i < lst.size(); i++) { Collections.swap(lst, i, k); permute(lst, res, k + 1); Collections.swap(lst, k, i); } if (k == lst.size()) res.add(new ArrayList<>(lst)); } void permuteOperators(List<List<Integer>> res, int n, int total) { for (int i = 0, npow = n * n; i < total; i++) res.add(Arrays.asList((i / npow), (i % npow) / n, i % n)); } }
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::string operation) { bool printOperation(false); for(const Digit& number : d) { if(printOperation) std::cout << operation; else printOperation = true; std::cout << number; } std::cout << std::endl; } void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") { std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl; } int main() { std::mt19937_64 randomGenerator; std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit}; for(int trial{10}; trial; --trial) { for(Digit& digit : d) { digit = digitDistro(randomGenerator); std::cout << digit << " "; } std::cout << std::endl; std::sort(d.begin(), d.end()); if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal) printTrivialOperation(" + "); if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal) printTrivialOperation(" * "); do { if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - "); if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + "); if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + "); if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )"); if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + "); if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )"); if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )"); if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - "); if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )"); if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )"); if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - "); if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - "); if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + "); if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )"); if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + "); if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / "); if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - "); if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / "); if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )"); if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / "); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )"); if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )"); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", ""); } while(std::next_permutation(d.begin(), d.end())); } return 0; }
Convert this Java block to C++, preserving its control flow and logic.
import java.util.*; public class Game24Player { final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo"}; final String ops = "+-*/^"; String solution; List<Integer> digits; public static void main(String[] args) { new Game24Player().play(); } void play() { digits = getSolvableDigits(); Scanner in = new Scanner(System.in); while (true) { System.out.print("Make 24 using these digits: "); System.out.println(digits); System.out.println("(Enter 'q' to quit, 's' for a solution)"); System.out.print("> "); String line = in.nextLine(); if (line.equalsIgnoreCase("q")) { System.out.println("\nThanks for playing"); return; } if (line.equalsIgnoreCase("s")) { System.out.println(solution); digits = getSolvableDigits(); continue; } char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray(); try { validate(entry); if (evaluate(infixToPostfix(entry))) { System.out.println("\nCorrect! Want to try another? "); digits = getSolvableDigits(); } else { System.out.println("\nNot correct."); } } catch (Exception e) { System.out.printf("%n%s Try again.%n", e.getMessage()); } } } void validate(char[] input) throws Exception { int total1 = 0, parens = 0, opsCount = 0; for (char c : input) { if (Character.isDigit(c)) total1 += 1 << (c - '0') * 4; else if (c == '(') parens++; else if (c == ')') parens--; else if (ops.indexOf(c) != -1) opsCount++; if (parens < 0) throw new Exception("Parentheses mismatch."); } if (parens != 0) throw new Exception("Parentheses mismatch."); if (opsCount != 3) throw new Exception("Wrong number of operators."); int total2 = 0; for (int d : digits) total2 += 1 << d * 4; if (total1 != total2) throw new Exception("Not the same digits."); } boolean evaluate(char[] line) throws Exception { Stack<Float> s = new Stack<>(); try { for (char c : line) { if ('0' <= c && c <= '9') s.push((float) c - '0'); else s.push(applyOperator(s.pop(), s.pop(), c)); } } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return (Math.abs(24 - s.peek()) < 0.001F); } float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } List<Integer> randomDigits() { Random r = new Random(); List<Integer> result = new ArrayList<>(4); for (int i = 0; i < 4; i++) result.add(r.nextInt(9) + 1); return result; } List<Integer> getSolvableDigits() { List<Integer> result; do { result = randomDigits(); } while (!isSolvable(result)); return result; } boolean isSolvable(List<Integer> digits) { Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2); permute(digits, dPerms, 0); int total = 4 * 4 * 4; List<List<Integer>> oPerms = new ArrayList<>(total); permuteOperators(oPerms, 4, total); StringBuilder sb = new StringBuilder(4 + 3); for (String pattern : patterns) { char[] patternChars = pattern.toCharArray(); for (List<Integer> dig : dPerms) { for (List<Integer> opr : oPerms) { int i = 0, j = 0; for (char c : patternChars) { if (c == 'n') sb.append(dig.get(i++)); else sb.append(ops.charAt(opr.get(j++))); } String candidate = sb.toString(); try { if (evaluate(candidate.toCharArray())) { solution = postfixToInfix(candidate); return true; } } catch (Exception ignored) { } sb.setLength(0); } } } return false; } String postfixToInfix(String postfix) { class Expression { String op, ex; int prec = 3; Expression(String e) { ex = e; } Expression(String e1, String e2, String o) { ex = String.format("%s %s %s", e1, o, e2); op = o; prec = ops.indexOf(o) / 2; } } Stack<Expression> expr = new Stack<>(); for (char c : postfix.toCharArray()) { int idx = ops.indexOf(c); if (idx != -1) { Expression r = expr.pop(); Expression l = expr.pop(); int opPrec = idx / 2; if (l.prec < opPrec) l.ex = '(' + l.ex + ')'; if (r.prec <= opPrec) r.ex = '(' + r.ex + ')'; expr.push(new Expression(l.ex, r.ex, "" + c)); } else { expr.push(new Expression("" + c)); } } return expr.peek().ex; } char[] infixToPostfix(char[] infix) throws Exception { StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); try { for (char c : infix) { int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 >= prec1) sb.append(ops.charAt(s.pop())); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())); s.pop(); } else { sb.append(c); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())); } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } return sb.toString().toCharArray(); } void permute(List<Integer> lst, Set<List<Integer>> res, int k) { for (int i = k; i < lst.size(); i++) { Collections.swap(lst, i, k); permute(lst, res, k + 1); Collections.swap(lst, k, i); } if (k == lst.size()) res.add(new ArrayList<>(lst)); } void permuteOperators(List<List<Integer>> res, int n, int total) { for (int i = 0, npow = n * n; i < total; i++) res.add(Arrays.asList((i / npow), (i % npow) / n, i % n)); } }
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::string operation) { bool printOperation(false); for(const Digit& number : d) { if(printOperation) std::cout << operation; else printOperation = true; std::cout << number; } std::cout << std::endl; } void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") { std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl; } int main() { std::mt19937_64 randomGenerator; std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit}; for(int trial{10}; trial; --trial) { for(Digit& digit : d) { digit = digitDistro(randomGenerator); std::cout << digit << " "; } std::cout << std::endl; std::sort(d.begin(), d.end()); if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal) printTrivialOperation(" + "); if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal) printTrivialOperation(" * "); do { if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - "); if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + "); if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + "); if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )"); if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + "); if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )"); if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )"); if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - "); if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )"); if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )"); if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - "); if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - "); if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + "); if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )"); if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + "); if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / "); if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - "); if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / "); if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )"); if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / "); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )"); if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )"); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", ""); } while(std::next_permutation(d.begin(), d.end())); } return 0; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
import java.util.Scanner; import java.util.Random; public class CheckpointSync{ public static void main(String[] args){ System.out.print("Enter number of workers to use: "); Scanner in = new Scanner(System.in); Worker.nWorkers = in.nextInt(); System.out.print("Enter number of tasks to complete:"); runTasks(in.nextInt()); } private static void runTasks(int nTasks){ for(int i = 0; i < nTasks; i++){ System.out.println("Starting task number " + (i+1) + "."); runThreads(); Worker.checkpoint(); } } private static void runThreads(){ for(int i = 0; i < Worker.nWorkers; i ++){ new Thread(new Worker(i+1)).start(); } } public static class Worker implements Runnable{ public Worker(int threadID){ this.threadID = threadID; } public void run(){ work(); } private synchronized void work(){ try { int workTime = rgen.nextInt(900) + 100; System.out.println("Worker " + threadID + " will work for " + workTime + " msec."); Thread.sleep(workTime); nFinished++; System.out.println("Worker " + threadID + " is ready"); } catch (InterruptedException e) { System.err.println("Error: thread execution interrupted"); e.printStackTrace(); } } public static synchronized void checkpoint(){ while(nFinished != nWorkers){ try { Thread.sleep(10); } catch (InterruptedException e) { System.err.println("Error: thread execution interrupted"); e.printStackTrace(); } } nFinished = 0; } private int threadID; private static Random rgen = new Random(); private static int nFinished = 0; public static int nWorkers = 0; } }
#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 the given Java code snippet into C++ without altering its behavior.
import java.util.Scanner; import java.util.Random; public class CheckpointSync{ public static void main(String[] args){ System.out.print("Enter number of workers to use: "); Scanner in = new Scanner(System.in); Worker.nWorkers = in.nextInt(); System.out.print("Enter number of tasks to complete:"); runTasks(in.nextInt()); } private static void runTasks(int nTasks){ for(int i = 0; i < nTasks; i++){ System.out.println("Starting task number " + (i+1) + "."); runThreads(); Worker.checkpoint(); } } private static void runThreads(){ for(int i = 0; i < Worker.nWorkers; i ++){ new Thread(new Worker(i+1)).start(); } } public static class Worker implements Runnable{ public Worker(int threadID){ this.threadID = threadID; } public void run(){ work(); } private synchronized void work(){ try { int workTime = rgen.nextInt(900) + 100; System.out.println("Worker " + threadID + " will work for " + workTime + " msec."); Thread.sleep(workTime); nFinished++; System.out.println("Worker " + threadID + " is ready"); } catch (InterruptedException e) { System.err.println("Error: thread execution interrupted"); e.printStackTrace(); } } public static synchronized void checkpoint(){ while(nFinished != nWorkers){ try { Thread.sleep(10); } catch (InterruptedException e) { System.err.println("Error: thread execution interrupted"); e.printStackTrace(); } } nFinished = 0; } private int threadID; private static Random rgen = new Random(); private static int nFinished = 0; public static int nWorkers = 0; } }
#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"; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
public class VLQCode { public static byte[] encode(long n) { int numRelevantBits = 64 - Long.numberOfLeadingZeros(n); int numBytes = (numRelevantBits + 6) / 7; if (numBytes == 0) numBytes = 1; byte[] output = new byte[numBytes]; for (int i = numBytes - 1; i >= 0; i--) { int curByte = (int)(n & 0x7F); if (i != (numBytes - 1)) curByte |= 0x80; output[i] = (byte)curByte; n >>>= 7; } return output; } public static long decode(byte[] b) { long n = 0; for (int i = 0; i < b.length; i++) { int curByte = b[i] & 0xFF; n = (n << 7) | (curByte & 0x7F); if ((curByte & 0x80) == 0) break; } return n; } public static String byteArrayToString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { if (i > 0) sb.append(", "); String s = Integer.toHexString(b[i] & 0xFF); if (s.length() < 2) s = "0" + s; sb.append(s); } return sb.toString(); } public static void main(String[] args) { long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L }; for (long n : testNumbers) { byte[] encoded = encode(n); long decoded = decode(encoded); System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL")); } } }
#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; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
import java.io.*; import java.security.*; import java.util.*; public class SHA256MerkleTree { public static void main(String[] args) { if (args.length != 1) { System.err.println("missing file argument"); System.exit(1); } try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) { byte[] digest = sha256MerkleTree(in, 1024); if (digest != null) System.out.println(digestToString(digest)); } catch (Exception e) { e.printStackTrace(); } } private static String digestToString(byte[] digest) { StringBuilder result = new StringBuilder(); for (int i = 0; i < digest.length; ++i) result.append(String.format("%02x", digest[i])); return result.toString(); } private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception { byte[] buffer = new byte[blockSize]; int bytes; MessageDigest md = MessageDigest.getInstance("SHA-256"); List<byte[]> digests = new ArrayList<>(); while ((bytes = in.read(buffer)) > 0) { md.reset(); md.update(buffer, 0, bytes); digests.add(md.digest()); } int length = digests.size(); if (length == 0) return null; while (length > 1) { int j = 0; for (int i = 0; i < length; i += 2, ++j) { byte[] digest1 = digests.get(i); if (i + 1 < length) { byte[] digest2 = digests.get(i + 1); md.reset(); md.update(digest1); md.update(digest2); digests.set(j, md.digest()); } else { digests.set(j, digest1); } } length = j; } return digests.get(0); } }
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <vector> #include <openssl/sha.h> class sha256_exception : public std::exception { public: const char* what() const noexcept override { return "SHA-256 error"; } }; class sha256 { public: sha256() { reset(); } sha256(const sha256&) = delete; sha256& operator=(const sha256&) = delete; void reset() { if (SHA256_Init(&context_) == 0) throw sha256_exception(); } void update(const void* data, size_t length) { if (SHA256_Update(&context_, data, length) == 0) throw sha256_exception(); } std::vector<unsigned char> digest() { std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH); if (SHA256_Final(digest.data(), &context_) == 0) throw sha256_exception(); return digest; } private: SHA256_CTX context_; }; std::string digest_to_string(const std::vector<unsigned char>& digest) { std::ostringstream out; out << std::hex << std::setfill('0'); for (size_t i = 0; i < digest.size(); ++i) out << std::setw(2) << static_cast<int>(digest[i]); return out.str(); } std::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) { std::vector<std::vector<unsigned char>> hashes; std::vector<char> buffer(block_size); sha256 md; while (in) { in.read(buffer.data(), block_size); size_t bytes = in.gcount(); if (bytes == 0) break; md.reset(); md.update(buffer.data(), bytes); hashes.push_back(md.digest()); } if (hashes.empty()) return {}; size_t length = hashes.size(); while (length > 1) { size_t j = 0; for (size_t i = 0; i < length; i += 2, ++j) { auto& digest1 = hashes[i]; auto& digest_out = hashes[j]; if (i + 1 < length) { auto& digest2 = hashes[i + 1]; md.reset(); md.update(digest1.data(), digest1.size()); md.update(digest2.data(), digest2.size()); digest_out = md.digest(); } else { digest_out = digest1; } } length = j; } return hashes[0]; } int main(int argc, char** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " filename\n"; return EXIT_FAILURE; } std::ifstream in(argv[1], std::ios::binary); if (!in) { std::cerr << "Cannot open file " << argv[1] << ".\n"; return EXIT_FAILURE; } try { std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\n'; } catch (const std::exception& ex) { std::cerr << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Port the provided Java code into C++ while preserving the original functionality.
String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); System.out.println("ÀàÒÑçñßæΡбế".toUpperCase()); System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
#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); }
Convert this Java snippet to C++ and keep its semantics consistent.
String str = "alphaBETA"; System.out.println(str.toUpperCase()); System.out.println(str.toLowerCase()); System.out.println("ÀàÒÑçñßæΡбế".toUpperCase()); System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
#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); }
Change the programming language of this snippet from Java to C++ without modifying what it does.
import javax.swing.*; public class GetInputSwing { public static void main(String[] args) throws Exception { int number = Integer.parseInt( JOptionPane.showInputDialog ("Enter an Integer")); String string = JOptionPane.showInputDialog ("Enter a String"); } }
#ifndef TASK_H #define TASK_H #include <QWidget> class QLabel ; class QLineEdit ; class QVBoxLayout ; class QHBoxLayout ; class EntryWidget : public QWidget { Q_OBJECT public : EntryWidget( QWidget *parent = 0 ) ; private : QHBoxLayout *upperpart , *lowerpart ; QVBoxLayout *entryLayout ; QLineEdit *stringinput ; QLineEdit *numberinput ; QLabel *stringlabel ; QLabel *numberlabel ; } ; #endif
Convert this Java snippet to C++ and keep its semantics consistent.
import javax.swing.*; public class GetInputSwing { public static void main(String[] args) throws Exception { int number = Integer.parseInt( JOptionPane.showInputDialog ("Enter an Integer")); String string = JOptionPane.showInputDialog ("Enter a String"); } }
#ifndef TASK_H #define TASK_H #include <QWidget> class QLabel ; class QLineEdit ; class QVBoxLayout ; class QHBoxLayout ; class EntryWidget : public QWidget { Q_OBJECT public : EntryWidget( QWidget *parent = 0 ) ; private : QHBoxLayout *upperpart , *lowerpart ; QVBoxLayout *entryLayout ; QLineEdit *stringinput ; QLineEdit *numberinput ; QLabel *stringlabel ; QLabel *numberlabel ; } ; #endif
Please provide an equivalent version of this Java code in C++.
final PVector t = new PVector(20, 30, 60); void setup() { size(450, 400); noLoop(); background(0, 0, 200); stroke(-1); sc(7, 400, -60, t); } PVector sc(int o, float l, final int a, final PVector s) { if (o > 0) { sc(--o, l *= .5, -a, s).z += a; sc(o, l, a, s).z += a; sc(o, l, -a, s); } else line(s.x, s.y, s.x += cos(radians(s.z)) * l, s.y += sin(radians(s.z)) * l); return s; }
#include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; struct point { double x; double y; }; std::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(3*(size - 1) + 1); double x0, y0, x1, y1; size_t j = 0; for (size_t i = 0; i + 1 < size; ++i, j += 3) { x0 = points[i].x; y0 = points[i].y; x1 = points[i + 1].x; y1 = points[i + 1].y; double dx = x1 - x0; output[j] = {x0, y0}; if (y0 == y1) { double d = dx * sqrt3_2/2; if (d < 0) d = -d; output[j + 1] = {x0 + dx/4, y0 - d}; output[j + 2] = {x1 - dx/4, y0 - d}; } else if (y1 < y0) { output[j + 1] = {x1, y0}; output[j + 2] = {x1 + dx/2, (y0 + y1)/2}; } else { output[j + 1] = {x0 - dx/2, (y0 + y1)/2}; output[j + 2] = {x0, y1}; } } output[j] = {x1, y1}; return output; } void write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) { out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; const double margin = 20.0; const double side = size - 2.0 * margin; const double x = margin; const double y = 0.5 * size + 0.5 * sqrt3_2 * side; std::vector<point> points{{x, y}, {x + side, y}}; for (int i = 0; i < iterations; ++i) points = sierpinski_arrowhead_next(points); for (size_t i = 0, n = points.size(); i < n; ++i) out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n'; out << "'/>\n</svg>\n"; } int main() { std::ofstream out("sierpinski_arrowhead.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); return EXIT_SUCCESS; }
Translate this program into C++ but keep the logic exactly as in Java.
import java.io.File; import java.util.*; import static java.lang.System.out; public class TextProcessing1 { public static void main(String[] args) throws Exception { Locale.setDefault(new Locale("en", "US")); Metrics metrics = new Metrics(); int dataGap = 0; String gapBeginDate = null; try (Scanner lines = new Scanner(new File("readings.txt"))) { while (lines.hasNextLine()) { double lineTotal = 0.0; int linePairs = 0; int lineInvalid = 0; String lineDate; try (Scanner line = new Scanner(lines.nextLine())) { lineDate = line.next(); while (line.hasNext()) { final double value = line.nextDouble(); if (line.nextInt() <= 0) { if (dataGap == 0) gapBeginDate = lineDate; dataGap++; lineInvalid++; continue; } lineTotal += value; linePairs++; metrics.addDataGap(dataGap, gapBeginDate, lineDate); dataGap = 0; } } metrics.addLine(lineTotal, linePairs); metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal); } metrics.report(); } } private static class Metrics { private List<String[]> gapDates; private int maxDataGap = -1; private double total; private int pairs; private int lineResultCount; void addLine(double tot, double prs) { total += tot; pairs += prs; } void addDataGap(int gap, String begin, String end) { if (gap > 0 && gap >= maxDataGap) { if (gap > maxDataGap) { maxDataGap = gap; gapDates = new ArrayList<>(); } gapDates.add(new String[]{begin, end}); } } void lineResult(String date, int invalid, int prs, double tot) { if (lineResultCount >= 3) return; out.printf("%10s out: %2d in: %2d tot: %10.3f avg: %10.3f%n", date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0); lineResultCount++; } void report() { out.printf("%ntotal = %10.3f%n", total); out.printf("readings = %6d%n", pairs); out.printf("average = %010.3f%n", total / pairs); out.printf("%nmaximum run(s) of %d invalid measurements: %n", maxDataGap); for (String[] dates : gapDates) out.printf("begins at %s and ends at %s%n", dates[0], dates[1]); } } }
#include <iostream> #include <fstream> #include <string> #include <vector> #include <iomanip> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> using std::cout; using std::endl; const int NumFlags = 24; int main() { std::fstream file("readings.txt"); int badCount = 0; std::string badDate; int badCountMax = 0; while(true) { std::string line; getline(file, line); if(!file.good()) break; std::vector<std::string> tokens; boost::algorithm::split(tokens, line, boost::is_space()); if(tokens.size() != NumFlags * 2 + 1) { cout << "Bad input file." << endl; return 0; } double total = 0.0; int accepted = 0; for(size_t i = 1; i < tokens.size(); i += 2) { double val = boost::lexical_cast<double>(tokens[i]); int flag = boost::lexical_cast<int>(tokens[i+1]); if(flag > 0) { total += val; ++accepted; badCount = 0; } else { ++badCount; if(badCount > badCountMax) { badCountMax = badCount; badDate = tokens[0]; } } } cout << tokens[0]; cout << " Reject: " << std::setw(2) << (NumFlags - accepted); cout << " Accept: " << std::setw(2) << accepted; cout << " Average: " << std::setprecision(5) << total / accepted << endl; } cout << endl; cout << "Maximum number of consecutive bad readings is " << badCountMax << endl; cout << "Ends on date " << badDate << endl; }
Write the same algorithm in C++ as shown in this Java implementation.
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Digester { public static void main(String[] args) { System.out.println(hexDigest("Rosetta code", "MD5")); } static String hexDigest(String str, String digestName) { try { MessageDigest md = MessageDigest.getInstance(digestName); byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8)); char[] hex = new char[digest.length * 2]; for (int i = 0; i < digest.length; i++) { hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4); hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f); } return new String(hex); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } }
#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 ; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } void classify_aliquot_sequence(integer n) { constexpr int limit = 16; integer terms[limit]; terms[0] = n; std::string classification("non-terminating"); int length = 1; for (int i = 1; i < limit; ++i) { ++length; terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1]; if (terms[i] == n) { classification = (i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable")); break; } int j = 1; for (; j < i; ++j) { if (terms[i] == terms[i - j]) break; } if (j < i) { classification = (j == 1 ? "aspiring" : "cyclic"); break; } if (terms[i] == 0) { classification = "terminating"; break; } } std::cout << n << ": " << classification << ", sequence: " << terms[0]; for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i) std::cout << ' ' << terms[i]; std::cout << '\n'; } int main() { for (integer i = 1; i <= 10; ++i) classify_aliquot_sequence(i); for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}) classify_aliquot_sequence(i); classify_aliquot_sequence(15355717786080); classify_aliquot_sequence(153557177860800); return 0; }
Ensure the translated C++ code behaves exactly like the original Java snippet.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; public class AliquotSequenceClassifications { private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); } static boolean aliquot(long n, int maxLen, long maxTerm) { List<Long> s = new ArrayList<>(maxLen); s.add(n); long newN = n; while (s.size() <= maxLen && newN < maxTerm) { newN = properDivsSum(s.get(s.size() - 1)); if (s.contains(newN)) { if (s.get(0) == newN) { switch (s.size()) { case 1: return report("Perfect", s); case 2: return report("Amicable", s); default: return report("Sociable of length " + s.size(), s); } } else if (s.get(s.size() - 1) == newN) { return report("Aspiring", s); } else return report("Cyclic back to " + newN, s); } else { s.add(newN); if (newN == 0) return report("Terminating", s); } } return report("Non-terminating", s); } static boolean report(String msg, List<Long> result) { System.out.println(msg + ": " + result); return false; } public static void main(String[] args) { long[] arr = { 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}; LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47)); System.out.println(); Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47)); } }
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } void classify_aliquot_sequence(integer n) { constexpr int limit = 16; integer terms[limit]; terms[0] = n; std::string classification("non-terminating"); int length = 1; for (int i = 1; i < limit; ++i) { ++length; terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1]; if (terms[i] == n) { classification = (i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable")); break; } int j = 1; for (; j < i; ++j) { if (terms[i] == terms[i - j]) break; } if (j < i) { classification = (j == 1 ? "aspiring" : "cyclic"); break; } if (terms[i] == 0) { classification = "terminating"; break; } } std::cout << n << ": " << classification << ", sequence: " << terms[0]; for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i) std::cout << ' ' << terms[i]; std::cout << '\n'; } int main() { for (integer i = 1; i <= 10; ++i) classify_aliquot_sequence(i); for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}) classify_aliquot_sequence(i); classify_aliquot_sequence(15355717786080); classify_aliquot_sequence(153557177860800); return 0; }
Keep all operations the same but rewrite the snippet in C++.
import java.time.*; import java.time.format.*; class Main { public static void main(String args[]) { String dateStr = "March 7 2009 7:30pm EST"; DateTimeFormatter df = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendPattern("MMMM d yyyy h:mma zzz") .toFormatter(); ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12); System.out.println("Date: " + dateStr); System.out.println("+12h: " + after12Hours.format(df)); ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of("CET")); System.out.println("+12h (in Central Europe): " + after12HoursInCentralEuropeTime.format(df)); } }
#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 ; }
Convert this Java block to C++, preserving its control flow and logic.
import java.util.concurrent.CountDownLatch; public class SleepSort { public static void sleepSortAndPrint(int[] nums) { final CountDownLatch doneSignal = new CountDownLatch(nums.length); for (final int num : nums) { new Thread(new Runnable() { public void run() { doneSignal.countDown(); try { doneSignal.await(); Thread.sleep(num * 1000); System.out.println(num); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } public static void main(String[] args) { int[] nums = new int[args.length]; for (int i = 0; i < args.length; i++) nums[i] = Integer.parseInt(args[i]); sleepSortAndPrint(nums); } }
#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(); } }
Produce a functionally identical C++ code for the snippet given in Java.
import java.util.Random; public class NestedLoopTest { public static final Random gen = new Random(); public static void main(String[] args) { int[][] a = new int[10][10]; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) a[i][j] = gen.nextInt(20) + 1; Outer:for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.print(" " + a[i][j]); if (a[i][j] == 20) break Outer; } System.out.println(); } System.out.println(); } }
#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; }
Translate the given Java code snippet into C++ without altering its behavior.
import java.util.Random; public class NestedLoopTest { public static final Random gen = new Random(); public static void main(String[] args) { int[][] a = new int[10][10]; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) a[i][j] = gen.nextInt(20) + 1; Outer:for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.print(" " + a[i][j]); if (a[i][j] == 20) break Outer; } System.out.println(); } System.out.println(); } }
#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; }
Generate an equivalent C++ version of this Java code.
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
#include <cmath> #include <iostream> #include <numeric> #include <tuple> #include <vector> using namespace std; auto CountTriplets(unsigned long long maxPerimeter) { unsigned long long totalCount = 0; unsigned long long primitveCount = 0; auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1; for(unsigned long long m = 2; m < max_M; ++m) { for(unsigned long long n = 1 + m % 2; n < m; n+=2) { if(gcd(m,n) != 1) { continue; } auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto perimeter = a + b + c; if(perimeter <= maxPerimeter) { primitveCount++; totalCount+= maxPerimeter / perimeter; } } } return tuple(totalCount, primitveCount); } int main() { vector<unsigned long long> inputs{100, 1000, 10'000, 100'000, 1000'000, 10'000'000, 100'000'000, 1000'000'000, 10'000'000'000}; for(auto maxPerimeter : inputs) { auto [total, primitive] = CountTriplets(maxPerimeter); cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ; } }
Write the same algorithm in C++ as shown in this Java implementation.
import java.math.BigInteger; import static java.math.BigInteger.ONE; public class PythTrip{ public static void main(String[] args){ long tripCount = 0, primCount = 0; BigInteger periLimit = BigInteger.valueOf(100), peri2 = periLimit.divide(BigInteger.valueOf(2)), peri3 = periLimit.divide(BigInteger.valueOf(3)); for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){ BigInteger aa = a.multiply(a); for(BigInteger b = a.add(ONE); b.compareTo(peri2) < 0; b = b.add(ONE)){ BigInteger bb = b.multiply(b); BigInteger ab = a.add(b); BigInteger aabb = aa.add(bb); for(BigInteger c = b.add(ONE); c.compareTo(peri2) < 0; c = c.add(ONE)){ int compare = aabb.compareTo(c.multiply(c)); if(ab.add(c).compareTo(periLimit) > 0){ break; } if(compare < 0){ break; }else if (compare == 0){ tripCount++; System.out.print(a + ", " + b + ", " + c); if(a.gcd(b).equals(ONE)){ System.out.print(" primitive"); primCount++; } System.out.println(); } } } } System.out.println("Up to a perimeter of " + periLimit + ", there are " + tripCount + " triples, of which " + primCount + " are primitive."); } }
#include <cmath> #include <iostream> #include <numeric> #include <tuple> #include <vector> using namespace std; auto CountTriplets(unsigned long long maxPerimeter) { unsigned long long totalCount = 0; unsigned long long primitveCount = 0; auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1; for(unsigned long long m = 2; m < max_M; ++m) { for(unsigned long long n = 1 + m % 2; n < m; n+=2) { if(gcd(m,n) != 1) { continue; } auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto perimeter = a + b + c; if(perimeter <= maxPerimeter) { primitveCount++; totalCount+= maxPerimeter / perimeter; } } } return tuple(totalCount, primitveCount); } int main() { vector<unsigned long long> inputs{100, 1000, 10'000, 100'000, 1000'000, 10'000'000, 100'000'000, 1000'000'000, 10'000'000'000}; for(auto maxPerimeter : inputs) { auto [total, primitive] = CountTriplets(maxPerimeter); cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ; } }
Write the same algorithm in C++ as shown in this Java implementation.
module RetainUniqueValues { @Inject Console console; void run() { Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1]; array = array.distinct().toArray(); console.print($"result={array}"); } }
#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; }
Convert the following code from Java to C++, ensuring the logic remains intact.
public static String lookandsay(String number){ StringBuilder result= new StringBuilder(); char repeat= number.charAt(0); number= number.substring(1) + " "; int times= 1; for(char actual: number.toCharArray()){ if(actual != repeat){ result.append(times + "" + repeat); times= 1; repeat= actual; }else{ times+= 1; } } return result.toString(); }
#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'; } }
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.Stack; public class StackTest { public static void main( final String[] args ) { final Stack<String> stack = new Stack<String>(); System.out.println( "New stack empty? " + stack.empty() ); stack.push( "There can be only one" ); System.out.println( "Pushed stack empty? " + stack.empty() ); System.out.println( "Popped single entry: " + stack.pop() ); stack.push( "First" ); stack.push( "Second" ); System.out.println( "Popped entry should be second: " + stack.pop() ); stack.pop(); stack.pop(); } }
#include <stack>
Transform the following Java implementation into C++, maintaining the same output and logic.
import java.util.Stack; public class StackTest { public static void main( final String[] args ) { final Stack<String> stack = new Stack<String>(); System.out.println( "New stack empty? " + stack.empty() ); stack.push( "There can be only one" ); System.out.println( "Pushed stack empty? " + stack.empty() ); System.out.println( "Popped single entry: " + stack.pop() ); stack.push( "First" ); stack.push( "Second" ); System.out.println( "Popped entry should be second: " + stack.pop() ); stack.pop(); stack.pop(); } }
#include <stack>
Generate an equivalent C++ version of this Java code.
public class TotientFunction { public static void main(String[] args) { computePhi(); System.out.println("Compute and display phi for the first 25 integers."); System.out.printf("n Phi IsPrime%n"); for ( int n = 1 ; n <= 25 ; n++ ) { System.out.printf("%2d %2d %b%n", n, phi[n], (phi[n] == n-1)); } for ( int i = 2 ; i < 8 ; i++ ) { int max = (int) Math.pow(10, i); System.out.printf("The count of the primes up toΒ %,10d = %d%n", max, countPrimes(1, max)); } } private static int countPrimes(int min, int max) { int count = 0; for ( int i = min ; i <= max ; i++ ) { if ( phi[i] == i-1 ) { count++; } } return count; } private static final int max = 10000000; private static final int[] phi = new int[max+1]; private static final void computePhi() { for ( int i = 1 ; i <= max ; i++ ) { phi[i] = i; } for ( int i = 2 ; i <= max ; i++ ) { if (phi[i] < i) continue; for ( int j = i ; j <= max ; j += i ) { phi[j] -= phi[j] / i; } } } }
#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 following code from Java to C++ with equivalent syntax and logic.
if (s == 'Hello World') { foo(); } else if (s == 'Bye World') { bar(); } else { deusEx(); }
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;
Write a version of this Java function in C++ with identical behavior.
import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Fractran{ public static void main(String []args){ new Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2); } final int limit = 15; Vector<Integer> num = new Vector<>(); Vector<Integer> den = new Vector<>(); public Fractran(String prog, Integer val){ compile(prog); dump(); exec(2); } void compile(String prog){ Pattern regexp = Pattern.compile("\\s*(\\d*)\\s*\\/\\s*(\\d*)\\s*(.*)"); Matcher matcher = regexp.matcher(prog); while(matcher.find()){ num.add(Integer.parseInt(matcher.group(1))); den.add(Integer.parseInt(matcher.group(2))); matcher = regexp.matcher(matcher.group(3)); } } void exec(Integer val){ int n = 0; while(val != null && n<limit){ System.out.println(n+": "+val); val = step(val); n++; } } Integer step(int val){ int i=0; while(i<den.size() && val%den.get(i) != 0) i++; if(i<den.size()) return num.get(i)*val/den.get(i); return null; } void dump(){ for(int i=0; i<den.size(); i++) System.out.print(num.get(i)+"/"+den.get(i)+" "); System.out.println(); } }
#include <iostream> #include <sstream> #include <iterator> #include <vector> #include <cmath> using namespace std; class fractran { public: void run( std::string p, int s, int l ) { start = s; limit = l; istringstream iss( p ); vector<string> tmp; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) ); string item; vector< pair<float, float> > v; pair<float, float> a; for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ ) { string::size_type pos = ( *i ).find( '/', 0 ); if( pos != std::string::npos ) { a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) ); v.push_back( a ); } } exec( &v ); } private: void exec( vector< pair<float, float> >* v ) { int cnt = 0; while( cnt < limit ) { cout << cnt << "Β : " << start << "\n"; cnt++; vector< pair<float, float> >::iterator it = v->begin(); bool found = false; float r; while( it != v->end() ) { r = start * ( ( *it ).first / ( *it ).second ); if( r == floor( r ) ) { found = true; break; } ++it; } if( found ) start = ( int )r; else break; } } int start, limit; }; int main( int argc, char* argv[] ) { fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 ); cin.get(); return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.Arrays; public class Stooge { public static void main(String[] args) { int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5}; stoogeSort(nums); System.out.println(Arrays.toString(nums)); } public static void stoogeSort(int[] L) { stoogeSort(L, 0, L.length - 1); } public static void stoogeSort(int[] L, int i, int j) { if (L[j] < L[i]) { int tmp = L[i]; L[i] = L[j]; L[j] = tmp; } if (j - i > 1) { int t = (j - i + 1) / 3; stoogeSort(L, i, j - t); stoogeSort(L, i + t, j); stoogeSort(L, i, j - t); } } }
#include <iostream> #include <time.h> using namespace std; class stooge { public: void sort( int* arr, int start, int end ) { if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] ); int n = end - start; if( n > 2 ) { n /= 3; sort( arr, start, end - n ); sort( arr, start + n, end ); sort( arr, start, end - n ); } } }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; cout << "before:\n"; for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20; cout << a[x] << " "; } s.sort( a, 0, m ); cout << "\n\nafter:\n"; for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n"; return system( "pause" ); }
Ensure the translated C++ code behaves exactly like the original Java snippet.
import java.util.Random; import java.util.List; import java.util.ArrayList; public class GaltonBox { public static void main( final String[] args ) { new GaltonBox( 8, 200 ).run(); } private final int m_pinRows; private final int m_startRow; private final Position[] m_balls; private final Random m_random = new Random(); public GaltonBox( final int pinRows, final int ballCount ) { m_pinRows = pinRows; m_startRow = pinRows + 1; m_balls = new Position[ ballCount ]; for ( int ball = 0; ball < ballCount; ball++ ) m_balls[ ball ] = new Position( m_startRow, 0, 'o' ); } private static class Position { int m_row; int m_col; char m_char; Position( final int row, final int col, final char ch ) { m_row = row; m_col = col; m_char = ch; } } public void run() { for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) { ballsInPlay = dropBalls(); print(); } } private int dropBalls() { int ballsInPlay = 0; int ballToStart = -1; for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == m_startRow ) ballToStart = ball; for ( int ball = 0; ball < m_balls.length; ball++ ) if ( ball == ballToStart ) { m_balls[ ball ].m_row = m_pinRows; ballsInPlay++; } else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) { m_balls[ ball ].m_row -= 1; m_balls[ ball ].m_col += m_random.nextInt( 2 ); if ( 0 != m_balls[ ball ].m_row ) ballsInPlay++; } return ballsInPlay; } private void print() { for ( int row = m_startRow; row --> 1; ) { for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == row ) printBall( m_balls[ ball ] ); System.out.println(); printPins( row ); } printCollectors(); System.out.println(); } private static void printBall( final Position pos ) { for ( int col = pos.m_row + 1; col --> 0; ) System.out.print( ' ' ); for ( int col = 0; col < pos.m_col; col++ ) System.out.print( " " ); System.out.print( pos.m_char ); } private void printPins( final int row ) { for ( int col = row + 1; col --> 0; ) System.out.print( ' ' ); for ( int col = m_startRow - row; col --> 0; ) System.out.print( ". " ); System.out.println(); } private void printCollectors() { final List<List<Position>> collectors = new ArrayList<List<Position>>(); for ( int col = 0; col < m_startRow; col++ ) { final List<Position> collector = new ArrayList<Position>(); collectors.add( collector ); for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col ) collector.add( m_balls[ ball ] ); } for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) { for ( int col = 0; col < m_startRow; col++ ) { final List<Position> collector = collectors.get( col ); final int pos = row + collector.size() - rows; System.out.print( '|' ); if ( pos >= 0 ) System.out.print( collector.get( pos ).m_char ); else System.out.print( ' ' ); } System.out.println( '|' ); } } private static final int longest( final List<List<Position>> collectors ) { int result = 0; for ( final List<Position> collector : collectors ) result = Math.max( collector.size(), result ); return result; } }
#include "stdafx.h" #include <windows.h> #include <stdlib.h> const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120; 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(); } 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 point { public: int x; float y; void set( int a, float b ) { x = a; y = b; } }; typedef struct { point position, offset; bool alive, start; }ball; class galton { public : galton() { bmp.create( BMP_WID, BMP_HEI ); initialize(); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } void simulate() { draw(); update(); Sleep( 1 ); } private: void draw() { bmp.clear(); bmp.setPenColor( RGB( 0, 255, 0 ) ); bmp.setBrushColor( RGB( 0, 255, 0 ) ); int xx, yy; for( int y = 3; y < 14; y++ ) { yy = 10 * y; for( int x = 0; x < 41; x++ ) { xx = 10 * x; if( pins[y][x] ) Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 ); } } bmp.setPenColor( RGB( 255, 0, 0 ) ); bmp.setBrushColor( RGB( 255, 0, 0 ) ); ball* b; for( int x = 0; x < MAX_BALLS; x++ ) { b = &balls[x]; if( b->alive ) Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) ); } for( int x = 0; x < 70; x++ ) { if( cols[x] > 0 ) { xx = 10 * x; Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] ); } } HDC dc = GetDC( _hwnd ); BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( _hwnd, dc ); } void update() { ball* b; for( int x = 0; x < MAX_BALLS; x++ ) { b = &balls[x]; if( b->alive ) { b->position.x += b->offset.x; b->position.y += b->offset.y; if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) { b->start = true; balls[x + 1].alive = true; } int c = ( int )b->position.x, d = ( int )b->position.y + 6; if( d > 10 || d < 41 ) { if( pins[d / 10][c / 10] ) { if( rand() % 30 < 15 ) b->position.x -= 10; else b->position.x += 10; } } if( b->position.y > 160 ) { b->alive = false; cols[c / 10] += 1; } } } } void initialize() { for( int x = 0; x < MAX_BALLS; x++ ) { balls[x].position.set( 200, -10 ); balls[x].offset.set( 0, 0.5f ); balls[x].alive = balls[x].start = false; } balls[0].alive = true; for( int x = 0; x < 70; x++ ) cols[x] = 0; for( int y = 0; y < 70; y++ ) for( int x = 0; x < 41; x++ ) pins[x][y] = false; int p; for( int y = 0; y < 11; y++ ) { p = ( 41 / 2 ) - y; for( int z = 0; z < y + 1; z++ ) { pins[3 + y][p] = true; p += 2; } } } myBitmap bmp; HWND _hwnd; bool pins[70][40]; ball balls[MAX_BALLS]; int cols[70]; }; class wnd { public: int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _gtn.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 _gtn.simulate(); } return UnregisterClass( "_GALTON_", _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 static_cast<int>( 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 = "_GALTON_"; RegisterClassEx( &wcex ); RECT rc; SetRect( &rc, 0, 0, BMP_WID, BMP_HEI ); AdjustWindowRect( &rc, WS_CAPTION, FALSE ); return CreateWindow( "_GALTON_", ".: Galton Box -- PJorenteΒ :.", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL ); } HINSTANCE _hInst; HWND _hwnd; galton _gtn; }; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.util.Random; import java.util.List; import java.util.ArrayList; public class GaltonBox { public static void main( final String[] args ) { new GaltonBox( 8, 200 ).run(); } private final int m_pinRows; private final int m_startRow; private final Position[] m_balls; private final Random m_random = new Random(); public GaltonBox( final int pinRows, final int ballCount ) { m_pinRows = pinRows; m_startRow = pinRows + 1; m_balls = new Position[ ballCount ]; for ( int ball = 0; ball < ballCount; ball++ ) m_balls[ ball ] = new Position( m_startRow, 0, 'o' ); } private static class Position { int m_row; int m_col; char m_char; Position( final int row, final int col, final char ch ) { m_row = row; m_col = col; m_char = ch; } } public void run() { for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) { ballsInPlay = dropBalls(); print(); } } private int dropBalls() { int ballsInPlay = 0; int ballToStart = -1; for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == m_startRow ) ballToStart = ball; for ( int ball = 0; ball < m_balls.length; ball++ ) if ( ball == ballToStart ) { m_balls[ ball ].m_row = m_pinRows; ballsInPlay++; } else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) { m_balls[ ball ].m_row -= 1; m_balls[ ball ].m_col += m_random.nextInt( 2 ); if ( 0 != m_balls[ ball ].m_row ) ballsInPlay++; } return ballsInPlay; } private void print() { for ( int row = m_startRow; row --> 1; ) { for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == row ) printBall( m_balls[ ball ] ); System.out.println(); printPins( row ); } printCollectors(); System.out.println(); } private static void printBall( final Position pos ) { for ( int col = pos.m_row + 1; col --> 0; ) System.out.print( ' ' ); for ( int col = 0; col < pos.m_col; col++ ) System.out.print( " " ); System.out.print( pos.m_char ); } private void printPins( final int row ) { for ( int col = row + 1; col --> 0; ) System.out.print( ' ' ); for ( int col = m_startRow - row; col --> 0; ) System.out.print( ". " ); System.out.println(); } private void printCollectors() { final List<List<Position>> collectors = new ArrayList<List<Position>>(); for ( int col = 0; col < m_startRow; col++ ) { final List<Position> collector = new ArrayList<Position>(); collectors.add( collector ); for ( int ball = 0; ball < m_balls.length; ball++ ) if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col ) collector.add( m_balls[ ball ] ); } for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) { for ( int col = 0; col < m_startRow; col++ ) { final List<Position> collector = collectors.get( col ); final int pos = row + collector.size() - rows; System.out.print( '|' ); if ( pos >= 0 ) System.out.print( collector.get( pos ).m_char ); else System.out.print( ' ' ); } System.out.println( '|' ); } } private static final int longest( final List<List<Position>> collectors ) { int result = 0; for ( final List<Position> collector : collectors ) result = Math.max( collector.size(), result ); return result; } }
#include "stdafx.h" #include <windows.h> #include <stdlib.h> const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120; 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(); } 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 point { public: int x; float y; void set( int a, float b ) { x = a; y = b; } }; typedef struct { point position, offset; bool alive, start; }ball; class galton { public : galton() { bmp.create( BMP_WID, BMP_HEI ); initialize(); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } void simulate() { draw(); update(); Sleep( 1 ); } private: void draw() { bmp.clear(); bmp.setPenColor( RGB( 0, 255, 0 ) ); bmp.setBrushColor( RGB( 0, 255, 0 ) ); int xx, yy; for( int y = 3; y < 14; y++ ) { yy = 10 * y; for( int x = 0; x < 41; x++ ) { xx = 10 * x; if( pins[y][x] ) Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 ); } } bmp.setPenColor( RGB( 255, 0, 0 ) ); bmp.setBrushColor( RGB( 255, 0, 0 ) ); ball* b; for( int x = 0; x < MAX_BALLS; x++ ) { b = &balls[x]; if( b->alive ) Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) ); } for( int x = 0; x < 70; x++ ) { if( cols[x] > 0 ) { xx = 10 * x; Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] ); } } HDC dc = GetDC( _hwnd ); BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( _hwnd, dc ); } void update() { ball* b; for( int x = 0; x < MAX_BALLS; x++ ) { b = &balls[x]; if( b->alive ) { b->position.x += b->offset.x; b->position.y += b->offset.y; if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) { b->start = true; balls[x + 1].alive = true; } int c = ( int )b->position.x, d = ( int )b->position.y + 6; if( d > 10 || d < 41 ) { if( pins[d / 10][c / 10] ) { if( rand() % 30 < 15 ) b->position.x -= 10; else b->position.x += 10; } } if( b->position.y > 160 ) { b->alive = false; cols[c / 10] += 1; } } } } void initialize() { for( int x = 0; x < MAX_BALLS; x++ ) { balls[x].position.set( 200, -10 ); balls[x].offset.set( 0, 0.5f ); balls[x].alive = balls[x].start = false; } balls[0].alive = true; for( int x = 0; x < 70; x++ ) cols[x] = 0; for( int y = 0; y < 70; y++ ) for( int x = 0; x < 41; x++ ) pins[x][y] = false; int p; for( int y = 0; y < 11; y++ ) { p = ( 41 / 2 ) - y; for( int z = 0; z < y + 1; z++ ) { pins[3 + y][p] = true; p += 2; } } } myBitmap bmp; HWND _hwnd; bool pins[70][40]; ball balls[MAX_BALLS]; int cols[70]; }; class wnd { public: int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _gtn.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 _gtn.simulate(); } return UnregisterClass( "_GALTON_", _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 static_cast<int>( 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 = "_GALTON_"; RegisterClassEx( &wcex ); RECT rc; SetRect( &rc, 0, 0, BMP_WID, BMP_HEI ); AdjustWindowRect( &rc, WS_CAPTION, FALSE ); return CreateWindow( "_GALTON_", ".: Galton Box -- PJorenteΒ :.", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL ); } HINSTANCE _hInst; HWND _hwnd; galton _gtn; }; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
Convert this Java snippet to C++ and keep its semantics consistent.
import java.util.Arrays; public class CircleSort { public static void main(String[] args) { circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}); } public static void circleSort(int[] arr) { if (arr.length > 0) do { System.out.println(Arrays.toString(arr)); } while (circleSortR(arr, 0, arr.length - 1, 0) != 0); } private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) { if (lo == hi) return numSwaps; int high = hi; int low = lo; int mid = (hi - lo) / 2; while (lo < hi) { if (arr[lo] > arr[hi]) { swap(arr, lo, hi); numSwaps++; } lo++; hi--; } if (lo == hi && arr[lo] > arr[hi + 1]) { swap(arr, lo, hi + 1); numSwaps++; } numSwaps = circleSortR(arr, low, low + mid, numSwaps); numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps); return numSwaps; } private static void swap(int[] arr, int idx1, int idx2) { int tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp; } }
#include <iostream> int circlesort(int* arr, int lo, int hi, int swaps) { if(lo == hi) { return swaps; } int high = hi; int low = lo; int mid = (high - low) / 2; while(lo < hi) { if(arr[lo] > arr[hi]) { int temp = arr[lo]; arr[lo] = arr[hi]; arr[hi] = temp; swaps++; } lo++; hi--; } if(lo == hi) { if(arr[lo] > arr[hi+1]) { int temp = arr[lo]; arr[lo] = arr[hi+1]; arr[hi+1] = temp; swaps++; } } swaps = circlesort(arr, low, low+mid, swaps); swaps = circlesort(arr, low+mid+1, high, swaps); return swaps; } void circlesortDriver(int* arr, int n) { do { for(int i = 0; i < n; i++) { std::cout << arr[i] << ' '; } std::cout << std::endl; } while(circlesort(arr, 0, n-1, 0)); } int main() { int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 }; circlesortDriver(arr, sizeof(arr)/sizeof(int)); return 0; }
Generate an equivalent C++ version of this Java code.
package kronecker; public class ProductFractals { public static int[][] product(final int[][] a, final int[][] b) { final int[][] c = new int[a.length*b.length][]; for (int ix = 0; ix < c.length; ix++) { final int num_cols = a[0].length*b[0].length; c[ix] = new int[num_cols]; } for (int ia = 0; ia < a.length; ia++) { for (int ja = 0; ja < a[ia].length; ja++) { for (int ib = 0; ib < b.length; ib++) { for (int jb = 0; jb < b[ib].length; jb++) { c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb]; } } } } return c; } public static void show_matrix(final int[][] m, final char nz, final char z) { for (int im = 0; im < m.length; im++) { for (int jm = 0; jm < m[im].length; jm++) { System.out.print(m[im][jm] == 0 ? z : nz); } System.out.println(); } } public static int[][] power(final int[][] m, final int n) { int[][] m_pow = m; for (int ix = 1; ix < n; ix++) { m_pow = product(m, m_pow); } return m_pow; } private static void test(final int[][] m, final int n) { System.out.println("Test matrix"); show_matrix(m, '*', ' '); final int[][] m_pow = power(m, n); System.out.println("Matrix power " + n); show_matrix(m_pow, '*', ' '); } private static void test1() { final int[][] m = {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}; test(m, 4); } private static void test2() { final int[][] m = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; test(m, 4); } private static void test3() { final int[][] m = {{1, 0, 1}, {1, 0, 1}, {0, 1, 0}}; test(m, 4); } public static void main(final String[] args) { test1(); test2(); test3(); } }
#include <cassert> #include <vector> #include <QImage> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<scalar_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[i]); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const scalar_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } scalar_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } private: size_t rows_; size_t columns_; std::vector<scalar_type> elements_; }; template <typename scalar_type> matrix<scalar_type> kronecker_product(const matrix<scalar_type>& a, const matrix<scalar_type>& b) { size_t arows = a.rows(); size_t acolumns = a.columns(); size_t brows = b.rows(); size_t bcolumns = b.columns(); matrix<scalar_type> c(arows * brows, acolumns * bcolumns); for (size_t i = 0; i < arows; ++i) for (size_t j = 0; j < acolumns; ++j) for (size_t k = 0; k < brows; ++k) for (size_t l = 0; l < bcolumns; ++l) c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l); return c; } bool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) { matrix<unsigned char> result = m; for (int i = 0; i < order; ++i) result = kronecker_product(result, m); size_t height = result.rows(); size_t width = result.columns(); size_t bytesPerLine = 4 * ((width + 3)/4); std::vector<uchar> imageData(bytesPerLine * height); for (size_t i = 0; i < height; ++i) for (size_t j = 0; j < width; ++j) imageData[i * bytesPerLine + j] = result(i, j); QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8); QVector<QRgb> colours(2); colours[0] = qRgb(0, 0, 0); colours[1] = qRgb(255, 255, 255); image.setColorTable(colours); return image.save(fileName); } int main() { matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}}); matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}}); matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}}); kronecker_fractal("vicsek.png", matrix1, 5); kronecker_fractal("sierpinski_carpet.png", matrix2, 5); kronecker_fractal("sierpinski_triangle.png", matrix3, 8); return 0; }
Port the provided Java code into C++ while preserving the original functionality.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConfigReader { private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" ); private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>() {{ put( "needspeeling", false ); put( "seedsremoved", false ); }}; public static void main( final String[] args ) { System.out.println( parseFile( args[ 0 ] ) ); } public static Map<String, Object> parseFile( final String fileName ) { final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS ); BufferedReader reader = null; try { reader = new BufferedReader( new FileReader( fileName ) ); for ( String line; null != ( line = reader.readLine() ); ) { parseLine( line, result ); } } catch ( final IOException x ) { throw new RuntimeException( "Oops: " + x, x ); } finally { if ( null != reader ) try { reader.close(); } catch ( final IOException x2 ) { System.err.println( "Could not close " + fileName + " - " + x2 ); } } return result; } private static void parseLine( final String line, final Map<String, Object> map ) { if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) ) return; final Matcher matcher = LINE_PATTERN.matcher( line ); if ( ! matcher.matches() ) { System.err.println( "Bad config line: " + line ); return; } final String key = matcher.group( 1 ).trim().toLowerCase(); final String value = matcher.group( 2 ).trim(); if ( "".equals( value ) ) { map.put( key, true ); } else if ( -1 == value.indexOf( ',' ) ) { map.put( key, value ); } else { final String[] values = value.split( "," ); for ( int i = 0; i < values.length; i++ ) { values[ i ] = values[ i ].trim(); } map.put( key, Arrays.asList( values ) ); } } }
#include "stdafx.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string/case_conv.hpp> using namespace std; using namespace boost; typedef boost::tokenizer<boost::char_separator<char> > Tokenizer; static const char_separator<char> sep(" ","#;,"); struct configs{ string fullname; string favoritefruit; bool needspelling; bool seedsremoved; vector<string> otherfamily; } conf; void parseLine(const string &line, configs &conf) { if (line[0] == '#' || line.empty()) return; Tokenizer tokenizer(line, sep); vector<string> tokens; for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++) tokens.push_back(*iter); if (tokens[0] == ";"){ algorithm::to_lower(tokens[1]); if (tokens[1] == "needspeeling") conf.needspelling = false; if (tokens[1] == "seedsremoved") conf.seedsremoved = false; } algorithm::to_lower(tokens[0]); if (tokens[0] == "needspeeling") conf.needspelling = true; if (tokens[0] == "seedsremoved") conf.seedsremoved = true; if (tokens[0] == "fullname"){ for (unsigned int i=1; i<tokens.size(); i++) conf.fullname += tokens[i] + " "; conf.fullname.erase(conf.fullname.size() -1, 1); } if (tokens[0] == "favouritefruit") for (unsigned int i=1; i<tokens.size(); i++) conf.favoritefruit += tokens[i]; if (tokens[0] == "otherfamily"){ unsigned int i=1; string tmp; while (i<=tokens.size()){ if ( i == tokens.size() || tokens[i] ==","){ tmp.erase(tmp.size()-1, 1); conf.otherfamily.push_back(tmp); tmp = ""; i++; } else{ tmp += tokens[i]; tmp += " "; i++; } } } } int _tmain(int argc, TCHAR* argv[]) { if (argc != 2) { wstring tmp = argv[0]; wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl; return -1; } ifstream file (argv[1]); if (file.is_open()) while(file.good()) { char line[255]; file.getline(line, 255); string linestring(line); parseLine(linestring, conf); } else { cout << "Unable to open the file" << endl; return -2; } cout << "Fullname= " << conf.fullname << endl; cout << "Favorite Fruit= " << conf.favoritefruit << endl; cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl; cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl; string otherFamily; for (unsigned int i = 0; i < conf.otherfamily.size(); i++) otherFamily += conf.otherfamily[i] + ", "; otherFamily.erase(otherFamily.size()-2, 2); cout << "Other Family= " << otherFamily << endl; return 0; }
Convert the following code from Java to C++, ensuring the logic remains intact.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConfigReader { private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" ); private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>() {{ put( "needspeeling", false ); put( "seedsremoved", false ); }}; public static void main( final String[] args ) { System.out.println( parseFile( args[ 0 ] ) ); } public static Map<String, Object> parseFile( final String fileName ) { final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS ); BufferedReader reader = null; try { reader = new BufferedReader( new FileReader( fileName ) ); for ( String line; null != ( line = reader.readLine() ); ) { parseLine( line, result ); } } catch ( final IOException x ) { throw new RuntimeException( "Oops: " + x, x ); } finally { if ( null != reader ) try { reader.close(); } catch ( final IOException x2 ) { System.err.println( "Could not close " + fileName + " - " + x2 ); } } return result; } private static void parseLine( final String line, final Map<String, Object> map ) { if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) ) return; final Matcher matcher = LINE_PATTERN.matcher( line ); if ( ! matcher.matches() ) { System.err.println( "Bad config line: " + line ); return; } final String key = matcher.group( 1 ).trim().toLowerCase(); final String value = matcher.group( 2 ).trim(); if ( "".equals( value ) ) { map.put( key, true ); } else if ( -1 == value.indexOf( ',' ) ) { map.put( key, value ); } else { final String[] values = value.split( "," ); for ( int i = 0; i < values.length; i++ ) { values[ i ] = values[ i ].trim(); } map.put( key, Arrays.asList( values ) ); } } }
#include "stdafx.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string/case_conv.hpp> using namespace std; using namespace boost; typedef boost::tokenizer<boost::char_separator<char> > Tokenizer; static const char_separator<char> sep(" ","#;,"); struct configs{ string fullname; string favoritefruit; bool needspelling; bool seedsremoved; vector<string> otherfamily; } conf; void parseLine(const string &line, configs &conf) { if (line[0] == '#' || line.empty()) return; Tokenizer tokenizer(line, sep); vector<string> tokens; for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++) tokens.push_back(*iter); if (tokens[0] == ";"){ algorithm::to_lower(tokens[1]); if (tokens[1] == "needspeeling") conf.needspelling = false; if (tokens[1] == "seedsremoved") conf.seedsremoved = false; } algorithm::to_lower(tokens[0]); if (tokens[0] == "needspeeling") conf.needspelling = true; if (tokens[0] == "seedsremoved") conf.seedsremoved = true; if (tokens[0] == "fullname"){ for (unsigned int i=1; i<tokens.size(); i++) conf.fullname += tokens[i] + " "; conf.fullname.erase(conf.fullname.size() -1, 1); } if (tokens[0] == "favouritefruit") for (unsigned int i=1; i<tokens.size(); i++) conf.favoritefruit += tokens[i]; if (tokens[0] == "otherfamily"){ unsigned int i=1; string tmp; while (i<=tokens.size()){ if ( i == tokens.size() || tokens[i] ==","){ tmp.erase(tmp.size()-1, 1); conf.otherfamily.push_back(tmp); tmp = ""; i++; } else{ tmp += tokens[i]; tmp += " "; i++; } } } } int _tmain(int argc, TCHAR* argv[]) { if (argc != 2) { wstring tmp = argv[0]; wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl; return -1; } ifstream file (argv[1]); if (file.is_open()) while(file.good()) { char line[255]; file.getline(line, 255); string linestring(line); parseLine(linestring, conf); } else { cout << "Unable to open the file" << endl; return -2; } cout << "Fullname= " << conf.fullname << endl; cout << "Favorite Fruit= " << conf.favoritefruit << endl; cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl; cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl; string otherFamily; for (unsigned int i = 0; i < conf.otherfamily.size(); i++) otherFamily += conf.otherfamily[i] + ", "; otherFamily.erase(otherFamily.size()-2, 2); cout << "Other Family= " << otherFamily << endl; return 0; }
Port the following code from Java to C++ with equivalent syntax and logic.
import java.util.Comparator; import java.util.Arrays; public class Test { public static void main(String[] args) { String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; Arrays.sort(strings, new Comparator<String>() { public int compare(String s1, String s2) { int c = s2.length() - s1.length(); if (c == 0) c = s1.compareToIgnoreCase(s2); return c; } }); for (String s: strings) System.out.print(s + " "); } }
#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; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
import java.math.BigInteger; import java.util.Arrays; public class CircularPrimes { public static void main(String[] args) { System.out.println("First 19 circular primes:"); int p = 2; for (int count = 0; count < 19; ++p) { if (isCircularPrime(p)) { if (count > 0) System.out.print(", "); System.out.print(p); ++count; } } System.out.println(); System.out.println("Next 4 circular primes:"); int repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; BigInteger bignum = BigInteger.valueOf(repunit); for (int count = 0; count < 4; ) { if (bignum.isProbablePrime(15)) { if (count > 0) System.out.print(", "); System.out.printf("R(%d)", digits); ++count; } ++digits; bignum = bignum.multiply(BigInteger.TEN); bignum = bignum.add(BigInteger.ONE); } System.out.println(); testRepunit(5003); testRepunit(9887); testRepunit(15073); testRepunit(25031); } private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } private static int cycle(int n) { int m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); } private static boolean isCircularPrime(int p) { if (!isPrime(p)) return false; int p2 = cycle(p); while (p2 != p) { if (p2 < p || !isPrime(p2)) return false; p2 = cycle(p2); } return true; } private static void testRepunit(int digits) { BigInteger repunit = repunit(digits); if (repunit.isProbablePrime(15)) System.out.printf("R(%d) is probably prime.\n", digits); else System.out.printf("R(%d) is not prime.\n", digits); } private static BigInteger repunit(int digits) { char[] ch = new char[digits]; Arrays.fill(ch, '1'); return new BigInteger(new String(ch)); } }
#include <cstdint> #include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_prime(const integer& n, int reps = 50) { return mpz_probab_prime_p(n.get_mpz_t(), reps); } std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } bool is_circular_prime(const integer& p) { if (!is_prime(p)) return false; std::string str(to_string(p)); for (size_t i = 0, n = str.size(); i + 1 < n; ++i) { std::rotate(str.begin(), str.begin() + 1, str.end()); integer p2(str, 10); if (p2 < p || !is_prime(p2)) return false; } return true; } integer next_repunit(const integer& n) { integer p = 1; while (p < n) p = 10 * p + 1; return p; } integer repunit(int digits) { std::string str(digits, '1'); integer p(str); return p; } void test_repunit(int digits) { if (is_prime(repunit(digits), 10)) std::cout << "R(" << digits << ") is probably prime\n"; else std::cout << "R(" << digits << ") is not prime\n"; } int main() { integer p = 2; std::cout << "First 19 circular primes:\n"; for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) std::cout << ", "; std::cout << p; ++count; } } std::cout << '\n'; std::cout << "Next 4 circular primes:\n"; p = next_repunit(p); std::string str(to_string(p)); int digits = str.size(); for (int count = 0; count < 4; ) { if (is_prime(p, 15)) { if (count > 0) std::cout << ", "; std::cout << "R(" << digits << ")"; ++count; } p = repunit(++digits); } std::cout << '\n'; test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
Change the following Java code into C++ without altering its purpose.
import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants; public class Rotate { private static class State { private final String text = "Hello World! "; private int startIndex = 0; private boolean rotateRight = true; } public static void main(String[] args) { State state = new State(); JLabel label = new JLabel(state.text); label.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent event) { state.rotateRight = !state.rotateRight; } }); TimerTask task = new TimerTask() { public void run() { int delta = state.rotateRight ? 1 : -1; state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length(); label.setText(rotate(state.text, state.startIndex)); } }; Timer timer = new Timer(false); timer.schedule(task, 0, 500); JFrame rot = new JFrame(); rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); rot.add(label); rot.pack(); rot.setLocationRelativeTo(null); rot.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { timer.cancel(); } }); rot.setVisible(true); } private static String rotate(String text, int startIdx) { char[] rotated = new char[text.length()]; for (int i = 0; i < text.length(); i++) { rotated[i] = text.charAt((i + startIdx) % text.length()); } return String.valueOf(rotated); } }
#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_; }
Produce a language-to-language conversion: from Java to C++, same semantics.
public static int[] sort(int[] old) { for (int shift = Integer.SIZE - 1; shift > -1; shift--) { int[] tmp = new int[old.length]; int j = 0; for (int i = 0; i < old.length; i++) { boolean move = old[i] << shift >= 0; if (shift == 0 ? !move : move) { tmp[j] = old[i]; j++; } else { old[i - j] = old[i]; } } for (int i = j; i < tmp.length; i++) { tmp[i] = old[i - j]; } old = tmp; } return old; }
#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; }