Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in C.
Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean) Dim i As Integer, stReplace As String If bSpace = True Then stReplace = " " Else stReplace = "" End If For i = 1 To Len(stStripChars) stString = Replace(stString, Mid(stStripChars, i, 1), stReplace) Next i StripChars = stString End Function
#include <string.h> #include <stdio.h> #include <stdlib.h> char *strip_chars(const char *string, const char *chars) { char * newstr = malloc(strlen(string) + 1); int counter = 0; for ( ; *string; string++) { if (!strchr(chars, *string)) { newstr[ counter ] = *string; ++ counter; } } newstr[counter] = 0; return newstr; } int main(void) { char *new = strip_chars("She was a soul stripper. She took my heart!", "aei"); printf("%s\n", new); free(new); return 0; }
Translate this program into C but keep the logic exactly as in VB.
Private Function mean(v() As Double, ByVal leng As Integer) As Variant Dim sum As Double, i As Integer sum = 0: i = 0 For i = 0 To leng - 1 sum = sum + vv Next i If leng = 0 Then mean = CVErr(xlErrDiv0) Else mean = sum / leng End If End Function Public Sub main() Dim v(4) As Double Dim i As Integer, leng As Integer v(0) = 1# v(1) = 2# v(2) = 2.178 v(3) = 3# v(4) = 3.142 For leng = 5 To 0 Step -1 Debug.Print "mean["; For i = 0 To leng - 1 Debug.Print IIf(i, "; " & v(i), "" & v(i)); Next i Debug.Print "] = "; mean(v, leng) Next leng End Sub
#include <stdio.h> double mean(double *v, int len) { double sum = 0; int i; for (i = 0; i < len; i++) sum += v[i]; return sum / len; } int main(void) { double v[] = {1, 2, 2.718, 3, 3.142}; int i, len; for (len = 5; len >= 0; len--) { printf("mean["); for (i = 0; i < len; i++) printf(i ? ", %g" : "%g", v[i]); printf("] = %g\n", mean(v, len)); } return 0; }
Port the provided VB code into C while preserving the original functionality.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " commandtable = Split(s, " ") Dim i As Integer, word As Variant, number As Integer For i = LBound(commandtable) To UBound(commandtable) word = commandtable(i) If Len(word) > 0 Then i = i + 1 Do While Len(commandtable(i)) = 0: i = i + 1: Loop number = Val(commandtable(i)) If number > 0 Then command_table.Add Key:=word, Item:=number Else command_table.Add Key:=word, Item:=Len(word) i = i - 1 End If End If Next i For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = word_len; new_cmd->cmd = uppercase(word, word_len); if (i + 1 < count) { char* eptr = 0; unsigned long min_len = strtoul(words[i + 1], &eptr, 10); if (min_len > 0 && *eptr == 0) { free(words[i + 1]); new_cmd->min_len = min_len; ++i; } } new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Write the same code in C as shown below in VB.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " commandtable = Split(s, " ") Dim i As Integer, word As Variant, number As Integer For i = LBound(commandtable) To UBound(commandtable) word = commandtable(i) If Len(word) > 0 Then i = i + 1 Do While Len(commandtable(i)) = 0: i = i + 1: Loop number = Val(commandtable(i)) If number > 0 Then command_table.Add Key:=word, Item:=number Else command_table.Add Key:=word, Item:=Len(word) i = i - 1 End If End If Next i For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = word_len; new_cmd->cmd = uppercase(word, word_len); if (i + 1 < count) { char* eptr = 0; unsigned long min_len = strtoul(words[i + 1], &eptr, 10); if (min_len > 0 && *eptr == 0) { free(words[i + 1]); new_cmd->min_len = min_len; ++i; } } new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Can you help me rewrite this code in C instead of VB, keeping it the same logically?
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " commandtable = Split(s, " ") Dim i As Integer, word As Variant, number As Integer For i = LBound(commandtable) To UBound(commandtable) word = commandtable(i) If Len(word) > 0 Then i = i + 1 Do While Len(commandtable(i)) = 0: i = i + 1: Loop number = Val(commandtable(i)) If number > 0 Then command_table.Add Key:=word, Item:=number Else command_table.Add Key:=word, Item:=Len(word) i = i - 1 End If End If Next i For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; typedef struct command_tag { char* cmd; size_t length; size_t min_len; struct command_tag* next; } command_t; bool command_match(const command_t* command, const char* str) { size_t olen = strlen(str); return olen >= command->min_len && olen <= command->length && strncmp(str, command->cmd, olen) == 0; } char* uppercase(char* str, size_t n) { for (size_t i = 0; i < n; ++i) str[i] = toupper((unsigned char)str[i]); return str; } void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } char** split_into_words(const char* str, size_t* count) { size_t size = 0; size_t capacity = 16; char** words = xmalloc(capacity * sizeof(char*)); size_t len = strlen(str); for (size_t begin = 0; begin < len; ) { size_t i = begin; for (; i < len && isspace((unsigned char)str[i]); ++i) {} begin = i; for (; i < len && !isspace((unsigned char)str[i]); ++i) {} size_t word_len = i - begin; if (word_len == 0) break; char* word = xmalloc(word_len + 1); memcpy(word, str + begin, word_len); word[word_len] = 0; begin += word_len; if (capacity == size) { capacity *= 2; words = xrealloc(words, capacity * sizeof(char*)); } words[size++] = word; } *count = size; return words; } command_t* make_command_list(const char* table) { command_t* cmd = NULL; size_t count = 0; char** words = split_into_words(table, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; command_t* new_cmd = xmalloc(sizeof(command_t)); size_t word_len = strlen(word); new_cmd->length = word_len; new_cmd->min_len = word_len; new_cmd->cmd = uppercase(word, word_len); if (i + 1 < count) { char* eptr = 0; unsigned long min_len = strtoul(words[i + 1], &eptr, 10); if (min_len > 0 && *eptr == 0) { free(words[i + 1]); new_cmd->min_len = min_len; ++i; } } new_cmd->next = cmd; cmd = new_cmd; } free(words); return cmd; } void free_command_list(command_t* cmd) { while (cmd != NULL) { command_t* next = cmd->next; free(cmd->cmd); free(cmd); cmd = next; } } const command_t* find_command(const command_t* commands, const char* word) { for (const command_t* cmd = commands; cmd != NULL; cmd = cmd->next) { if (command_match(cmd, word)) return cmd; } return NULL; } void test(const command_t* commands, const char* input) { printf(" input: %s\n", input); printf("output:"); size_t count = 0; char** words = split_into_words(input, &count); for (size_t i = 0; i < count; ++i) { char* word = words[i]; uppercase(word, strlen(word)); const command_t* cmd_ptr = find_command(commands, word); printf(" %s", cmd_ptr ? cmd_ptr->cmd : "*error*"); free(word); } free(words); printf("\n"); } int main() { command_t* commands = make_command_list(command_table); const char* input = "riG rePEAT copies put mo rest types fup. 6 poweRin"; test(commands, input); free_command_list(commands); return 0; }
Preserve the algorithm and functionality while converting the code from VB to C.
Private Function tokenize(s As String, sep As String, esc As String) As Collection Dim ret As New Collection Dim this As String Dim skip As Boolean If Len(s) <> 0 Then For i = 1 To Len(s) si = Mid(s, i, 1) If skip Then this = this & si skip = False Else If si = esc Then skip = True Else If si = sep Then ret.Add this this = "" Else this = this & si End If End If End If Next i ret.Add this End If Set tokenize = ret End Function Public Sub main() Dim out As Collection Set out = tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^") Dim outstring() As String ReDim outstring(out.Count - 1) For i = 0 To out.Count - 1 outstring(i) = out(i + 1) Next i Debug.Print Join(outstring, ", ") End Sub
#include <stdlib.h> #include <stdio.h> #define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|" #define SEP '|' #define ESC '^' typedef char* Str; unsigned int ElQ( const char *s, char sep, char esc ); Str *Tokenize( char *s, char sep, char esc, unsigned int *q ); int main() { char s[] = STR_DEMO; unsigned int i, q; Str *list = Tokenize( s, SEP, ESC, &q ); if( list != NULL ) { printf( "\n Original string: %s\n\n", STR_DEMO ); printf( " %d tokens:\n\n", q ); for( i=0; i<q; ++i ) printf( " %4d. %s\n", i+1, list[i] ); free( list ); } return 0; } unsigned int ElQ( const char *s, char sep, char esc ) { unsigned int q, e; const char *p; for( e=0, q=1, p=s; *p; ++p ) { if( *p == esc ) e = !e; else if( *p == sep ) q += !e; else e = 0; } return q; } Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) { Str *list = NULL; *q = ElQ( s, sep, esc ); list = malloc( *q * sizeof(Str) ); if( list != NULL ) { unsigned int e, i; char *p; i = 0; list[i++] = s; for( e=0, p=s; *p; ++p ) { if( *p == esc ) { e = !e; } else if( *p == sep && !e ) { list[i++] = p+1; *p = '\0'; } else { e = 0; } } } return list; }
Keep all operations the same but rewrite the snippet in C.
Module ForwardDifference Sub Main() Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}) For i As UInteger = 0 To 9 Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray())) Next Console.ReadKey() End Sub Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer) If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers") For i As Integer = 1 To Level Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _ Select Numbers(n + 1) - Numbers(n)).ToList() Next Return Numbers End Function End Module
#include <stdlib.h> #include <string.h> #include <stdio.h> double* fwd_diff(double* x, unsigned int len, unsigned int order) { unsigned int i, j; double* y; if (order >= len) return 0; y = malloc(sizeof(double) * len); if (!order) { memcpy(y, x, sizeof(double) * len); return y; } for (j = 0; j < order; j++, x = y) for (i = 0, len--; i < len; i++) y[i] = x[i + 1] - x[i]; y = realloc(y, sizeof(double) * len); return y; } int main(void) { double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; int i, len = sizeof(x) / sizeof(x[0]); y = fwd_diff(x, len, 1); for (i = 0; i < len - 1; i++) printf("%g ", y[i]); putchar('\n'); return 0; }
Change the programming language of this snippet from VB to C without modifying what it does.
Option Explicit Sub FirstTwentyPrimes() Dim count As Integer, i As Long, t(19) As String Do i = i + 1 If IsPrime(i) Then t(count) = i count = count + 1 End If Loop While count <= UBound(t) Debug.Print Join(t, ", ") End Sub Function IsPrime(Nb As Long) As Boolean If Nb = 2 Then IsPrime = True ElseIf Nb < 2 Or Nb Mod 2 = 0 Then Exit Function Else Dim i As Long For i = 3 To Sqr(Nb) Step 2 If Nb Mod i = 0 Then Exit Function Next IsPrime = True End If End Function
int is_prime(unsigned int n) { unsigned int p; if (!(n & 1) || n < 2 ) return n == 2; for (p = 3; p <= n/p; p += 2) if (!(n % p)) return 0; return 1; }
Can you help me rewrite this code in C instead of VB, keeping it the same logically?
Function binomial(n,k) binomial = factorial(n)/(factorial(n-k)*factorial(k)) End Function Function factorial(n) If n = 0 Then factorial = 1 Else For i = n To 1 Step -1 If i = n Then factorial = n Else factorial = factorial * i End If Next End If End Function WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3) WScript.StdOut.WriteLine
#include <stdio.h> #include <limits.h> static unsigned long gcd_ui(unsigned long x, unsigned long y) { unsigned long t; if (y < x) { t = x; x = y; y = t; } while (y > 0) { t = y; y = x % y; x = t; } return x; } unsigned long binomial(unsigned long n, unsigned long k) { unsigned long d, g, r = 1; if (k == 0) return 1; if (k == 1) return n; if (k >= n) return (k == n); if (k > n/2) k = n-k; for (d = 1; d <= k; d++) { if (r >= ULONG_MAX/n) { unsigned long nr, dr; g = gcd_ui(n, d); nr = n/g; dr = d/g; g = gcd_ui(r, dr); r = r/g; dr = dr/g; if (r >= ULONG_MAX/nr) return 0; r *= nr; r /= dr; n--; } else { r *= n--; r /= d; } } return r; } int main() { printf("%lu\n", binomial(5, 3)); printf("%lu\n", binomial(40, 19)); printf("%lu\n", binomial(67, 31)); return 0; }
Ensure the translated C code behaves exactly like the original VB snippet.
Dim coll As New Collection coll.Add "apple" coll.Add "banana"
#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) int ar[10]; ar[0] = 1; ar[1] = 2; int* p; for (p=ar; p<(ar+cSize(ar)); p++) { printf("%d\n",*p); }
Please provide an equivalent version of this VB code in C.
Private Sub Iterate(ByVal list As LinkedList(Of Integer)) Dim node = list.First Do Until node Is Nothing node = node.Next Loop End Sub
struct link *first; struct link *iter; for(iter = first; iter != NULL; iter = iter->next) { }
Write the same algorithm in C++ as shown in this Java implementation.
module BitwiseOps { @Inject Console console; void run() { for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF]) { static String hex(Int64 n) { return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString(); } console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}): | {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)} | {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)} | {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)} | NOT {hex(n1)} = {hex(~n1)} | left shift {hex(n1)} by {n2} = {hex(n1 << n2)} | right shift {hex(n1)} by {n2} = {hex(n1 >> n2)} | right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)} | left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))} | right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))} | leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)} | rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)} | leading zero count of {hex(n1)} = {n1.leadingZeroCount} | trailing zero count of {hex(n1)} = {n1.trailingZeroCount} | bit count (aka "population") of {hex(n1)} = {n1.bitCount} | reversed bits of {hex(n1)} = {hex(n1.reverseBits())} | reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())} | ); } } }
#include <iostream> void bitwise(int a, int b) { std::cout << "a and b: " << (a & b) << '\n'; std::cout << "a or b: " << (a | b) << '\n'; std::cout << "a xor b: " << (a ^ b) << '\n'; std::cout << "not a: " << ~a << '\n'; std::cout << "a shl b: " << (a << b) << '\n'; std::cout << "a shr b: " << (a >> b) << '\n'; unsigned int ua = a; std::cout << "a lsr b: " << (ua >> b) << '\n'; std::cout << "a rol b: " << std::rotl(ua, b) << '\n'; std::cout << "a ror b: " << std::rotr(ua, b) << '\n'; }
Transform the following Java implementation into C++, maintaining the same output and logic.
import java.awt.Color; import java.awt.Graphics; import java.util.*; import javax.swing.JFrame; public class DragonCurve extends JFrame { private List<Integer> turns; private double startingAngle, side; public DragonCurve(int iter) { super("Dragon Curve"); setBounds(100, 100, 800, 600); setDefaultCloseOperation(EXIT_ON_CLOSE); turns = getSequence(iter); startingAngle = -iter * (Math.PI / 4); side = 400 / Math.pow(2, iter / 2.); } public List<Integer> getSequence(int iterations) { List<Integer> turnSequence = new ArrayList<Integer>(); for (int i = 0; i < iterations; i++) { List<Integer> copy = new ArrayList<Integer>(turnSequence); Collections.reverse(copy); turnSequence.add(1); for (Integer turn : copy) { turnSequence.add(-turn); } } return turnSequence; } @Override public void paint(Graphics g) { g.setColor(Color.BLACK); double angle = startingAngle; int x1 = 230, y1 = 350; int x2 = x1 + (int) (Math.cos(angle) * side); int y2 = y1 + (int) (Math.sin(angle) * side); g.drawLine(x1, y1, x2, y2); x1 = x2; y1 = y2; for (Integer turn : turns) { angle += turn * (Math.PI / 2); x2 = x1 + (int) (Math.cos(angle) * side); y2 = y1 + (int) (Math.sin(angle) * side); g.drawLine(x1, y1, x2, y2); x1 = x2; y1 = y2; } } public static void main(String[] args) { new DragonCurve(14).setVisible(true); } }
#include <windows.h> #include <iostream> using namespace std; const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class dragonC { public: dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; } void draw( int iterations ) { generate( iterations ); draw(); } private: void generate( int it ) { generator.push_back( 1 ); string temp; for( int y = 0; y < it - 1; y++ ) { temp = generator; temp.push_back( 1 ); for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ ) temp.push_back( !( *x ) ); generator = temp; } } void draw() { HDC dc = bmp.getDC(); unsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff }; int mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0; for( int t = 0; t < 4; t++ ) { int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++]; MoveToEx( dc, a, b, NULL ); bmp.setPenColor( clr[t] ); for( string::iterator x = generator.begin(); x < generator.end(); x++ ) { switch( dir ) { case NORTH: if( *x ) { a += LEN; dir = EAST; } else { a -= LEN; dir = WEST; } break; case EAST: if( *x ) { b += LEN; dir = SOUTH; } else { b -= LEN; dir = NORTH; } break; case SOUTH: if( *x ) { a -= LEN; dir = WEST; } else { a += LEN; dir = EAST; } break; case WEST: if( *x ) { b -= LEN; dir = NORTH; } else { b += LEN; dir = SOUTH; } } LineTo( dc, a, b ); } } bmp.saveBitmap( "f:/rc/dragonCpp.bmp" ); } int dir; myBitmap bmp; string generator; }; int main( int argc, char* argv[] ) { dragonC d; d.draw( 17 ); return system( "pause" ); }
Convert this Java snippet to C++ and keep its semantics consistent.
import java.io.BufferedReader; import java.io.FileReader; public class ReadFileByLines { private static void processLine(int lineNo, String line) { } public static void main(String[] args) { for (String filename : args) { BufferedReader br = null; FileReader fr = null; try { fr = new FileReader(filename); br = new BufferedReader(fr); String line; int lineNo = 0; while ((line = br.readLine()) != null) { processLine(++lineNo, line); } } catch (Exception x) { x.printStackTrace(); } finally { if (fr != null) { try {br.close();} catch (Exception ignoreMe) {} try {fr.close();} catch (Exception ignoreMe) {} } } } } }
#include <fstream> #include <string> #include <iostream> int main( int argc , char** argv ) { int linecount = 0 ; std::string line ; std::ifstream infile( argv[ 1 ] ) ; if ( infile ) { while ( getline( infile , line ) ) { std::cout << linecount << ": " << line << '\n' ; linecount++ ; } } infile.close( ) ; return 0 ; }
Keep all operations the same but rewrite the snippet in C++.
import java.util.LinkedList; @SuppressWarnings("serial") public class DoublyLinkedListInsertion<T> extends LinkedList<T> { public static void main(String[] args) { DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>(); list.addFirst("Add First 1"); list.addFirst("Add First 2"); list.addFirst("Add First 3"); list.addFirst("Add First 4"); list.addFirst("Add First 5"); traverseList(list); list.addAfter("Add First 3", "Add New"); traverseList(list); } public void addAfter(T after, T element) { int index = indexOf(after); if ( index >= 0 ) { add(index + 1, element); } else { addLast(element); } } private static void traverseList(LinkedList<String> list) { System.out.println("Traverse List:"); for ( int i = 0 ; i < list.size() ; i++ ) { System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i)); } System.out.println(); } }
template <typename T> void insert_after(Node<T>* N, T&& data) { auto node = new Node<T>{N, N->next, std::forward(data)}; if(N->next != nullptr) N->next->prev = node; N->next = node; }
Change the following Java code into C++ without altering its purpose.
public class SmarandachePrimeDigitalSequence { public static void main(String[] args) { long s = getNextSmarandache(7); System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 "); for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { System.out.printf("%d ", s); count++; } } System.out.printf("%n%n"); for (int i = 2 ; i <=5 ; i++ ) { long n = (long) Math.pow(10, i); System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n)); } } private static final long getSmarandachePrime(long n) { if ( n < 10 ) { switch ((int) n) { case 1: return 2; case 2: return 3; case 3: return 5; case 4: return 7; } } long s = getNextSmarandache(7); long result = 0; for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { count++; result = s; } } return result; } private static final boolean isPrime(long test) { if ( test % 2 == 0 ) return false; for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) { if ( test % i == 0 ) { return false; } } return true; } private static long getNextSmarandache(long n) { if ( n % 10 == 3 ) { return n+4; } long retVal = n-4; int k = 0; while ( n % 10 == 7 ) { k++; n /= 10; } long digit = n % 10; long coeff = (digit == 2 ? 1 : 2); retVal += coeff * Math.pow(10, k); while ( k > 1 ) { retVal -= 5 * Math.pow(10, k-1); k--; } return retVal; } }
#include <iostream> #include <cstdint> using integer = uint32_t; integer next_prime_digit_number(integer n) { if (n == 0) return 2; switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: return 2 + next_prime_digit_number(n/10) * 10; } } bool is_prime(integer n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 }; integer p = 7; for (;;) { for (integer w : wheel) { if (p * p > n) return true; if (n % p == 0) return false; p += w; } } } int main() { std::cout.imbue(std::locale("")); const integer limit = 1000000000; integer n = 0, max = 0; std::cout << "First 25 SPDS primes:\n"; for (int i = 0; n < limit; ) { n = next_prime_digit_number(n); if (!is_prime(n)) continue; if (i < 25) { if (i > 0) std::cout << ' '; std::cout << n; } else if (i == 25) std::cout << '\n'; ++i; if (i == 100) std::cout << "Hundredth SPDS prime: " << n << '\n'; else if (i == 1000) std::cout << "Thousandth SPDS prime: " << n << '\n'; else if (i == 10000) std::cout << "Ten thousandth SPDS prime: " << n << '\n'; max = n; } std::cout << "Largest SPDS prime less than " << limit << ": " << max << '\n'; return 0; }
Port the provided Java code into C++ while preserving the original functionality.
import java.util.Random; public class QuickSelect { private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) { E pivotVal = arr[pivot]; swap(arr, pivot, right); int storeIndex = left; for (int i = left; i < right; i++) { if (arr[i].compareTo(pivotVal) < 0) { swap(arr, i, storeIndex); storeIndex++; } } swap(arr, right, storeIndex); return storeIndex; } private static <E extends Comparable<? super E>> E select(E[] arr, int n) { int left = 0; int right = arr.length - 1; Random rand = new Random(); while (right >= left) { int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left); if (pivotIndex == n) { return arr[pivotIndex]; } else if (pivotIndex < n) { left = pivotIndex + 1; } else { right = pivotIndex - 1; } } return null; } private static void swap(Object[] arr, int i1, int i2) { if (i1 != i2) { Object temp = arr[i1]; arr[i1] = arr[i2]; arr[i2] = temp; } } public static void main(String[] args) { for (int i = 0; i < 10; i++) { Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; System.out.print(select(input, i)); if (i < 9) System.out.print(", "); } System.out.println(); } }
#include <algorithm> #include <iostream> int main() { for (int i = 0; i < 10; i++) { int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a)); std::cout << a[i]; if (i < 9) std::cout << ", "; } std::cout << std::endl; return 0; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
public static long backToTen(String num, int oldBase){ return Long.parseLong(num, oldBase); } public static String tenToBase(long num, int newBase){ return Long.toString(num, newBase); }
#include <string> #include <cstdlib> #include <algorithm> #include <cassert> std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz"; std::string to_base(unsigned long num, int base) { if (num == 0) return "0"; std::string result; while (num > 0) { std::ldiv_t temp = std::div(num, (long)base); result += digits[temp.rem]; num = temp.quot; } std::reverse(result.begin(), result.end()); return result; } unsigned long from_base(std::string const& num_str, int base) { unsigned long result = 0; for (std::string::size_type pos = 0; pos < num_str.length(); ++pos) result = result * base + digits.find(num_str[pos]); return result; }
Rewrite this program in C++ while keeping its functionality equivalent to the Java version.
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Port the provided Java code into C++ while preserving the original functionality.
import java.util.*; import java.util.stream.*; public class StateNamePuzzle { static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory",}; public static void main(String[] args) { solve(Arrays.asList(states)); } static void solve(List<String> input) { Map<String, String> orig = input.stream().collect(Collectors.toMap( s -> s.replaceAll("\\s", "").toLowerCase(), s -> s, (s, a) -> s)); input = new ArrayList<>(orig.keySet()); Map<String, List<String[]>> map = new HashMap<>(); for (int i = 0; i < input.size() - 1; i++) { String pair0 = input.get(i); for (int j = i + 1; j < input.size(); j++) { String[] pair = {pair0, input.get(j)}; String s = pair0 + pair[1]; String key = Arrays.toString(s.chars().sorted().toArray()); List<String[]> val = map.getOrDefault(key, new ArrayList<>()); val.add(pair); map.put(key, val); } } map.forEach((key, list) -> { for (int i = 0; i < list.size() - 1; i++) { String[] a = list.get(i); for (int j = i + 1; j < list.size(); j++) { String[] b = list.get(j); if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4) continue; System.out.printf("%s + %s = %s + %s %n", orig.get(a[0]), orig.get(a[1]), orig.get(b[0]), orig.get(b[1])); } } }); } }
#include <algorithm> #include <iostream> #include <string> #include <array> #include <vector> template<typename T> T unique(T&& src) { T retval(std::move(src)); std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>()); retval.erase(std::unique(retval.begin(), retval.end()), retval.end()); return retval; } #define USE_FAKES 1 auto states = unique(std::vector<std::string>({ #if USE_FAKES "Slender Dragon", "Abalamara", #endif "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" })); struct counted_pair { std::string name; std::array<int, 26> count{}; void count_characters(const std::string& s) { for (auto&& c : s) { if (c >= 'a' && c <= 'z') count[c - 'a']++; if (c >= 'A' && c <= 'Z') count[c - 'A']++; } } counted_pair(const std::string& s1, const std::string& s2) : name(s1 + " + " + s2) { count_characters(s1); count_characters(s2); } }; bool operator<(const counted_pair& lhs, const counted_pair& rhs) { auto lhs_size = lhs.name.size(); auto rhs_size = rhs.name.size(); return lhs_size == rhs_size ? std::lexicographical_compare(lhs.count.begin(), lhs.count.end(), rhs.count.begin(), rhs.count.end()) : lhs_size < rhs_size; } bool operator==(const counted_pair& lhs, const counted_pair& rhs) { return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count; } int main() { const int n_states = states.size(); std::vector<counted_pair> pairs; for (int i = 0; i < n_states; i++) { for (int j = 0; j < i; j++) { pairs.emplace_back(counted_pair(states[i], states[j])); } } std::sort(pairs.begin(), pairs.end()); auto start = pairs.begin(); while (true) { auto match = std::adjacent_find(start, pairs.end()); if (match == pairs.end()) { break; } auto next = match + 1; std::cout << match->name << " => " << next->name << "\n"; start = next; } }
Ensure the translated C++ code behaves exactly like the original Java snippet.
import java.util.*; import java.util.stream.*; public class StateNamePuzzle { static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory",}; public static void main(String[] args) { solve(Arrays.asList(states)); } static void solve(List<String> input) { Map<String, String> orig = input.stream().collect(Collectors.toMap( s -> s.replaceAll("\\s", "").toLowerCase(), s -> s, (s, a) -> s)); input = new ArrayList<>(orig.keySet()); Map<String, List<String[]>> map = new HashMap<>(); for (int i = 0; i < input.size() - 1; i++) { String pair0 = input.get(i); for (int j = i + 1; j < input.size(); j++) { String[] pair = {pair0, input.get(j)}; String s = pair0 + pair[1]; String key = Arrays.toString(s.chars().sorted().toArray()); List<String[]> val = map.getOrDefault(key, new ArrayList<>()); val.add(pair); map.put(key, val); } } map.forEach((key, list) -> { for (int i = 0; i < list.size() - 1; i++) { String[] a = list.get(i); for (int j = i + 1; j < list.size(); j++) { String[] b = list.get(j); if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4) continue; System.out.printf("%s + %s = %s + %s %n", orig.get(a[0]), orig.get(a[1]), orig.get(b[0]), orig.get(b[1])); } } }); } }
#include <algorithm> #include <iostream> #include <string> #include <array> #include <vector> template<typename T> T unique(T&& src) { T retval(std::move(src)); std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>()); retval.erase(std::unique(retval.begin(), retval.end()), retval.end()); return retval; } #define USE_FAKES 1 auto states = unique(std::vector<std::string>({ #if USE_FAKES "Slender Dragon", "Abalamara", #endif "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" })); struct counted_pair { std::string name; std::array<int, 26> count{}; void count_characters(const std::string& s) { for (auto&& c : s) { if (c >= 'a' && c <= 'z') count[c - 'a']++; if (c >= 'A' && c <= 'Z') count[c - 'A']++; } } counted_pair(const std::string& s1, const std::string& s2) : name(s1 + " + " + s2) { count_characters(s1); count_characters(s2); } }; bool operator<(const counted_pair& lhs, const counted_pair& rhs) { auto lhs_size = lhs.name.size(); auto rhs_size = rhs.name.size(); return lhs_size == rhs_size ? std::lexicographical_compare(lhs.count.begin(), lhs.count.end(), rhs.count.begin(), rhs.count.end()) : lhs_size < rhs_size; } bool operator==(const counted_pair& lhs, const counted_pair& rhs) { return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count; } int main() { const int n_states = states.size(); std::vector<counted_pair> pairs; for (int i = 0; i < n_states; i++) { for (int j = 0; j < i; j++) { pairs.emplace_back(counted_pair(states[i], states[j])); } } std::sort(pairs.begin(), pairs.end()); auto start = pairs.begin(); while (true) { auto match = std::adjacent_find(start, pairs.end()); if (match == pairs.end()) { break; } auto next = match + 1; std::cout << match->name << " => " << next->name << "\n"; start = next; } }
Convert this Java snippet to C++ and keep its semantics consistent.
import java.util.zip.* ; public class CRCMaker { public static void main( String[ ] args ) { String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ; CRC32 myCRC = new CRC32( ) ; myCRC.update( toBeEncoded.getBytes( ) ) ; System.out.println( "The CRC-32 value is : " + Long.toHexString( myCRC.getValue( ) ) + " !" ) ; } }
#include <algorithm> #include <array> #include <cstdint> #include <numeric> #include <iomanip> #include <iostream> #include <string> std::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept { auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL}; struct byte_checksum { std::uint_fast32_t operator()() noexcept { auto checksum = static_cast<std::uint_fast32_t>(n++); for (auto i = 0; i < 8; ++i) checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0); return checksum; } unsigned n = 0; }; auto table = std::array<std::uint_fast32_t, 256>{}; std::generate(table.begin(), table.end(), byte_checksum{}); return table; } template <typename InputIterator> std::uint_fast32_t crc(InputIterator first, InputIterator last) { static auto const table = generate_crc_lookup_table(); return std::uint_fast32_t{0xFFFFFFFFuL} & ~std::accumulate(first, last, ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL}, [](std::uint_fast32_t checksum, std::uint_fast8_t value) { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); }); } int main() { auto const s = std::string{"The quick brown fox jumps over the lazy dog"}; std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\n'; }
Convert this Java block to C++, preserving its control flow and logic.
grammar csv2html; dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ; header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");}; body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");}; row : field ',' field '\r'? '\n'; field : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");}; Field : ~[,\n\r]+;
#include <string> #include <boost/regex.hpp> #include <iostream> std::string csvToHTML( const std::string & ) ; int main( ) { std::string text = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!\n" ; std::cout << csvToHTML( text ) ; return 0 ; } std::string csvToHTML( const std::string & csvtext ) { std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ; const char* replacements [ 5 ] = { "&lt;" , "&gt;" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ; boost::regex e1( regexes[ 0 ] ) ; std::string tabletext = boost::regex_replace( csvtext , e1 , replacements[ 0 ] , boost::match_default | boost::format_all ) ; for ( int i = 1 ; i < 5 ; i++ ) { e1.assign( regexes[ i ] ) ; tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ; } tabletext = std::string( "<TABLE>\n" ) + tabletext ; tabletext.append( "</TABLE>\n" ) ; return tabletext ; }
Produce a language-to-language conversion: from Java to C++, same semantics.
grammar csv2html; dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ; header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");}; body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");}; row : field ',' field '\r'? '\n'; field : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");}; Field : ~[,\n\r]+;
#include <string> #include <boost/regex.hpp> #include <iostream> std::string csvToHTML( const std::string & ) ; int main( ) { std::string text = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!\n" ; std::cout << csvToHTML( text ) ; return 0 ; } std::string csvToHTML( const std::string & csvtext ) { std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ; const char* replacements [ 5 ] = { "&lt;" , "&gt;" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ; boost::regex e1( regexes[ 0 ] ) ; std::string tabletext = boost::regex_replace( csvtext , e1 , replacements[ 0 ] , boost::match_default | boost::format_all ) ; for ( int i = 1 ; i < 5 ; i++ ) { e1.assign( regexes[ i ] ) ; tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ; } tabletext = std::string( "<TABLE>\n" ) + tabletext ; tabletext.append( "</TABLE>\n" ) ; return tabletext ; }
Please provide an equivalent version of this Java code in C++.
public class MyClass{ private int variable; public MyClass(){ } public void someMethod(){ this.variable = 1; } }
PRAGMA COMPILER g++ PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive OPTION PARSE FALSE '---The class does the declaring for you CLASS Books public: const char* title; const char* author; const char* subject; int book_id; END CLASS '---pointer to an object declaration (we use a class called Books) DECLARE Book1 TYPE Books '--- the correct syntax for class Book1 = Books() '--- initialize the strings const char* in c++ Book1.title = "C++ Programming to bacon " Book1.author = "anyone" Book1.subject ="RECORD Tutorial" Book1.book_id = 1234567 PRINT "Book title  : " ,Book1.title FORMAT "%s%s\n" PRINT "Book author  : ", Book1.author FORMAT "%s%s\n" PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n" PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"
Produce a language-to-language conversion: from Java to C++, same semantics.
public class Kaprekar { private static String[] splitAt(String str, int idx){ String[] ans = new String[2]; ans[0] = str.substring(0, idx); if(ans[0].equals("")) ans[0] = "0"; ans[1] = str.substring(idx); return ans; } public static void main(String[] args){ int count = 0; int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10; for(long i = 1; i <= 1000000; i++){ String sqrStr = Long.toString(i * i, base); for(int j = 0; j < sqrStr.length() / 2 + 1; j++){ String[] parts = splitAt(sqrStr, j); long firstNum = Long.parseLong(parts[0], base); long secNum = Long.parseLong(parts[1], base); if(secNum == 0) break; if(firstNum + secNum == i){ System.out.println(i + "\t" + Long.toString(i, base) + "\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]); count++; break; } } } System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base); } }
#include <vector> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <utility> long string2long( const std::string & s ) { long result ; std::istringstream( s ) >> result ; return result ; } bool isKaprekar( long number ) { long long squarenumber = ((long long)number) * number ; std::ostringstream numberbuf ; numberbuf << squarenumber ; std::string numberstring = numberbuf.str( ) ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) { std::string firstpart = numberstring.substr( 0 , i ) , secondpart = numberstring.substr( i ) ; if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) { return false ; } if ( string2long( firstpart ) + string2long( secondpart ) == number ) { return true ; } } return false ; } int main( ) { std::vector<long> kaprekarnumbers ; kaprekarnumbers.push_back( 1 ) ; for ( int i = 2 ; i < 1000001 ; i++ ) { if ( isKaprekar( i ) ) kaprekarnumbers.push_back( i ) ; } std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ; std::cout << "Kaprekar numbers up to 10000: \n" ; while ( *svi < 10000 ) { std::cout << *svi << " " ; svi++ ; } std::cout << '\n' ; std::cout << "All the Kaprekar numbers up to 1000000 :\n" ; std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) , std::ostream_iterator<long>( std::cout , "\n" ) ) ; std::cout << "There are " << kaprekarnumbers.size( ) << " Kaprekar numbers less than one million!\n" ; return 0 ; }
Convert the following code from Java to C++, ensuring the logic remains intact.
public class Kaprekar { private static String[] splitAt(String str, int idx){ String[] ans = new String[2]; ans[0] = str.substring(0, idx); if(ans[0].equals("")) ans[0] = "0"; ans[1] = str.substring(idx); return ans; } public static void main(String[] args){ int count = 0; int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10; for(long i = 1; i <= 1000000; i++){ String sqrStr = Long.toString(i * i, base); for(int j = 0; j < sqrStr.length() / 2 + 1; j++){ String[] parts = splitAt(sqrStr, j); long firstNum = Long.parseLong(parts[0], base); long secNum = Long.parseLong(parts[1], base); if(secNum == 0) break; if(firstNum + secNum == i){ System.out.println(i + "\t" + Long.toString(i, base) + "\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]); count++; break; } } } System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base); } }
#include <vector> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <utility> long string2long( const std::string & s ) { long result ; std::istringstream( s ) >> result ; return result ; } bool isKaprekar( long number ) { long long squarenumber = ((long long)number) * number ; std::ostringstream numberbuf ; numberbuf << squarenumber ; std::string numberstring = numberbuf.str( ) ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) { std::string firstpart = numberstring.substr( 0 , i ) , secondpart = numberstring.substr( i ) ; if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) { return false ; } if ( string2long( firstpart ) + string2long( secondpart ) == number ) { return true ; } } return false ; } int main( ) { std::vector<long> kaprekarnumbers ; kaprekarnumbers.push_back( 1 ) ; for ( int i = 2 ; i < 1000001 ; i++ ) { if ( isKaprekar( i ) ) kaprekarnumbers.push_back( i ) ; } std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ; std::cout << "Kaprekar numbers up to 10000: \n" ; while ( *svi < 10000 ) { std::cout << *svi << " " ; svi++ ; } std::cout << '\n' ; std::cout << "All the Kaprekar numbers up to 1000000 :\n" ; std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) , std::ostream_iterator<long>( std::cout , "\n" ) ) ; std::cout << "There are " << kaprekarnumbers.size( ) << " Kaprekar numbers less than one million!\n" ; return 0 ; }
Convert this Java block to C++, preserving its control flow and logic.
import java.util.*; public class LZW { public static List<Integer> compress(String uncompressed) { int dictSize = 256; Map<String,Integer> dictionary = new HashMap<String,Integer>(); for (int i = 0; i < 256; i++) dictionary.put("" + (char)i, i); String w = ""; List<Integer> result = new ArrayList<Integer>(); for (char c : uncompressed.toCharArray()) { String wc = w + c; if (dictionary.containsKey(wc)) w = wc; else { result.add(dictionary.get(w)); dictionary.put(wc, dictSize++); w = "" + c; } } if (!w.equals("")) result.add(dictionary.get(w)); return result; } public static String decompress(List<Integer> compressed) { int dictSize = 256; Map<Integer,String> dictionary = new HashMap<Integer,String>(); for (int i = 0; i < 256; i++) dictionary.put(i, "" + (char)i); String w = "" + (char)(int)compressed.remove(0); StringBuffer result = new StringBuffer(w); for (int k : compressed) { String entry; if (dictionary.containsKey(k)) entry = dictionary.get(k); else if (k == dictSize) entry = w + w.charAt(0); else throw new IllegalArgumentException("Bad compressed k: " + k); result.append(entry); dictionary.put(dictSize++, w + entry.charAt(0)); w = entry; } return result.toString(); } public static void main(String[] args) { List<Integer> compressed = compress("TOBEORNOTTOBEORTOBEORNOT"); System.out.println(compressed); String decompressed = decompress(compressed); System.out.println(decompressed); } }
#include <string> #include <map> template <typename Iterator> Iterator compress(const std::string &uncompressed, Iterator result) { int dictSize = 256; std::map<std::string,int> dictionary; for (int i = 0; i < 256; i++) dictionary[std::string(1, i)] = i; std::string w; for (std::string::const_iterator it = uncompressed.begin(); it != uncompressed.end(); ++it) { char c = *it; std::string wc = w + c; if (dictionary.count(wc)) w = wc; else { *result++ = dictionary[w]; dictionary[wc] = dictSize++; w = std::string(1, c); } } if (!w.empty()) *result++ = dictionary[w]; return result; } template <typename Iterator> std::string decompress(Iterator begin, Iterator end) { int dictSize = 256; std::map<int,std::string> dictionary; for (int i = 0; i < 256; i++) dictionary[i] = std::string(1, i); std::string w(1, *begin++); std::string result = w; std::string entry; for ( ; begin != end; begin++) { int k = *begin; if (dictionary.count(k)) entry = dictionary[k]; else if (k == dictSize) entry = w + w[0]; else throw "Bad compressed k"; result += entry; dictionary[dictSize++] = w + entry[0]; w = entry; } return result; } #include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> compressed; compress("TOBEORNOTTOBEORTOBEORNOT", std::back_inserter(compressed)); copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; std::string decompressed = decompress(compressed.begin(), compressed.end()); std::cout << decompressed << std::endl; return 0; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.util.*; class Hofstadter { private static List<Integer> getSequence(int rlistSize, int slistSize) { List<Integer> rlist = new ArrayList<Integer>(); List<Integer> slist = new ArrayList<Integer>(); Collections.addAll(rlist, 1, 3, 7); Collections.addAll(slist, 2, 4, 5, 6); List<Integer> list = (rlistSize > 0) ? rlist : slist; int targetSize = (rlistSize > 0) ? rlistSize : slistSize; while (list.size() > targetSize) list.remove(list.size() - 1); while (list.size() < targetSize) { int lastIndex = rlist.size() - 1; int lastr = rlist.get(lastIndex).intValue(); int r = lastr + slist.get(lastIndex).intValue(); rlist.add(Integer.valueOf(r)); for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++) slist.add(Integer.valueOf(s)); } return list; } public static int ffr(int n) { return getSequence(n, 0).get(n - 1).intValue(); } public static int ffs(int n) { return getSequence(0, n).get(n - 1).intValue(); } public static void main(String[] args) { System.out.print("R():"); for (int n = 1; n <= 10; n++) System.out.print(" " + ffr(n)); System.out.println(); Set<Integer> first40R = new HashSet<Integer>(); for (int n = 1; n <= 40; n++) first40R.add(Integer.valueOf(ffr(n))); Set<Integer> first960S = new HashSet<Integer>(); for (int n = 1; n <= 960; n++) first960S.add(Integer.valueOf(ffs(n))); for (int i = 1; i <= 1000; i++) { Integer n = Integer.valueOf(i); if (first40R.contains(n) == first960S.contains(n)) System.out.println("Integer " + i + " either in both or neither set"); } System.out.println("Done"); } }
#include <iomanip> #include <iostream> #include <set> #include <vector> using namespace std; unsigned hofstadter(unsigned rlistSize, unsigned slistSize) { auto n = rlistSize > slistSize ? rlistSize : slistSize; auto rlist = new vector<unsigned> { 1, 3, 7 }; auto slist = new vector<unsigned> { 2, 4, 5, 6 }; auto list = rlistSize > 0 ? rlist : slist; auto target_size = rlistSize > 0 ? rlistSize : slistSize; while (list->size() > target_size) list->pop_back(); while (list->size() < target_size) { auto lastIndex = rlist->size() - 1; auto lastr = (*rlist)[lastIndex]; auto r = lastr + (*slist)[lastIndex]; rlist->push_back(r); for (auto s = lastr + 1; s < r && list->size() < target_size;) slist->push_back(s++); } auto v = (*list)[n - 1]; delete rlist; delete slist; return v; } ostream& operator<<(ostream& os, const set<unsigned>& s) { cout << '(' << s.size() << "):"; auto i = 0; for (auto c = s.begin(); c != s.end();) { if (i++ % 20 == 0) os << endl; os << setw(5) << *c++; } return os; } int main(int argc, const char* argv[]) { const auto v1 = atoi(argv[1]); const auto v2 = atoi(argv[2]); set<unsigned> r, s; for (auto n = 1; n <= v2; n++) { if (n <= v1) r.insert(hofstadter(n, 0)); s.insert(hofstadter(0, n)); } cout << "R" << r << endl; cout << "S" << s << endl; int m = max(*r.rbegin(), *s.rbegin()); for (auto n = 1; n <= m; n++) if (r.count(n) == s.count(n)) clog << "integer " << n << " either in both or neither set" << endl; return 0; }
Produce a language-to-language conversion: from Java to C++, same semantics.
import java.util.*; class Hofstadter { private static List<Integer> getSequence(int rlistSize, int slistSize) { List<Integer> rlist = new ArrayList<Integer>(); List<Integer> slist = new ArrayList<Integer>(); Collections.addAll(rlist, 1, 3, 7); Collections.addAll(slist, 2, 4, 5, 6); List<Integer> list = (rlistSize > 0) ? rlist : slist; int targetSize = (rlistSize > 0) ? rlistSize : slistSize; while (list.size() > targetSize) list.remove(list.size() - 1); while (list.size() < targetSize) { int lastIndex = rlist.size() - 1; int lastr = rlist.get(lastIndex).intValue(); int r = lastr + slist.get(lastIndex).intValue(); rlist.add(Integer.valueOf(r)); for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++) slist.add(Integer.valueOf(s)); } return list; } public static int ffr(int n) { return getSequence(n, 0).get(n - 1).intValue(); } public static int ffs(int n) { return getSequence(0, n).get(n - 1).intValue(); } public static void main(String[] args) { System.out.print("R():"); for (int n = 1; n <= 10; n++) System.out.print(" " + ffr(n)); System.out.println(); Set<Integer> first40R = new HashSet<Integer>(); for (int n = 1; n <= 40; n++) first40R.add(Integer.valueOf(ffr(n))); Set<Integer> first960S = new HashSet<Integer>(); for (int n = 1; n <= 960; n++) first960S.add(Integer.valueOf(ffs(n))); for (int i = 1; i <= 1000; i++) { Integer n = Integer.valueOf(i); if (first40R.contains(n) == first960S.contains(n)) System.out.println("Integer " + i + " either in both or neither set"); } System.out.println("Done"); } }
#include <iomanip> #include <iostream> #include <set> #include <vector> using namespace std; unsigned hofstadter(unsigned rlistSize, unsigned slistSize) { auto n = rlistSize > slistSize ? rlistSize : slistSize; auto rlist = new vector<unsigned> { 1, 3, 7 }; auto slist = new vector<unsigned> { 2, 4, 5, 6 }; auto list = rlistSize > 0 ? rlist : slist; auto target_size = rlistSize > 0 ? rlistSize : slistSize; while (list->size() > target_size) list->pop_back(); while (list->size() < target_size) { auto lastIndex = rlist->size() - 1; auto lastr = (*rlist)[lastIndex]; auto r = lastr + (*slist)[lastIndex]; rlist->push_back(r); for (auto s = lastr + 1; s < r && list->size() < target_size;) slist->push_back(s++); } auto v = (*list)[n - 1]; delete rlist; delete slist; return v; } ostream& operator<<(ostream& os, const set<unsigned>& s) { cout << '(' << s.size() << "):"; auto i = 0; for (auto c = s.begin(); c != s.end();) { if (i++ % 20 == 0) os << endl; os << setw(5) << *c++; } return os; } int main(int argc, const char* argv[]) { const auto v1 = atoi(argv[1]); const auto v2 = atoi(argv[2]); set<unsigned> r, s; for (auto n = 1; n <= v2; n++) { if (n <= v1) r.insert(hofstadter(n, 0)); s.insert(hofstadter(0, n)); } cout << "R" << r << endl; cout << "S" << s << endl; int m = max(*r.rbegin(), *s.rbegin()); for (auto n = 1; n <= m; n++) if (r.count(n) == s.count(n)) clog << "integer " << n << " either in both or neither set" << endl; return 0; }
Generate an equivalent C++ version of this Java code.
public class MagicSquare { public static void main(String[] args) { int n = 5; for (int[] row : magicSquareOdd(n)) { for (int x : row) System.out.format("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int base) { if (base % 2 == 0 || base < 3) throw new IllegalArgumentException("base must be odd and > 2"); int[][] grid = new int[base][base]; int r = 0, number = 0; int size = base * base; int c = base / 2; while (number++ < size) { grid[r][c] = number; if (r == 0) { if (c == base - 1) { r++; } else { r = base - 1; c++; } } else { if (c == base - 1) { r--; c = 0; } else { if (grid[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } } } return grid; } }
#include <iostream> #include <sstream> #include <iomanip> #include <cassert> #include <vector> using namespace std; class MagicSquare { public: MagicSquare(int d) : sqr(d*d,0), sz(d) { assert(d&1); fillSqr(); } void display() { cout << "Odd Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) cout << setw( l + 2 ) << sqr[yy + x]; cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { int sx = sz / 2, sy = 0, c = 0; while( c < sz * sz ) { if( !sqr[sx + sy * sz] ) { sqr[sx + sy * sz]= c + 1; inc( sx ); dec( sy ); c++; } else { dec( sx ); inc( sy ); inc( sy ); } } } int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } vector<int> sqr; int sz; }; int main() { MagicSquare s(7); s.display(); return 0; }
Produce a language-to-language conversion: from Java to C++, same semantics.
public class MagicSquare { public static void main(String[] args) { int n = 5; for (int[] row : magicSquareOdd(n)) { for (int x : row) System.out.format("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int base) { if (base % 2 == 0 || base < 3) throw new IllegalArgumentException("base must be odd and > 2"); int[][] grid = new int[base][base]; int r = 0, number = 0; int size = base * base; int c = base / 2; while (number++ < size) { grid[r][c] = number; if (r == 0) { if (c == base - 1) { r++; } else { r = base - 1; c++; } } else { if (c == base - 1) { r--; c = 0; } else { if (grid[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } } } return grid; } }
#include <iostream> #include <sstream> #include <iomanip> #include <cassert> #include <vector> using namespace std; class MagicSquare { public: MagicSquare(int d) : sqr(d*d,0), sz(d) { assert(d&1); fillSqr(); } void display() { cout << "Odd Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) cout << setw( l + 2 ) << sqr[yy + x]; cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { int sx = sz / 2, sy = 0, c = 0; while( c < sz * sz ) { if( !sqr[sx + sy * sz] ) { sqr[sx + sy * sz]= c + 1; inc( sx ); dec( sy ); c++; } else { dec( sx ); inc( sy ); inc( sy ); } } } int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } vector<int> sqr; int sz; }; int main() { MagicSquare s(7); s.display(); return 0; }
Write the same algorithm in C++ as shown in this Java implementation.
import java.util.ArrayList; import java.util.List; public class YellowstoneSequence { public static void main(String[] args) { System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30)); } private static List<Integer> yellowstoneSequence(int sequenceCount) { List<Integer> yellowstoneList = new ArrayList<Integer>(); yellowstoneList.add(1); yellowstoneList.add(2); yellowstoneList.add(3); int num = 4; List<Integer> notYellowstoneList = new ArrayList<Integer>(); int yellowSize = 3; while ( yellowSize < sequenceCount ) { int found = -1; for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) { int test = notYellowstoneList.get(index); if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) { found = index; break; } } if ( found >= 0 ) { yellowstoneList.add(notYellowstoneList.remove(found)); yellowSize++; } else { while ( true ) { if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) { yellowstoneList.add(num); yellowSize++; num++; break; } notYellowstoneList.add(num); num++; } } } return yellowstoneList; } private static final int gcd(int a, int b) { if ( b == 0 ) { return a; } return gcd(b, a%b); } }
#include <iostream> #include <numeric> #include <set> template <typename integer> class yellowstone_generator { public: integer next() { n2_ = n1_; n1_ = n_; if (n_ < 3) { ++n_; } else { for (n_ = min_; !(sequence_.count(n_) == 0 && std::gcd(n1_, n_) == 1 && std::gcd(n2_, n_) > 1); ++n_) {} } sequence_.insert(n_); for (;;) { auto it = sequence_.find(min_); if (it == sequence_.end()) break; sequence_.erase(it); ++min_; } return n_; } private: std::set<integer> sequence_; integer min_ = 1; integer n_ = 0; integer n1_ = 0; integer n2_ = 0; }; int main() { std::cout << "First 30 Yellowstone numbers:\n"; yellowstone_generator<unsigned int> ygen; std::cout << ygen.next(); for (int i = 1; i < 30; ++i) std::cout << ' ' << ygen.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.util.ArrayList; import java.util.List; public class YellowstoneSequence { public static void main(String[] args) { System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30)); } private static List<Integer> yellowstoneSequence(int sequenceCount) { List<Integer> yellowstoneList = new ArrayList<Integer>(); yellowstoneList.add(1); yellowstoneList.add(2); yellowstoneList.add(3); int num = 4; List<Integer> notYellowstoneList = new ArrayList<Integer>(); int yellowSize = 3; while ( yellowSize < sequenceCount ) { int found = -1; for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) { int test = notYellowstoneList.get(index); if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) { found = index; break; } } if ( found >= 0 ) { yellowstoneList.add(notYellowstoneList.remove(found)); yellowSize++; } else { while ( true ) { if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) { yellowstoneList.add(num); yellowSize++; num++; break; } notYellowstoneList.add(num); num++; } } } return yellowstoneList; } private static final int gcd(int a, int b) { if ( b == 0 ) { return a; } return gcd(b, a%b); } }
#include <iostream> #include <numeric> #include <set> template <typename integer> class yellowstone_generator { public: integer next() { n2_ = n1_; n1_ = n_; if (n_ < 3) { ++n_; } else { for (n_ = min_; !(sequence_.count(n_) == 0 && std::gcd(n1_, n_) == 1 && std::gcd(n2_, n_) > 1); ++n_) {} } sequence_.insert(n_); for (;;) { auto it = sequence_.find(min_); if (it == sequence_.end()) break; sequence_.erase(it); ++min_; } return n_; } private: std::set<integer> sequence_; integer min_ = 1; integer n_ = 0; integer n1_ = 0; integer n2_ = 0; }; int main() { std::cout << "First 30 Yellowstone numbers:\n"; yellowstone_generator<unsigned int> ygen; std::cout << ygen.next(); for (int i = 1; i < 30; ++i) std::cout << ' ' << ygen.next(); std::cout << '\n'; return 0; }
Ensure the translated C++ code behaves exactly like the original Java snippet.
import java.util.*; public class CutRectangle { private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; public static void main(String[] args) { cutRectangle(2, 2); cutRectangle(4, 3); } static void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) return; int[][] grid = new int[h][w]; Stack<Integer> stack = new Stack<>(); int half = (w * h) / 2; long bits = (long) Math.pow(2, half) - 1; for (; bits > 0; bits -= 2) { for (int i = 0; i < half; i++) { int r = i / w; int c = i % w; grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0; grid[h - r - 1][w - c - 1] = 1 - grid[r][c]; } stack.push(0); grid[0][0] = 2; int count = 1; while (!stack.empty()) { int pos = stack.pop(); int r = pos / w; int c = pos % w; for (int[] dir : dirs) { int nextR = r + dir[0]; int nextC = c + dir[1]; if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) { if (grid[nextR][nextC] == 1) { stack.push(nextR * w + nextC); grid[nextR][nextC] = 2; count++; } } } } if (count == half) { printResult(grid); } } } static void printResult(int[][] arr) { for (int[] a : arr) System.out.println(Arrays.toString(a)); System.out.println(); } }
#include <array> #include <iostream> #include <stack> #include <vector> const std::array<std::pair<int, int>, 4> DIRS = { std::make_pair(0, -1), std::make_pair(-1, 0), std::make_pair(0, 1), std::make_pair(1, 0), }; void printResult(const std::vector<std::vector<int>> &v) { for (auto &row : v) { auto it = row.cbegin(); auto end = row.cend(); std::cout << '['; if (it != end) { std::cout << *it; it = std::next(it); } while (it != end) { std::cout << ", " << *it; it = std::next(it); } std::cout << "]\n"; } } void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) { return; } std::vector<std::vector<int>> grid(h, std::vector<int>(w)); std::stack<int> stack; int half = (w * h) / 2; long bits = (long)pow(2, half) - 1; for (; bits > 0; bits -= 2) { for (int i = 0; i < half; i++) { int r = i / w; int c = i % w; grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0; grid[h - r - 1][w - c - 1] = 1 - grid[r][c]; } stack.push(0); grid[0][0] = 2; int count = 1; while (!stack.empty()) { int pos = stack.top(); stack.pop(); int r = pos / w; int c = pos % w; for (auto dir : DIRS) { int nextR = r + dir.first; int nextC = c + dir.second; if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) { if (grid[nextR][nextC] == 1) { stack.push(nextR * w + nextC); grid[nextR][nextC] = 2; count++; } } } } if (count == half) { printResult(grid); std::cout << '\n'; } } } int main() { cutRectangle(2, 2); cutRectangle(4, 3); return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.*; public class CutRectangle { private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; public static void main(String[] args) { cutRectangle(2, 2); cutRectangle(4, 3); } static void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) return; int[][] grid = new int[h][w]; Stack<Integer> stack = new Stack<>(); int half = (w * h) / 2; long bits = (long) Math.pow(2, half) - 1; for (; bits > 0; bits -= 2) { for (int i = 0; i < half; i++) { int r = i / w; int c = i % w; grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0; grid[h - r - 1][w - c - 1] = 1 - grid[r][c]; } stack.push(0); grid[0][0] = 2; int count = 1; while (!stack.empty()) { int pos = stack.pop(); int r = pos / w; int c = pos % w; for (int[] dir : dirs) { int nextR = r + dir[0]; int nextC = c + dir[1]; if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) { if (grid[nextR][nextC] == 1) { stack.push(nextR * w + nextC); grid[nextR][nextC] = 2; count++; } } } } if (count == half) { printResult(grid); } } } static void printResult(int[][] arr) { for (int[] a : arr) System.out.println(Arrays.toString(a)); System.out.println(); } }
#include <array> #include <iostream> #include <stack> #include <vector> const std::array<std::pair<int, int>, 4> DIRS = { std::make_pair(0, -1), std::make_pair(-1, 0), std::make_pair(0, 1), std::make_pair(1, 0), }; void printResult(const std::vector<std::vector<int>> &v) { for (auto &row : v) { auto it = row.cbegin(); auto end = row.cend(); std::cout << '['; if (it != end) { std::cout << *it; it = std::next(it); } while (it != end) { std::cout << ", " << *it; it = std::next(it); } std::cout << "]\n"; } } void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) { return; } std::vector<std::vector<int>> grid(h, std::vector<int>(w)); std::stack<int> stack; int half = (w * h) / 2; long bits = (long)pow(2, half) - 1; for (; bits > 0; bits -= 2) { for (int i = 0; i < half; i++) { int r = i / w; int c = i % w; grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0; grid[h - r - 1][w - c - 1] = 1 - grid[r][c]; } stack.push(0); grid[0][0] = 2; int count = 1; while (!stack.empty()) { int pos = stack.top(); stack.pop(); int r = pos / w; int c = pos % w; for (auto dir : DIRS) { int nextR = r + dir.first; int nextC = c + dir.second; if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) { if (grid[nextR][nextC] == 1) { stack.push(nextR * w + nextC); grid[nextR][nextC] = 2; count++; } } } } if (count == half) { printResult(grid); std::cout << '\n'; } } } int main() { cutRectangle(2, 2); cutRectangle(4, 3); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
public class MertensFunction { public static void main(String[] args) { System.out.printf("First 199 terms of the merten function are as follows:%n "); for ( int n = 1 ; n < 200 ; n++ ) { System.out.printf("%2d ", mertenFunction(n)); if ( (n+1) % 20 == 0 ) { System.out.printf("%n"); } } for ( int exponent = 3 ; exponent<= 8 ; exponent++ ) { int zeroCount = 0; int zeroCrossingCount = 0; int positiveCount = 0; int negativeCount = 0; int mSum = 0; int mMin = Integer.MAX_VALUE; int mMinIndex = 0; int mMax = Integer.MIN_VALUE; int mMaxIndex = 0; int nMax = (int) Math.pow(10, exponent); for ( int n = 1 ; n <= nMax ; n++ ) { int m = mertenFunction(n); mSum += m; if ( m < mMin ) { mMin = m; mMinIndex = n; } if ( m > mMax ) { mMax = m; mMaxIndex = n; } if ( m > 0 ) { positiveCount++; } if ( m < 0 ) { negativeCount++; } if ( m == 0 ) { zeroCount++; } if ( m == 0 && mertenFunction(n - 1) != 0 ) { zeroCrossingCount++; } } System.out.printf("%nFor M(x) with x from 1 to %,d%n", nMax); System.out.printf("The maximum of M(x) is M(%,d) = %,d.%n", mMaxIndex, mMax); System.out.printf("The minimum of M(x) is M(%,d) = %,d.%n", mMinIndex, mMin); System.out.printf("The sum of M(x) is %,d.%n", mSum); System.out.printf("The count of positive M(x) is %,d, count of negative M(x) is %,d.%n", positiveCount, negativeCount); System.out.printf("M(x) has %,d zeroes in the interval.%n", zeroCount); System.out.printf("M(x) has %,d crossings in the interval.%n", zeroCrossingCount); } } private static int MU_MAX = 100_000_000; private static int[] MU = null; private static int[] MERTEN = null; private static int mertenFunction(int n) { if ( MERTEN != null ) { return MERTEN[n]; } MU = new int[MU_MAX+1]; MERTEN = new int[MU_MAX+1]; MERTEN[1] = 1; int sqrt = (int) Math.sqrt(MU_MAX); for ( int i = 0 ; i < MU_MAX ; i++ ) { MU[i] = 1; } for ( int i = 2 ; i <= sqrt ; i++ ) { if ( MU[i] == 1 ) { for ( int j = i ; j <= MU_MAX ; j += i ) { MU[j] *= -i; } for ( int j = i*i ; j <= MU_MAX ; j += i*i ) { MU[j] = 0; } } } int sum = 1; for ( int i = 2 ; i <= MU_MAX ; i++ ) { if ( MU[i] == i ) { MU[i] = 1; } else if ( MU[i] == -i ) { MU[i] = -1; } else if ( MU[i] < 0 ) { MU[i] = 1; } else if ( MU[i] > 0 ) { MU[i] = -1; } sum += MU[i]; MERTEN[i] = sum; } return MERTEN[n]; } }
#include <iomanip> #include <iostream> #include <vector> std::vector<int> mertens_numbers(int max) { std::vector<int> m(max + 1, 1); for (int n = 2; n <= max; ++n) { for (int k = 2; k <= n; ++k) m[n] -= m[n / k]; } return m; } int main() { const int max = 1000; auto m(mertens_numbers(max)); std::cout << "First 199 Mertens numbers:\n"; for (int i = 0, column = 0; i < 200; ++i) { if (column > 0) std::cout << ' '; if (i == 0) std::cout << " "; else std::cout << std::setw(2) << m[i]; ++column; if (column == 20) { std::cout << '\n'; column = 0; } } int zero = 0, cross = 0, previous = 0; for (int i = 1; i <= max; ++i) { if (m[i] == 0) { ++zero; if (previous != 0) ++cross; } previous = m[i]; } std::cout << "M(n) is zero " << zero << " times for 1 <= n <= 1000.\n"; std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n"; return 0; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.util.*; public class SortComp1 { public static void main(String[] args) { List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange"); List<String> sortedItems = new ArrayList<>(); Comparator<String> interactiveCompare = new Comparator<String>() { int count = 0; Scanner s = new Scanner(System.in); public int compare(String s1, String s2) { System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2); return s.nextInt(); } }; for (String item : items) { System.out.printf("Inserting '%s' into %s\n", item, sortedItems); int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare); if (spotToInsert < 0) spotToInsert = ~spotToInsert; sortedItems.add(spotToInsert, item); } System.out.println(sortedItems); } }
#include <algorithm> #include <iostream> #include <vector> using namespace std; bool InteractiveCompare(const string& s1, const string& s2) { if(s1 == s2) return false; static int count = 0; string response; cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? "; getline(cin, response); return !response.empty() && response.front() == 'y'; } void PrintOrder(const vector<string>& items) { cout << "{ "; for(auto& item : items) cout << item << " "; cout << "}\n"; } int main() { const vector<string> items { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }; vector<string> sortedItems; for(auto& item : items) { cout << "Inserting '" << item << "' into "; PrintOrder(sortedItems); auto spotToInsert = lower_bound(sortedItems.begin(), sortedItems.end(), item, InteractiveCompare); sortedItems.insert(spotToInsert, item); } PrintOrder(sortedItems); return 0; }
Change the following Java code into C++ without altering its purpose.
import java.math.BigInteger; import java.util.Locale; public class BenfordsLaw { private static BigInteger[] generateFibonacci(int n) { BigInteger[] fib = new BigInteger[n]; fib[0] = BigInteger.ONE; fib[1] = BigInteger.ONE; for (int i = 2; i < fib.length; i++) { fib[i] = fib[i - 2].add(fib[i - 1]); } return fib; } public static void main(String[] args) { BigInteger[] numbers = generateFibonacci(1000); int[] firstDigits = new int[10]; for (BigInteger number : numbers) { firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++; } for (int i = 1; i < firstDigits.length; i++) { System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n", i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i)); } } }
#include <cln/integer.h> #include <cln/integer_io.h> #include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <sstream> #include <string> #include <cstdlib> #include <cmath> #include <map> using namespace cln ; class NextNum { public : NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { } cl_I operator( )( ) { cl_I result = first + second ; first = second ; second = result ; return result ; } private : cl_I first ; cl_I second ; } ; void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) { for ( cl_I bignumber : fibos ) { std::ostringstream os ; fprintdecimal ( os , bignumber ) ; int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ; auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ; if ( ! result.second ) numberfrequencies[ firstdigit ]++ ; } } int main( ) { std::vector<cl_I> fibonaccis( 1000 ) ; fibonaccis[ 0 ] = 0 ; fibonaccis[ 1 ] = 1 ; cl_I a = 0 ; cl_I b = 1 ; std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ; std::cout << std::endl ; std::map<int , int> frequencies ; findFrequencies( fibonaccis , frequencies ) ; std::cout << " found expected\n" ; for ( int i = 1 ; i < 10 ; i++ ) { double found = static_cast<double>( frequencies[ i ] ) / 1000 ; double expected = std::log10( 1 + 1 / static_cast<double>( i )) ; std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ; std::cout.precision( 3 ) ; std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ; } return 0 ; }
Convert the following code from Java to C++, ensuring the logic remains intact.
import java.math.BigInteger; import java.util.Locale; public class BenfordsLaw { private static BigInteger[] generateFibonacci(int n) { BigInteger[] fib = new BigInteger[n]; fib[0] = BigInteger.ONE; fib[1] = BigInteger.ONE; for (int i = 2; i < fib.length; i++) { fib[i] = fib[i - 2].add(fib[i - 1]); } return fib; } public static void main(String[] args) { BigInteger[] numbers = generateFibonacci(1000); int[] firstDigits = new int[10]; for (BigInteger number : numbers) { firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++; } for (int i = 1; i < firstDigits.length; i++) { System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n", i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i)); } } }
#include <cln/integer.h> #include <cln/integer_io.h> #include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <sstream> #include <string> #include <cstdlib> #include <cmath> #include <map> using namespace cln ; class NextNum { public : NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { } cl_I operator( )( ) { cl_I result = first + second ; first = second ; second = result ; return result ; } private : cl_I first ; cl_I second ; } ; void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) { for ( cl_I bignumber : fibos ) { std::ostringstream os ; fprintdecimal ( os , bignumber ) ; int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ; auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ; if ( ! result.second ) numberfrequencies[ firstdigit ]++ ; } } int main( ) { std::vector<cl_I> fibonaccis( 1000 ) ; fibonaccis[ 0 ] = 0 ; fibonaccis[ 1 ] = 1 ; cl_I a = 0 ; cl_I b = 1 ; std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ; std::cout << std::endl ; std::map<int , int> frequencies ; findFrequencies( fibonaccis , frequencies ) ; std::cout << " found expected\n" ; for ( int i = 1 ; i < 10 ; i++ ) { double found = static_cast<double>( frequencies[ i ] ) / 1000 ; double expected = std::log10( 1 + 1 / static_cast<double>( i )) ; std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ; std::cout.precision( 3 ) ; std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ; } return 0 ; }
Keep all operations the same but rewrite the snippet in C++.
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; public class NauticalBell extends Thread { public static void main(String[] args) { NauticalBell bells = new NauticalBell(); bells.setDaemon(true); bells.start(); try { bells.join(); } catch (InterruptedException e) { System.out.println(e); } } @Override public void run() { DateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); int numBells = 0; long time = System.currentTimeMillis(); long next = time - (time % (24 * 60 * 60 * 1000)); while (next < time) { next += 30 * 60 * 1000; numBells = 1 + (numBells % 8); } while (true) { long wait = 100L; time = System.currentTimeMillis(); if (time - next >= 0) { String bells = numBells == 1 ? "bell" : "bells"; String timeString = sdf.format(time); System.out.printf("%s : %d %s\n", timeString, numBells, bells); next += 30 * 60 * 1000; wait = next - time; numBells = 1 + (numBells % 8); } try { Thread.sleep(wait); } catch (InterruptedException e) { return; } } } }
#include <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight"; _inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL ); } private: static DWORD WINAPI bell( LPVOID p ) { DWORD wait = _inst->waitTime(); while( true ) { Sleep( wait ); _inst->playBell(); wait = _inst->waitTime(); } return 0; } DWORD waitTime() { GetLocalTime( &st ); int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute; return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) ); } void playBell() { GetLocalTime( &st ); int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b; int w = ( 60 * st.wHour + st.wMinute ); if( w < 1 ) w = 5; else w = ( w - 1 ) / 240; char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute ); cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell"; if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl; for( int x = 0, c = 1; x < b; x++, c++ ) { cout << "\7"; Sleep( 500 ); if( !( c % 2 ) ) Sleep( 300 ); } } SYSTEMTIME st; string watch[7], count[8]; static bells* _inst; }; bells* bells::_inst = 0; int main( int argc, char* argv[] ) { bells b; b.start(); while( 1 ); return 0; }
Transform the following Java implementation into C++, maintaining the same output and logic.
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; public class NauticalBell extends Thread { public static void main(String[] args) { NauticalBell bells = new NauticalBell(); bells.setDaemon(true); bells.start(); try { bells.join(); } catch (InterruptedException e) { System.out.println(e); } } @Override public void run() { DateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); int numBells = 0; long time = System.currentTimeMillis(); long next = time - (time % (24 * 60 * 60 * 1000)); while (next < time) { next += 30 * 60 * 1000; numBells = 1 + (numBells % 8); } while (true) { long wait = 100L; time = System.currentTimeMillis(); if (time - next >= 0) { String bells = numBells == 1 ? "bell" : "bells"; String timeString = sdf.format(time); System.out.printf("%s : %d %s\n", timeString, numBells, bells); next += 30 * 60 * 1000; wait = next - time; numBells = 1 + (numBells % 8); } try { Thread.sleep(wait); } catch (InterruptedException e) { return; } } } }
#include <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight"; _inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL ); } private: static DWORD WINAPI bell( LPVOID p ) { DWORD wait = _inst->waitTime(); while( true ) { Sleep( wait ); _inst->playBell(); wait = _inst->waitTime(); } return 0; } DWORD waitTime() { GetLocalTime( &st ); int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute; return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) ); } void playBell() { GetLocalTime( &st ); int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b; int w = ( 60 * st.wHour + st.wMinute ); if( w < 1 ) w = 5; else w = ( w - 1 ) / 240; char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute ); cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell"; if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl; for( int x = 0, c = 1; x < b; x++, c++ ) { cout << "\7"; Sleep( 500 ); if( !( c % 2 ) ) Sleep( 300 ); } } SYSTEMTIME st; string watch[7], count[8]; static bells* _inst; }; bells* bells::_inst = 0; int main( int argc, char* argv[] ) { bells b; b.start(); while( 1 ); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.TimeZone; public class NauticalBell extends Thread { public static void main(String[] args) { NauticalBell bells = new NauticalBell(); bells.setDaemon(true); bells.start(); try { bells.join(); } catch (InterruptedException e) { System.out.println(e); } } @Override public void run() { DateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); int numBells = 0; long time = System.currentTimeMillis(); long next = time - (time % (24 * 60 * 60 * 1000)); while (next < time) { next += 30 * 60 * 1000; numBells = 1 + (numBells % 8); } while (true) { long wait = 100L; time = System.currentTimeMillis(); if (time - next >= 0) { String bells = numBells == 1 ? "bell" : "bells"; String timeString = sdf.format(time); System.out.printf("%s : %d %s\n", timeString, numBells, bells); next += 30 * 60 * 1000; wait = next - time; numBells = 1 + (numBells % 8); } try { Thread.sleep(wait); } catch (InterruptedException e) { return; } } } }
#include <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight"; _inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL ); } private: static DWORD WINAPI bell( LPVOID p ) { DWORD wait = _inst->waitTime(); while( true ) { Sleep( wait ); _inst->playBell(); wait = _inst->waitTime(); } return 0; } DWORD waitTime() { GetLocalTime( &st ); int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute; return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) ); } void playBell() { GetLocalTime( &st ); int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b; int w = ( 60 * st.wHour + st.wMinute ); if( w < 1 ) w = 5; else w = ( w - 1 ) / 240; char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute ); cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell"; if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl; for( int x = 0, c = 1; x < b; x++, c++ ) { cout << "\7"; Sleep( 500 ); if( !( c % 2 ) ) Sleep( 300 ); } } SYSTEMTIME st; string watch[7], count[8]; static bells* _inst; }; bells* bells::_inst = 0; int main( int argc, char* argv[] ) { bells b; b.start(); while( 1 ); return 0; }
Write the same algorithm in C++ as shown in this Java implementation.
public static long fib(int n) { if (n < 0) throw new IllegalArgumentException("n can not be a negative number"); return new Object() { private long fibInner(int n) { return (n < 2) ? n : (fibInner(n - 1) + fibInner(n - 2)); } }.fibInner(n); }
double fib(double n) { if(n < 0) { throw "Invalid argument passed to fib"; } else { struct actual_fib { static double calc(double n) { if(n < 2) { return n; } else { return calc(n-1) + calc(n-2); } } }; return actual_fib::calc(n); } }
Translate this program into C++ but keep the logic exactly as in Java.
String strOrig = 'brooms'; String str1 = strOrig.substring(1, strOrig.length()); system.debug(str1); String str2 = strOrig.substring(0, strOrig.length()-1); system.debug(str2); String str3 = strOrig.substring(1, strOrig.length()-1); system.debug(str3); String strOrig = 'brooms'; String str1 = strOrig.replaceAll( '^.', '' ); system.debug(str1); String str2 = strOrig.replaceAll( '.$', '' ) ; system.debug(str2); String str3 = strOrig.replaceAll( '^.|.$', '' ); system.debug(str3);
#include <string> #include <iostream> int main( ) { std::string word( "Premier League" ) ; std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ; std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ; std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ; return 0 ; }
Preserve the algorithm and functionality while converting the code from Java to C++.
String strOrig = 'brooms'; String str1 = strOrig.substring(1, strOrig.length()); system.debug(str1); String str2 = strOrig.substring(0, strOrig.length()-1); system.debug(str2); String str3 = strOrig.substring(1, strOrig.length()-1); system.debug(str3); String strOrig = 'brooms'; String str1 = strOrig.replaceAll( '^.', '' ); system.debug(str1); String str2 = strOrig.replaceAll( '.$', '' ) ; system.debug(str2); String str3 = strOrig.replaceAll( '^.|.$', '' ); system.debug(str3);
#include <string> #include <iostream> int main( ) { std::string word( "Premier League" ) ; std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ; std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ; std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ; return 0 ; }
Preserve the algorithm and functionality while converting the code from Java to C++.
import java.util.*; public class LegendrePrimeCounter { public static void main(String[] args) { LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000); for (int i = 0, n = 1; i < 10; ++i, n *= 10) System.out.printf("10^%d\t%d\n", i, counter.primeCount((n))); } private List<Integer> primes; public LegendrePrimeCounter(int limit) { primes = generatePrimes((int)Math.sqrt((double)limit)); } public int primeCount(int n) { if (n < 2) return 0; int a = primeCount((int)Math.sqrt((double)n)); return phi(n, a) + a - 1; } private int phi(int x, int a) { if (a == 0) return x; if (a == 1) return x - (x >> 1); int pa = primes.get(a - 1); if (x <= pa) return 1; return phi(x, a - 1) - phi(x / pa, a - 1); } private static List<Integer> generatePrimes(int limit) { boolean[] sieve = new boolean[limit >> 1]; Arrays.fill(sieve, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve[q >> 1] = false; } s += (p + 1) << 2; } List<Integer> primes = new ArrayList<>(); if (limit > 2) primes.add(2); for (int i = 1; i < sieve.length; ++i) { if (sieve[i]) primes.add((i << 1) + 1); } return primes; } }
#include <cmath> #include <iostream> #include <vector> std::vector<int> generate_primes(int limit) { std::vector<bool> sieve(limit >> 1, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve[q >> 1] = false; } s += (p + 1) << 2; } std::vector<int> primes; if (limit > 2) primes.push_back(2); for (int i = 1; i < sieve.size(); ++i) { if (sieve[i]) primes.push_back((i << 1) + 1); } return primes; } class legendre_prime_counter { public: explicit legendre_prime_counter(int limit); int prime_count(int n); private: int phi(int x, int a); std::vector<int> primes; }; legendre_prime_counter::legendre_prime_counter(int limit) : primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {} int legendre_prime_counter::prime_count(int n) { if (n < 2) return 0; int a = prime_count(static_cast<int>(std::sqrt(n))); return phi(n, a) + a - 1; } int legendre_prime_counter::phi(int x, int a) { if (a == 0) return x; if (a == 1) return x - (x >> 1); int pa = primes[a - 1]; if (x <= pa) return 1; return phi(x, a - 1) - phi(x / pa, a - 1); } int main() { legendre_prime_counter counter(1000000000); for (int i = 0, n = 1; i < 10; ++i, n *= 10) std::cout << "10^" << i << "\t" << counter.prime_count(n) << '\n'; }
Convert this Java block to C++, preserving its control flow and logic.
public class Query { public static boolean call(byte[] data, int[] length) throws java.io.UnsupportedEncodingException { String message = "Here am I"; byte[] mb = message.getBytes("utf-8"); if (length[0] < mb.length) return false; length[0] = mb.length; System.arraycopy(mb, 0, data, 0, mb.length); return true; } }
#include <string> using std::string; extern "C" int Query (char *Data, size_t *Length) { const string Message = "Here am I"; if (*Length < Message.length()) return false; *Length = Message.length(); Message.copy(Data, *Length); return true; }
Keep all operations the same but rewrite the snippet in C++.
import java.io.File; import java.util.Scanner; public class LongestStringChallenge { public static void main(String[] args) throws Exception { String lines = "", longest = ""; try (Scanner sc = new Scanner(new File("lines.txt"))) { while(sc.hasNext()) { String line = sc.nextLine(); if (longer(longest, line)) lines = longest = line; else if (!longer(line, longest)) lines = lines.concat("\n").concat(line); } } System.out.println(lines); } static boolean longer(String a, String b) { try { String dummy = a.substring(b.length()); } catch (StringIndexOutOfBoundsException e) { return true; } return false; } }
#include <iostream> #include <string.h> int main() { std::string longLine, longestLines, newLine; while (std::cin >> newLine) { auto isNewLineShorter = longLine.c_str(); auto isLongLineShorter = newLine.c_str(); while (*isNewLineShorter && *isLongLineShorter) { isNewLineShorter = &isNewLineShorter[1]; isLongLineShorter = &isLongLineShorter[1]; } if(*isNewLineShorter) continue; if(*isLongLineShorter) { longLine = newLine; longestLines = newLine; } else { longestLines+=newLine; } longestLines+="\n"; } std::cout << "\nLongest string:\n" << longestLines; }
Convert this Java block to C++, preserving its control flow and logic.
import java.io.File; import java.util.Scanner; public class LongestStringChallenge { public static void main(String[] args) throws Exception { String lines = "", longest = ""; try (Scanner sc = new Scanner(new File("lines.txt"))) { while(sc.hasNext()) { String line = sc.nextLine(); if (longer(longest, line)) lines = longest = line; else if (!longer(line, longest)) lines = lines.concat("\n").concat(line); } } System.out.println(lines); } static boolean longer(String a, String b) { try { String dummy = a.substring(b.length()); } catch (StringIndexOutOfBoundsException e) { return true; } return false; } }
#include <iostream> #include <string.h> int main() { std::string longLine, longestLines, newLine; while (std::cin >> newLine) { auto isNewLineShorter = longLine.c_str(); auto isLongLineShorter = newLine.c_str(); while (*isNewLineShorter && *isLongLineShorter) { isNewLineShorter = &isNewLineShorter[1]; isLongLineShorter = &isLongLineShorter[1]; } if(*isNewLineShorter) continue; if(*isLongLineShorter) { longLine = newLine; longestLines = newLine; } else { longestLines+=newLine; } longestLines+="\n"; } std::cout << "\nLongest string:\n" << longestLines; }
Produce a language-to-language conversion: from Java to C++, same semantics.
import java.io.*; public class CreateFileTest { public static void main(String args[]) { try { new File("output.txt").createNewFile(); new File(File.separator + "output.txt").createNewFile(); new File("docs").mkdir(); new File(File.separator + "docs").mkdir(); } catch (IOException e) { System.err.println(e.getMessage()); } } }
#include <direct.h> #include <fstream> int main() { std::fstream f("output.txt", std::ios::out); f.close(); f.open("/output.txt", std::ios::out); f.close(); _mkdir("docs"); _mkdir("/docs"); return 0; }
Write a version of this Java function in C++ with identical behavior.
import java.io.*; public class CreateFileTest { public static void main(String args[]) { try { new File("output.txt").createNewFile(); new File(File.separator + "output.txt").createNewFile(); new File("docs").mkdir(); new File(File.separator + "docs").mkdir(); } catch (IOException e) { System.err.println(e.getMessage()); } } }
#include <direct.h> #include <fstream> int main() { std::fstream f("output.txt", std::ios::out); f.close(); f.open("/output.txt", std::ios::out); f.close(); _mkdir("docs"); _mkdir("/docs"); return 0; }
Translate this program into C++ but keep the logic exactly as in Java.
public class UnprimeableNumbers { private static int MAX = 10_000_000; private static boolean[] primes = new boolean[MAX]; public static void main(String[] args) { sieve(); System.out.println("First 35 unprimeable numbers:"); displayUnprimeableNumbers(35); int n = 600; System.out.printf("%nThe %dth unprimeable number = %,d%n%n", n, nthUnprimeableNumber(n)); int[] lowest = genLowest(); System.out.println("Least unprimeable number that ends in:"); for ( int i = 0 ; i <= 9 ; i++ ) { System.out.printf(" %d is %,d%n", i, lowest[i]); } } private static int[] genLowest() { int[] lowest = new int[10]; int count = 0; int test = 1; while ( count < 10 ) { test++; if ( unPrimable(test) && lowest[test % 10] == 0 ) { lowest[test % 10] = test; count++; } } return lowest; } private static int nthUnprimeableNumber(int maxCount) { int test = 1; int count = 0; int result = 0; while ( count < maxCount ) { test++; if ( unPrimable(test) ) { count++; result = test; } } return result; } private static void displayUnprimeableNumbers(int maxCount) { int test = 1; int count = 0; while ( count < maxCount ) { test++; if ( unPrimable(test) ) { count++; System.out.printf("%d ", test); } } System.out.println(); } private static boolean unPrimable(int test) { if ( primes[test] ) { return false; } String s = test + ""; for ( int i = 0 ; i < s.length() ; i++ ) { for ( int j = 0 ; j <= 9 ; j++ ) { if ( primes[Integer.parseInt(replace(s, i, j))] ) { return false; } } } return true; } private static String replace(String str, int position, int value) { char[] sChar = str.toCharArray(); sChar[position] = (char) value; return str.substring(0, position) + value + str.substring(position + 1); } private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } }
#include <iostream> #include <cstdint> #include "prime_sieve.hpp" typedef uint32_t integer; int count_digits(integer n) { int digits = 0; for (; n > 0; ++digits) n /= 10; return digits; } integer change_digit(integer n, int index, int new_digit) { integer p = 1; integer changed = 0; for (; index > 0; p *= 10, n /= 10, --index) changed += p * (n % 10); changed += (10 * (n/10) + new_digit) * p; return changed; } bool unprimeable(const prime_sieve& sieve, integer n) { if (sieve.is_prime(n)) return false; int d = count_digits(n); for (int i = 0; i < d; ++i) { for (int j = 0; j <= 9; ++j) { integer m = change_digit(n, i, j); if (m != n && sieve.is_prime(m)) return false; } } return true; } int main() { const integer limit = 10000000; prime_sieve sieve(limit); std::cout.imbue(std::locale("")); std::cout << "First 35 unprimeable numbers:\n"; integer n = 100; integer lowest[10] = { 0 }; for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) { if (unprimeable(sieve, n)) { if (count < 35) { if (count != 0) std::cout << ", "; std::cout << n; } ++count; if (count == 600) std::cout << "\n600th unprimeable number: " << n << '\n'; int last_digit = n % 10; if (lowest[last_digit] == 0) { lowest[last_digit] = n; ++found; } } } for (int i = 0; i < 10; ++i) std::cout << "Least unprimeable number ending in " << i << ": " << lowest[i] << '\n'; return 0; }
Write the same algorithm in C++ as shown in this Java implementation.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PascalsTrianglePuzzle { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d), Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d), Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d), Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d)); List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d); List<Double> solution = cramersRule(mat, b); System.out.println("Solution = " + cramersRule(mat, b)); System.out.printf("X = %.2f%n", solution.get(8)); System.out.printf("Y = %.2f%n", solution.get(9)); System.out.printf("Z = %.2f%n", solution.get(10)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
#include <iostream> #include <iomanip> inline int sign(int i) { return i < 0 ? -1 : i > 0; } inline int& E(int *x, int row, int col) { return x[row * (row + 1) / 2 + col]; } int iter(int *v, int *diff) { E(v, 0, 0) = 151; E(v, 2, 0) = 40; E(v, 4, 1) = 11; E(v, 4, 3) = 4; for (auto i = 1u; i < 5u; i++) for (auto j = 0u; j <= i; j++) { E(diff, i, j) = 0; if (j < i) E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j); if (j) E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j); } for (auto i = 0u; i < 4u; i++) for (auto j = 0u; j < i; j++) E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j); E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2); uint sum; int e = 0; for (auto i = sum = 0u; i < 15u; i++) { sum += !!sign(e = diff[i]); if (e >= 4 || e <= -4) v[i] += e / 5; else if (rand() < RAND_MAX / 4) v[i] += sign(e); } return sum; } void show(int *x) { for (auto i = 0u; i < 5u; i++) for (auto j = 0u; j <= i; j++) std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n'); } int main() { int v[15] = { 0 }, diff[15] = { 0 }; for (auto i = 1u, s = 1u; s; i++) { s = iter(v, diff); std::cout << "pass " << i << ": " << s << std::endl; } show(v); return 0; }
Produce a language-to-language conversion: from Java to C++, same semantics.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PascalsTrianglePuzzle { public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d), Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d), Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d), Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d), Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d), Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d)); List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d); List<Double> solution = cramersRule(mat, b); System.out.println("Solution = " + cramersRule(mat, b)); System.out.printf("X = %.2f%n", solution.get(8)); System.out.printf("Y = %.2f%n", solution.get(9)); System.out.printf("Z = %.2f%n", solution.get(10)); } private static List<Double> cramersRule(Matrix matrix, List<Double> b) { double denominator = matrix.determinant(); List<Double> result = new ArrayList<>(); for ( int i = 0 ; i < b.size() ; i++ ) { result.add(matrix.replaceColumn(b, i).determinant() / denominator); } return result; } private static class Matrix { private List<List<Double>> matrix; @Override public String toString() { return matrix.toString(); } @SafeVarargs public Matrix(List<Double> ... lists) { matrix = new ArrayList<>(); for ( List<Double> list : lists) { matrix.add(list); } } public Matrix(List<List<Double>> mat) { matrix = mat; } public double determinant() { if ( matrix.size() == 1 ) { return get(0, 0); } if ( matrix.size() == 2 ) { return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); } double sum = 0; double sign = 1; for ( int i = 0 ; i < matrix.size() ; i++ ) { sum += sign * get(0, i) * coFactor(0, i).determinant(); sign *= -1; } return sum; } private Matrix coFactor(int row, int col) { List<List<Double>> mat = new ArrayList<>(); for ( int i = 0 ; i < matrix.size() ; i++ ) { if ( i == row ) { continue; } List<Double> list = new ArrayList<>(); for ( int j = 0 ; j < matrix.size() ; j++ ) { if ( j == col ) { continue; } list.add(get(i, j)); } mat.add(list); } return new Matrix(mat); } private Matrix replaceColumn(List<Double> b, int column) { List<List<Double>> mat = new ArrayList<>(); for ( int row = 0 ; row < matrix.size() ; row++ ) { List<Double> list = new ArrayList<>(); for ( int col = 0 ; col < matrix.size() ; col++ ) { double value = get(row, col); if ( col == column ) { value = b.get(row); } list.add(value); } mat.add(list); } return new Matrix(mat); } private double get(int row, int col) { return matrix.get(row).get(col); } } }
#include <iostream> #include <iomanip> inline int sign(int i) { return i < 0 ? -1 : i > 0; } inline int& E(int *x, int row, int col) { return x[row * (row + 1) / 2 + col]; } int iter(int *v, int *diff) { E(v, 0, 0) = 151; E(v, 2, 0) = 40; E(v, 4, 1) = 11; E(v, 4, 3) = 4; for (auto i = 1u; i < 5u; i++) for (auto j = 0u; j <= i; j++) { E(diff, i, j) = 0; if (j < i) E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j); if (j) E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j); } for (auto i = 0u; i < 4u; i++) for (auto j = 0u; j < i; j++) E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j); E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2); uint sum; int e = 0; for (auto i = sum = 0u; i < 15u; i++) { sum += !!sign(e = diff[i]); if (e >= 4 || e <= -4) v[i] += e / 5; else if (rand() < RAND_MAX / 4) v[i] += sign(e); } return sum; } void show(int *x) { for (auto i = 0u; i < 5u; i++) for (auto j = 0u; j <= i; j++) std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n'); } int main() { int v[15] = { 0 }, diff[15] = { 0 }; for (auto i = 1u, s = 1u; s; i++) { s = iter(v, diff); std::cout << "pass " << i << ": " << s << std::endl; } show(v); return 0; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class ChernicksCarmichaelNumbers { public static void main(String[] args) { for ( long n = 3 ; n < 10 ; n++ ) { long m = 0; boolean foundComposite = true; List<Long> factors = null; while ( foundComposite ) { m += (n <= 4 ? 1 : (long) Math.pow(2, n-4) * 5); factors = U(n, m); foundComposite = false; for ( long factor : factors ) { if ( ! isPrime(factor) ) { foundComposite = true; break; } } } System.out.printf("U(%d, %d) = %s = %s %n", n, m, display(factors), multiply(factors)); } } private static String display(List<Long> factors) { return factors.toString().replace("[", "").replace("]", "").replaceAll(", ", " * "); } private static BigInteger multiply(List<Long> factors) { BigInteger result = BigInteger.ONE; for ( long factor : factors ) { result = result.multiply(BigInteger.valueOf(factor)); } return result; } private static List<Long> U(long n, long m) { List<Long> factors = new ArrayList<>(); factors.add(6*m + 1); factors.add(12*m + 1); for ( int i = 1 ; i <= n-2 ; i++ ) { factors.add(((long)Math.pow(2, i)) * 9 * m + 1); } return factors; } 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 <gmp.h> #include <iostream> using namespace std; typedef unsigned long long int u64; bool primality_pretest(u64 k) { if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23) ) { return (k <= 23); } return true; } bool probprime(u64 k, mpz_t n) { mpz_set_ui(n, k); return mpz_probab_prime_p(n, 0); } bool is_chernick(int n, u64 m, mpz_t z) { if (!primality_pretest(6 * m + 1)) { return false; } if (!primality_pretest(12 * m + 1)) { return false; } u64 t = 9 * m; for (int i = 1; i <= n - 2; i++) { if (!primality_pretest((t << i) + 1)) { return false; } } if (!probprime(6 * m + 1, z)) { return false; } if (!probprime(12 * m + 1, z)) { return false; } for (int i = 1; i <= n - 2; i++) { if (!probprime((t << i) + 1, z)) { return false; } } return true; } int main() { mpz_t z; mpz_inits(z, NULL); for (int n = 3; n <= 10; n++) { u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1; if (n > 5) { multiplier *= 5; } for (u64 k = 1; ; k++) { u64 m = k * multiplier; if (is_chernick(n, m, z)) { cout << "a(" << n << ") has m = " << m << endl; break; } } } return 0; }
Convert this Java block to C++, preserving its control flow and logic.
import java.util.Objects; public class FindTriangle { private static final double EPS = 0.001; private static final double EPS_SQUARE = EPS * EPS; public static class Point { private final double x, y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } @Override public String toString() { return String.format("(%f, %f)", x, y); } } public static class Triangle { private final Point p1, p2, p3; public Triangle(Point p1, Point p2, Point p3) { this.p1 = Objects.requireNonNull(p1); this.p2 = Objects.requireNonNull(p2); this.p3 = Objects.requireNonNull(p3); } public Point getP1() { return p1; } public Point getP2() { return p2; } public Point getP3() { return p3; } private boolean pointInTriangleBoundingBox(Point p) { var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS; var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS; var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS; var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS; return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY()); } private static double side(Point p1, Point p2, Point p) { return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY()); } private boolean nativePointInTriangle(Point p) { boolean checkSide1 = side(p1, p2, p) >= 0; boolean checkSide2 = side(p2, p3, p) >= 0; boolean checkSide3 = side(p3, p1, p) >= 0; return checkSide1 && checkSide2 && checkSide3; } private double distanceSquarePointToSegment(Point p1, Point p2, Point p) { double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY()); double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength; if (dotProduct < 0) { return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY()); } if (dotProduct <= 1) { double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY()); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY()); } private boolean accuratePointInTriangle(Point p) { if (!pointInTriangleBoundingBox(p)) { return false; } if (nativePointInTriangle(p)) { return true; } if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) { return true; } return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE; } public boolean within(Point p) { Objects.requireNonNull(p); return accuratePointInTriangle(p); } @Override public String toString() { return String.format("Triangle[%s, %s, %s]", p1, p2, p3); } } private static void test(Triangle t, Point p) { System.out.println(t); System.out.printf("Point %s is within triangle? %s\n", p, t.within(p)); } public static void main(String[] args) { var p1 = new Point(1.5, 2.4); var p2 = new Point(5.1, -3.1); var p3 = new Point(-3.8, 1.2); var tri = new Triangle(p1, p2, p3); test(tri, new Point(0, 0)); test(tri, new Point(0, 1)); test(tri, new Point(3, 1)); System.out.println(); p1 = new Point(1.0 / 10, 1.0 / 9); p2 = new Point(100.0 / 8, 100.0 / 3); p3 = new Point(100.0 / 4, 100.0 / 9); tri = new Triangle(p1, p2, p3); var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY())); test(tri, pt); System.out.println(); p3 = new Point(-100.0 / 8, 100.0 / 6); tri = new Triangle(p1, p2, p3); test(tri, pt); } }
#include <iostream> const double EPS = 0.001; const double EPS_SQUARE = EPS * EPS; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = std::min(x1, std::min(x2, x3)) - EPS; double xMax = std::max(x1, std::max(x2, x3)) + EPS; double yMin = std::min(y1, std::min(y2, y3)) - EPS; double yMax = std::max(y1, std::max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { std::cout << '(' << x << ", " << y << ')'; } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { std::cout << "Triangle is ["; printPoint(x1, y1); std::cout << ", "; printPoint(x2, y2); std::cout << ", "; printPoint(x3, y3); std::cout << "]\n"; } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); std::cout << "Point "; printPoint(x, y); std::cout << " is within triangle? "; if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { std::cout << "true\n"; } else { std::cout << "false\n"; } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); std::cout << '\n'; test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); std::cout << '\n'; test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); std::cout << '\n'; return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.Objects; public class FindTriangle { private static final double EPS = 0.001; private static final double EPS_SQUARE = EPS * EPS; public static class Point { private final double x, y; public Point(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y; } @Override public String toString() { return String.format("(%f, %f)", x, y); } } public static class Triangle { private final Point p1, p2, p3; public Triangle(Point p1, Point p2, Point p3) { this.p1 = Objects.requireNonNull(p1); this.p2 = Objects.requireNonNull(p2); this.p3 = Objects.requireNonNull(p3); } public Point getP1() { return p1; } public Point getP2() { return p2; } public Point getP3() { return p3; } private boolean pointInTriangleBoundingBox(Point p) { var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS; var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS; var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS; var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS; return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY()); } private static double side(Point p1, Point p2, Point p) { return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY()); } private boolean nativePointInTriangle(Point p) { boolean checkSide1 = side(p1, p2, p) >= 0; boolean checkSide2 = side(p2, p3, p) >= 0; boolean checkSide3 = side(p3, p1, p) >= 0; return checkSide1 && checkSide2 && checkSide3; } private double distanceSquarePointToSegment(Point p1, Point p2, Point p) { double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY()); double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength; if (dotProduct < 0) { return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY()); } if (dotProduct <= 1) { double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY()); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY()); } private boolean accuratePointInTriangle(Point p) { if (!pointInTriangleBoundingBox(p)) { return false; } if (nativePointInTriangle(p)) { return true; } if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) { return true; } return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE; } public boolean within(Point p) { Objects.requireNonNull(p); return accuratePointInTriangle(p); } @Override public String toString() { return String.format("Triangle[%s, %s, %s]", p1, p2, p3); } } private static void test(Triangle t, Point p) { System.out.println(t); System.out.printf("Point %s is within triangle? %s\n", p, t.within(p)); } public static void main(String[] args) { var p1 = new Point(1.5, 2.4); var p2 = new Point(5.1, -3.1); var p3 = new Point(-3.8, 1.2); var tri = new Triangle(p1, p2, p3); test(tri, new Point(0, 0)); test(tri, new Point(0, 1)); test(tri, new Point(3, 1)); System.out.println(); p1 = new Point(1.0 / 10, 1.0 / 9); p2 = new Point(100.0 / 8, 100.0 / 3); p3 = new Point(100.0 / 4, 100.0 / 9); tri = new Triangle(p1, p2, p3); var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY())); test(tri, pt); System.out.println(); p3 = new Point(-100.0 / 8, 100.0 / 6); tri = new Triangle(p1, p2, p3); test(tri, pt); } }
#include <iostream> const double EPS = 0.001; const double EPS_SQUARE = EPS * EPS; double side(double x1, double y1, double x2, double y2, double x, double y) { return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1); } bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0; double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0; double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { double xMin = std::min(x1, std::min(x2, x3)) - EPS; double xMax = std::max(x1, std::max(x2, x3)) + EPS; double yMin = std::min(y1, std::min(y2, y3)) - EPS; double yMax = std::max(y1, std::max(y2, y3)) + EPS; return !(x < xMin || xMax < x || y < yMin || yMax < y); } double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) { double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength; if (dotProduct < 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } else if (dotProduct <= 1) { double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength; } else { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } } bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) { return false; } if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { return true; } if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) { return true; } if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) { return true; } return false; } void printPoint(double x, double y) { std::cout << '(' << x << ", " << y << ')'; } void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) { std::cout << "Triangle is ["; printPoint(x1, y1); std::cout << ", "; printPoint(x2, y2); std::cout << ", "; printPoint(x3, y3); std::cout << "]\n"; } void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) { printTriangle(x1, y1, x2, y2, x3, y3); std::cout << "Point "; printPoint(x, y); std::cout << " is within triangle? "; if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) { std::cout << "true\n"; } else { std::cout << "false\n"; } } int main() { test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1); test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1); std::cout << '\n'; test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348); std::cout << '\n'; test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348); std::cout << '\n'; return 0; }
Produce a language-to-language conversion: from Java to C++, same semantics.
public class TauFunction { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } public static void main(String[] args) { final int limit = 100; System.out.printf("Count of divisors for the first %d positive integers:\n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%3d", divisorCount(n)); if (n % 20 == 0) { System.out.println(); } } } }
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } int main() { const unsigned int limit = 100; std::cout << "Count of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(3) << divisor_count(n); if (n % 20 == 0) std::cout << '\n'; } }
Write the same code in C++ as shown below in Java.
public class TauFunction { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } public static void main(String[] args) { final int limit = 100; System.out.printf("Count of divisors for the first %d positive integers:\n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%3d", divisorCount(n)); if (n % 20 == 0) { System.out.println(); } } } }
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } int main() { const unsigned int limit = 100; std::cout << "Count of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(3) << divisor_count(n); if (n % 20 == 0) std::cout << '\n'; } }
Port the following code from Java to C++ with equivalent syntax and logic.
import java.math.BigInteger; public class PrimorialPrimes { final static int sieveLimit = 1550_000; static boolean[] notPrime = sieve(sieveLimit); public static void main(String[] args) { int count = 0; for (int i = 1; i < 1000_000 && count < 20; i++) { BigInteger b = primorial(i); if (b.add(BigInteger.ONE).isProbablePrime(1) || b.subtract(BigInteger.ONE).isProbablePrime(1)) { System.out.printf("%d ", i); count++; } } } static BigInteger primorial(int n) { if (n == 0) return BigInteger.ONE; BigInteger result = BigInteger.ONE; for (int i = 0; i < sieveLimit && n > 0; i++) { if (notPrime[i]) continue; result = result.multiply(BigInteger.valueOf(i)); n--; } return result; } public static boolean[] sieve(int limit) { boolean[] composite = new boolean[limit]; composite[0] = composite[1] = true; int max = (int) Math.sqrt(limit); for (int n = 2; n <= max; n++) { if (!composite[n]) { for (int k = n * n; k < limit; k += n) { composite[k] = true; } } } return composite; } }
#include <cstdint> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_probably_prime(const integer& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0; } 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; } int main() { const unsigned int max = 20; integer primorial = 1; for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) { if (!is_prime(p)) continue; primorial *= p; ++index; if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) { if (count > 0) std::cout << ' '; std::cout << index; ++count; } } std::cout << '\n'; return 0; }
Port the provided Java code into C++ while preserving the original functionality.
import java.util.HashMap; import java.util.Map; public class orderedSequence { public static void main(String[] args) { Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"); gene.runSequence(); } } public class Sequence { private final String seq; public Sequence(String sq) { this.seq = sq; } public void prettyPrint() { System.out.println("Sequence:"); int i = 0; for ( ; i < seq.length() - 50 ; i += 50) { System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50)); } System.out.printf("%5s : %s\n", seq.length(), seq.substring(i)); } public void displayCount() { Map<Character, Integer> counter = new HashMap<>(); for (int i = 0 ; i < seq.length() ; ++i) { counter.merge(seq.charAt(i), 1, Integer::sum); } System.out.println("Base vs. Count:"); counter.forEach( key, value -> System.out.printf("%5s : %s\n", key, value)); System.out.printf("%5s: %s\n", "SUM", seq.length()); } public void runSequence() { this.prettyPrint(); this.displayCount(); } }
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"; class DnaBase { public: DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) { for (auto elm : dna) { if (count.find(elm) == count.end()) count[elm] = 0; ++count[elm]; } } void viewGenome() { std::cout << "Sequence:" << std::endl; std::cout << std::endl; int limit = genome.size() / displayWidth; if (genome.size() % displayWidth != 0) ++limit; for (int i = 0; i < limit; ++i) { int beginPos = i * displayWidth; std::cout << std::setw(4) << beginPos << "  :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl; } std::cout << std::endl; std::cout << "Base Count" << std::endl; std::cout << "----------" << std::endl; std::cout << std::endl; int total = 0; for (auto elm : count) { std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl; total += elm.second; } std::cout << std::endl; std::cout << "Total: " << total << std::endl; } private: std::string genome; std::map<char, int> count; int displayWidth; }; int main(void) { auto d = new DnaBase(); d->viewGenome(); delete d; return 0; }
Change the programming language of this snippet from Java to C++ without modifying what it does.
import java.util.HashMap; import java.util.Map; public class orderedSequence { public static void main(String[] args) { Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"); gene.runSequence(); } } public class Sequence { private final String seq; public Sequence(String sq) { this.seq = sq; } public void prettyPrint() { System.out.println("Sequence:"); int i = 0; for ( ; i < seq.length() - 50 ; i += 50) { System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50)); } System.out.printf("%5s : %s\n", seq.length(), seq.substring(i)); } public void displayCount() { Map<Character, Integer> counter = new HashMap<>(); for (int i = 0 ; i < seq.length() ; ++i) { counter.merge(seq.charAt(i), 1, Integer::sum); } System.out.println("Base vs. Count:"); counter.forEach( key, value -> System.out.printf("%5s : %s\n", key, value)); System.out.printf("%5s: %s\n", "SUM", seq.length()); } public void runSequence() { this.prettyPrint(); this.displayCount(); } }
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"; class DnaBase { public: DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) { for (auto elm : dna) { if (count.find(elm) == count.end()) count[elm] = 0; ++count[elm]; } } void viewGenome() { std::cout << "Sequence:" << std::endl; std::cout << std::endl; int limit = genome.size() / displayWidth; if (genome.size() % displayWidth != 0) ++limit; for (int i = 0; i < limit; ++i) { int beginPos = i * displayWidth; std::cout << std::setw(4) << beginPos << "  :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl; } std::cout << std::endl; std::cout << "Base Count" << std::endl; std::cout << "----------" << std::endl; std::cout << std::endl; int total = 0; for (auto elm : count) { std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl; total += elm.second; } std::cout << std::endl; std::cout << "Total: " << total << std::endl; } private: std::string genome; std::map<char, int> count; int displayWidth; }; int main(void) { auto d = new DnaBase(); d->viewGenome(); delete d; return 0; }
Translate this program into C++ but keep the logic exactly as in Java.
import java.util.HashMap; import java.util.Map; public class orderedSequence { public static void main(String[] args) { Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"); gene.runSequence(); } } public class Sequence { private final String seq; public Sequence(String sq) { this.seq = sq; } public void prettyPrint() { System.out.println("Sequence:"); int i = 0; for ( ; i < seq.length() - 50 ; i += 50) { System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50)); } System.out.printf("%5s : %s\n", seq.length(), seq.substring(i)); } public void displayCount() { Map<Character, Integer> counter = new HashMap<>(); for (int i = 0 ; i < seq.length() ; ++i) { counter.merge(seq.charAt(i), 1, Integer::sum); } System.out.println("Base vs. Count:"); counter.forEach( key, value -> System.out.printf("%5s : %s\n", key, value)); System.out.printf("%5s: %s\n", "SUM", seq.length()); } public void runSequence() { this.prettyPrint(); this.displayCount(); } }
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"; class DnaBase { public: DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) { for (auto elm : dna) { if (count.find(elm) == count.end()) count[elm] = 0; ++count[elm]; } } void viewGenome() { std::cout << "Sequence:" << std::endl; std::cout << std::endl; int limit = genome.size() / displayWidth; if (genome.size() % displayWidth != 0) ++limit; for (int i = 0; i < limit; ++i) { int beginPos = i * displayWidth; std::cout << std::setw(4) << beginPos << "  :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl; } std::cout << std::endl; std::cout << "Base Count" << std::endl; std::cout << "----------" << std::endl; std::cout << std::endl; int total = 0; for (auto elm : count) { std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl; total += elm.second; } std::cout << std::endl; std::cout << "Total: " << total << std::endl; } private: std::string genome; std::map<char, int> count; int displayWidth; }; int main(void) { auto d = new DnaBase(); d->viewGenome(); delete d; return 0; }
Change the programming language of this snippet from Java to C++ without modifying what it does.
import java.util.HashMap; import java.util.Map; public class orderedSequence { public static void main(String[] args) { Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"); gene.runSequence(); } } public class Sequence { private final String seq; public Sequence(String sq) { this.seq = sq; } public void prettyPrint() { System.out.println("Sequence:"); int i = 0; for ( ; i < seq.length() - 50 ; i += 50) { System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50)); } System.out.printf("%5s : %s\n", seq.length(), seq.substring(i)); } public void displayCount() { Map<Character, Integer> counter = new HashMap<>(); for (int i = 0 ; i < seq.length() ; ++i) { counter.merge(seq.charAt(i), 1, Integer::sum); } System.out.println("Base vs. Count:"); counter.forEach( key, value -> System.out.printf("%5s : %s\n", key, value)); System.out.printf("%5s: %s\n", "SUM", seq.length()); } public void runSequence() { this.prettyPrint(); this.displayCount(); } }
#include <map> #include <string> #include <iostream> #include <iomanip> const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"; class DnaBase { public: DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) { for (auto elm : dna) { if (count.find(elm) == count.end()) count[elm] = 0; ++count[elm]; } } void viewGenome() { std::cout << "Sequence:" << std::endl; std::cout << std::endl; int limit = genome.size() / displayWidth; if (genome.size() % displayWidth != 0) ++limit; for (int i = 0; i < limit; ++i) { int beginPos = i * displayWidth; std::cout << std::setw(4) << beginPos << "  :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl; } std::cout << std::endl; std::cout << "Base Count" << std::endl; std::cout << "----------" << std::endl; std::cout << std::endl; int total = 0; for (auto elm : count) { std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl; total += elm.second; } std::cout << std::endl; std::cout << "Total: " << total << std::endl; } private: std::string genome; std::map<char, int> count; int displayWidth; }; int main(void) { auto d = new DnaBase(); d->viewGenome(); delete d; return 0; }
Preserve the algorithm and functionality while converting the code from Java to C++.
package diningphilosophers; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; enum PhilosopherState { Get, Eat, Pon } class Fork { public static final int ON_TABLE = -1; static int instances = 0; public int id; public AtomicInteger holder = new AtomicInteger(ON_TABLE); Fork() { id = instances++; } } class Philosopher implements Runnable { static final int maxWaitMs = 100; static AtomicInteger token = new AtomicInteger(0); static int instances = 0; static Random rand = new Random(); AtomicBoolean end = new AtomicBoolean(false); int id; PhilosopherState state = PhilosopherState.Get; Fork left; Fork right; int timesEaten = 0; Philosopher() { id = instances++; left = Main.forks.get(id); right = Main.forks.get((id+1)%Main.philosopherCount); } void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); } catch (InterruptedException ex) {} } void waitForFork(Fork fork) { do { if (fork.holder.get() == Fork.ON_TABLE) { fork.holder.set(id); return; } else { sleep(); } } while (true); } public void run() { do { if (state == PhilosopherState.Pon) { state = PhilosopherState.Get; } else { if (token.get() == id) { waitForFork(left); waitForFork(right); token.set((id+2)% Main.philosopherCount); state = PhilosopherState.Eat; timesEaten++; sleep(); left.holder.set(Fork.ON_TABLE); right.holder.set(Fork.ON_TABLE); state = PhilosopherState.Pon; sleep(); } else { sleep(); } } } while (!end.get()); } } public class Main { static final int philosopherCount = 5; static final int runSeconds = 15; static ArrayList<Fork> forks = new ArrayList<Fork>(); static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>(); public static void main(String[] args) { for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork()); for (int i = 0 ; i < philosopherCount ; i++) philosophers.add(new Philosopher()); for (Philosopher p : philosophers) new Thread(p).start(); long endTime = System.currentTimeMillis() + (runSeconds * 1000); do { StringBuilder sb = new StringBuilder("|"); for (Philosopher p : philosophers) { sb.append(p.state.toString()); sb.append("|"); } sb.append(" |"); for (Fork f : forks) { int holder = f.holder.get(); sb.append(holder==-1?" ":String.format("P%02d",holder)); sb.append("|"); } System.out.println(sb.toString()); try {Thread.sleep(1000);} catch (Exception ex) {} } while (System.currentTimeMillis() < endTime); for (Philosopher p : philosophers) p.end.set(true); for (Philosopher p : philosophers) System.out.printf("P%02d: ate %,d times, %,d/sec\n", p.id, p.timesEaten, p.timesEaten/runSeconds); } }
#include <algorithm> #include <array> #include <chrono> #include <iostream> #include <mutex> #include <random> #include <string> #include <string_view> #include <thread> const int timeScale = 42; void Message(std::string_view message) { static std::mutex cout_mutex; std::scoped_lock cout_lock(cout_mutex); std::cout << message << std::endl; } struct Fork { std::mutex mutex; }; struct Dinner { std::array<Fork, 5> forks; ~Dinner() { Message("Dinner is over"); } }; class Philosopher { std::mt19937 rng{std::random_device {}()}; const std::string name; Fork& left; Fork& right; std::thread worker; void live(); void dine(); void ponder(); public: Philosopher(std::string name_, Fork& l, Fork& r) : name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this) {} ~Philosopher() { worker.join(); Message(name + " went to sleep."); } }; void Philosopher::live() { for(;;) { { std::scoped_lock dine_lock(left.mutex, right.mutex); dine(); } ponder(); } } void Philosopher::dine() { Message(name + " started eating."); thread_local std::array<const char*, 3> foods {"chicken", "rice", "soda"}; thread_local std::array<const char*, 3> reactions { "I like this %s!", "This %s is good.", "Mmm, %s..." }; thread_local std::uniform_int_distribution<> dist(1, 6); std::shuffle( foods.begin(), foods.end(), rng); std::shuffle(reactions.begin(), reactions.end(), rng); constexpr size_t buf_size = 64; char buffer[buf_size]; for(int i = 0; i < 3; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale)); snprintf(buffer, buf_size, reactions[i], foods[i]); Message(name + ": " + buffer); } std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale); Message(name + " finished and left."); } void Philosopher::ponder() { static constexpr std::array<const char*, 5> topics {{ "politics", "art", "meaning of life", "source of morality", "how many straws makes a bale" }}; thread_local std::uniform_int_distribution<> wait(1, 6); thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1); while(dist(rng) > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale)); Message(name + " is pondering about " + topics[dist(rng)] + "."); } std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale)); Message(name + " is hungry again!"); } int main() { Dinner dinner; Message("Dinner started!"); std::array<Philosopher, 5> philosophers {{ {"Aristotle", dinner.forks[0], dinner.forks[1]}, {"Democritus", dinner.forks[1], dinner.forks[2]}, {"Plato", dinner.forks[2], dinner.forks[3]}, {"Pythagoras", dinner.forks[3], dinner.forks[4]}, {"Socrates", dinner.forks[4], dinner.forks[0]}, }}; Message("It is dark outside..."); }
Port the provided Java code into C++ while preserving the original functionality.
public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 10:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,10); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 11:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,11); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 12:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,12); if(multiplied == i){ System.out.print(i + "\t"); } } } public static int factorialRec(int n){ int result = 1; return n == 0 ? result : result * n * factorialRec(n-1); } public static int operate(String s, int base){ int sum = 0; String strx = fromDeci(base, Integer.parseInt(s)); for(int i = 0; i < strx.length(); i++){ if(strx.charAt(i) == 'A'){ sum += factorialRec(10); }else if(strx.charAt(i) == 'B') { sum += factorialRec(11); }else if(strx.charAt(i) == 'C') { sum += factorialRec(12); }else { sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base)); } } return sum; } static char reVal(int num) { if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65); } static String fromDeci(int base, int num){ StringBuilder s = new StringBuilder(); while (num > 0) { s.append(reVal(num % base)); num /= base; } return new String(new StringBuilder(s).reverse()); } }
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return sum == i; } private: ulong f[12]; }; int main() { factorion_t factorion; for (uint b = 9u; b <= 12u; ++b) { std::cout << "factorions for base " << b << ':'; for (uint i = 1u; i < 1500000u; ++i) if (factorion(i, b)) std::cout << ' ' << i; std::cout << std::endl; } return 0; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 10:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,10); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 11:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,11); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 12:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,12); if(multiplied == i){ System.out.print(i + "\t"); } } } public static int factorialRec(int n){ int result = 1; return n == 0 ? result : result * n * factorialRec(n-1); } public static int operate(String s, int base){ int sum = 0; String strx = fromDeci(base, Integer.parseInt(s)); for(int i = 0; i < strx.length(); i++){ if(strx.charAt(i) == 'A'){ sum += factorialRec(10); }else if(strx.charAt(i) == 'B') { sum += factorialRec(11); }else if(strx.charAt(i) == 'C') { sum += factorialRec(12); }else { sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base)); } } return sum; } static char reVal(int num) { if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65); } static String fromDeci(int base, int num){ StringBuilder s = new StringBuilder(); while (num > 0) { s.append(reVal(num % base)); num /= base; } return new String(new StringBuilder(s).reverse()); } }
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return sum == i; } private: ulong f[12]; }; int main() { factorion_t factorion; for (uint b = 9u; b <= 12u; ++b) { std::cout << "factorions for base " << b << ':'; for (uint i = 1u; i < 1500000u; ++i) if (factorion(i, b)) std::cout << ' ' << i; std::cout << std::endl; } return 0; }
Write the same code in C++ as shown below in Java.
public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 10:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,10); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 11:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,11); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 12:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,12); if(multiplied == i){ System.out.print(i + "\t"); } } } public static int factorialRec(int n){ int result = 1; return n == 0 ? result : result * n * factorialRec(n-1); } public static int operate(String s, int base){ int sum = 0; String strx = fromDeci(base, Integer.parseInt(s)); for(int i = 0; i < strx.length(); i++){ if(strx.charAt(i) == 'A'){ sum += factorialRec(10); }else if(strx.charAt(i) == 'B') { sum += factorialRec(11); }else if(strx.charAt(i) == 'C') { sum += factorialRec(12); }else { sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base)); } } return sum; } static char reVal(int num) { if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65); } static String fromDeci(int base, int num){ StringBuilder s = new StringBuilder(); while (num > 0) { s.append(reVal(num % base)); num /= base; } return new String(new StringBuilder(s).reverse()); } }
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return sum == i; } private: ulong f[12]; }; int main() { factorion_t factorion; for (uint b = 9u; b <= 12u; ++b) { std::cout << "factorions for base " << b << ':'; for (uint i = 1u; i < 1500000u; ++i) if (factorion(i, b)) std::cout << ' ' << i; std::cout << std::endl; } return 0; }
Convert this Java block to C++, preserving its control flow and logic.
import java.util.List; import java.util.function.Function; public class LogisticCurveFitting { private static final double K = 7.8e9; private static final int N0 = 27; private static final List<Double> ACTUAL = List.of( 27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, 60.0, 61.0, 61.0, 66.0, 83.0, 219.0, 239.0, 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0, 4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, 20615.0, 24522.0, 28273.0, 31491.0, 34933.0, 37552.0, 40540.0, 43105.0, 45177.0, 60328.0, 64543.0, 67103.0, 69265.0, 71332.0, 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0, 80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, 90664.0, 93077.0, 95316.0, 98172.0, 102133.0, 105824.0, 109695.0, 114232.0, 118610.0, 125497.0, 133852.0, 143227.0, 151367.0, 167418.0, 180096.0, 194836.0, 213150.0, 242364.0, 271106.0, 305117.0, 338133.0, 377918.0, 416845.0, 468049.0, 527767.0, 591704.0, 656866.0, 715353.0, 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0 ); private static double f(double r) { var sq = 0.0; var len = ACTUAL.size(); for (int i = 0; i < len; i++) { var eri = Math.exp(r * i); var guess = (N0 * eri) / (1.0 + N0 * (eri - 1.0) / K); var diff = guess - ACTUAL.get(i); sq += diff * diff; } return sq; } private static double solve(Function<Double, Double> fn) { return solve(fn, 0.5, 0.0); } private static double solve(Function<Double, Double> fn, double guess, double epsilon) { double delta; if (guess != 0.0) { delta = guess; } else { delta = 1.0; } var f0 = fn.apply(guess); var factor = 2.0; while (delta > epsilon && guess != guess - delta) { var nf = fn.apply(guess - delta); if (nf < f0) { f0 = nf; guess -= delta; } else { nf = fn.apply(guess + delta); if (nf < f0) { f0 = nf; guess += delta; } else { factor = 0.5; } } delta *= factor; } return guess; } public static void main(String[] args) { var r = solve(LogisticCurveFitting::f); var r0 = Math.exp(12.0 * r); System.out.printf("r = %.16f, R0 = %.16f\n", r, r0); } }
#include <cmath> #include <functional> #include <iostream> constexpr double K = 7.8e9; constexpr int n0 = 27; constexpr double actual[] = { 27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497, 133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364, 271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704, 656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652 }; double f(double r) { double sq = 0; constexpr size_t len = std::size(actual); for (size_t i = 0; i < len; ++i) { double eri = std::exp(r * i); double guess = (n0 * eri)/(1 + n0 * (eri - 1)/K); double diff = guess - actual[i]; sq += diff * diff; } return sq; } double solve(std::function<double(double)> fn, double guess=0.5, double epsilon=0) { for (double delta = guess ? guess : 1, f0 = fn(guess), factor = 2; delta > epsilon && guess != guess - delta; delta *= factor) { double nf = fn(guess - delta); if (nf < f0) { f0 = nf; guess -= delta; } else { nf = fn(guess + delta); if (nf < f0) { f0 = nf; guess += delta; } else factor = 0.5; } } return guess; } int main() { double r = solve(f); double R0 = std::exp(12 * r); std::cout << "r = " << r << ", R0 = " << R0 << '\n'; return 0; }
Write the same code in C++ as shown below in Java.
import java.util.Arrays; import java.util.LinkedList; public class Strand{ public static <E extends Comparable<? super E>> LinkedList<E> strandSort(LinkedList<E> list){ if(list.size() <= 1) return list; LinkedList<E> result = new LinkedList<E>(); while(list.size() > 0){ LinkedList<E> sorted = new LinkedList<E>(); sorted.add(list.removeFirst()); for(Iterator<E> it = list.iterator(); it.hasNext(); ){ E elem = it.next(); if(sorted.peekLast().compareTo(elem) <= 0){ sorted.addLast(elem); it.remove(); } } result = merge(sorted, result); } return result; } private static <E extends Comparable<? super E>> LinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){ LinkedList<E> result = new LinkedList<E>(); while(!left.isEmpty() && !right.isEmpty()){ if(left.peek().compareTo(right.peek()) <= 0) result.add(left.remove()); else result.add(right.remove()); } result.addAll(left); result.addAll(right); return result; } public static void main(String[] args){ System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5)))); System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5)))); System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6)))); } }
#include <list> template <typename T> std::list<T> strandSort(std::list<T> lst) { if (lst.size() <= 1) return lst; std::list<T> result; std::list<T> sorted; while (!lst.empty()) { sorted.push_back(lst.front()); lst.pop_front(); for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) { if (sorted.back() <= *it) { sorted.push_back(*it); it = lst.erase(it); } else it++; } result.merge(sorted); } return result; }
Rewrite this program in C++ while keeping its functionality equivalent to the Java version.
public class additivePrimes { public static void main(String[] args) { int additive_primes = 0; for (int i = 2; i < 500; i++) { if(isPrime(i) && isPrime(digitSum(i))){ additive_primes++; System.out.print(i + " "); } } System.out.print("\nFound " + additive_primes + " additive primes less than 500"); } static boolean isPrime(int n) { int counter = 1; if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) { return false; } while (counter * 6 - 1 <= Math.sqrt(n)) { if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) { return false; } else { counter++; } } return true; } static int digitSum(int n) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } }
#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; } unsigned int digit_sum(unsigned int n) { unsigned int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int main() { const unsigned int limit = 500; std::cout << "Additive primes less than " << limit << ":\n"; unsigned int count = 0; for (unsigned int n = 1; n < limit; ++n) { if (is_prime(digit_sum(n)) && is_prime(n)) { std::cout << std::setw(3) << n; if (++count % 10 == 0) std::cout << '\n'; else std::cout << ' '; } } std::cout << '\n' << count << " additive primes found.\n"; }
Translate this program into C++ but keep the logic exactly as in Java.
import java.util.ArrayList; import java.util.List; public class PerfectTotientNumbers { public static void main(String[] args) { computePhi(); int n = 20; System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n)); } private static final List<Integer> perfectTotient(int n) { int test = 2; List<Integer> results = new ArrayList<Integer>(); for ( int i = 0 ; i < n ; test++ ) { int phiLoop = test; int sum = 0; do { phiLoop = phi[phiLoop]; sum += phiLoop; } while ( phiLoop > 1); if ( sum == test ) { i++; results.add(test); } } return results; } private static final int max = 100000; 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 <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_; }; bool perfect_totient_number(const totient_calculator& tc, int n) { int sum = 0; for (int m = n; m > 1; ) { int t = tc.totient(m); sum += t; m = t; } return sum == n; } int main() { totient_calculator tc(10000); int count = 0, n = 1; std::cout << "First 20 perfect totient numbers:\n"; for (; count < 20; ++n) { if (perfect_totient_number(tc, n)) { if (count > 0) std::cout << ' '; ++count; std::cout << n; } } std::cout << '\n'; 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 PerfectTotientNumbers { public static void main(String[] args) { computePhi(); int n = 20; System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n)); } private static final List<Integer> perfectTotient(int n) { int test = 2; List<Integer> results = new ArrayList<Integer>(); for ( int i = 0 ; i < n ; test++ ) { int phiLoop = test; int sum = 0; do { phiLoop = phi[phiLoop]; sum += phiLoop; } while ( phiLoop > 1); if ( sum == test ) { i++; results.add(test); } } return results; } private static final int max = 100000; 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 <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_; }; bool perfect_totient_number(const totient_calculator& tc, int n) { int sum = 0; for (int m = n; m > 1; ) { int t = tc.totient(m); sum += t; m = t; } return sum == n; } int main() { totient_calculator tc(10000); int count = 0, n = 1; std::cout << "First 20 perfect totient numbers:\n"; for (; count < 20; ++n) { if (perfect_totient_number(tc, n)) { if (count > 0) std::cout << ' '; ++count; std::cout << n; } } std::cout << '\n'; return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
interface Thingable { String thing(); } class Delegator { public Thingable delegate; public String operation() { if (delegate == null) return "default implementation"; else return delegate.thing(); } } class Delegate implements Thingable { public String thing() { return "delegate implementation"; } } public class DelegateExample { public static void main(String[] args) { Delegator a = new Delegator(); assert a.operation().equals("default implementation"); Delegate d = new Delegate(); a.delegate = d; assert a.operation().equals("delegate implementation"); a.delegate = new Thingable() { public String thing() { return "anonymous delegate implementation"; } }; assert a.operation().equals("anonymous delegate implementation"); } }
#include <tr1/memory> #include <string> #include <iostream> #include <tr1/functional> using namespace std; using namespace std::tr1; using std::tr1::function; class IDelegate { public: virtual ~IDelegate() {} }; class IThing { public: virtual ~IThing() {} virtual std::string Thing() = 0; }; class DelegateA : virtual public IDelegate { }; class DelegateB : public IThing, public IDelegate { std::string Thing() { return "delegate implementation"; } }; class Delegator { public: std::string Operation() { if(Delegate) if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get())) return pThing->Thing(); return "default implementation"; } shared_ptr<IDelegate> Delegate; }; int main() { shared_ptr<DelegateA> delegateA(new DelegateA()); shared_ptr<DelegateB> delegateB(new DelegateB()); Delegator delegator; std::cout << delegator.Operation() << std::endl; delegator.Delegate = delegateA; std::cout << delegator.Operation() << std::endl; delegator.Delegate = delegateB; std::cout << delegator.Operation() << std::endl; }
Change the programming language of this snippet from Java to C++ without modifying what it does.
public class DivisorSum { private static long divisorSum(long n) { var total = 1L; var power = 2L; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (long p = 3; p * p <= n; p += 2) { long sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } public static void main(String[] args) { final long limit = 100; System.out.printf("Sum of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%4d", divisorSum(n)); if (n % 10 == 0) { System.out.println(); } } } }
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } int main() { const unsigned int limit = 100; std::cout << "Sum of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(4) << divisor_sum(n); if (n % 10 == 0) std::cout << '\n'; } }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
public class DivisorSum { private static long divisorSum(long n) { var total = 1L; var power = 2L; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (long p = 3; p * p <= n; p += 2) { long sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } public static void main(String[] args) { final long limit = 100; System.out.printf("Sum of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; ++n) { System.out.printf("%4d", divisorSum(n)); if (n % 10 == 0) { System.out.println(); } } } }
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } int main() { const unsigned int limit = 100; std::cout << "Sum of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(4) << divisor_sum(n); if (n % 10 == 0) std::cout << '\n'; } }
Convert this Java snippet to C++ and keep its semantics consistent.
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class AbbreviationsEasy { private static final Scanner input = new Scanner(System.in); private static final String COMMAND_TABLE = " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" + " COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" + " NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" + " Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" + " MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" + " READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" + " RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; public static void main(String[] args) { String[] cmdTableArr = COMMAND_TABLE.split("\\s+"); Map<String, Integer> cmd_table = new HashMap<String, Integer>(); for (String word : cmdTableArr) { cmd_table.put(word, countCaps(word)); } System.out.print("Please enter your command to verify: "); String userInput = input.nextLine(); String[] user_input = userInput.split("\\s+"); for (String s : user_input) { boolean match = false; for (String cmd : cmd_table.keySet()) { if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) { String temp = cmd.toUpperCase(); if (temp.startsWith(s.toUpperCase())) { System.out.print(temp + " "); match = true; } } } if (!match) { System.out.print("*error* "); } } } private static int countCaps(String word) { int numCaps = 0; for (int i = 0; i < word.length(); i++) { if (Character.isUpperCase(word.charAt(i))) { numCaps++; } } return numCaps; } }
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } size_t get_min_length(const std::string& str) { size_t len = 0, n = str.length(); while (len < n && std::isupper(static_cast<unsigned char>(str[len]))) ++len; return len; } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::vector<command> commands; std::istringstream is(table); std::string word; while (is >> word) { size_t len = get_min_length(word); uppercase(word); commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Keep all operations the same but rewrite the snippet in C++.
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class AbbreviationsEasy { private static final Scanner input = new Scanner(System.in); private static final String COMMAND_TABLE = " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" + " COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" + " NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" + " Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" + " MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" + " READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" + " RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; public static void main(String[] args) { String[] cmdTableArr = COMMAND_TABLE.split("\\s+"); Map<String, Integer> cmd_table = new HashMap<String, Integer>(); for (String word : cmdTableArr) { cmd_table.put(word, countCaps(word)); } System.out.print("Please enter your command to verify: "); String userInput = input.nextLine(); String[] user_input = userInput.split("\\s+"); for (String s : user_input) { boolean match = false; for (String cmd : cmd_table.keySet()) { if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) { String temp = cmd.toUpperCase(); if (temp.startsWith(s.toUpperCase())) { System.out.print(temp + " "); match = true; } } } if (!match) { System.out.print("*error* "); } } } private static int countCaps(String word) { int numCaps = 0; for (int i = 0; i < word.length(); i++) { if (Character.isUpperCase(word.charAt(i))) { numCaps++; } } return numCaps; } }
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } size_t get_min_length(const std::string& str) { size_t len = 0, n = str.length(); while (len < n && std::isupper(static_cast<unsigned char>(str[len]))) ++len; return len; } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::vector<command> commands; std::istringstream is(table); std::string word; while (is >> word) { size_t len = get_min_length(word); uppercase(word); commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
Change the following Java code into C++ without altering its purpose.
final int immutableInt = 4; int mutableInt = 4; mutableInt = 6; immutableInt = 6;
#include <iostream> class MyOtherClass { public: const int m_x; MyOtherClass(const int initX = 0) : m_x(initX) { } }; int main() { MyOtherClass mocA, mocB(7); std::cout << mocA.m_x << std::endl; std::cout << mocB.m_x << std::endl; return 0; }
Translate the given Java code snippet into C++ without altering its behavior.
import java.awt.*; import java.awt.geom.Line2D; import java.util.*; import java.util.List; import javax.swing.*; public class SutherlandHodgman extends JFrame { SutherlandHodgmanPanel panel; public static void main(String[] args) { JFrame f = new SutherlandHodgman(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } public SutherlandHodgman() { Container content = getContentPane(); content.setLayout(new BorderLayout()); panel = new SutherlandHodgmanPanel(); content.add(panel, BorderLayout.CENTER); setTitle("SutherlandHodgman"); pack(); setLocationRelativeTo(null); } } class SutherlandHodgmanPanel extends JPanel { List<double[]> subject, clipper, result; public SutherlandHodgmanPanel() { setPreferredSize(new Dimension(600, 500)); double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}; double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}}; subject = new ArrayList<>(Arrays.asList(subjPoints)); result = new ArrayList<>(subject); clipper = new ArrayList<>(Arrays.asList(clipPoints)); clipPolygon(); } private void clipPolygon() { int len = clipper.size(); for (int i = 0; i < len; i++) { int len2 = result.size(); List<double[]> input = result; result = new ArrayList<>(len2); double[] A = clipper.get((i + len - 1) % len); double[] B = clipper.get(i); for (int j = 0; j < len2; j++) { double[] P = input.get((j + len2 - 1) % len2); double[] Q = input.get(j); if (isInside(A, B, Q)) { if (!isInside(A, B, P)) result.add(intersection(A, B, P, Q)); result.add(Q); } else if (isInside(A, B, P)) result.add(intersection(A, B, P, Q)); } } } private boolean isInside(double[] a, double[] b, double[] c) { return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]); } private double[] intersection(double[] a, double[] b, double[] p, double[] q) { double A1 = b[1] - a[1]; double B1 = a[0] - b[0]; double C1 = A1 * a[0] + B1 * a[1]; double A2 = q[1] - p[1]; double B2 = p[0] - q[0]; double C2 = A2 * p[0] + B2 * p[1]; double det = A1 * B2 - A2 * B1; double x = (B2 * C1 - B1 * C2) / det; double y = (A1 * C2 - A2 * C1) / det; return new double[]{x, y}; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.translate(80, 60); g2.setStroke(new BasicStroke(3)); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawPolygon(g2, subject, Color.blue); drawPolygon(g2, clipper, Color.red); drawPolygon(g2, result, Color.green); } private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) { g2.setColor(color); int len = points.size(); Line2D line = new Line2D.Double(); for (int i = 0; i < len; i++) { double[] p1 = points.get(i); double[] p2 = points.get((i + 1) % len); line.setLine(p1[0], p1[1], p2[0], p2[1]); g2.draw(line); } } }
#include <iostream> #include <span> #include <vector> struct vec2 { float x = 0.0f, y = 0.0f; constexpr vec2 operator+(vec2 other) const { return vec2{x + other.x, y + other.y}; } constexpr vec2 operator-(vec2 other) const { return vec2{x - other.x, y - other.y}; } }; constexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; } constexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; } constexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; } constexpr bool is_inside(vec2 point, vec2 a, vec2 b) { return (cross(a - b, point) + cross(b, a)) < 0.0f; } constexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) { return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) * (1.0f / cross(a1 - a2, b1 - b2)); } std::vector<vec2> suther_land_hodgman( std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) { if (clip_polygon.empty() || subject_polygon.empty()) { return {}; } std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()}; vec2 p1 = clip_polygon[clip_polygon.size() - 1]; std::vector<vec2> input; for (vec2 p2 : clip_polygon) { input.clear(); input.insert(input.end(), ring.begin(), ring.end()); vec2 s = input[input.size() - 1]; ring.clear(); for (vec2 e : input) { if (is_inside(e, p1, p2)) { if (!is_inside(s, p1, p2)) { ring.push_back(intersection(p1, p2, s, e)); } ring.push_back(e); } else if (is_inside(s, p1, p2)) { ring.push_back(intersection(p1, p2, s, e)); } s = e; } p1 = p2; } return ring; } int main(int argc, char **argv) { vec2 subject_polygon[] = {{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}; vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}}; std::vector<vec2> clipped_polygon = suther_land_hodgman(subject_polygon, clip_polygon); std::cout << "Clipped polygon points:" << std::endl; for (vec2 p : clipped_polygon) { std::cout << "(" << p.x << ", " << p.y << ")" << std::endl; } return EXIT_SUCCESS; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
import java.util.HashMap; import java.util.Map; import java.util.Objects; public class BaconCipher { private static final Map<Character, String> codes; static { codes = new HashMap<>(); codes.putAll(Map.of( 'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA", 'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB" )); codes.putAll(Map.of( 'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA", 'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB" )); codes.putAll(Map.of( 'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA", 'z', "BBAAB", ' ', "BBBAA" )); } private static String encode(String plainText, String message) { String pt = plainText.toLowerCase(); StringBuilder sb = new StringBuilder(); for (char c : pt.toCharArray()) { if ('a' <= c && c <= 'z') sb.append(codes.get(c)); else sb.append(codes.get(' ')); } String et = sb.toString(); String mg = message.toLowerCase(); sb.setLength(0); int count = 0; for (char c : mg.toCharArray()) { if ('a' <= c && c <= 'z') { if (et.charAt(count) == 'A') sb.append(c); else sb.append(((char) (c - 32))); count++; if (count == et.length()) break; } else sb.append(c); } return sb.toString(); } private static String decode(String message) { StringBuilder sb = new StringBuilder(); for (char c : message.toCharArray()) { if ('a' <= c && c <= 'z') sb.append('A'); if ('A' <= c && c <= 'Z') sb.append('B'); } String et = sb.toString(); sb.setLength(0); for (int i = 0; i < et.length(); i += 5) { String quintet = et.substring(i, i + 5); Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null); sb.append(key); } return sb.toString(); } public static void main(String[] args) { String plainText = "the quick brown fox jumps over the lazy dog"; String message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; String cipherText = encode(plainText, message); System.out.printf("Cipher text ->\n\n%s\n", cipherText); String decodedText = decode(cipherText); System.out.printf("\nHidden text ->\n\n%s\n", decodedText); } }
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.HashMap; import java.util.Map; import java.util.Objects; public class BaconCipher { private static final Map<Character, String> codes; static { codes = new HashMap<>(); codes.putAll(Map.of( 'a', "AAAAA", 'b', "AAAAB", 'c', "AAABA", 'd', "AAABB", 'e', "AABAA", 'f', "AABAB", 'g', "AABBA", 'h', "AABBB", 'i', "ABAAA", 'j', "ABAAB" )); codes.putAll(Map.of( 'k', "ABABA", 'l', "ABABB", 'm', "ABBAA", 'n', "ABBAB", 'o', "ABBBA", 'p', "ABBBB", 'q', "BAAAA", 'r', "BAAAB", 's', "BAABA", 't', "BAABB" )); codes.putAll(Map.of( 'u', "BABAA", 'v', "BABAB", 'w', "BABBA", 'x', "BABBB", 'y', "BBAAA", 'z', "BBAAB", ' ', "BBBAA" )); } private static String encode(String plainText, String message) { String pt = plainText.toLowerCase(); StringBuilder sb = new StringBuilder(); for (char c : pt.toCharArray()) { if ('a' <= c && c <= 'z') sb.append(codes.get(c)); else sb.append(codes.get(' ')); } String et = sb.toString(); String mg = message.toLowerCase(); sb.setLength(0); int count = 0; for (char c : mg.toCharArray()) { if ('a' <= c && c <= 'z') { if (et.charAt(count) == 'A') sb.append(c); else sb.append(((char) (c - 32))); count++; if (count == et.length()) break; } else sb.append(c); } return sb.toString(); } private static String decode(String message) { StringBuilder sb = new StringBuilder(); for (char c : message.toCharArray()) { if ('a' <= c && c <= 'z') sb.append('A'); if ('A' <= c && c <= 'Z') sb.append('B'); } String et = sb.toString(); sb.setLength(0); for (int i = 0; i < et.length(); i += 5) { String quintet = et.substring(i, i + 5); Character key = codes.entrySet().stream().filter(a -> Objects.equals(a.getValue(), quintet)).findFirst().map(Map.Entry::getKey).orElse(null); sb.append(key); } return sb.toString(); } public static void main(String[] args) { String plainText = "the quick brown fox jumps over the lazy dog"; String message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; String cipherText = encode(plainText, message); System.out.printf("Cipher text ->\n\n%s\n", cipherText); String decodedText = decode(cipherText); System.out.printf("\nHidden text ->\n\n%s\n", decodedText); } }
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Transform the following Java implementation into C++, maintaining the same output and logic.
public class Blah { public static void main(String[] args) { print2dArray(getSpiralArray(5)); } public static int[][] getSpiralArray(int dimension) { int[][] spiralArray = new int[dimension][dimension]; int numConcentricSquares = (int) Math.ceil((dimension) / 2.0); int j; int sideLen = dimension; int currNum = 0; for (int i = 0; i < numConcentricSquares; i++) { for (j = 0; j < sideLen; j++) { spiralArray[i][i + j] = currNum++; } for (j = 1; j < sideLen; j++) { spiralArray[i + j][dimension - 1 - i] = currNum++; } for (j = sideLen - 2; j > -1; j--) { spiralArray[dimension - 1 - i][i + j] = currNum++; } for (j = sideLen - 2; j > 0; j--) { spiralArray[i + j][i] = currNum++; } sideLen -= 2; } return spiralArray; } public static void print2dArray(int[][] array) { for (int[] row : array) { for (int elem : row) { System.out.printf("%3d", elem); } System.out.println(); } } }
#include <vector> #include <memory> #include <cmath> #include <iostream> #include <iomanip> using namespace std; typedef vector< int > IntRow; typedef vector< IntRow > IntTable; auto_ptr< IntTable > getSpiralArray( int dimension ) { auto_ptr< IntTable > spiralArrayPtr( new IntTable( dimension, IntRow( dimension ) ) ); int numConcentricSquares = static_cast< int >( ceil( static_cast< double >( dimension ) / 2.0 ) ); int j; int sideLen = dimension; int currNum = 0; for ( int i = 0; i < numConcentricSquares; i++ ) { for ( j = 0; j < sideLen; j++ ) ( *spiralArrayPtr )[ i ][ i + j ] = currNum++; for ( j = 1; j < sideLen; j++ ) ( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++; for ( j = sideLen - 2; j > -1; j-- ) ( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++; for ( j = sideLen - 2; j > 0; j-- ) ( *spiralArrayPtr )[ i + j ][ i ] = currNum++; sideLen -= 2; } return spiralArrayPtr; } void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr ) { size_t dimension = spiralArrayPtr->size(); int fieldWidth = static_cast< int >( floor( log10( static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; size_t col; for ( size_t row = 0; row < dimension; row++ ) { for ( col = 0; col < dimension; col++ ) cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ]; cout << endl; } } int main() { printSpiralArray( getSpiralArray( 5 ) ); }
Rewrite this program in C++ while keeping its functionality equivalent to the Java version.
module OptionalParameters { typedef Type<String >.Orderer as ColumnOrderer; typedef Type<String[]>.Orderer as RowOrderer; static String[][] sort(String[][] table, ColumnOrderer? orderer = Null, Int column = 0, Boolean reverse = False, ) { orderer ?:= (s1, s2) -> s1 <=> s2; ColumnOrderer byString = reverse ? ((s1, s2) -> orderer(s1, s2).reversed) : orderer; RowOrderer byColumn = (row1, row2) -> byString(row1[column], row2[column]); return table.sorted(byColumn); } void run() { String[][] table = [ ["c", "x", "i"], ["a", "y", "p"], ["b", "z", "a"], ]; show("original input", table); show("by default sort on column 0", sort(table)); show("by column 2", sort(table, column=2)); show("by column 2 reversed", sort(table, column=2, reverse=True)); } void show(String title, String[][] table) { @Inject Console console; console.print($"{title}:"); for (val row : table) { console.print($" {row}"); } console.print(); } }
#include <vector> #include <algorithm> #include <string> template <class T> struct sort_table_functor { typedef bool (*CompFun)(const T &, const T &); const CompFun ordering; const int column; const bool reverse; sort_table_functor(CompFun o, int c, bool r) : ordering(o), column(c), reverse(r) { } bool operator()(const std::vector<T> &x, const std::vector<T> &y) const { const T &a = x[column], &b = y[column]; return reverse ? ordering(b, a) : ordering(a, b); } }; template <class T> bool myLess(const T &x, const T &y) { return x < y; } template <class T> void sort_table(std::vector<std::vector<T> > &table, int column = 0, bool reverse = false, bool (*ordering)(const T &, const T &) = myLess) { std::sort(table.begin(), table.end(), sort_table_functor<T>(ordering, column, reverse)); } #include <iostream> template <class T> void print_matrix(std::vector<std::vector<T> > &data) { for () { for (int j = 0; j < 3; j++) std::cout << data[i][j] << "\t"; std::cout << std::endl; } } bool desc_len_comparator(const std::string &x, const std::string &y) { return x.length() > y.length(); } int main() { std::string data_array[3][3] = { {"a", "b", "c"}, {"", "q", "z"}, {"zap", "zip", "Zot"} }; std::vector<std::vector<std::string> > data_orig; for (int i = 0; i < 3; i++) { std::vector<std::string> row; for (int j = 0; j < 3; j++) row.push_back(data_array[i][j]); data_orig.push_back(row); } print_matrix(data_orig); std::vector<std::vector<std::string> > data = data_orig; sort_table(data); print_matrix(data); data = data_orig; sort_table(data, 2); print_matrix(data); data = data_orig; sort_table(data, 1); print_matrix(data); data = data_orig; sort_table(data, 1, true); print_matrix(data); data = data_orig; sort_table(data, 0, false, desc_len_comparator); print_matrix(data); return 0; }
Convert the following code from Java to C++, ensuring the logic remains intact.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { static double p = 3; static BufferedImage I; static int px[], py[], color[], cells = 100, size = 1000; public Voronoi() { super("Voronoi Diagram"); setBounds(0, 0, size, size); setDefaultCloseOperation(EXIT_ON_CLOSE); int n = 0; Random rand = new Random(); I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); px = new int[cells]; py = new int[cells]; color = new int[cells]; for (int i = 0; i < cells; i++) { px[i] = rand.nextInt(size); py[i] = rand.nextInt(size); color[i] = rand.nextInt(16777215); } for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { n = 0; for (byte i = 0; i < cells; i++) { if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) { n = i; } } I.setRGB(x, y, color[n]); } } Graphics2D g = I.createGraphics(); g.setColor(Color.BLACK); for (int i = 0; i < cells; i++) { g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5)); } try { ImageIO.write(I, "png", new File("voronoi.png")); } catch (IOException e) { } } public void paint(Graphics g) { g.drawImage(I, 0, 0, this); } static double distance(int x1, int x2, int y1, int y2) { double d; d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); return d; } public static void main(String[] args) { new Voronoi().setVisible(true); } }
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); 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; void *bits_ptr = nullptr; HDC dc = GetDC(GetConsoleWindow()); bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0); if (!bmp_) return false; hdc_ = CreateCompatibleDC(dc); SelectObject(hdc_, bmp_); ReleaseDC(GetConsoleWindow(), dc); width_ = w; height_ = h; return true; } void SetPenColor(DWORD clr) { if (pen_) DeleteObject(pen_); pen_ = CreatePen(PS_SOLID, 1, clr); SelectObject(hdc_, pen_); } bool SaveBitmap(const char* path) { HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return false; } BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; GetObject(bmp_, sizeof(bitmap), &bitmap); DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD)); ZeroMemory(&infoheader, sizeof(BITMAPINFO)); ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER)); infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS); DWORD wb; WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr); WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr); WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr); CloseHandle(file); delete[] dwp_bits; return true; } HDC hdc() { return hdc_; } int width() { return width_; } int height() { return height_; } private: HBITMAP bmp_; HDC hdc_; HPEN pen_; int width_, height_; }; static int DistanceSqrd(const Point& point, int x, int y) { int xd = x - point.x; int yd = y - point.y; return (xd * xd) + (yd * yd); } class Voronoi { public: void Make(MyBitmap* bmp, int count) { bmp_ = bmp; CreatePoints(count); CreateColors(); CreateSites(); SetSitesPoints(); } private: void CreateSites() { int w = bmp_->width(), h = bmp_->height(), d; for (int hh = 0; hh < h; hh++) { for (int ww = 0; ww < w; ww++) { int ind = -1, dist = INT_MAX; for (size_t it = 0; it < points_.size(); it++) { const Point& p = points_[it]; d = DistanceSqrd(p, ww, hh); if (d < dist) { dist = d; ind = it; } } if (ind > -1) SetPixel(bmp_->hdc(), ww, hh, colors_[ind]); else __asm nop } } } void SetSitesPoints() { for (const auto& point : points_) { int x = point.x, y = point.y; for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) SetPixel(bmp_->hdc(), x + i, y + j, 0); } } void CreatePoints(int count) { const int w = bmp_->width() - 20, h = bmp_->height() - 20; for (int i = 0; i < count; i++) { points_.push_back({ rand() % w + 10, rand() % h + 10 }); } } void CreateColors() { for (size_t i = 0; i < points_.size(); i++) { DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50); colors_.push_back(c); } } vector<Point> points_; vector<DWORD> colors_; MyBitmap* bmp_; }; int main(int argc, char* argv[]) { ShowWindow(GetConsoleWindow(), SW_MAXIMIZE); srand(GetTickCount()); MyBitmap bmp; bmp.Create(512, 512); bmp.SetPenColor(0); Voronoi v; v.Make(&bmp, 50); BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY); bmp.SaveBitmap("v.bmp"); system("pause"); return 0; }
Port the following code from Java to C++ with equivalent syntax and logic.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; public class Voronoi extends JFrame { static double p = 3; static BufferedImage I; static int px[], py[], color[], cells = 100, size = 1000; public Voronoi() { super("Voronoi Diagram"); setBounds(0, 0, size, size); setDefaultCloseOperation(EXIT_ON_CLOSE); int n = 0; Random rand = new Random(); I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); px = new int[cells]; py = new int[cells]; color = new int[cells]; for (int i = 0; i < cells; i++) { px[i] = rand.nextInt(size); py[i] = rand.nextInt(size); color[i] = rand.nextInt(16777215); } for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { n = 0; for (byte i = 0; i < cells; i++) { if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) { n = i; } } I.setRGB(x, y, color[n]); } } Graphics2D g = I.createGraphics(); g.setColor(Color.BLACK); for (int i = 0; i < cells; i++) { g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5)); } try { ImageIO.write(I, "png", new File("voronoi.png")); } catch (IOException e) { } } public void paint(Graphics g) { g.drawImage(I, 0, 0, this); } static double distance(int x1, int x2, int y1, int y2) { double d; d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); return d; } public static void main(String[] args) { new Voronoi().setVisible(true); } }
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); 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; void *bits_ptr = nullptr; HDC dc = GetDC(GetConsoleWindow()); bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0); if (!bmp_) return false; hdc_ = CreateCompatibleDC(dc); SelectObject(hdc_, bmp_); ReleaseDC(GetConsoleWindow(), dc); width_ = w; height_ = h; return true; } void SetPenColor(DWORD clr) { if (pen_) DeleteObject(pen_); pen_ = CreatePen(PS_SOLID, 1, clr); SelectObject(hdc_, pen_); } bool SaveBitmap(const char* path) { HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return false; } BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; GetObject(bmp_, sizeof(bitmap), &bitmap); DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory(dwp_bits, bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD)); ZeroMemory(&infoheader, sizeof(BITMAPINFO)); ZeroMemory(&fileheader, sizeof(BITMAPFILEHEADER)); infoheader.bmiHeader.biBitCount = sizeof(DWORD) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof(infoheader.bmiHeader); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof(DWORD); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof(infoheader.bmiHeader) + sizeof(BITMAPFILEHEADER); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits(hdc_, bmp_, 0, height_, (LPVOID)dwp_bits, &infoheader, DIB_RGB_COLORS); DWORD wb; WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr); WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr); WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr); CloseHandle(file); delete[] dwp_bits; return true; } HDC hdc() { return hdc_; } int width() { return width_; } int height() { return height_; } private: HBITMAP bmp_; HDC hdc_; HPEN pen_; int width_, height_; }; static int DistanceSqrd(const Point& point, int x, int y) { int xd = x - point.x; int yd = y - point.y; return (xd * xd) + (yd * yd); } class Voronoi { public: void Make(MyBitmap* bmp, int count) { bmp_ = bmp; CreatePoints(count); CreateColors(); CreateSites(); SetSitesPoints(); } private: void CreateSites() { int w = bmp_->width(), h = bmp_->height(), d; for (int hh = 0; hh < h; hh++) { for (int ww = 0; ww < w; ww++) { int ind = -1, dist = INT_MAX; for (size_t it = 0; it < points_.size(); it++) { const Point& p = points_[it]; d = DistanceSqrd(p, ww, hh); if (d < dist) { dist = d; ind = it; } } if (ind > -1) SetPixel(bmp_->hdc(), ww, hh, colors_[ind]); else __asm nop } } } void SetSitesPoints() { for (const auto& point : points_) { int x = point.x, y = point.y; for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) SetPixel(bmp_->hdc(), x + i, y + j, 0); } } void CreatePoints(int count) { const int w = bmp_->width() - 20, h = bmp_->height() - 20; for (int i = 0; i < count; i++) { points_.push_back({ rand() % w + 10, rand() % h + 10 }); } } void CreateColors() { for (size_t i = 0; i < points_.size(); i++) { DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50); colors_.push_back(c); } } vector<Point> points_; vector<DWORD> colors_; MyBitmap* bmp_; }; int main(int argc, char* argv[]) { ShowWindow(GetConsoleWindow(), SW_MAXIMIZE); srand(GetTickCount()); MyBitmap bmp; bmp.Create(512, 512); bmp.SetPenColor(0); Voronoi v; v.Make(&bmp, 50); BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY); bmp.SaveBitmap("v.bmp"); system("pause"); return 0; }
Convert the following code from Java to C++, ensuring the logic remains intact.
public class JNIDemo { static { System.loadLibrary("JNIDemo"); } public static void main(String[] args) { System.out.println(callStrdup("Hello World!")); } private static native String callStrdup(String s); }
FUNCTION MULTIPLY(X, Y) DOUBLE PRECISION MULTIPLY, X, Y
Port the following code from Java to C++ with equivalent syntax and logic.
import java.util.*; class SOfN<T> { private static final Random rand = new Random(); private List<T> sample; private int i = 0; private int n; public SOfN(int _n) { n = _n; sample = new ArrayList<T>(n); } public List<T> process(T item) { if (++i <= n) { sample.add(item); } else if (rand.nextInt(i) < n) { sample.set(rand.nextInt(n), item); } return sample; } } public class AlgorithmS { public static void main(String[] args) { int[] bin = new int[10]; for (int trial = 0; trial < 100000; trial++) { SOfN<Integer> s_of_n = new SOfN<Integer>(3); for (int i = 0; i < 9; i++) s_of_n.process(i); for (int s : s_of_n.process(9)) bin[s]++; } System.out.println(Arrays.toString(bin)); } }
#include <iostream> #include <functional> #include <vector> #include <cstdlib> #include <ctime> template <typename T> std::function<std::vector<T>(T)> s_of_n_creator(int n) { std::vector<T> sample; int i = 0; return [=](T item) mutable { i++; if (i <= n) { sample.push_back(item); } else if (std::rand() % i < n) { sample[std::rand() % n] = item; } return sample; }; } int main() { std::srand(std::time(NULL)); int bin[10] = {0}; for (int trial = 0; trial < 100000; trial++) { auto s_of_n = s_of_n_creator<int>(3); std::vector<int> sample; for (int i = 0; i < 10; i++) sample = s_of_n(i); for (int s : sample) bin[s]++; } for (int x : bin) std::cout << x << std::endl; return 0; }
Transform the following Java implementation into C++, maintaining the same output and logic.
import java.util.*; class SOfN<T> { private static final Random rand = new Random(); private List<T> sample; private int i = 0; private int n; public SOfN(int _n) { n = _n; sample = new ArrayList<T>(n); } public List<T> process(T item) { if (++i <= n) { sample.add(item); } else if (rand.nextInt(i) < n) { sample.set(rand.nextInt(n), item); } return sample; } } public class AlgorithmS { public static void main(String[] args) { int[] bin = new int[10]; for (int trial = 0; trial < 100000; trial++) { SOfN<Integer> s_of_n = new SOfN<Integer>(3); for (int i = 0; i < 9; i++) s_of_n.process(i); for (int s : s_of_n.process(9)) bin[s]++; } System.out.println(Arrays.toString(bin)); } }
#include <iostream> #include <functional> #include <vector> #include <cstdlib> #include <ctime> template <typename T> std::function<std::vector<T>(T)> s_of_n_creator(int n) { std::vector<T> sample; int i = 0; return [=](T item) mutable { i++; if (i <= n) { sample.push_back(item); } else if (std::rand() % i < n) { sample[std::rand() % n] = item; } return sample; }; } int main() { std::srand(std::time(NULL)); int bin[10] = {0}; for (int trial = 0; trial < 100000; trial++) { auto s_of_n = s_of_n_creator<int>(3); std::vector<int> sample; for (int i = 0; i < 10; i++) sample = s_of_n(i); for (int s : sample) bin[s]++; } for (int x : bin) std::cout << x << std::endl; return 0; }
Preserve the algorithm and functionality while converting the code from Java to C++.
import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.stream.LongStream; public class FaulhabersTriangle { private static final MathContext MC = new MathContext(256); private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } private static class Frac implements Comparable<Frac> { private long num; private long denom; public static final Frac ZERO = new Frac(0, 1); public Frac(long n, long d) { if (d == 0) throw new IllegalArgumentException("d must not be zero"); long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.abs(gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } public Frac plus(Frac rhs) { return new Frac(num * rhs.denom + denom * rhs.num, rhs.denom * denom); } public Frac unaryMinus() { return new Frac(-num, denom); } public Frac minus(Frac rhs) { return this.plus(rhs.unaryMinus()); } public Frac times(Frac rhs) { return new Frac(this.num * rhs.num, this.denom * rhs.denom); } @Override public int compareTo(Frac o) { double diff = toDouble() - o.toDouble(); return Double.compare(diff, 0.0); } @Override public boolean equals(Object obj) { return null != obj && obj instanceof Frac && this.compareTo((Frac) obj) == 0; } @Override public String toString() { if (denom == 1) { return Long.toString(num); } return String.format("%d/%d", num, denom); } public double toDouble() { return (double) num / denom; } public BigDecimal toBigDecimal() { return BigDecimal.valueOf(num).divide(BigDecimal.valueOf(denom), MC); } } private static Frac bernoulli(int n) { if (n < 0) throw new IllegalArgumentException("n may not be negative or zero"); Frac[] a = new Frac[n + 1]; Arrays.fill(a, Frac.ZERO); for (int m = 0; m <= n; ++m) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; --j) { a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1)); } } if (n != 1) return a[0]; return a[0].unaryMinus(); } private static long binomial(int n, int k) { if (n < 0 || k < 0 || n < k) throw new IllegalArgumentException(); if (n == 0 || k == 0) return 1; long num = LongStream.rangeClosed(k + 1, n).reduce(1, (a, b) -> a * b); long den = LongStream.rangeClosed(2, n - k).reduce(1, (acc, i) -> acc * i); return num / den; } private static Frac[] faulhaberTriangle(int p) { Frac[] coeffs = new Frac[p + 1]; Arrays.fill(coeffs, Frac.ZERO); Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; ++j) { sign *= -1; coeffs[p - j] = q.times(new Frac(sign, 1)).times(new Frac(binomial(p + 1, j), 1)).times(bernoulli(j)); } return coeffs; } public static void main(String[] args) { for (int i = 0; i <= 9; ++i) { Frac[] coeffs = faulhaberTriangle(i); for (Frac coeff : coeffs) { System.out.printf("%5s ", coeff); } System.out.println(); } System.out.println(); int k = 17; Frac[] cc = faulhaberTriangle(k); int n = 1000; BigDecimal nn = BigDecimal.valueOf(n); BigDecimal np = BigDecimal.ONE; BigDecimal sum = BigDecimal.ZERO; for (Frac c : cc) { np = np.multiply(nn); sum = sum.add(np.multiply(c.toBigDecimal())); } System.out.println(sum.toBigInteger()); } }
#include <exception> #include <iomanip> #include <iostream> #include <numeric> #include <sstream> #include <vector> class Frac { public: Frac() : num(0), denom(1) {} Frac(int n, int d) { if (d == 0) { throw std::runtime_error("d must not be zero"); } int sign_of_d = d < 0 ? -1 : 1; int g = std::gcd(n, d); num = sign_of_d * n / g; denom = sign_of_d * d / g; } Frac operator-() const { return Frac(-num, denom); } Frac operator+(const Frac& rhs) const { return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom); } Frac operator-(const Frac& rhs) const { return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom); } Frac operator*(const Frac& rhs) const { return Frac(num*rhs.num, denom*rhs.denom); } Frac operator*(int rhs) const { return Frac(num * rhs, denom); } friend std::ostream& operator<<(std::ostream&, const Frac&); private: int num; int denom; }; std::ostream & operator<<(std::ostream & os, const Frac &f) { if (f.num == 0 || f.denom == 1) { return os << f.num; } std::stringstream ss; ss << f.num << "/" << f.denom; return os << ss.str(); } Frac bernoulli(int n) { if (n < 0) { throw std::runtime_error("n may not be negative or zero"); } std::vector<Frac> a; for (int m = 0; m <= n; m++) { a.push_back(Frac(1, m + 1)); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * j; } } if (n != 1) return a[0]; return -a[0]; } int binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw std::runtime_error("parameters are invalid"); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num *= i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom *= i; } return num / denom; } std::vector<Frac> faulhaberTraingle(int p) { std::vector<Frac> coeffs(p + 1); Frac q{ 1, p + 1 }; int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j); } return coeffs; } int main() { for (int i = 0; i < 10; i++) { std::vector<Frac> coeffs = faulhaberTraingle(i); for (auto frac : coeffs) { std::cout << std::right << std::setw(5) << frac << " "; } std::cout << std::endl; } return 0; }
Produce a functionally identical C++ code for the snippet given in Java.
public class Arguments { public static void main(String[] args) { System.out.println("There are " + args.length + " arguments given."); for(int i = 0; i < args.length; i++) System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i); } }
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl; return 0; }
Change the following Java code into C++ without altering its purpose.
public class Arguments { public static void main(String[] args) { System.out.println("There are " + args.length + " arguments given."); for(int i = 0; i < args.length; i++) System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i); } }
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl; return 0; }
Ensure the translated C++ code behaves exactly like the original Java snippet.
String[] fruits = ["apples", "oranges"]; String[] grains = ["wheat", "corn"]; String[] all = fruits + grains;
#include <vector> #include <iostream> int main() { std::vector<int> a(3), b(4); a[0] = 11; a[1] = 12; a[2] = 13; b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24; a.insert(a.end(), b.begin(), b.end()); for (int i = 0; i < a.size(); ++i) std::cout << "a[" << i << "] = " << a[i] << "\n"; }
Write the same algorithm in C++ as shown in this Java implementation.
import java.util.Scanner; public class GetInput { public static void main(String[] args) throws Exception { Scanner s = new Scanner(System.in); System.out.print("Enter a string: "); String str = s.nextLine(); System.out.print("Enter an integer: "); int i = Integer.parseInt(s.next()); } }
#include <iostream> #include <string> using namespace std; int main() { long int integer_input; string string_input; cout << "Enter an integer: "; cin >> integer_input; cout << "Enter a string: "; cin >> string_input; return 0; }
Write the same code in C++ as shown below in Java.
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) { std::cout << "Error opening MIDI Output..." << std::endl; device = 0; } } ~midi() { midiOutReset( device ); midiOutClose( device ); } bool isOpen() { return device != 0; } void setInstrument( byte i ) { message.data[0] = 0xc0; message.data[1] = i; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void playNote( byte n, unsigned i ) { playNote( n ); Sleep( i ); stopNote( n ); } private: void playNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 127; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void stopNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } HMIDIOUT device; midi_msg message; }; int main( int argc, char* argv[] ) { midi m; if( m.isOpen() ) { byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 }; m.setInstrument( 42 ); for( int x = 0; x < 8; x++ ) m.playNote( notes[x], rand() % 100 + 158 ); Sleep( 1000 ); } return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
import processing.sound.*; float[] frequencies = {261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25}; SinOsc sine; size(500,500); sine = new SinOsc(this); for(int i=0;i<frequencies.length;i++){ sine.freq(frequencies[i]); sine.play(); delay(500); }
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOERROR ) { std::cout << "Error opening MIDI Output..." << std::endl; device = 0; } } ~midi() { midiOutReset( device ); midiOutClose( device ); } bool isOpen() { return device != 0; } void setInstrument( byte i ) { message.data[0] = 0xc0; message.data[1] = i; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void playNote( byte n, unsigned i ) { playNote( n ); Sleep( i ); stopNote( n ); } private: void playNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 127; message.data[3] = 0; midiOutShortMsg( device, message.word ); } void stopNote( byte n ) { message.data[0] = 0x90; message.data[1] = n; message.data[2] = 0; message.data[3] = 0; midiOutShortMsg( device, message.word ); } HMIDIOUT device; midi_msg message; }; int main( int argc, char* argv[] ) { midi m; if( m.isOpen() ) { byte notes[] = { 60, 62, 64, 65, 67, 69, 71, 72 }; m.setInstrument( 42 ); for( int x = 0; x < 8; x++ ) m.playNote( notes[x], rand() % 100 + 158 ); Sleep( 1000 ); } return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
package hu.pj.alg.test; import hu.pj.alg.ZeroOneKnapsack; import hu.pj.obj.Item; import java.util.*; import java.text.*; public class ZeroOneKnapsackForTourists { public ZeroOneKnapsackForTourists() { ZeroOneKnapsack zok = new ZeroOneKnapsack(400); zok.add("map", 9, 150); zok.add("compass", 13, 35); zok.add("water", 153, 200); zok.add("sandwich", 50, 160); zok.add("glucose", 15, 60); zok.add("tin", 68, 45); zok.add("banana", 27, 60); zok.add("apple", 39, 40); zok.add("cheese", 23, 30); zok.add("beer", 52, 10); zok.add("suntan cream", 11, 70); zok.add("camera", 32, 30); zok.add("t-shirt", 24, 15); zok.add("trousers", 48, 10); zok.add("umbrella", 73, 40); zok.add("waterproof trousers", 42, 70); zok.add("waterproof overclothes", 43, 75); zok.add("note-case", 22, 80); zok.add("sunglasses", 7, 20); zok.add("towel", 18, 12); zok.add("socks", 4, 50); zok.add("book", 30, 10); List<Item> itemList = zok.calcSolution(); if (zok.isCalculated()) { NumberFormat nf = NumberFormat.getInstance(); System.out.println( "Maximal weight = " + nf.format(zok.getMaxWeight() / 100.0) + " kg" ); System.out.println( "Total weight of solution = " + nf.format(zok.getSolutionWeight() / 100.0) + " kg" ); System.out.println( "Total value = " + zok.getProfit() ); System.out.println(); System.out.println( "You can carry the following materials " + "in the knapsack:" ); for (Item item : itemList) { if (item.getInKnapsack() == 1) { System.out.format( "%1$-23s %2$-3s %3$-5s %4$-15s \n", item.getName(), item.getWeight(), "dag ", "(value = " + item.getValue() + ")" ); } } } else { System.out.println( "The problem is not solved. " + "Maybe you gave wrong data." ); } } public static void main(String[] args) { new ZeroOneKnapsackForTourists(); } }
#include <vector> #include <string> #include <iostream> #include <boost/tuple/tuple.hpp> #include <set> int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , std::set<int> & , const int ) ; int main( ) { std::vector<boost::tuple<std::string , int , int> > items ; items.push_back( boost::make_tuple( "" , 0 , 0 ) ) ; items.push_back( boost::make_tuple( "map" , 9 , 150 ) ) ; items.push_back( boost::make_tuple( "compass" , 13 , 35 ) ) ; items.push_back( boost::make_tuple( "water" , 153 , 200 ) ) ; items.push_back( boost::make_tuple( "sandwich", 50 , 160 ) ) ; items.push_back( boost::make_tuple( "glucose" , 15 , 60 ) ) ; items.push_back( boost::make_tuple( "tin", 68 , 45 ) ) ; items.push_back( boost::make_tuple( "banana", 27 , 60 ) ) ; items.push_back( boost::make_tuple( "apple" , 39 , 40 ) ) ; items.push_back( boost::make_tuple( "cheese" , 23 , 30 ) ) ; items.push_back( boost::make_tuple( "beer" , 52 , 10 ) ) ; items.push_back( boost::make_tuple( "suntan creme" , 11 , 70 ) ) ; items.push_back( boost::make_tuple( "camera" , 32 , 30 ) ) ; items.push_back( boost::make_tuple( "T-shirt" , 24 , 15 ) ) ; items.push_back( boost::make_tuple( "trousers" , 48 , 10 ) ) ; items.push_back( boost::make_tuple( "umbrella" , 73 , 40 ) ) ; items.push_back( boost::make_tuple( "waterproof trousers" , 42 , 70 ) ) ; items.push_back( boost::make_tuple( "waterproof overclothes" , 43 , 75 ) ) ; items.push_back( boost::make_tuple( "note-case" , 22 , 80 ) ) ; items.push_back( boost::make_tuple( "sunglasses" , 7 , 20 ) ) ; items.push_back( boost::make_tuple( "towel" , 18 , 12 ) ) ; items.push_back( boost::make_tuple( "socks" , 4 , 50 ) ) ; items.push_back( boost::make_tuple( "book" , 30 , 10 ) ) ; const int maximumWeight = 400 ; std::set<int> bestItems ; int bestValue = findBestPack( items , bestItems , maximumWeight ) ; std::cout << "The best value that can be packed in the given knapsack is " << bestValue << " !\n" ; int totalweight = 0 ; std::cout << "The following items should be packed in the knapsack:\n" ; for ( std::set<int>::const_iterator si = bestItems.begin( ) ; si != bestItems.end( ) ; si++ ) { std::cout << (items.begin( ) + *si)->get<0>( ) << "\n" ; totalweight += (items.begin( ) + *si)->get<1>( ) ; } std::cout << "The total weight of all items is " << totalweight << " !\n" ; return 0 ; } int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) { const int n = items.size( ) ; int bestValues [ n ][ weightlimit ] ; std::set<int> solutionSets[ n ][ weightlimit ] ; std::set<int> emptyset ; for ( int i = 0 ; i < n ; i++ ) { for ( int j = 0 ; j < weightlimit ; j++ ) { bestValues[ i ][ j ] = 0 ; solutionSets[ i ][ j ] = emptyset ; } } for ( int i = 0 ; i < n ; i++ ) { for ( int weight = 0 ; weight < weightlimit ; weight++ ) { if ( i == 0 ) bestValues[ i ][ weight ] = 0 ; else { int itemweight = (items.begin( ) + i)->get<1>( ) ; if ( weight < itemweight ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } else { if ( bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) > bestValues[ i - 1 ][ weight ] ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight - itemweight ] ; solutionSets[ i ][ weight ].insert( i ) ; } else { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } } } } } bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ; return bestValues[ n - 1 ][ weightlimit - 1 ] ; }
Preserve the algorithm and functionality while converting the code from Java to C++.
import java.io.*; import java.util.*; public class PrimeDescendants { public static void main(String[] args) { try (Writer writer = new BufferedWriter(new OutputStreamWriter(System.out))) { printPrimeDesc(writer, 100); } catch (IOException ex) { ex.printStackTrace(); } } private static void printPrimeDesc(Writer writer, int limit) throws IOException { List<Long> primes = findPrimes(limit); List<Long> ancestor = new ArrayList<>(limit); List<List<Long>> descendants = new ArrayList<>(limit); for (int i = 0; i < limit; ++i) { ancestor.add(Long.valueOf(0)); descendants.add(new ArrayList<Long>()); } for (Long prime : primes) { int p = prime.intValue(); descendants.get(p).add(prime); for (int i = 0; i + p < limit; ++i) { int s = i + p; for (Long n : descendants.get(i)) { Long prod = n * p; descendants.get(s).add(prod); if (prod < limit) ancestor.set(prod.intValue(), Long.valueOf(s)); } } } int totalDescendants = 0; for (int i = 1; i < limit; ++i) { List<Long> ancestors = getAncestors(ancestor, i); writer.write("[" + i + "] Level: " + ancestors.size() + "\n"); writer.write("Ancestors: "); Collections.sort(ancestors); print(writer, ancestors); writer.write("Descendants: "); List<Long> desc = descendants.get(i); if (!desc.isEmpty()) { Collections.sort(desc); if (desc.get(0) == i) desc.remove(0); } writer.write(desc.size() + "\n"); totalDescendants += desc.size(); if (!desc.isEmpty()) print(writer, desc); writer.write("\n"); } writer.write("Total descendants: " + totalDescendants + "\n"); } private static List<Long> findPrimes(int limit) { boolean[] isprime = new boolean[limit]; Arrays.fill(isprime, true); isprime[0] = isprime[1] = false; for (int p = 2; p * p < limit; ++p) { if (isprime[p]) { for (int i = p * p; i < limit; i += p) isprime[i] = false; } } List<Long> primes = new ArrayList<>(); for (int p = 2; p < limit; ++p) { if (isprime[p]) primes.add(Long.valueOf(p)); } return primes; } private static List<Long> getAncestors(List<Long> ancestor, int n) { List<Long> result = new ArrayList<>(); for (Long a = ancestor.get(n); a != 0 && a != n; ) { n = a.intValue(); a = ancestor.get(n); result.add(Long.valueOf(n)); } return result; } private static void print(Writer writer, List<Long> list) throws IOException { if (list.isEmpty()) { writer.write("none\n"); return; } int i = 0; writer.write(String.valueOf(list.get(i++))); for (; i != list.size(); ++i) writer.write(", " + list.get(i)); writer.write("\n"); } }
#include <algorithm> #include <iostream> #include <vector> typedef unsigned long long integer; std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) { std::vector<integer> result; for (integer a = ancestor[n]; a != 0 && a != n; ) { n = a; a = ancestor[n]; result.push_back(n); } return result; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()) { std::cout << "none\n"; return; } auto i = vec.begin(); std::cout << *i++; for (; i != vec.end(); ++i) std::cout << ", " << *i; std::cout << '\n'; } bool is_prime(integer n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; for (integer p = 3; p * p <= n; p += 2) { if (n % p == 0) return false; } return true; } int main(int argc, char** argv) { const size_t limit = 100; std::vector<integer> ancestor(limit, 0); std::vector<std::vector<integer>> descendants(limit); for (size_t prime = 0; prime < limit; ++prime) { if (!is_prime(prime)) continue; descendants[prime].push_back(prime); for (size_t i = 0; i + prime < limit; ++i) { integer s = i + prime; for (integer n : descendants[i]) { integer prod = n * prime; descendants[s].push_back(prod); if (prod < limit) ancestor[prod] = s; } } } size_t total_descendants = 0; for (integer i = 1; i < limit; ++i) { std::vector<integer> ancestors(get_ancestors(ancestor, i)); std::cout << "[" << i << "] Level: " << ancestors.size() << '\n'; std::cout << "Ancestors: "; std::sort(ancestors.begin(), ancestors.end()); print_vector(ancestors); std::cout << "Descendants: "; std::vector<integer>& desc = descendants[i]; if (!desc.empty()) { std::sort(desc.begin(), desc.end()); if (desc[0] == i) desc.erase(desc.begin()); } std::cout << desc.size() << '\n'; total_descendants += desc.size(); if (!desc.empty()) print_vector(desc); std::cout << '\n'; } std::cout << "Total descendants: " << total_descendants << '\n'; return 0; }
Convert this Java snippet to C++ and keep its semantics consistent.
import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Optional.of; import static java.util.stream.Collectors.toList; import java.util.List; public class CartesianProduct { public List<?> product(List<?>... a) { if (a.length >= 2) { List<?> product = a[0]; for (int i = 1; i < a.length; i++) { product = product(product, a[i]); } return product; } return emptyList(); } private <A, B> List<?> product(List<A> a, List<B> b) { return of(a.stream() .map(e1 -> of(b.stream().map(e2 -> asList(e1, e2)).collect(toList())).orElse(emptyList())) .flatMap(List::stream) .collect(toList())).orElse(emptyList()); } }
#include <iostream> #include <vector> #include <algorithm> void print(const std::vector<std::vector<int>>& v) { std::cout << "{ "; for (const auto& p : v) { std::cout << "("; for (const auto& e : p) { std::cout << e << " "; } std::cout << ") "; } std::cout << "}" << std::endl; } auto product(const std::vector<std::vector<int>>& lists) { std::vector<std::vector<int>> result; if (std::find_if(std::begin(lists), std::end(lists), [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) { return result; } for (auto& e : lists[0]) { result.push_back({ e }); } for (size_t i = 1; i < lists.size(); ++i) { std::vector<std::vector<int>> temp; for (auto& e : result) { for (auto f : lists[i]) { auto e_tmp = e; e_tmp.push_back(f); temp.push_back(e_tmp); } } result = temp; } return result; } int main() { std::vector<std::vector<int>> prods[] = { { { 1, 2 }, { 3, 4 } }, { { 3, 4 }, { 1, 2} }, { { 1, 2 }, { } }, { { }, { 1, 2 } }, { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } }, { { 1, 2, 3 }, { 30 }, { 500, 100 } }, { { 1, 2, 3 }, { }, { 500, 100 } } }; for (const auto& p : prods) { print(product(p)); } std::cin.ignore(); std::cin.get(); return 0; }