Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into VB but keep the logic exactly as in C.
#include <stdio.h> #include <ctype.h> #include <stdlib.h> int main(int argc, char **argv) { typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State; typedef struct statechange { const int in; const State out; } statechange; #define MAXINPUTS 3 typedef struct FSM { const State state; void (*Action)(void); const statechange table[MAXINPUTS]; } FSM; char str[10]; void Ready(void) { fprintf(stderr, "\nMachine is READY. (D)eposit or (Q)uit :"); scanf("%s", str); } void Waiting(void) { fprintf(stderr, "(S)elect product or choose to (R)efund :"); scanf("%s", str); } void Refund(void) { fprintf(stderr, "Please collect refund.\n"); } void Dispense(void) { fprintf(stderr, "Dispensing product...\n"); } void Collect(void) { fprintf(stderr, "Please (C)ollect product. :"); scanf("%s", str); } void Quit(void) { fprintf(stderr, "Thank you, shutting down now.\n"); exit(0); } const FSM fsm[] = { { READY, &Ready, {{'D', WAITING}, {'Q', QUIT }, {-1, READY} }}, { WAITING, &Waiting, {{'S', DISPENSE}, {'R', REFUND}, {-1, WAITING} }}, { REFUND, &Refund, {{ -1, READY} }}, { DISPENSE, &Dispense, {{ -1, COLLECT} }}, { COLLECT, &Collect, {{'C', READY}, { -1, COLLECT } }}, { QUIT, &Quit, {{ -1, QUIT} }}, }; int each; State state = READY; for (;;) { fsm[state].Action(); each = 0; while (!( ((fsm[state].table[each].in == -1) || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++; state = fsm[state].table[each].out; } return 0; }
Enum states READY WAITING DISPENSE REFUND QU1T End Enum Public Sub finite_state_machine() Dim state As Integer: state = READY: ch = " " Do While True Debug.Print ch Select Case state Case READY: Debug.Print "Machine is READY. (D)eposit or (Q)uit :" Do While True If ch = "D" Then state = WAITING Exit Do End If If ch = "Q" Then state = QU1T Exit Do End If ch = InputBox("Machine is READY. (D)eposit or (Q)uit :") Loop Case WAITING: Debug.Print "(S)elect product or choose to (R)efund :" Do While True If ch = "S" Then state = DISPENSE Exit Do End If If ch = "R" Then state = REFUND Exit Do End If ch = InputBox("(S)elect product or choose to (R)efund :") Loop Case DISPENSE: Debug.Print "Dispensing product..." Do While True If ch = "C" Then state = READY Exit Do End If ch = InputBox("Please (C)ollect product. :") Loop Case REFUND: Debug.Print "Please collect refund." state = READY ch = " " Case QU1T: Debug.Print "Thank you, shutting down now." Exit Sub End Select Loop End Sub
Write the same algorithm in VB as shown in this C implementation.
#include <stdio.h> #include <ctype.h> #include <stdlib.h> int main(int argc, char **argv) { typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT } State; typedef struct statechange { const int in; const State out; } statechange; #define MAXINPUTS 3 typedef struct FSM { const State state; void (*Action)(void); const statechange table[MAXINPUTS]; } FSM; char str[10]; void Ready(void) { fprintf(stderr, "\nMachine is READY. (D)eposit or (Q)uit :"); scanf("%s", str); } void Waiting(void) { fprintf(stderr, "(S)elect product or choose to (R)efund :"); scanf("%s", str); } void Refund(void) { fprintf(stderr, "Please collect refund.\n"); } void Dispense(void) { fprintf(stderr, "Dispensing product...\n"); } void Collect(void) { fprintf(stderr, "Please (C)ollect product. :"); scanf("%s", str); } void Quit(void) { fprintf(stderr, "Thank you, shutting down now.\n"); exit(0); } const FSM fsm[] = { { READY, &Ready, {{'D', WAITING}, {'Q', QUIT }, {-1, READY} }}, { WAITING, &Waiting, {{'S', DISPENSE}, {'R', REFUND}, {-1, WAITING} }}, { REFUND, &Refund, {{ -1, READY} }}, { DISPENSE, &Dispense, {{ -1, COLLECT} }}, { COLLECT, &Collect, {{'C', READY}, { -1, COLLECT } }}, { QUIT, &Quit, {{ -1, QUIT} }}, }; int each; State state = READY; for (;;) { fsm[state].Action(); each = 0; while (!( ((fsm[state].table[each].in == -1) || (isalpha(str[0]) && fsm[state].table[each].in == toupper(str[0]) )))) each++; state = fsm[state].table[each].out; } return 0; }
Enum states READY WAITING DISPENSE REFUND QU1T End Enum Public Sub finite_state_machine() Dim state As Integer: state = READY: ch = " " Do While True Debug.Print ch Select Case state Case READY: Debug.Print "Machine is READY. (D)eposit or (Q)uit :" Do While True If ch = "D" Then state = WAITING Exit Do End If If ch = "Q" Then state = QU1T Exit Do End If ch = InputBox("Machine is READY. (D)eposit or (Q)uit :") Loop Case WAITING: Debug.Print "(S)elect product or choose to (R)efund :" Do While True If ch = "S" Then state = DISPENSE Exit Do End If If ch = "R" Then state = REFUND Exit Do End If ch = InputBox("(S)elect product or choose to (R)efund :") Loop Case DISPENSE: Debug.Print "Dispensing product..." Do While True If ch = "C" Then state = READY Exit Do End If ch = InputBox("Please (C)ollect product. :") Loop Case REFUND: Debug.Print "Please collect refund." state = READY ch = " " Case QU1T: Debug.Print "Thank you, shutting down now." Exit Sub End Select Loop End Sub
Produce a language-to-language conversion: from C to VB, same semantics.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> struct fp2 { int64_t x, y; }; uint64_t randULong(uint64_t min, uint64_t max) { uint64_t t = (uint64_t)rand(); return min + t % (max - min); } uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) { uint64_t x = 0, y = a % modulus; while (b > 0) { if ((b & 1) == 1) { x = (x + y) % modulus; } y = (y << 1) % modulus; b = b >> 1; } return x; } uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) { uint64_t x = 1; while (power > 0) { if ((power & 1) == 1) { x = mul_mod(x, b, modulus); } b = mul_mod(b, b, modulus); power = power >> 1; } return x; } bool isPrime(uint64_t n, int64_t k) { uint64_t a, x, n_one = n - 1, d = n_one; uint32_t s = 0; uint32_t r; if (n < 2) { return false; } if (n > 9223372036854775808ull) { printf("The number is too big, program will end.\n"); exit(1); } if ((n % 2) == 0) { return n == 2; } while ((d & 1) == 0) { d = d >> 1; s = s + 1; } while (k > 0) { k = k - 1; a = randULong(2, n); x = pow_mod(a, d, n); if (x == 1 || x == n_one) { continue; } for (r = 1; r < s; r++) { x = pow_mod(x, 2, n); if (x == 1) return false; if (x == n_one) goto continue_while; } if (x != n_one) { return false; } continue_while: {} } return true; } int64_t legendre_symbol(int64_t a, int64_t p) { int64_t x = pow_mod(a, (p - 1) / 2, p); if ((p - 1) == x) { return x - p; } else { return x; } } struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) { struct fp2 answer; uint64_t tmp1, tmp2; tmp1 = mul_mod(a.x, b.x, p); tmp2 = mul_mod(a.y, b.y, p); tmp2 = mul_mod(tmp2, w2, p); answer.x = (tmp1 + tmp2) % p; tmp1 = mul_mod(a.x, b.y, p); tmp2 = mul_mod(a.y, b.x, p); answer.y = (tmp1 + tmp2) % p; return answer; } struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) { return fp2mul(a, a, p, w2); } struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) { struct fp2 ret; if (n == 0) { ret.x = 1; ret.y = 0; return ret; } if (n == 1) { return a; } if ((n & 1) == 0) { return fp2square(fp2pow(a, n / 2, p, w2), p, w2); } else { return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2); } } void test(int64_t n, int64_t p) { int64_t a, w2; int64_t x1, x2; struct fp2 answer; printf("Find solution for n = %lld and p = %lld\n", n, p); if (p == 2 || !isPrime(p, 15)) { printf("No solution, p is not an odd prime.\n\n"); return; } if (legendre_symbol(n, p) != 1) { printf(" %lld is not a square in F%lld\n\n", n, p); return; } while (true) { do { a = randULong(2, p); w2 = a * a - n; } while (legendre_symbol(w2, p) != -1); answer.x = a; answer.y = 1; answer = fp2pow(answer, (p + 1) / 2, p, w2); if (answer.y != 0) { continue; } x1 = answer.x; x2 = p - x1; if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) { printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2); return; } } } int main() { srand((size_t)time(0)); test(10, 13); test(56, 101); test(8218, 10007); test(8219, 10007); test(331575, 1000003); test(665165880, 1000000007); return 0; }
Imports System.Numerics Module Module1 ReadOnly BIG = BigInteger.Pow(10, 50) + 151 Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean) Dim n = BigInteger.Parse(ns) Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG) Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p) If ls(n) <> 1 Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If Dim a = BigInteger.Zero Dim omega2 As BigInteger Do omega2 = (a * a + p - n) Mod p If ls(omega2) = p - 1 Then Exit Do End If a += 1 Loop Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger)) Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p) End Function Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero) Dim s = Tuple.Create(a, BigInteger.One) Dim nn = ((p + 1) >> 1) Mod p While nn > 0 If nn Mod 2 = 1 Then r = mul(r, s) End If s = mul(s, s) nn >>= 1 End While If r.Item2 <> 0 Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If If r.Item1 * r.Item1 Mod p <> n Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If Return Tuple.Create(r.Item1, p - r.Item1, True) End Function Sub Main() Console.WriteLine(C("10", "13")) Console.WriteLine(C("56", "101")) Console.WriteLine(C("8218", "10007")) Console.WriteLine(C("8219", "10007")) Console.WriteLine(C("331575", "1000003")) Console.WriteLine(C("665165880", "1000000007")) Console.WriteLine(C("881398088036", "1000000000039")) Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")) End Sub End Module
Port the provided C code into VB while preserving the original functionality.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> struct fp2 { int64_t x, y; }; uint64_t randULong(uint64_t min, uint64_t max) { uint64_t t = (uint64_t)rand(); return min + t % (max - min); } uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) { uint64_t x = 0, y = a % modulus; while (b > 0) { if ((b & 1) == 1) { x = (x + y) % modulus; } y = (y << 1) % modulus; b = b >> 1; } return x; } uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) { uint64_t x = 1; while (power > 0) { if ((power & 1) == 1) { x = mul_mod(x, b, modulus); } b = mul_mod(b, b, modulus); power = power >> 1; } return x; } bool isPrime(uint64_t n, int64_t k) { uint64_t a, x, n_one = n - 1, d = n_one; uint32_t s = 0; uint32_t r; if (n < 2) { return false; } if (n > 9223372036854775808ull) { printf("The number is too big, program will end.\n"); exit(1); } if ((n % 2) == 0) { return n == 2; } while ((d & 1) == 0) { d = d >> 1; s = s + 1; } while (k > 0) { k = k - 1; a = randULong(2, n); x = pow_mod(a, d, n); if (x == 1 || x == n_one) { continue; } for (r = 1; r < s; r++) { x = pow_mod(x, 2, n); if (x == 1) return false; if (x == n_one) goto continue_while; } if (x != n_one) { return false; } continue_while: {} } return true; } int64_t legendre_symbol(int64_t a, int64_t p) { int64_t x = pow_mod(a, (p - 1) / 2, p); if ((p - 1) == x) { return x - p; } else { return x; } } struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) { struct fp2 answer; uint64_t tmp1, tmp2; tmp1 = mul_mod(a.x, b.x, p); tmp2 = mul_mod(a.y, b.y, p); tmp2 = mul_mod(tmp2, w2, p); answer.x = (tmp1 + tmp2) % p; tmp1 = mul_mod(a.x, b.y, p); tmp2 = mul_mod(a.y, b.x, p); answer.y = (tmp1 + tmp2) % p; return answer; } struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) { return fp2mul(a, a, p, w2); } struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) { struct fp2 ret; if (n == 0) { ret.x = 1; ret.y = 0; return ret; } if (n == 1) { return a; } if ((n & 1) == 0) { return fp2square(fp2pow(a, n / 2, p, w2), p, w2); } else { return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2); } } void test(int64_t n, int64_t p) { int64_t a, w2; int64_t x1, x2; struct fp2 answer; printf("Find solution for n = %lld and p = %lld\n", n, p); if (p == 2 || !isPrime(p, 15)) { printf("No solution, p is not an odd prime.\n\n"); return; } if (legendre_symbol(n, p) != 1) { printf(" %lld is not a square in F%lld\n\n", n, p); return; } while (true) { do { a = randULong(2, p); w2 = a * a - n; } while (legendre_symbol(w2, p) != -1); answer.x = a; answer.y = 1; answer = fp2pow(answer, (p + 1) / 2, p, w2); if (answer.y != 0) { continue; } x1 = answer.x; x2 = p - x1; if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) { printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2); return; } } } int main() { srand((size_t)time(0)); test(10, 13); test(56, 101); test(8218, 10007); test(8219, 10007); test(331575, 1000003); test(665165880, 1000000007); return 0; }
Imports System.Numerics Module Module1 ReadOnly BIG = BigInteger.Pow(10, 50) + 151 Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean) Dim n = BigInteger.Parse(ns) Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG) Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p) If ls(n) <> 1 Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If Dim a = BigInteger.Zero Dim omega2 As BigInteger Do omega2 = (a * a + p - n) Mod p If ls(omega2) = p - 1 Then Exit Do End If a += 1 Loop Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger)) Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p) End Function Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero) Dim s = Tuple.Create(a, BigInteger.One) Dim nn = ((p + 1) >> 1) Mod p While nn > 0 If nn Mod 2 = 1 Then r = mul(r, s) End If s = mul(s, s) nn >>= 1 End While If r.Item2 <> 0 Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If If r.Item1 * r.Item1 Mod p <> n Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If Return Tuple.Create(r.Item1, p - r.Item1, True) End Function Sub Main() Console.WriteLine(C("10", "13")) Console.WriteLine(C("56", "101")) Console.WriteLine(C("8218", "10007")) Console.WriteLine(C("8219", "10007")) Console.WriteLine(C("331575", "1000003")) Console.WriteLine(C("665165880", "1000000007")) Console.WriteLine(C("881398088036", "1000000000039")) Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")) End Sub End Module
Translate the given C code snippet into VB without altering its behavior.
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> struct fp2 { int64_t x, y; }; uint64_t randULong(uint64_t min, uint64_t max) { uint64_t t = (uint64_t)rand(); return min + t % (max - min); } uint64_t mul_mod(uint64_t a, uint64_t b, uint64_t modulus) { uint64_t x = 0, y = a % modulus; while (b > 0) { if ((b & 1) == 1) { x = (x + y) % modulus; } y = (y << 1) % modulus; b = b >> 1; } return x; } uint64_t pow_mod(uint64_t b, uint64_t power, uint64_t modulus) { uint64_t x = 1; while (power > 0) { if ((power & 1) == 1) { x = mul_mod(x, b, modulus); } b = mul_mod(b, b, modulus); power = power >> 1; } return x; } bool isPrime(uint64_t n, int64_t k) { uint64_t a, x, n_one = n - 1, d = n_one; uint32_t s = 0; uint32_t r; if (n < 2) { return false; } if (n > 9223372036854775808ull) { printf("The number is too big, program will end.\n"); exit(1); } if ((n % 2) == 0) { return n == 2; } while ((d & 1) == 0) { d = d >> 1; s = s + 1; } while (k > 0) { k = k - 1; a = randULong(2, n); x = pow_mod(a, d, n); if (x == 1 || x == n_one) { continue; } for (r = 1; r < s; r++) { x = pow_mod(x, 2, n); if (x == 1) return false; if (x == n_one) goto continue_while; } if (x != n_one) { return false; } continue_while: {} } return true; } int64_t legendre_symbol(int64_t a, int64_t p) { int64_t x = pow_mod(a, (p - 1) / 2, p); if ((p - 1) == x) { return x - p; } else { return x; } } struct fp2 fp2mul(struct fp2 a, struct fp2 b, int64_t p, int64_t w2) { struct fp2 answer; uint64_t tmp1, tmp2; tmp1 = mul_mod(a.x, b.x, p); tmp2 = mul_mod(a.y, b.y, p); tmp2 = mul_mod(tmp2, w2, p); answer.x = (tmp1 + tmp2) % p; tmp1 = mul_mod(a.x, b.y, p); tmp2 = mul_mod(a.y, b.x, p); answer.y = (tmp1 + tmp2) % p; return answer; } struct fp2 fp2square(struct fp2 a, int64_t p, int64_t w2) { return fp2mul(a, a, p, w2); } struct fp2 fp2pow(struct fp2 a, int64_t n, int64_t p, int64_t w2) { struct fp2 ret; if (n == 0) { ret.x = 1; ret.y = 0; return ret; } if (n == 1) { return a; } if ((n & 1) == 0) { return fp2square(fp2pow(a, n / 2, p, w2), p, w2); } else { return fp2mul(a, fp2pow(a, n - 1, p, w2), p, w2); } } void test(int64_t n, int64_t p) { int64_t a, w2; int64_t x1, x2; struct fp2 answer; printf("Find solution for n = %lld and p = %lld\n", n, p); if (p == 2 || !isPrime(p, 15)) { printf("No solution, p is not an odd prime.\n\n"); return; } if (legendre_symbol(n, p) != 1) { printf(" %lld is not a square in F%lld\n\n", n, p); return; } while (true) { do { a = randULong(2, p); w2 = a * a - n; } while (legendre_symbol(w2, p) != -1); answer.x = a; answer.y = 1; answer = fp2pow(answer, (p + 1) / 2, p, w2); if (answer.y != 0) { continue; } x1 = answer.x; x2 = p - x1; if (mul_mod(x1, x1, p) == n && mul_mod(x2, x2, p) == n) { printf("Solution found: x1 = %lld, x2 = %lld\n\n", x1, x2); return; } } } int main() { srand((size_t)time(0)); test(10, 13); test(56, 101); test(8218, 10007); test(8219, 10007); test(331575, 1000003); test(665165880, 1000000007); return 0; }
Imports System.Numerics Module Module1 ReadOnly BIG = BigInteger.Pow(10, 50) + 151 Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean) Dim n = BigInteger.Parse(ns) Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG) Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p) If ls(n) <> 1 Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If Dim a = BigInteger.Zero Dim omega2 As BigInteger Do omega2 = (a * a + p - n) Mod p If ls(omega2) = p - 1 Then Exit Do End If a += 1 Loop Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger)) Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p) End Function Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero) Dim s = Tuple.Create(a, BigInteger.One) Dim nn = ((p + 1) >> 1) Mod p While nn > 0 If nn Mod 2 = 1 Then r = mul(r, s) End If s = mul(s, s) nn >>= 1 End While If r.Item2 <> 0 Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If If r.Item1 * r.Item1 Mod p <> n Then Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False) End If Return Tuple.Create(r.Item1, p - r.Item1, True) End Function Sub Main() Console.WriteLine(C("10", "13")) Console.WriteLine(C("56", "101")) Console.WriteLine(C("8218", "10007")) Console.WriteLine(C("8219", "10007")) Console.WriteLine(C("331575", "1000003")) Console.WriteLine(C("665165880", "1000000007")) Console.WriteLine(C("881398088036", "1000000000039")) Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")) End Sub End Module
Rewrite this program in VB while keeping its functionality equivalent to the C version.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #include<time.h> #define pi M_PI int main(){ time_t t; double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0; int i,iter,choice,numSides; printf("Enter number of sides : "); scanf("%d",&numSides); printf("Enter polygon side length : "); scanf("%lf",&side); printf("Enter number of iterations : "); scanf("%d",&iter); initwindow(windowSide,windowSide,"Polygon Chaos"); vertices = (double**)malloc(numSides*sizeof(double*)); for(i=0;i<numSides;i++){ vertices[i] = (double*)malloc(2 * sizeof(double)); vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides); vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides); sumX+= vertices[i][0]; sumY+= vertices[i][1]; putpixel(vertices[i][0],vertices[i][1],15); } srand((unsigned)time(&t)); seedX = sumX/numSides; seedY = sumY/numSides; putpixel(seedX,seedY,15); for(i=0;i<iter;i++){ choice = rand()%numSides; seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1); seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1); putpixel(seedX,seedY,15); } free(vertices); getch(); closegraph(); return 0; }
Private Sub sierpinski(Order_ As Integer, Side As Double) Dim Circumradius As Double, Inradius As Double Dim Height As Double, Diagonal As Double, HeightDiagonal As Double Dim Pi As Double, p(5) As String, Shp As Shape Circumradius = Sqr(50 + 10 * Sqr(5)) / 10 Inradius = Sqr(25 + 10 * Sqr(5)) / 10 Height = Circumradius + Inradius Diagonal = (1 + Sqr(5)) / 2 HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4 Pi = WorksheetFunction.Pi Ratio = Height / (2 * Height + HeightDiagonal) Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _ 2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side) p(0) = Shp.Name Shp.Rotation = 180 Shp.Line.Weight = 0 For j = 1 To Order_ For i = 0 To 4 Set Shp = Shp.Duplicate p(i + 1) = Shp.Name If i = 0 Then Shp.Rotation = 0 Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5) Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5) Shp.Visible = msoTrue Next i Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group p(0) = Shp.Name If j < Order_ Then Shp.ScaleHeight Ratio, False Shp.ScaleWidth Ratio, False Shp.Rotation = 180 Shp.Left = 2 * Side Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side End If Next j End Sub Public Sub main() sierpinski Order_:=5, Side:=200 End Sub
Can you help me rewrite this code in VB instead of C, keeping it the same logically?
#include <stdio.h> #include <string.h> int repstr(char *str) { if (!str) return 0; size_t sl = strlen(str) / 2; while (sl > 0) { if (strstr(str, str + sl) == str) return sl; --sl; } return 0; } int main(void) { char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1" }; size_t strslen = sizeof(strs) / sizeof(strs[0]); size_t i; for (i = 0; i < strslen; ++i) { int n = repstr(strs[i]); if (n) printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]); else printf("\"%s\" = not a rep-string\n", strs[i]); } return 0; }
Function rep_string(s) max_len = Int(Len(s)/2) tmp = "" If max_len = 0 Then rep_string = "No Repeating String" Exit Function End If For i = 1 To max_len If InStr(i+1,s,tmp & Mid(s,i,1))Then tmp = tmp & Mid(s,i,1) Else Exit For End If Next Do While Len(tmp) > 0 If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then rep_string = tmp Exit Do Else tmp = Mid(tmp,1,Len(tmp)-1) End If Loop If Len(tmp) > 0 Then rep_string = tmp Else rep_string = "No Repeating String" End If End Function arr = Array("1001110011","1110111011","0010010010","1010101010",_ "1111111111","0100101101","0100100","101","11","00","1") For n = 0 To UBound(arr) WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n)) WScript.StdOut.WriteLine Next
Rewrite this program in VB while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <string.h> int repstr(char *str) { if (!str) return 0; size_t sl = strlen(str) / 2; while (sl > 0) { if (strstr(str, str + sl) == str) return sl; --sl; } return 0; } int main(void) { char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1" }; size_t strslen = sizeof(strs) / sizeof(strs[0]); size_t i; for (i = 0; i < strslen; ++i) { int n = repstr(strs[i]); if (n) printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]); else printf("\"%s\" = not a rep-string\n", strs[i]); } return 0; }
Function rep_string(s) max_len = Int(Len(s)/2) tmp = "" If max_len = 0 Then rep_string = "No Repeating String" Exit Function End If For i = 1 To max_len If InStr(i+1,s,tmp & Mid(s,i,1))Then tmp = tmp & Mid(s,i,1) Else Exit For End If Next Do While Len(tmp) > 0 If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then rep_string = tmp Exit Do Else tmp = Mid(tmp,1,Len(tmp)-1) End If Loop If Len(tmp) > 0 Then rep_string = tmp Else rep_string = "No Repeating String" End If End Function arr = Array("1001110011","1110111011","0010010010","1010101010",_ "1111111111","0100101101","0100100","101","11","00","1") For n = 0 To UBound(arr) WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n)) WScript.StdOut.WriteLine Next
Preserve the algorithm and functionality while converting the code from C to VB.
#include<windows.h> #include<stdio.h> int main() { printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN)); return 0; }
TYPE syswindowstru screenheight AS INTEGER screenwidth AS INTEGER maxheight AS INTEGER maxwidth AS INTEGER END TYPE DIM syswindow AS syswindowstru syswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX syswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY
Produce a functionally identical VB code for the snippet given in C.
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
Enum fruits apple banana cherry End Enum Enum fruits2 pear = 5 mango = 10 kiwi = 20 pineapple = 20 End Enum Sub test() Dim f As fruits f = apple Debug.Print "apple equals "; f Debug.Print "kiwi equals "; kiwi Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple End Sub
Please provide an equivalent version of this C code in VB.
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY", "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" }; int stroke=0,fill=0,back=0,i; double centerX = 300,centerY = 300,coreSide,armLength,pentaLength; printf("Enter core pentagon side length : "); scanf("%lf",&coreSide); printf("Enter pentagram arm length : "); scanf("%lf",&armLength); printf("Available colours are :\n"); for(i=0;i<16;i++){ printf("%d. %s\t",i+1,colourNames[i]); if((i+1) % 3 == 0){ printf("\n"); } } while(stroke==fill && fill==back){ printf("\nEnter three diffrenet options for stroke, fill and background : "); scanf("%d%d%d",&stroke,&fill,&back); } pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4); initwindow(2*centerX,2*centerY,"Pentagram"); setcolor(stroke-1); setfillstyle(SOLID_FILL,back-1); bar(0,0,2*centerX,2*centerY); floodfill(centerX,centerY,back-1); setfillstyle(SOLID_FILL,fill-1); for(i=0;i<5;i++){ line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5))); line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1); } floodfill(centerX,centerY,stroke-1); getch(); closegraph(); }
Sub pentagram() With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400) .Fill.ForeColor.RGB = RGB(255, 0, 0) .Line.Weight = 3 .Line.ForeColor.RGB = RGB(0, 0, 255) End With End Sub
Can you help me rewrite this code in VB instead of C, keeping it the same logically?
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY", "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" }; int stroke=0,fill=0,back=0,i; double centerX = 300,centerY = 300,coreSide,armLength,pentaLength; printf("Enter core pentagon side length : "); scanf("%lf",&coreSide); printf("Enter pentagram arm length : "); scanf("%lf",&armLength); printf("Available colours are :\n"); for(i=0;i<16;i++){ printf("%d. %s\t",i+1,colourNames[i]); if((i+1) % 3 == 0){ printf("\n"); } } while(stroke==fill && fill==back){ printf("\nEnter three diffrenet options for stroke, fill and background : "); scanf("%d%d%d",&stroke,&fill,&back); } pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4); initwindow(2*centerX,2*centerY,"Pentagram"); setcolor(stroke-1); setfillstyle(SOLID_FILL,back-1); bar(0,0,2*centerX,2*centerY); floodfill(centerX,centerY,back-1); setfillstyle(SOLID_FILL,fill-1); for(i=0;i<5;i++){ line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5))); line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1); } floodfill(centerX,centerY,stroke-1); getch(); closegraph(); }
Sub pentagram() With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400) .Fill.ForeColor.RGB = RGB(255, 0, 0) .Line.Weight = 3 .Line.ForeColor.RGB = RGB(0, 0, 255) End With End Sub
Translate the given C code snippet into VB without altering its behavior.
#include<graphics.h> #include<stdio.h> #include<math.h> #define pi M_PI int main(){ char colourNames[][14] = { "BLACK", "BLUE", "GREEN", "CYAN", "RED", "MAGENTA", "BROWN", "LIGHTGRAY", "DARKGRAY", "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN", "LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE" }; int stroke=0,fill=0,back=0,i; double centerX = 300,centerY = 300,coreSide,armLength,pentaLength; printf("Enter core pentagon side length : "); scanf("%lf",&coreSide); printf("Enter pentagram arm length : "); scanf("%lf",&armLength); printf("Available colours are :\n"); for(i=0;i<16;i++){ printf("%d. %s\t",i+1,colourNames[i]); if((i+1) % 3 == 0){ printf("\n"); } } while(stroke==fill && fill==back){ printf("\nEnter three diffrenet options for stroke, fill and background : "); scanf("%d%d%d",&stroke,&fill,&back); } pentaLength = coreSide/(2 * tan(pi/5)) + sqrt(armLength*armLength - coreSide*coreSide/4); initwindow(2*centerX,2*centerY,"Pentagram"); setcolor(stroke-1); setfillstyle(SOLID_FILL,back-1); bar(0,0,2*centerX,2*centerY); floodfill(centerX,centerY,back-1); setfillstyle(SOLID_FILL,fill-1); for(i=0;i<5;i++){ line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5))); line(centerX + coreSide*cos(i*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); line(centerX + coreSide*cos((i+1)*2*pi/5)/(2*sin(pi/5)),centerY + coreSide*sin((i+1)*2*pi/5)/(2*sin(pi/5)),centerX + pentaLength*cos(i*2*pi/5 + pi/5),centerY + pentaLength*sin(i*2*pi/5 + pi/5)); floodfill(centerX + coreSide*cos(i*2*pi/5 + pi/10)/(2*sin(pi/5)),centerY + coreSide*sin(i*2*pi/5 + pi/10)/(2*sin(pi/5)),stroke-1); } floodfill(centerX,centerY,stroke-1); getch(); closegraph(); }
Sub pentagram() With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400) .Fill.ForeColor.RGB = RGB(255, 0, 0) .Line.Weight = 3 .Line.ForeColor.RGB = RGB(0, 0, 255) End With End Sub
Preserve the algorithm and functionality while converting the code from C to VB.
#include <string.h> #include <memory.h> static unsigned int _parseDecimal ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' ) { nVal *= 10; nVal += chNow - '0'; ++*pchCursor; } return nVal; } static unsigned int _parseHex ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor & 0x5f, (chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) || (chNow >= 'A' && chNow <= 'F') ) { unsigned char nybbleValue; chNow -= 0x10; nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow ); nVal <<= 4; nVal += nybbleValue; ++*pchCursor; } return nVal; } int ParseIPv4OrIPv6 ( const char** ppszText, unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 ) { unsigned char* abyAddrLocal; unsigned char abyDummyAddr[16]; const char* pchColon = strchr ( *ppszText, ':' ); const char* pchDot = strchr ( *ppszText, '.' ); const char* pchOpenBracket = strchr ( *ppszText, '[' ); const char* pchCloseBracket = NULL; int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot || ( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) ); if ( bIsIPv6local ) { pchCloseBracket = strchr ( *ppszText, ']' ); if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket || pchCloseBracket < pchOpenBracket ) ) return 0; } else { if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) ) return 0; } if ( NULL != pbIsIPv6 ) *pbIsIPv6 = bIsIPv6local; abyAddrLocal = abyAddr; if ( NULL == abyAddrLocal ) abyAddrLocal = abyDummyAddr; if ( ! bIsIPv6local ) { unsigned char* pbyAddrCursor = abyAddrLocal; unsigned int nVal; const char* pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 255 || pszTextBefore == *ppszText ) return 0; *(pbyAddrCursor++) = (unsigned char) nVal; if ( ':' == **ppszText && NULL != pnPort ) { unsigned short usPortNetwork; ++(*ppszText); pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 65535 || pszTextBefore == *ppszText ) return 0; ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8; ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff ); *pnPort = usPortNetwork; return 1; } else { if ( NULL != pnPort ) *pnPort = 0; return 1; } } else { unsigned char* pbyAddrCursor; unsigned char* pbyZerosLoc; int bIPv4Detected; int nIdx; if ( NULL != pchOpenBracket ) *ppszText = pchOpenBracket + 1; pbyAddrCursor = abyAddrLocal; pbyZerosLoc = NULL; bIPv4Detected = 0; for ( nIdx = 0; nIdx < 8; ++nIdx ) { const char* pszTextBefore = *ppszText; unsigned nVal =_parseHex ( ppszText ); if ( pszTextBefore == *ppszText ) { if ( NULL != pbyZerosLoc ) { if ( pbyZerosLoc == pbyAddrCursor ) { --nIdx; break; } return 0; } if ( ':' != **ppszText ) return 0; if ( 0 == nIdx ) { ++(*ppszText); if ( ':' != **ppszText ) return 0; } pbyZerosLoc = pbyAddrCursor; ++(*ppszText); } else { if ( '.' == **ppszText ) { const char* pszTextlocal = pszTextBefore; unsigned char abyAddrlocal[16]; int bIsIPv6local; int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local ); *ppszText = pszTextlocal; if ( ! bParseResultlocal || bIsIPv6local ) return 0; *(pbyAddrCursor++) = abyAddrlocal[0]; *(pbyAddrCursor++) = abyAddrlocal[1]; *(pbyAddrCursor++) = abyAddrlocal[2]; *(pbyAddrCursor++) = abyAddrlocal[3]; ++nIdx; bIPv4Detected = 1; break; } if ( nVal > 65535 ) return 0; *(pbyAddrCursor++) = nVal >> 8; *(pbyAddrCursor++) = nVal & 0xff; if ( ':' == **ppszText ) { ++(*ppszText); } else { break; } } } if ( NULL != pbyZerosLoc ) { int nHead = (int)( pbyZerosLoc - abyAddrLocal ); int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); int nZeros = 16 - nTail - nHead; memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail ); memset ( pbyZerosLoc, 0, nZeros ); } if ( bIPv4Detected ) { static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff }; if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) ) return 0; } if ( NULL != pchOpenBracket ) { if ( ']' != **ppszText ) return 0; ++(*ppszText); } if ( ':' == **ppszText && NULL != pnPort ) { const char* pszTextBefore; unsigned int nVal; unsigned short usPortNetwork; ++(*ppszText); pszTextBefore = *ppszText; pszTextBefore = *ppszText; nVal =_parseDecimal ( ppszText ); if ( nVal > 65535 || pszTextBefore == *ppszText ) return 0; ((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8; ((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff ); *pnPort = usPortNetwork; return 1; } else { if ( NULL != pnPort ) *pnPort = 0; return 1; } } } int ParseIPv4OrIPv6_2 ( const char* pszText, unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 ) { const char* pszTextLocal = pszText; return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6); }
Function parse_ip(addr) Set ipv4_pattern = New RegExp ipv4_pattern.Global = True ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}" Set ipv6_pattern = New RegExp ipv6_pattern.Global = True ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}" If ipv4_pattern.Test(addr) Then port = Split(addr,":") octet = Split(port(0),".") ipv4_hex = "" For i = 0 To UBound(octet) If octet(i) <= 255 And octet(i) >= 0 Then ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2) Else ipv4_hex = "Erroneous Address" Exit For End If Next parse_ip = "Test Case: " & addr & vbCrLf &_ "Address: " & ipv4_hex & vbCrLf If UBound(port) = 1 Then If port(1) <= 65535 And port(1) >= 0 Then parse_ip = parse_ip & "Port: " & port(1) & vbCrLf Else parse_ip = parse_ip & "Port: Invalid" & vbCrLf End If End If End If If ipv6_pattern.Test(addr) Then parse_ip = "Test Case: " & addr & vbCrLf port_v6 = "Port: " ipv6_hex = "" If InStr(1,addr,"[") Then port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1))) addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1)) End If word = Split(addr,":") word_count = 0 For i = 0 To UBound(word) If word(i) = "" Then If i < UBound(word) Then If Int((7-(i+1))/2) = 1 Then k = 1 ElseIf UBound(word) < 6 Then k = Int((7-(i+1))/2) ElseIf UBound(word) >= 6 Then k = Int((7-(i+1))/2)-1 End If For j = 0 To k ipv6_hex = ipv6_hex & "0000" word_count = word_count + 1 Next Else For j = 0 To (7-word_count) ipv6_hex = ipv6_hex & "0000" Next End If Else ipv6_hex = ipv6_hex & Right("0000" & word(i),4) word_count = word_count + 1 End If Next parse_ip = parse_ip & "Address: " & ipv6_hex &_ vbCrLf & port_v6 & vbCrLf End If If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then parse_ip = "Test Case: " & addr & vbCrLf &_ "Address: Invalid Address" & vbCrLf End If End Function ip_arr = Array("127.0.0.1","127.0.0.1:80","::1",_ "[::1]:80","2605:2700:0:3::4713:93e3","[2605:2700:0:3::4713:93e3]:80","RosettaCode") For n = 0 To UBound(ip_arr) WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf Next
Produce a language-to-language conversion: from C to VB, same semantics.
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; double value; double weight; double volume; } item_t; item_t items[] = { {"panacea", 3000.0, 0.3, 0.025}, {"ichor", 1800.0, 0.2, 0.015}, {"gold", 2500.0, 2.0, 0.002}, }; int n = sizeof (items) / sizeof (item_t); int *count; int *best; double best_value; void knapsack (int i, double value, double weight, double volume) { int j, m1, m2, m; if (i == n) { if (value > best_value) { best_value = value; for (j = 0; j < n; j++) { best[j] = count[j]; } } return; } m1 = weight / items[i].weight; m2 = volume / items[i].volume; m = m1 < m2 ? m1 : m2; for (count[i] = m; count[i] >= 0; count[i]--) { knapsack( i + 1, value + count[i] * items[i].value, weight - count[i] * items[i].weight, volume - count[i] * items[i].volume ); } } int main () { count = malloc(n * sizeof (int)); best = malloc(n * sizeof (int)); best_value = 0; knapsack(0, 0.0, 25.0, 0.25); int i; for (i = 0; i < n; i++) { printf("%d %s\n", best[i], items[i].name); } printf("best value: %.0f\n", best_value); free(count); free(best); return 0; }
Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function Sub Main() Const Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5 Dim P&, I&, G&, A&, M, Cur(Value To Volume) Dim S As New Collection: S.Add Array(0) Const SackW = 25, SackV = 0.25 Dim Panacea: Panacea = Array(3000, 0.3, 0.025) Dim Ichor: Ichor = Array(1800, 0.2, 0.015) Dim Gold: Gold = Array(2500, 2, 0.002) For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume))) For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume))) For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume))) For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _ S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1 Next G, I, P Debug.Print "Value", "Weight", "Volume", "PanaceaCount", "IchorCount", "GoldCount" For Each M In S If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC) Next End Sub
Rewrite this program in VB while keeping its functionality equivalent to the C version.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <glib.h> char text_char(char c) { switch (c) { case 'a': case 'b': case 'c': return '2'; case 'd': case 'e': case 'f': return '3'; case 'g': case 'h': case 'i': return '4'; case 'j': case 'k': case 'l': return '5'; case 'm': case 'n': case 'o': return '6'; case 'p': case 'q': case 'r': case 's': return '7'; case 't': case 'u': case 'v': return '8'; case 'w': case 'x': case 'y': case 'z': return '9'; default: return 0; } } bool text_string(const GString* word, GString* text) { g_string_set_size(text, word->len); for (size_t i = 0; i < word->len; ++i) { char c = text_char(g_ascii_tolower(word->str[i])); if (c == 0) return false; text->str[i] = c; } return true; } typedef struct textonym_tag { const char* text; size_t length; GPtrArray* words; } textonym_t; int compare_by_text_length(const void* p1, const void* p2) { const textonym_t* t1 = p1; const textonym_t* t2 = p2; if (t1->length > t2->length) return -1; if (t1->length < t2->length) return 1; return strcmp(t1->text, t2->text); } int compare_by_word_count(const void* p1, const void* p2) { const textonym_t* t1 = p1; const textonym_t* t2 = p2; if (t1->words->len > t2->words->len) return -1; if (t1->words->len < t2->words->len) return 1; return strcmp(t1->text, t2->text); } void print_words(GPtrArray* words) { for (guint i = 0, n = words->len; i < n; ++i) { if (i > 0) printf(", "); printf("%s", g_ptr_array_index(words, i)); } printf("\n"); } void print_top_words(GArray* textonyms, guint top) { for (guint i = 0; i < top; ++i) { const textonym_t* t = &g_array_index(textonyms, textonym_t, i); printf("%s = ", t->text); print_words(t->words); } } void free_strings(gpointer ptr) { g_ptr_array_free(ptr, TRUE); } bool find_textonyms(const char* filename, GError** error_ptr) { GError* error = NULL; GIOChannel* channel = g_io_channel_new_file(filename, "r", &error); if (channel == NULL) { g_propagate_error(error_ptr, error); return false; } GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, free_strings); GString* word = g_string_sized_new(64); GString* text = g_string_sized_new(64); guint count = 0; gsize term_pos; while (g_io_channel_read_line_string(channel, word, &term_pos, &error) == G_IO_STATUS_NORMAL) { g_string_truncate(word, term_pos); if (!text_string(word, text)) continue; GPtrArray* words = g_hash_table_lookup(ht, text->str); if (words == NULL) { words = g_ptr_array_new_full(1, g_free); g_hash_table_insert(ht, g_strdup(text->str), words); } g_ptr_array_add(words, g_strdup(word->str)); ++count; } g_io_channel_unref(channel); g_string_free(word, TRUE); g_string_free(text, TRUE); if (error != NULL) { g_propagate_error(error_ptr, error); g_hash_table_destroy(ht); return false; } GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t)); GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, ht); while (g_hash_table_iter_next(&iter, &key, &value)) { GPtrArray* v = value; if (v->len > 1) { textonym_t textonym; textonym.text = key; textonym.length = strlen(key); textonym.words = v; g_array_append_val(words, textonym); } } printf("There are %u words in '%s' which can be represented by the digit key mapping.\n", count, filename); guint size = g_hash_table_size(ht); printf("They require %u digit combinations to represent them.\n", size); guint textonyms = words->len; printf("%u digit combinations represent Textonyms.\n", textonyms); guint top = 5; if (textonyms < top) top = textonyms; printf("\nTop %u by number of words:\n", top); g_array_sort(words, compare_by_word_count); print_top_words(words, top); printf("\nTop %u by length:\n", top); g_array_sort(words, compare_by_text_length); print_top_words(words, top); g_array_free(words, TRUE); g_hash_table_destroy(ht); return true; } int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s word-list\n", argv[0]); return EXIT_FAILURE; } GError* error = NULL; if (!find_textonyms(argv[1], &error)) { if (error != NULL) { fprintf(stderr, "%s: %s\n", argv[1], error->message); g_error_free(error); } return EXIT_FAILURE; } return EXIT_SUCCESS; }
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1) Set objKeyMap = CreateObject("Scripting.Dictionary") With objKeyMap .Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5" .Add "MNO", "6" : .Add "PQRS", "7" : .Add "TUV", "8" : .Add "WXYZ", "9" End With TotalWords = 0 UniqueCombinations = 0 Set objUniqueWords = CreateObject("Scripting.Dictionary") Set objMoreThanOneWord = CreateObject("Scripting.Dictionary") Do Until objInFile.AtEndOfStream Word = objInFile.ReadLine c = 0 Num = "" If Word <> "" Then For i = 1 To Len(Word) For Each Key In objKeyMap.Keys If InStr(1,Key,Mid(Word,i,1),1) > 0 Then Num = Num & objKeyMap.Item(Key) c = c + 1 End If Next Next If c = Len(Word) Then TotalWords = TotalWords + 1 If objUniqueWords.Exists(Num) = False Then objUniqueWords.Add Num, "" UniqueCombinations = UniqueCombinations + 1 Else If objMoreThanOneWord.Exists(Num) = False Then objMoreThanOneWord.Add Num, "" End If End If End If End If Loop WScript.Echo "There are " & TotalWords & " words in ""unixdict.txt"" which can be represented by the digit key mapping." & vbCrLf &_ "They require " & UniqueCombinations & " digit combinations to represent them." & vbCrLf &_ objMoreThanOneWord.Count & " digit combinations represent Textonyms." objInFile.Close
Transform the following C implementation into VB, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> size_t rprint(char *s, int *x, int len) { #define sep (a > s ? "," : "") #define ol (s ? 100 : 0) int i, j; char *a = s; for (i = j = 0; i < len; i = ++j) { for (; j < len - 1 && x[j + 1] == x[j] + 1; j++); if (i + 1 < j) a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]); else while (i <= j) a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]); } return a - s; #undef sep #undef ol } int main() { int x[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1); rprint(s, x, sizeof(x) / sizeof(int)); printf("%s\n", s); return 0; }
Public Function RangeExtraction(AList) As String Const RangeDelim = "-" Dim result As String Dim InRange As Boolean Dim Posn, ub, lb, rangestart, rangelen As Integer result = "" ub = UBound(AList) lb = LBound(AList) Posn = lb While Posn < ub rangestart = Posn rangelen = 0 InRange = True While InRange rangelen = rangelen + 1 If Posn = ub Then InRange = False Else InRange = (AList(Posn + 1) = AList(Posn) + 1) Posn = Posn + 1 End If Wend If rangelen > 2 Then result = result & "," & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1)) Else For i = rangestart To rangestart + rangelen - 1 result = result & "," & Format$(AList(i)) Next End If Posn = rangestart + rangelen Wend RangeExtraction = Mid$(result, 2) End Function Public Sub RangeTest() Dim MyList As Variant MyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39) Debug.Print "a) "; RangeExtraction(MyList) Dim MyOtherList(1 To 20) As Integer MyOtherList(1) = -6 MyOtherList(2) = -3 MyOtherList(3) = -2 MyOtherList(4) = -1 MyOtherList(5) = 0 MyOtherList(6) = 1 MyOtherList(7) = 3 MyOtherList(8) = 4 MyOtherList(9) = 5 MyOtherList(10) = 7 MyOtherList(11) = 8 MyOtherList(12) = 9 MyOtherList(13) = 10 MyOtherList(14) = 11 MyOtherList(15) = 14 MyOtherList(16) = 15 MyOtherList(17) = 17 MyOtherList(18) = 18 MyOtherList(19) = 19 MyOtherList(20) = 20 Debug.Print "b) "; RangeExtraction(MyOtherList) End Sub
Produce a language-to-language conversion: from C to VB, same semantics.
#include<stdio.h> #include<ctype.h> void typeDetector(char* str){ if(isalnum(str[0])!=0) printf("\n%c is alphanumeric",str[0]); if(isalpha(str[0])!=0) printf("\n%c is alphabetic",str[0]); if(iscntrl(str[0])!=0) printf("\n%c is a control character",str[0]); if(isdigit(str[0])!=0) printf("\n%c is a digit",str[0]); if(isprint(str[0])!=0) printf("\n%c is printable",str[0]); if(ispunct(str[0])!=0) printf("\n%c is a punctuation character",str[0]); if(isxdigit(str[0])!=0) printf("\n%c is a hexadecimal digit",str[0]); } int main(int argC, char* argV[]) { int i; if(argC==1) printf("Usage : %s <followed by ASCII characters>"); else{ for(i=1;i<argC;i++) typeDetector(argV[i]); } return 0; }
Public Sub main() Dim c(1) As Currency Dim d(1) As Double Dim dt(1) As Date Dim a(1) As Integer Dim l(1) As Long Dim s(1) As Single Dim e As Variant Dim o As Object Set o = New Application Debug.Print TypeName(o) Debug.Print TypeName(1 = 1) Debug.Print TypeName(CByte(1)) Set o = New Collection Debug.Print TypeName(o) Debug.Print TypeName(1@) Debug.Print TypeName(c) Debug.Print TypeName(CDate(1)) Debug.Print TypeName(dt) Debug.Print TypeName(CDec(1)) Debug.Print TypeName(1#) Debug.Print TypeName(d) Debug.Print TypeName(e) Debug.Print TypeName(CVErr(1)) Debug.Print TypeName(1) Debug.Print TypeName(a) Debug.Print TypeName(1&) Debug.Print TypeName(l) Set o = Nothing Debug.Print TypeName(o) Debug.Print TypeName([A1]) Debug.Print TypeName(1!) Debug.Print TypeName(s) Debug.Print TypeName(CStr(1)) Debug.Print TypeName(Worksheets(1)) End Sub
Maintain the same structure and functionality when rewriting this code in VB.
#include <stdio.h> #include <math.h> #define max(x,y) ((x) > (y) ? (x) : (y)) int tri[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; int main(void) { const int len = sizeof(tri) / sizeof(tri[0]); const int base = (sqrt(8*len + 1) - 1) / 2; int step = base - 1; int stepc = 0; int i; for (i = len - base - 1; i >= 0; --i) { tri[i] += max(tri[i + step], tri[i + step + 1]); if (++stepc == step) { step--; stepc = 0; } } printf("%d\n", tri[0]); return 0; }
Set objfso = CreateObject("Scripting.FileSystemObject") Set objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\triangle.txt",1,False) row = Split(objinfile.ReadAll,vbCrLf) For i = UBound(row) To 0 Step -1 row(i) = Split(row(i)," ") If i < UBound(row) Then For j = 0 To UBound(row(i)) If (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j)) Else row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1)) End If Next End If Next WScript.Echo row(0)(0) objinfile.Close Set objfso = Nothing
Write a version of this C function in VB with identical behavior.
#include<stdlib.h> #include<stdio.h> char** imageMatrix; char blankPixel,imagePixel; typedef struct{ int row,col; }pixel; int getBlackNeighbours(int row,int col){ int i,j,sum = 0; for(i=-1;i<=1;i++){ for(j=-1;j<=1;j++){ if(i!=0 || j!=0) sum+= (imageMatrix[row+i][col+j]==imagePixel); } } return sum; } int getBWTransitions(int row,int col){ return ((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel) +(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel) +(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel) +(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel) +(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel) +(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel) +(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel) +(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel)); } int zhangSuenTest1(int row,int col){ int neighbours = getBlackNeighbours(row,col); return ((neighbours>=2 && neighbours<=6) && (getBWTransitions(row,col)==1) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) && (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel)); } int zhangSuenTest2(int row,int col){ int neighbours = getBlackNeighbours(row,col); return ((neighbours>=2 && neighbours<=6) && (getBWTransitions(row,col)==1) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel)); } void zhangSuen(char* inputFile, char* outputFile){ int startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed; pixel* markers; FILE* inputP = fopen(inputFile,"r"); fscanf(inputP,"%d%d",&rows,&cols); fscanf(inputP,"%d%d",&blankPixel,&imagePixel); blankPixel<=9?blankPixel+='0':blankPixel; imagePixel<=9?imagePixel+='0':imagePixel; printf("\nPrinting original image :\n"); imageMatrix = (char**)malloc(rows*sizeof(char*)); for(i=0;i<rows;i++){ imageMatrix[i] = (char*)malloc((cols+1)*sizeof(char)); fscanf(inputP,"%s\n",imageMatrix[i]); printf("\n%s",imageMatrix[i]); } fclose(inputP); endRow = rows-2; endCol = cols-2; do{ markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel)); count = 0; for(i=startRow;i<=endRow;i++){ for(j=startCol;j<=endCol;j++){ if(imageMatrix[i][j]==imagePixel && zhangSuenTest1(i,j)==1){ markers[count].row = i; markers[count].col = j; count++; } } } processed = (count>0); for(i=0;i<count;i++){ imageMatrix[markers[i].row][markers[i].col] = blankPixel; } free(markers); markers = (pixel*)malloc((endRow-startRow+1)*(endCol-startCol+1)*sizeof(pixel)); count = 0; for(i=startRow;i<=endRow;i++){ for(j=startCol;j<=endCol;j++){ if(imageMatrix[i][j]==imagePixel && zhangSuenTest2(i,j)==1){ markers[count].row = i; markers[count].col = j; count++; } } } if(processed==0) processed = (count>0); for(i=0;i<count;i++){ imageMatrix[markers[i].row][markers[i].col] = blankPixel; } free(markers); }while(processed==1); FILE* outputP = fopen(outputFile,"w"); printf("\n\n\nPrinting image after applying Zhang Suen Thinning Algorithm : \n\n\n"); for(i=0;i<rows;i++){ for(j=0;j<cols;j++){ printf("%c",imageMatrix[i][j]); fprintf(outputP,"%c",imageMatrix[i][j]); } printf("\n"); fprintf(outputP,"\n"); } fclose(outputP); printf("\nImage also written to : %s",outputFile); } int main() { char inputFile[100],outputFile[100]; printf("Enter full path of input image file : "); scanf("%s",inputFile); printf("Enter full path of output image file : "); scanf("%s",outputFile); zhangSuen(inputFile,outputFile); return 0; }
Public n As Variant Private Sub init() n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}] End Sub Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant Dim wtb As Integer Dim bn As Integer Dim prev As String: prev = "#" Dim next_ As String Dim p2468 As String For i = 1 To UBound(n) next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1) wtb = wtb - (prev = "." And next_ <= "#") bn = bn - (i > 1 And next_ <= "#") If (i And 1) = 0 Then p2468 = p2468 & prev prev = next_ Next i If step = 2 Then p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2) End If Dim ret(2) As Variant ret(0) = wtb ret(1) = bn ret(2) = p2468 AB = ret End Function Private Sub Zhang_Suen(text As Variant) Dim wtb As Integer Dim bn As Integer Dim changed As Boolean, changes As Boolean Dim p2468 As String Dim x As Integer, y As Integer, step As Integer Do While True changed = False For step = 1 To 2 changes = False For y = 1 To UBound(text) - 1 For x = 2 To Len(text(y)) - 1 If Mid(text(y), x, 1) = "#" Then ret = AB(text, y, x, step) wtb = ret(0) bn = ret(1) p2468 = ret(2) If wtb = 1 _ And bn >= 2 And bn <= 6 _ And InStr(1, Mid(p2468, 1, 3), ".") _ And InStr(1, Mid(p2468, 2, 3), ".") Then changes = True text(y) = Left(text(y), x - 1) & "!" & Right(text(y), Len(text(y)) - x) End If End If Next x Next y If changes Then For y = 1 To UBound(text) - 1 text(y) = Replace(text(y), "!", ".") Next y changed = True End If Next step If Not changed Then Exit Do Loop Debug.Print Join(text, vbCrLf) End Sub Public Sub main() init Dim Small_rc(9) As String Small_rc(0) = "................................" Small_rc(1) = ".#########.......########......." Small_rc(2) = ".###...####.....####..####......" Small_rc(3) = ".###....###.....###....###......" Small_rc(4) = ".###...####.....###............." Small_rc(5) = ".#########......###............." Small_rc(6) = ".###.####.......###....###......" Small_rc(7) = ".###..####..###.####..####.###.." Small_rc(8) = ".###...####.###..########..###.." Small_rc(9) = "................................" Zhang_Suen (Small_rc) End Sub
Write the same algorithm in VB as shown in this C implementation.
#include <stdio.h> int main() { int i, gprev = 0; int s[7] = {1, 2, 2, 3, 4, 4, 5}; for (i = 0; i < 7; ++i) { int curr = s[i]; int prev = 0; if (i > 0 && curr == prev) printf("%d\n", i); prev = curr; } for (i = 0; i < 7; ++i) { int curr = s[i]; if (i > 0 && curr == gprev) printf("%d\n", i); gprev = curr; } return 0; }
Option Strict On Option Explicit On Imports System.IO Module vMain Public Sub Main Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5} For i As Integer = 0 To Ubound(s) Dim curr As Integer = s(i) Dim prev As Integer If i > 1 AndAlso curr = prev Then Console.Out.WriteLine(i) End If prev = curr Next i End Sub End Module
Produce a language-to-language conversion: from C to VB, same semantics.
#include<stdio.h> #define start main() int start { printf("Hello World !"); return 0; }
SUB Main() END
Write the same algorithm in VB as shown in this C implementation.
#include<stdio.h> #define start main() int start { printf("Hello World !"); return 0; }
SUB Main() END
Maintain the same structure and functionality when rewriting this code in VB.
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #define pi M_PI typedef struct{ double x,y; }point; void kochCurve(point p1,point p2,int times){ point p3,p4,p5; double theta = pi/3; if(times>0){ p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3}; p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3}; p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)}; kochCurve(p1,p3,times-1); kochCurve(p3,p4,times-1); kochCurve(p4,p5,times-1); kochCurve(p5,p2,times-1); } else{ line(p1.x,p1.y,p2.x,p2.y); } } int main(int argC, char** argV) { int w,h,r; point p1,p2; if(argC!=4){ printf("Usage : %s <window width> <window height> <recursion level>",argV[0]); } else{ w = atoi(argV[1]); h = atoi(argV[2]); r = atoi(argV[3]); initwindow(w,h,"Koch Curve"); p1 = (point){10,h-10}; p2 = (point){w-10,h-10}; kochCurve(p1,p2,r); getch(); closegraph(); } return 0; }
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public property let iangle(n):iang= n*pi180 :end property public sub pd() : pdown=true: end sub public sub pu() :pdown=FALSE :end sub public sub rt(i) ori=ori - i*iang: if ori<0 then ori = ori+pi*2 end sub public sub lt(i): ori=(ori + i*iang) if ori>(pi*2) then ori=ori-pi*2 end sub public sub bw(l) x= x+ cos(ori+pi)*l*incr y= y+ sin(ori+pi)*l*incr end sub public sub fw(l) dim x1,y1 x1=x + cos(ori)*l*incr y1=y + sin(ori)*l*incr if pdown then line x,y,x1,y1 x=x1:y=y1 end sub Private Sub Class_Initialize() setlocale "us" initsvg pdown=true end sub Private Sub Class_Terminate() disply end sub private sub line (x,y,x1,y1) svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>" end sub private sub disply() dim shell svg.WriteLine "</svg></body></html>" svg.close Set shell = CreateObject("Shell.Application") shell.ShellExecute fn,1,False end sub private sub initsvg() dim scriptpath Set fso = CreateObject ("Scripting.Filesystemobject") ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) fn=Scriptpath & "SIERP.HTML" Set svg = fso.CreateTextFile(fn,True) if SVG IS nothing then wscript.echo "Can svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>" svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>" svg.writeline "</head>"&vbcrlf & "<body>" svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" end sub end class sub koch (n,le) if n=0 then x.fw le :exit sub koch n-1, le/3 x.lt 1 koch n-1, le/3 x.rt 2 koch n-1, le/3 x.lt 1 koch n-1, le/3 end sub dim x,i set x=new turtle x.iangle=60 x.orient=0 x.incr=3 x.x=100:x.y=300 for i=0 to 3 koch 7,100 x.rt 2 next set x=nothing
Write a version of this C function in VB with identical behavior.
#include<graphics.h> int main() { initwindow(320,240,"Red Pixel"); putpixel(100,100,RED); getch(); return 0; }
Sub draw() Dim sh As Shape, sl As Shape Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240) Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100) sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0) End Sub
Keep all operations the same but rewrite the snippet in VB.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORD_SIZE 80 #define MIN_LENGTH 9 #define WORD_SIZE (MIN_LENGTH + 1) void fatal(const char* message) { fprintf(stderr, "%s\n", message); exit(1); } void* xmalloc(size_t n) { void* ptr = malloc(n); if (ptr == NULL) fatal("Out of memory"); return ptr; } void* xrealloc(void* p, size_t n) { void* ptr = realloc(p, n); if (ptr == NULL) fatal("Out of memory"); return ptr; } int word_compare(const void* p1, const void* p2) { return memcmp(p1, p2, WORD_SIZE); } int main(int argc, char** argv) { const char* filename = argc < 2 ? "unixdict.txt" : argv[1]; FILE* in = fopen(filename, "r"); if (!in) { perror(filename); return EXIT_FAILURE; } char line[MAX_WORD_SIZE]; size_t size = 0, capacity = 1024; char* words = xmalloc(WORD_SIZE * capacity); while (fgets(line, sizeof(line), in)) { size_t len = strlen(line) - 1; if (len < MIN_LENGTH) continue; line[len] = '\0'; if (size == capacity) { capacity *= 2; words = xrealloc(words, WORD_SIZE * capacity); } memcpy(&words[size * WORD_SIZE], line, WORD_SIZE); ++size; } fclose(in); qsort(words, size, WORD_SIZE, word_compare); int count = 0; char prev_word[WORD_SIZE] = { 0 }; for (size_t i = 0; i + MIN_LENGTH <= size; ++i) { char word[WORD_SIZE] = { 0 }; for (size_t j = 0; j < MIN_LENGTH; ++j) word[j] = words[(i + j) * WORD_SIZE + j]; if (word_compare(word, prev_word) == 0) continue; if (bsearch(word, words, size, WORD_SIZE, word_compare)) printf("%2d. %s\n", ++count, word); memcpy(prev_word, word, WORD_SIZE); } free(words); return EXIT_SUCCESS; }
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) set d=createobject("scripting.dictionary") redim b(ubound(a)) i=0 for each x in a s=trim(x) if len(s)>=9 then if len(s)= 9 then d.add s,"" b(i)=s i=i+1 end if next redim preserve b(i-1) wscript.echo i j=1 for i=0 to ubound(b)-9 s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_ mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1) if d.exists(s9) then wscript.echo j,s9 d.remove(s9) j=j+1 end if next
Write a version of this C function in VB with identical behavior.
#include <stdio.h> int main(){ int ptr=0, i=0, cell[7]; for( i=0; i<7; ++i) cell[i]=0; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 8; while(cell[ptr]) { ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 9; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 2; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; } cell[ptr]+= 1; ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr-= 2; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 4; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 2; if(ptr<0) perror("Program pointer underflow"); } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 7; putchar(cell[ptr]); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 7; putchar(cell[ptr]); ptr-= 3; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { while(cell[ptr]) { cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { cell[ptr]-= 1; } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 15; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); cell[ptr]-= 6; putchar(cell[ptr]); cell[ptr]-= 8; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; putchar(cell[ptr]); ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 4; putchar(cell[ptr]); return 0; }
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 If newd < 0 Then newd = (newd Mod 256) + 256 d(dp) = Chr(newd) Case ">" dp = dp + 1 If dp > UBound(d) Then ReDim Preserve d(UBound(d) + 1) d(dp) = Chr(0) End If Case "<" dp = dp - 1 Case "." o = o & d(dp) Case "," If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1) Case "[" If Asc(d(dp)) = 0 Then bracket = 1 While bracket And sp < Len(s) sp = sp + 1 If Mid(s, sp + 1, 1) = "[" Then bracket = bracket + 1 ElseIf Mid(s, sp + 1, 1) = "]" Then bracket = bracket - 1 End If WEnd Else pos = sp - 1 sp = sp + 1 If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos End If Case "]" BFInpt = Asc(d(dp)) <> 0 Exit Function End Select sp = sp + 1 WEnd End Function Function BFuck(source, input) Dim data() : ReDim data(0) data(0) = Chr(0) DataPtr = 0 SrcPtr = 0 InputPtr = 0 output = "" BFInpt source , SrcPtr , _ data , DataPtr , _ input , InputPtr , _ output BFuck = output End Function code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _ ">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++." inpstr = "" WScript.StdOut.Write BFuck(code, inpstr)
Produce a functionally identical VB code for the snippet given in C.
#include <stdio.h> int main(){ int ptr=0, i=0, cell[7]; for( i=0; i<7; ++i) cell[i]=0; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 8; while(cell[ptr]) { ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 9; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 2; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; } cell[ptr]+= 1; ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); while(cell[ptr]) { cell[ptr]-= 1; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; ptr-= 2; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 4; ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 2; if(ptr<0) perror("Program pointer underflow"); } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 7; putchar(cell[ptr]); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 7; putchar(cell[ptr]); ptr-= 3; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { while(cell[ptr]) { cell[ptr]-= 1; } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); while(cell[ptr]) { cell[ptr]-= 1; } ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); } ptr-= 1; if(ptr<0) perror("Program pointer underflow"); cell[ptr]+= 15; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); putchar(cell[ptr]); cell[ptr]+= 3; putchar(cell[ptr]); cell[ptr]-= 6; putchar(cell[ptr]); cell[ptr]-= 8; putchar(cell[ptr]); ptr+= 2; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 1; putchar(cell[ptr]); ptr+= 1; if(ptr>=7) perror("Program pointer overflow"); cell[ptr]+= 4; putchar(cell[ptr]); return 0; }
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 If newd < 0 Then newd = (newd Mod 256) + 256 d(dp) = Chr(newd) Case ">" dp = dp + 1 If dp > UBound(d) Then ReDim Preserve d(UBound(d) + 1) d(dp) = Chr(0) End If Case "<" dp = dp - 1 Case "." o = o & d(dp) Case "," If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1) Case "[" If Asc(d(dp)) = 0 Then bracket = 1 While bracket And sp < Len(s) sp = sp + 1 If Mid(s, sp + 1, 1) = "[" Then bracket = bracket + 1 ElseIf Mid(s, sp + 1, 1) = "]" Then bracket = bracket - 1 End If WEnd Else pos = sp - 1 sp = sp + 1 If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos End If Case "]" BFInpt = Asc(d(dp)) <> 0 Exit Function End Select sp = sp + 1 WEnd End Function Function BFuck(source, input) Dim data() : ReDim data(0) data(0) = Chr(0) DataPtr = 0 SrcPtr = 0 InputPtr = 0 output = "" BFInpt source , SrcPtr , _ data , DataPtr , _ input , InputPtr , _ output BFuck = output End Function code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _ ">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++." inpstr = "" WScript.StdOut.Write BFuck(code, inpstr)
Rewrite this program in VB while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #include <inttypes.h> typedef struct { char mask; char lead; uint32_t beg; uint32_t end; int bits_stored; }utf_t; utf_t * utf[] = { [0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 }, [1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 }, [2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 }, [3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 }, [4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 }, &(utf_t){0}, }; int codepoint_len(const uint32_t cp); int utf8_len(const char ch); char *to_utf8(const uint32_t cp); uint32_t to_cp(const char chr[4]); int codepoint_len(const uint32_t cp) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((cp >= (*u)->beg) && (cp <= (*u)->end)) { break; } ++len; } if(len > 4) exit(1); return len; } int utf8_len(const char ch) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((ch & ~(*u)->mask) == (*u)->lead) { break; } ++len; } if(len > 4) { exit(1); } return len; } char *to_utf8(const uint32_t cp) { static char ret[5]; const int bytes = codepoint_len(cp); int shift = utf[0]->bits_stored * (bytes - 1); ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead; shift -= utf[0]->bits_stored; for(int i = 1; i < bytes; ++i) { ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead; shift -= utf[0]->bits_stored; } ret[bytes] = '\0'; return ret; } uint32_t to_cp(const char chr[4]) { int bytes = utf8_len(*chr); int shift = utf[0]->bits_stored * (bytes - 1); uint32_t codep = (*chr++ & utf[bytes]->mask) << shift; for(int i = 1; i < bytes; ++i, ++chr) { shift -= utf[0]->bits_stored; codep |= ((char)*chr & utf[0]->mask) << shift; } return codep; } int main(void) { const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0}; printf("Character Unicode UTF-8 encoding (hex)\n"); printf("----------------------------------------\n"); char *utf8; uint32_t codepoint; for(in = input; *in; ++in) { utf8 = to_utf8(*in); codepoint = to_cp(utf8); printf("%s U+%-7.4x", utf8, codepoint); for(int i = 0; utf8[i] && i < 4; ++i) { printf("%hhx ", utf8[i]); } printf("\n"); } return 0; }
Private Function unicode_2_utf8(x As Long) As Byte() Dim y() As Byte Dim r As Long Select Case x Case 0 To &H7F ReDim y(0) y(0) = x Case &H80 To &H7FF ReDim y(1) y(0) = 192 + x \ 64 y(1) = 128 + x Mod 64 Case &H800 To &H7FFF ReDim y(2) y(2) = 128 + x Mod 64 r = x \ 64 y(1) = 128 + r Mod 64 y(0) = 224 + r \ 64 Case 32768 To 65535 ReDim y(2) y(2) = 128 + x Mod 64 r = x \ 64 y(1) = 128 + r Mod 64 y(0) = 224 + r \ 64 Case &H10000 To &H10FFFF ReDim y(3) y(3) = 128 + x Mod 64 r = x \ 64 y(2) = 128 + r Mod 64 r = r \ 64 y(1) = 128 + r Mod 64 y(0) = 240 + r \ 64 Case Else MsgBox "what else?" & x & " " & Hex(x) End Select unicode_2_utf8 = y End Function Private Function utf8_2_unicode(x() As Byte) As Long Dim first As Long, second As Long, third As Long, fourth As Long Dim total As Long Select Case UBound(x) - LBound(x) Case 0 If x(0) < 128 Then total = x(0) Else MsgBox "highest bit set error" End If Case 1 If x(0) \ 32 = 6 Then first = x(0) Mod 32 If x(1) \ 64 = 2 Then second = x(1) Mod 64 Else MsgBox "mask error" End If Else MsgBox "leading byte error" End If total = 64 * first + second Case 2 If x(0) \ 16 = 14 Then first = x(0) Mod 16 If x(1) \ 64 = 2 Then second = x(1) Mod 64 If x(2) \ 64 = 2 Then third = x(2) Mod 64 Else MsgBox "mask error last byte" End If Else MsgBox "mask error middle byte" End If Else MsgBox "leading byte error" End If total = 4096 * first + 64 * second + third Case 3 If x(0) \ 8 = 30 Then first = x(0) Mod 8 If x(1) \ 64 = 2 Then second = x(1) Mod 64 If x(2) \ 64 = 2 Then third = x(2) Mod 64 If x(3) \ 64 = 2 Then fourth = x(3) Mod 64 Else MsgBox "mask error last byte" End If Else MsgBox "mask error third byte" End If Else MsgBox "mask error second byte" End If Else MsgBox "mask error leading byte" End If total = CLng(262144 * first + 4096 * second + 64 * third + fourth) Case Else MsgBox "more bytes than expected" End Select utf8_2_unicode = total End Function Public Sub program() Dim cp As Variant Dim r() As Byte, s As String cp = [{65, 246, 1046, 8364, 119070}] Debug.Print "ch unicode UTF-8 encoded decoded" For Each cpi In cp r = unicode_2_utf8(CLng(cpi)) On Error Resume Next s = CStr(Hex(cpi)) Debug.Print ChrW(cpi); String$(10 - Len(s), " "); s, If Err.Number = 5 Then Debug.Print "?"; String$(10 - Len(s), " "); s, s = "" For Each yz In r s = s & CStr(Hex(yz)) & " " Next yz Debug.Print String$(13 - Len(s), " "); s; s = CStr(Hex(utf8_2_unicode(r))) Debug.Print String$(8 - Len(s), " "); s Next cpi End Sub
Change the programming language of this snippet from C to VB without modifying what it does.
#include<stdlib.h> #include<ctype.h> #include<stdio.h> int** doublyEvenMagicSquare(int n) { if (n < 4 || n % 4 != 0) return NULL; int bits = 38505; int size = n * n; int mult = n / 4,i,r,c,bitPos; int** result = (int**)malloc(n*sizeof(int*)); for(i=0;i<n;i++) result[i] = (int*)malloc(n*sizeof(int)); for (r = 0, i = 0; r < n; r++) { for (c = 0; c < n; c++, i++) { bitPos = c / mult + (r / mult) * 4; result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } int numDigits(int n){ int count = 1; while(n>=10){ n /= 10; count++; } return count; } void printMagicSquare(int** square,int rows){ int i,j,baseWidth = numDigits(rows*rows) + 3; printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2); for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]); } printf("\n"); } } int main(int argC,char* argV[]) { int n; if(argC!=2||isdigit(argV[1][0])==0) printf("Usage : %s <integer specifying rows in magic square>",argV[0]); else{ n = atoi(argV[1]); printMagicSquare(doublyEvenMagicSquare(n),n); } return 0; }
n=8 pattern="1001011001101001" size=n*n: w=len(size) mult=n\4 wscript.echo "Magic square : " & n & " x " & n i=0 For r=0 To n-1 l="" For c=0 To n-1 bit=Mid(pattern, c\mult+(r\mult)*4+1, 1) If bit="1" Then t=i+1 Else t=size-i l=l & Right(Space(w) & t, w) & " " i=i+1 Next wscript.echo l Next wscript.echo "Magic constant=" & (n*n+1)*n/2
Transform the following C implementation into VB, maintaining the same output and logic.
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_SIZE 100 int move_to_front(char *str,char c) { char *q,*p; int shift=0; p=(char *)malloc(strlen(str)+1); strcpy(p,str); q=strchr(p,c); shift=q-p; strncpy(str+1,p,shift); str[0]=c; free(p); return shift; } void decode(int* pass,int size,char *sym) { int i,index; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=table[pass[i]]; index=move_to_front(table,c); if(pass[i]!=index) printf("there is an error"); sym[i]=c; } sym[size]='\0'; } void encode(char *sym,int size,int *pass) { int i=0; char c; char table[]="abcdefghijklmnopqrstuvwxyz"; for(i=0;i<size;i++) { c=sym[i]; pass[i]=move_to_front(table,c); } } int check(char *sym,int size,int *pass) { int *pass2=malloc(sizeof(int)*size); char *sym2=malloc(sizeof(char)*size); int i,val=1; encode(sym,size,pass2); i=0; while(i<size && pass[i]==pass2[i])i++; if(i!=size)val=0; decode(pass,size,sym2); if(strcmp(sym,sym2)!=0)val=0; free(sym2); free(pass2); return val; } int main() { char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"}; int pass[MAX_SIZE]={0}; int i,len,j; for(i=0;i<3;i++) { len=strlen(sym[i]); encode(sym[i],len,pass); printf("%s : [",sym[i]); for(j=0;j<len;j++) printf("%d ",pass[j]); printf("]\n"); if(check(sym[i],len,pass)) printf("Correct :)\n"); else printf("Incorrect :(\n"); } return 0; }
Function mtf_encode(s) Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 symbol_table.Add Chr(j) Next output = "" For i = 1 To Len(s) char = Mid(s,i,1) If i = Len(s) Then output = output & symbol_table.IndexOf(char,0) symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char Else output = output & symbol_table.IndexOf(char,0) & " " symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char End If Next mtf_encode = output End Function Function mtf_decode(s) code = Split(s," ") Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 symbol_table.Add Chr(j) Next output = "" For i = 0 To UBound(code) char = symbol_table(code(i)) output = output & char If code(i) <> 0 Then symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) symbol_table.Insert 0,char End If Next mtf_decode = output End Function wordlist = Array("broood","bananaaa","hiphophiphop") For Each word In wordlist WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_ mtf_decode(mtf_encode(word)) & "." WScript.StdOut.WriteBlankLines(1) Next
Port the following code from C to VB with equivalent syntax and logic.
#include <stdlib.h> int main() { system("ls"); return 0; }
Set objShell = CreateObject("WScript.Shell") objShell.Run "%comspec% /K dir",3,True
Rewrite this program in VB while keeping its functionality equivalent to the C version.
#include <libxml/xmlschemastypes.h> int main(int argC, char** argV) { if (argC <= 2) { printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]); return 0; } xmlDocPtr doc; xmlSchemaPtr schema = NULL; xmlSchemaParserCtxtPtr ctxt; char *XMLFileName = argV[1]; char *XSDFileName = argV[2]; int ret; xmlLineNumbersDefault(1); ctxt = xmlSchemaNewParserCtxt(XSDFileName); xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); schema = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); doc = xmlReadFile(XMLFileName, NULL, 0); if (doc == NULL){ fprintf(stderr, "Could not parse %s\n", XMLFileName); } else{ xmlSchemaValidCtxtPtr ctxt; ctxt = xmlSchemaNewValidCtxt(schema); xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); ret = xmlSchemaValidateDoc(ctxt, doc); if (ret == 0){ printf("%s validates\n", XMLFileName); } else if (ret > 0){ printf("%s fails to validate\n", XMLFileName); } else{ printf("%s validation generated an internal error\n", XMLFileName); } xmlSchemaFreeValidCtxt(ctxt); xmlFreeDoc(doc); } if(schema != NULL) xmlSchemaFree(schema); xmlSchemaCleanupTypes(); xmlCleanupParser(); xmlMemoryDump(); return 0; }
Option explicit Function fileexists(fn) fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn) End Function Function xmlvalid(strfilename) Dim xmldoc,xmldoc2,objSchemas Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0") If fileexists(Replace(strfilename,".xml",".dtd")) Then xmlDoc.setProperty "ProhibitDTD", False xmlDoc.setProperty "ResolveExternals", True xmlDoc.validateOnParse = True xmlDoc.async = False xmlDoc.load(strFileName) ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then xmlDoc.setProperty "ProhibitDTD", True xmlDoc.setProperty "ResolveExternals", True xmlDoc.validateOnParse = True xmlDoc.async = False xmlDoc.load(strFileName) Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0") xmlDoc2.validateOnParse = True xmlDoc2.async = False xmlDoc2.load(Replace (strfilename,".xml",".xsd")) Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0") objSchemas.Add "", xmlDoc2 Else Set xmlvalid= Nothing:Exit Function End If Set xmlvalid=xmldoc.parseError End Function Sub displayerror (parserr) Dim strresult If parserr is Nothing Then strresult= "could not find dtd or xsd for " & strFileName Else With parserr Select Case .errorcode Case 0 strResult = "Valid: " & strFileName & vbCr Case Else strResult = vbCrLf & "ERROR! Failed to validate " & _ strFileName & vbCrLf &.reason & vbCr & _ "Error code: " & .errorCode & ", Line: " & _ .line & ", Character: " & _ .linepos & ", Source: """ & _ .srcText & """ - " & vbCrLf End Select End With End If WScript.Echo strresult End Sub Dim strfilename strfilename="shiporder.xml" displayerror xmlvalid (strfilename)
Rewrite this program in VB while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <math.h> #include <unistd.h> const char *shades = ".:!*oe&#%@"; double light[3] = { -50, 0, 50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } typedef struct { double cx, cy, cz, r; } sphere_t; sphere_t pos = { 20, 20, 0, 20 }, neg = { 1, 1, -6, 20 }; int hit_sphere(sphere_t *sph, double x, double y, double *z1, double *z2) { double zsq; x -= sph->cx; y -= sph->cy; zsq = sph->r * sph->r - (x * x + y * y); if (zsq < 0) return 0; zsq = sqrt(zsq); *z1 = sph->cz - zsq; *z2 = sph->cz + zsq; return 1; } void draw_sphere(double k, double ambient) { int i, j, intensity, hit_result; double b; double vec[3], x, y, zb1, zb2, zs1, zs2; for (i = floor(pos.cy - pos.r); i <= ceil(pos.cy + pos.r); i++) { y = i + .5; for (j = floor(pos.cx - 2 * pos.r); j <= ceil(pos.cx + 2 * pos.r); j++) { x = (j - pos.cx) / 2. + .5 + pos.cx; if (!hit_sphere(&pos, x, y, &zb1, &zb2)) hit_result = 0; else if (!hit_sphere(&neg, x, y, &zs1, &zs2)) hit_result = 1; else if (zs1 > zb1) hit_result = 1; else if (zs2 > zb2) hit_result = 0; else if (zs2 > zb1) hit_result = 2; else hit_result = 1; switch(hit_result) { case 0: putchar('+'); continue; case 1: vec[0] = x - pos.cx; vec[1] = y - pos.cy; vec[2] = zb1 - pos.cz; break; default: vec[0] = neg.cx - x; vec[1] = neg.cy - y; vec[2] = neg.cz - zs2; } normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } putchar('\n'); } } int main() { double ang = 0; while (1) { printf("\033[H"); light[1] = cos(ang * 2); light[2] = cos(ang); light[0] = sin(ang); normalize(light); ang += .05; draw_sphere(2, .3); usleep(100000); } return 0; }
option explicit const x_=0 const y_=1 const z_=2 const r_=3 function clamp(x,b,t) if x<b then clamp=b elseif x>t then clamp =t else clamp=x end if end function function dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function function normal (byval v) dim ilen:ilen=1/sqr(dot(v,v)): v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen: normal=v: end function function hittest(s,x,y) dim z z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2 if z>=0 then z=sqr(z) hittest=array(s(z_)-z,s(z_)+z) else hittest=0 end if end function sub deathstar(pos, neg, sun, k, amb) dim x,y,shades,result,shade,hp,hn,xx,b shades=array(" ",".",":","!","*","o","e","&","#","%","@") for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5 hp=hittest (pos, x, y) hn=hittest(neg,x,y) if not isarray(hp) then result=0 elseif not isarray(hn) then result=1 elseif hn(0)>hp(0) then result=1 elseif hn(1)>hp(1) then result=0 elseif hn(1)>hp(0) then result=2 else result=1 end if shade=-1 select case result case 0 shade=0 case 1 xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_))) case 2 xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1))) end select if shade <>0 then b=dot(sun,xx)^k+amb shade=clamp((1-b) *ubound(shades),1,ubound(shades)) end if wscript.stdout.write string(2,shades(shade)) next wscript.stdout.write vbcrlf next end sub deathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1
Produce a language-to-language conversion: from C to VB, same semantics.
#include <stdlib.h> #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif typedef double (* Ifctn)( double t); double Simpson3_8( Ifctn f, double a, double b, int N) { int j; double l1; double h = (b-a)/N; double h1 = h/3.0; double sum = f(a) + f(b); for (j=3*N-1; j>0; j--) { l1 = (j%3)? 3.0 : 2.0; sum += l1*f(a+h1*j) ; } return h*sum/8.0; } #define A 12 double Gamma_Spouge( double z ) { int k; static double cspace[A]; static double *coefs = NULL; double accum; double a = A; if (!coefs) { double k1_factrl = 1.0; coefs = cspace; coefs[0] = sqrt(2.0*M_PI); for(k=1; k<A; k++) { coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl; k1_factrl *= -k; } } accum = coefs[0]; for (k=1; k<A; k++) { accum += coefs[k]/(z+k); } accum *= exp(-(z+a)) * pow(z+a, z+0.5); return accum/z; } double aa1; double f0( double t) { return pow(t, aa1)*exp(-t); } double GammaIncomplete_Q( double a, double x) { double y, h = 1.5e-2; y = aa1 = a-1; while((f0(y) * (x-y) > 2.0e-8) && (y < x)) y += .4; if (y>x) y=x; return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a); }
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double Debug.Print "[1] ""Data set:"" "; For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) Total = Total + ObservationFrequencies(i) Debug.Print ObservationFrequencies(i); " "; Next i DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies) Ei = Total / (DegreesOfFreedom + 1) For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei Next i p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True) Debug.Print Debug.Print " Chi-squared test for given frequencies" Debug.Print "X-squared ="; ChiSquared; ", "; Debug.Print "df ="; DegreesOfFreedom; ", "; Debug.Print "p-value = "; Format(p_value, "0.0000") Test4DiscreteUniformDistribution = p_value > Significance End Function Public Sub test() Dim O() As Variant O = [{199809,200665,199607,200270,199649}] Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """" O = [{522573,244456,139979,71531,21461}] Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """" End Sub
Ensure the translated VB code behaves exactly like the original C snippet.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 128 typedef unsigned char character; typedef character *string; typedef struct node_t node; struct node_t { enum tag_t { NODE_LEAF, NODE_TREE, NODE_SEQ, } tag; union { string str; node *root; } data; node *next; }; node *allocate_node(enum tag_t tag) { node *n = malloc(sizeof(node)); if (n == NULL) { fprintf(stderr, "Failed to allocate node for tag: %d\n", tag); exit(1); } n->tag = tag; n->next = NULL; return n; } node *make_leaf(string str) { node *n = allocate_node(NODE_LEAF); n->data.str = str; return n; } node *make_tree() { node *n = allocate_node(NODE_TREE); n->data.root = NULL; return n; } node *make_seq() { node *n = allocate_node(NODE_SEQ); n->data.root = NULL; return n; } void deallocate_node(node *n) { if (n == NULL) { return; } deallocate_node(n->next); n->next = NULL; if (n->tag == NODE_LEAF) { free(n->data.str); n->data.str = NULL; } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) { deallocate_node(n->data.root); n->data.root = NULL; } else { fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag); exit(1); } free(n); } void append(node *root, node *elem) { if (root == NULL) { fprintf(stderr, "Cannot append to uninitialized node."); exit(1); } if (elem == NULL) { return; } if (root->tag == NODE_SEQ || root->tag == NODE_TREE) { if (root->data.root == NULL) { root->data.root = elem; } else { node *it = root->data.root; while (it->next != NULL) { it = it->next; } it->next = elem; } } else { fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag); exit(1); } } size_t count(node *n) { if (n == NULL) { return 0; } if (n->tag == NODE_LEAF) { return 1; } if (n->tag == NODE_TREE) { size_t sum = 0; node *it = n->data.root; while (it != NULL) { sum += count(it); it = it->next; } return sum; } if (n->tag == NODE_SEQ) { size_t prod = 1; node *it = n->data.root; while (it != NULL) { prod *= count(it); it = it->next; } return prod; } fprintf(stderr, "Cannot count node with tag: %d\n", n->tag); exit(1); } void expand(node *n, size_t pos) { if (n == NULL) { return; } if (n->tag == NODE_LEAF) { printf(n->data.str); } else if (n->tag == NODE_TREE) { node *it = n->data.root; while (true) { size_t cnt = count(it); if (pos < cnt) { expand(it, pos); break; } pos -= cnt; it = it->next; } } else if (n->tag == NODE_SEQ) { size_t prod = pos; node *it = n->data.root; while (it != NULL) { size_t cnt = count(it); size_t rem = prod % cnt; expand(it, rem); it = it->next; } } else { fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag); exit(1); } } string allocate_string(string src) { size_t len = strlen(src); string out = calloc(len + 1, sizeof(character)); if (out == NULL) { fprintf(stderr, "Failed to allocate a copy of the string."); exit(1); } strcpy(out, src); return out; } node *parse_seq(string input, size_t *pos); node *parse_tree(string input, size_t *pos) { node *root = make_tree(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; size_t depth = 0; bool asSeq = false; bool allow = false; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = '\\'; buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { buffer[bufpos++] = c; buffer[bufpos] = 0; asSeq = true; depth++; } else if (c == '}') { if (depth-- > 0) { buffer[bufpos++] = c; buffer[bufpos] = 0; } else { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); } else { append(root, make_leaf(allocate_string(buffer))); } break; } } else if (c == ',') { if (depth == 0) { if (asSeq) { size_t new_pos = 0; node *seq = parse_seq(buffer, &new_pos); append(root, seq); bufpos = 0; buffer[bufpos] = 0; asSeq = false; } else { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } return root; } node *parse_seq(string input, size_t *pos) { node *root = make_seq(); character buffer[BUFFER_SIZE] = { 0 }; size_t bufpos = 0; while (input[*pos] != 0) { character c = input[(*pos)++]; if (c == '\\') { c = input[(*pos)++]; if (c == 0) { break; } buffer[bufpos++] = c; buffer[bufpos] = 0; } else if (c == '{') { node *tree = parse_tree(input, pos); if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } append(root, tree); } else { buffer[bufpos++] = c; buffer[bufpos] = 0; } } if (bufpos > 0) { append(root, make_leaf(allocate_string(buffer))); bufpos = 0; buffer[bufpos] = 0; } return root; } void test(string input) { size_t pos = 0; node *n = parse_seq(input, &pos); size_t cnt = count(n); size_t i; printf("Pattern: %s\n", input); for (i = 0; i < cnt; i++) { expand(n, i); printf("\n"); } printf("\n"); deallocate_node(n); } int main() { test("~/{Downloads,Pictures}/*.{jpg,gif,png}"); test("It{{em,alic}iz,erat}e{d,}, please."); test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!"); return 0; }
Module Module1 Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String) Dim out As New List(Of String) Dim comma = False While Not String.IsNullOrEmpty(s) Dim gs = GetItem(s, depth) Dim g = gs.Item1 s = gs.Item2 If String.IsNullOrEmpty(s) Then Exit While End If out.AddRange(g) If s(0) = "}" Then If comma Then Return Tuple.Create(out, s.Substring(1)) End If Return Tuple.Create(out.Select(Function(a) "{" + a + "}").ToList(), s.Substring(1)) End If If s(0) = "," Then comma = True s = s.Substring(1) End If End While Return Nothing End Function Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String) Dim out As New List(Of String) From {""} While Not String.IsNullOrEmpty(s) Dim c = s(0) If depth > 0 AndAlso (c = "," OrElse c = "}") Then Return Tuple.Create(out, s) End If If c = "{" Then Dim x = GetGroup(s.Substring(1), depth + 1) If Not IsNothing(x) Then Dim tout As New List(Of String) For Each a In out For Each b In x.Item1 tout.Add(a + b) Next Next out = tout s = x.Item2 Continue While End If End If If c = "\" AndAlso s.Length > 1 Then c += s(1) s = s.Substring(1) End If out = out.Select(Function(a) a + c).ToList() s = s.Substring(1) End While Return Tuple.Create(out, s) End Function Sub Main() For Each s In { "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\, again\, }}more }cowbell!", "{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}" } Dim fmt = "{0}" + vbNewLine + vbTab + "{1}" Dim parts = GetItem(s) Dim res = String.Join(vbNewLine + vbTab, parts.Item1) Console.WriteLine(fmt, s, res) Next End Sub End Module
Change the following C code into VB without altering its purpose.
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
Function no_arguments() As String no_arguments = "ok" End Function Function fixed_number(argument1 As Integer, argument2 As Integer) fixed_number = argument1 + argument2 End Function Function optional_parameter(Optional argument1 = 1) As Integer optional_parameter = argument1 End Function Function variable_number(arguments As Variant) As Integer variable_number = UBound(arguments) End Function Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer named_arguments = argument1 + argument2 End Function Function statement() As String Debug.Print "function called as statement" statement = "ok" End Function Function return_value() As String return_value = "ok" End Function Sub foo() Debug.Print "subroutine", End Sub Function bar() As String bar = "function" End Function Function passed_by_value(ByVal s As String) As String s = "written over" passed_by_value = "passed by value" End Function Function passed_by_reference(ByRef s As String) As String s = "written over" passed_by_reference = "passed by reference" End Function Sub no_parentheses(myargument As String) Debug.Print myargument, End Sub Public Sub calling_a_function() Debug.Print "no arguments", , no_arguments Debug.Print "no arguments", , no_arguments() Debug.Print "fixed_number", , fixed_number(1, 1) Debug.Print "optional parameter", optional_parameter Debug.Print "optional parameter", optional_parameter(2) Debug.Print "variable number", variable_number([{"hello", "there"}]) Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1) statement s = "no_arguments" Debug.Print "first-class context", Application.Run(s) returnvalue = return_value Debug.Print "obtained return value", returnvalue foo Debug.Print , bar Dim t As String t = "unaltered" Debug.Print passed_by_value(t), t Debug.Print passed_by_reference(t), t no_parentheses "calling a subroutine" Debug.Print "does not require parentheses" Call no_parentheses("deprecated use") Debug.Print "of parentheses" End Sub
Change the programming language of this snippet from C to VB without modifying what it does.
f(); g(1, 2, 3); int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } void h(int a, ...) { va_list ap; va_start(ap); ... } h(1, 2, 3, 4, "abcd", (void*)0); struct v_args { int arg1; int arg2; char _sentinel; }; void _v(struct v_args args) { printf("%d, %d\n", args.arg1, args.arg2); } #define v(...) _v((struct v_args){__VA_ARGS__}) v(.arg2 = 5, .arg1 = 17); v(.arg2=1); v(); printf("%p", f); double a = asin(1);
Function no_arguments() As String no_arguments = "ok" End Function Function fixed_number(argument1 As Integer, argument2 As Integer) fixed_number = argument1 + argument2 End Function Function optional_parameter(Optional argument1 = 1) As Integer optional_parameter = argument1 End Function Function variable_number(arguments As Variant) As Integer variable_number = UBound(arguments) End Function Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer named_arguments = argument1 + argument2 End Function Function statement() As String Debug.Print "function called as statement" statement = "ok" End Function Function return_value() As String return_value = "ok" End Function Sub foo() Debug.Print "subroutine", End Sub Function bar() As String bar = "function" End Function Function passed_by_value(ByVal s As String) As String s = "written over" passed_by_value = "passed by value" End Function Function passed_by_reference(ByRef s As String) As String s = "written over" passed_by_reference = "passed by reference" End Function Sub no_parentheses(myargument As String) Debug.Print myargument, End Sub Public Sub calling_a_function() Debug.Print "no arguments", , no_arguments Debug.Print "no arguments", , no_arguments() Debug.Print "fixed_number", , fixed_number(1, 1) Debug.Print "optional parameter", optional_parameter Debug.Print "optional parameter", optional_parameter(2) Debug.Print "variable number", variable_number([{"hello", "there"}]) Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1) statement s = "no_arguments" Debug.Print "first-class context", Application.Run(s) returnvalue = return_value Debug.Print "obtained return value", returnvalue foo Debug.Print , bar Dim t As String t = "unaltered" Debug.Print passed_by_value(t), t Debug.Print passed_by_reference(t), t no_parentheses "calling a subroutine" Debug.Print "does not require parentheses" Call no_parentheses("deprecated use") Debug.Print "of parentheses" End Sub
Translate the given C code snippet into VB without altering its behavior.
#include <windows.h> #include "resource.h" BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) { switch( msg ) { case WM_INITDIALOG: srand( GetTickCount() ); SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE ); break; case WM_COMMAND: switch( LOWORD(wPar) ) { case IDC_INCREMENT: { UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE ); SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE ); } break; case IDC_RANDOM: { int reply = MessageBox( hwnd, "Do you really want to\nget a random number?", "Random input confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE ); } break; case IDC_QUIT: SendMessage( hwnd, WM_CLOSE, 0, 0 ); break; default: ; } break; case WM_CLOSE: { int reply = MessageBox( hwnd, "Do you really want to quit?", "Quit confirmation", MB_ICONQUESTION|MB_YESNO ); if( reply == IDYES ) EndDialog( hwnd, 0 ); } break; default: ; } return 0; } int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) { return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc ); }
VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 2265 ClientLeft = 60 ClientTop = 600 ClientWidth = 2175 LinkTopic = "Form1" ScaleHeight = 2265 ScaleWidth = 2175 StartUpPosition = 3 Begin VB.CommandButton cmdRnd Caption = "Random" Height = 495 Left = 120 TabIndex = 2 Top = 1680 Width = 1215 End Begin VB.CommandButton cmdInc Caption = "Increment" Height = 495 Left = 120 TabIndex = 1 Top = 1080 Width = 1215 End Begin VB.TextBox txtValue Height = 495 Left = 120 TabIndex = 0 Text = "0" Top = 240 Width = 1215 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private Sub Form_Load() Randomize Timer End Sub Private Sub cmdRnd_Click() If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11) End Sub Private Sub cmdInc_Click() If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1 End Sub Private Sub txtValue_KeyPress(KeyAscii As Integer) Select Case KeyAscii Case 8, 43, 45, 48 To 57 Case Else KeyAscii = 0 End Select End Sub
Generate a VB translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> inline int irand(int n) { int r, randmax = RAND_MAX/n * n; while ((r = rand()) >= randmax); return r / (randmax / n); } inline int one_of_n(int n) { int i, r = 0; for (i = 1; i < n; i++) if (!irand(i + 1)) r = i; return r; } int main(void) { int i, r[10] = {0}; for (i = 0; i < 1000000; i++, r[one_of_n(10)]++); for (i = 0; i < 10; i++) printf("%d%c", r[i], i == 9 ? '\n':' '); return 0; }
Dim chosen(10) For j = 1 To 1000000 c = one_of_n(10) chosen(c) = chosen(c) + 1 Next For k = 1 To 10 WScript.StdOut.WriteLine k & ". " & chosen(k) Next Function one_of_n(n) Randomize For i = 1 To n If Rnd(1) < 1/i Then one_of_n = i End If Next End Function
Generate an equivalent VB version of this C code.
#include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <glib.h> typedef uint64_t integer; typedef struct number_names_tag { const char* cardinal; const char* ordinal; } number_names; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; typedef struct named_number_tag { const char* cardinal; const char* ordinal; integer number; } named_number; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_small_name(const number_names* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const char* get_big_name(const named_number* n, bool ordinal) { return ordinal ? n->ordinal : n->cardinal; } const named_number* get_named_number(integer n) { const size_t names_len = sizeof(named_numbers)/sizeof(named_numbers[0]); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return &named_numbers[i]; } return &named_numbers[names_len - 1]; } void append_number_name(GString* gstr, integer n, bool ordinal) { if (n < 20) g_string_append(gstr, get_small_name(&small[n], ordinal)); else if (n < 100) { if (n % 10 == 0) { g_string_append(gstr, get_small_name(&tens[n/10 - 2], ordinal)); } else { g_string_append(gstr, get_small_name(&tens[n/10 - 2], false)); g_string_append_c(gstr, '-'); g_string_append(gstr, get_small_name(&small[n % 10], ordinal)); } } else { const named_number* num = get_named_number(n); integer p = num->number; append_number_name(gstr, n/p, false); g_string_append_c(gstr, ' '); if (n % p == 0) { g_string_append(gstr, get_big_name(num, ordinal)); } else { g_string_append(gstr, get_big_name(num, false)); g_string_append_c(gstr, ' '); append_number_name(gstr, n % p, ordinal); } } } GString* number_name(integer n, bool ordinal) { GString* result = g_string_sized_new(8); append_number_name(result, n, ordinal); return result; } void test_ordinal(integer n) { GString* name = number_name(n, true); printf("%llu: %s\n", n, name->str); g_string_free(name, TRUE); } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
Private Function ordinal(s As String) As String Dim irregs As New Collection irregs.Add "first", "one" irregs.Add "second", "two" irregs.Add "third", "three" irregs.Add "fifth", "five" irregs.Add "eighth", "eight" irregs.Add "ninth", "nine" irregs.Add "twelfth", "twelve" Dim i As Integer For i = Len(s) To 1 Step -1 ch = Mid(s, i, 1) If ch = " " Or ch = "-" Then Exit For Next i On Error GoTo 1 ord = irregs(Right(s, Len(s) - i)) ordinal = Left(s, i) & ord Exit Function 1: If Right(s, 1) = "y" Then s = Left(s, Len(s) - 1) & "ieth" Else s = s & "th" End If ordinal = s End Function Public Sub ordinals() tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}] init For i = 1 To UBound(tests) Debug.Print ordinal(spell(tests(i))) Next i End Sub
Maintain the same structure and functionality when rewriting this code in VB.
#include <stdio.h> inline int self_desc(unsigned long long xx) { register unsigned int d, x; unsigned char cnt[10] = {0}, dig[10] = {0}; for (d = 0; xx > ~0U; xx /= 10) cnt[ dig[d++] = xx % 10 ]++; for (x = xx; x; x /= 10) cnt[ dig[d++] = x % 10 ]++; while(d-- && dig[x++] == cnt[d]); return d == -1; } int main() { int i; for (i = 1; i < 100000000; i++) if (self_desc(i)) printf("%d\n", i); return 0; }
Function IsSelfDescribing(n) IsSelfDescribing = False Set digit = CreateObject("Scripting.Dictionary") For i = 1 To Len(n) k = Mid(n,i,1) If digit.Exists(k) Then digit.Item(k) = digit.Item(k) + 1 Else digit.Add k,1 End If Next c = 0 For j = 0 To Len(n)-1 l = Mid(n,j+1,1) If digit.Exists(CStr(j)) Then If digit.Item(CStr(j)) = CInt(l) Then c = c + 1 End If ElseIf l = 0 Then c = c + 1 Else Exit For End If Next If c = Len(n) Then IsSelfDescribing = True End If End Function start_time = Now s = "" For m = 1 To 100000000 If IsSelfDescribing(m) Then WScript.StdOut.WriteLine m End If Next end_time = Now WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
Ensure the translated VB code behaves exactly like the original C snippet.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 typedef int bool; typedef struct { int x, y; } pair; int* example = NULL; int exampleLen = 0; void reverse(int s[], int len) { int i, j, t; for (i = 0, j = len - 1; i < j; ++i, --j) { t = s[i]; s[i] = s[j]; s[j] = t; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen); pair checkSeq(int pos, int seq[], int n, int len, int minLen) { pair p; if (pos > minLen || seq[0] > n) { p.x = minLen; p.y = 0; return p; } else if (seq[0] == n) { example = malloc(len * sizeof(int)); memcpy(example, seq, len * sizeof(int)); exampleLen = len; p.x = pos; p.y = 1; return p; } else if (pos < minLen) { return tryPerm(0, pos, seq, n, len, minLen); } else { p.x = minLen; p.y = 0; return p; } } pair tryPerm(int i, int pos, int seq[], int n, int len, int minLen) { int *seq2; pair p, res1, res2; size_t size = sizeof(int); if (i > pos) { p.x = minLen; p.y = 0; return p; } seq2 = malloc((len + 1) * size); memcpy(seq2 + 1, seq, len * size); seq2[0] = seq[0] + seq[i]; res1 = checkSeq(pos + 1, seq2, n, len + 1, minLen); res2 = tryPerm(i + 1, pos, seq, n, len, res1.x); free(seq2); if (res2.x < res1.x) return res2; else if (res2.x == res1.x) { p.x = res2.x; p.y = res1.y + res2.y; return p; } else { printf("Error in tryPerm\n"); p.x = 0; p.y = 0; return p; } } pair initTryPerm(int x, int minLen) { int seq[1] = {1}; return tryPerm(0, 0, seq, x, 1, minLen); } void printArray(int a[], int len) { int i; printf("["); for (i = 0; i < len; ++i) printf("%d ", a[i]); printf("\b]\n"); } bool isBrauer(int a[], int len) { int i, j; bool ok; for (i = 2; i < len; ++i) { ok = FALSE; for (j = i - 1; j >= 0; j--) { if (a[i-1] + a[j] == a[i]) { ok = TRUE; break; } } if (!ok) return FALSE; } return TRUE; } bool isAdditionChain(int a[], int len) { int i, j, k; bool ok, exit; for (i = 2; i < len; ++i) { if (a[i] > a[i - 1] * 2) return FALSE; ok = FALSE; exit = FALSE; for (j = i - 1; j >= 0; --j) { for (k = j; k >= 0; --k) { if (a[j] + a[k] == a[i]) { ok = TRUE; exit = TRUE; break; } } if (exit) break; } if (!ok) return FALSE; } if (example == NULL && !isBrauer(a, len)) { example = malloc(len * sizeof(int)); memcpy(example, a, len * sizeof(int)); exampleLen = len; } return TRUE; } void nextChains(int index, int len, int seq[], int *pcount) { for (;;) { int i; if (index < len - 1) { nextChains(index + 1, len, seq, pcount); } if (seq[index] + len - 1 - index >= seq[len - 1]) return; seq[index]++; for (i = index + 1; i < len - 1; ++i) { seq[i] = seq[i-1] + 1; } if (isAdditionChain(seq, len)) (*pcount)++; } } int findNonBrauer(int num, int len, int brauer) { int i, count = 0; int *seq = malloc(len * sizeof(int)); seq[0] = 1; seq[len - 1] = num; for (i = 1; i < len - 1; ++i) { seq[i] = seq[i - 1] + 1; } if (isAdditionChain(seq, len)) count = 1; nextChains(2, len, seq, &count); free(seq); return count - brauer; } void findBrauer(int num, int minLen, int nbLimit) { pair p = initTryPerm(num, minLen); int actualMin = p.x, brauer = p.y, nonBrauer; printf("\nN = %d\n", num); printf("Minimum length of chains : L(%d) = %d\n", num, actualMin); printf("Number of minimum length Brauer chains : %d\n", brauer); if (brauer > 0) { printf("Brauer example : "); reverse(example, exampleLen); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } if (num <= nbLimit) { nonBrauer = findNonBrauer(num, actualMin + 1, brauer); printf("Number of minimum length non-Brauer chains : %d\n", nonBrauer); if (nonBrauer > 0) { printf("Non-Brauer example : "); printArray(example, exampleLen); } if (example != NULL) { free(example); example = NULL; exampleLen = 0; } } else { printf("Non-Brauer analysis suppressed\n"); } } int main() { int i; int nums[12] = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}; printf("Searching for Brauer chains up to a minimum length of 12:\n"); for (i = 0; i < 12; ++i) findBrauer(nums[i], 12, 79); return 0; }
Module Module1 Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer) Dim result As New List(Of Integer) From { n } result.AddRange(seq) Return result End Function Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer) If pos > min_len OrElse seq(0) > n Then Return Tuple.Create(min_len, 0) End If If seq(0) = n Then Return Tuple.Create(pos, 1) End If If pos < min_len Then Return TryPerm(0, pos, seq, n, min_len) End If Return Tuple.Create(min_len, 0) End Function Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer) If i > pos Then Return Tuple.Create(min_len, 0) End If Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len) Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1) If res2.Item1 < res1.Item1 Then Return res2 End If If res2.Item1 = res1.Item1 Then Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2) End If Throw New Exception("TryPerm exception") End Function Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer) Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12) End Function Sub FindBrauer(num As Integer) Dim res = InitTryPerm(num) Console.WriteLine("N = {0}", num) Console.WriteLine("Minimum length of chains: L(n) = {0}", res.Item1) Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2) Console.WriteLine() End Sub Sub Main() Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379} Array.ForEach(nums, Sub(n) FindBrauer(n)) End Sub End Module
Maintain the same structure and functionality when rewriting this code in VB.
#include <stdio.h> void repeat(void (*f)(void), unsigned int n) { while (n-->0) (*f)(); } void example() { printf("Example\n"); } int main(int argc, char *argv[]) { repeat(example, 4); return 0; }
Private Sub Repeat(rid As String, n As Integer) For i = 1 To n Application.Run rid Next i End Sub Private Sub Hello() Debug.Print "Hello" End Sub Public Sub main() Repeat "Hello", 5 End Sub
Port the following code from C to VB with equivalent syntax and logic.
#include<string.h> #include<stdlib.h> #include<locale.h> #include<stdio.h> #include<wchar.h> #include<math.h> int main(int argC,char* argV[]) { double* arr,min,max; char* str; int i,len; if(argC == 1) printf("Usage : %s <data points separated by spaces or commas>",argV[0]); else{ arr = (double*)malloc((argC-1)*sizeof(double)); for(i=1;i<argC;i++){ len = strlen(argV[i]); if(argV[i][len-1]==','){ str = (char*)malloc(len*sizeof(char)); strncpy(str,argV[i],len-1); arr[i-1] = atof(str); free(str); } else arr[i-1] = atof(argV[i]); if(i==1){ min = arr[i-1]; max = arr[i-1]; } else{ min=(min<arr[i-1]?min:arr[i-1]); max=(max>arr[i-1]?max:arr[i-1]); } } printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min); setlocale(LC_ALL, ""); for(i=1;i<argC;i++){ printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7))); } } return 0; }
sub ensure_cscript() if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then createobject("wscript.shell").run "CSCRIPT //nologo """ &_ WScript.ScriptFullName &"""" ,,0 wscript.quit end if end sub class bargraph private bar,mn,mx,nn,cnt Private sub class_initialize() bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_ chrw(&h2586)&chrw(&h2587)&chrw(&h2588) nn=8 end sub public function bg (s) a=split(replace(replace(s,","," ")," "," ")," ") mn=999999:mx=-999999:cnt=ubound(a)+1 for i=0 to ubound(a) a(i)=cdbl(trim(a(i))) if a(i)>mx then mx=a(i) if a(i)<mn then mn=a(i) next ss="Data: " for i=0 to ubound(a) :ss=ss & right (" "& a(i),6) :next ss=ss+vbcrlf + "sparkline: " for i=0 to ubound(a) x=scale(a(i)) ss=ss & string(6,mid(bar,x,1)) next bg=ss &vbcrlf & "min: "&mn & " max: "& mx & _ " cnt: "& ubound(a)+1 &vbcrlf end function private function scale(x) if x=<mn then scale=1 elseif x>=mx then scale=nn else scale=int(nn* (x-mn)/(mx-mn)+1) end if end function end class ensure_cscript set b=new bargraph wscript.stdout.writeblanklines 2 wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1") wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5") wscript.echo b.bg("0, 1, 19, 20") wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999") set b=nothing wscript.echo "If bars don "font to DejaVu Sans Mono or any other that has the bargrph characters" & _ vbcrlf wscript.stdout.write "Press any key.." : wscript.stdin.read 1
Generate a VB translation of this C snippet without changing its computational steps.
#include<string.h> #include<stdlib.h> #include<locale.h> #include<stdio.h> #include<wchar.h> #include<math.h> int main(int argC,char* argV[]) { double* arr,min,max; char* str; int i,len; if(argC == 1) printf("Usage : %s <data points separated by spaces or commas>",argV[0]); else{ arr = (double*)malloc((argC-1)*sizeof(double)); for(i=1;i<argC;i++){ len = strlen(argV[i]); if(argV[i][len-1]==','){ str = (char*)malloc(len*sizeof(char)); strncpy(str,argV[i],len-1); arr[i-1] = atof(str); free(str); } else arr[i-1] = atof(argV[i]); if(i==1){ min = arr[i-1]; max = arr[i-1]; } else{ min=(min<arr[i-1]?min:arr[i-1]); max=(max>arr[i-1]?max:arr[i-1]); } } printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min); setlocale(LC_ALL, ""); for(i=1;i<argC;i++){ printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7))); } } return 0; }
sub ensure_cscript() if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then createobject("wscript.shell").run "CSCRIPT //nologo """ &_ WScript.ScriptFullName &"""" ,,0 wscript.quit end if end sub class bargraph private bar,mn,mx,nn,cnt Private sub class_initialize() bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_ chrw(&h2586)&chrw(&h2587)&chrw(&h2588) nn=8 end sub public function bg (s) a=split(replace(replace(s,","," ")," "," ")," ") mn=999999:mx=-999999:cnt=ubound(a)+1 for i=0 to ubound(a) a(i)=cdbl(trim(a(i))) if a(i)>mx then mx=a(i) if a(i)<mn then mn=a(i) next ss="Data: " for i=0 to ubound(a) :ss=ss & right (" "& a(i),6) :next ss=ss+vbcrlf + "sparkline: " for i=0 to ubound(a) x=scale(a(i)) ss=ss & string(6,mid(bar,x,1)) next bg=ss &vbcrlf & "min: "&mn & " max: "& mx & _ " cnt: "& ubound(a)+1 &vbcrlf end function private function scale(x) if x=<mn then scale=1 elseif x>=mx then scale=nn else scale=int(nn* (x-mn)/(mx-mn)+1) end if end function end class ensure_cscript set b=new bargraph wscript.stdout.writeblanklines 2 wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1") wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5") wscript.echo b.bg("0, 1, 19, 20") wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999") set b=nothing wscript.echo "If bars don "font to DejaVu Sans Mono or any other that has the bargrph characters" & _ vbcrlf wscript.stdout.write "Press any key.." : wscript.stdin.read 1
Transform the following C implementation into VB, maintaining the same output and logic.
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { printf("%d\n", mul_inv(42, 2017)); return 0; }
Private Function mul_inv(a As Long, n As Long) As Variant If n < 0 Then n = -n If a < 0 Then a = n - ((-a) Mod n) Dim t As Long: t = 0 Dim nt As Long: nt = 1 Dim r As Long: r = n Dim nr As Long: nr = a Dim q As Long Do While nr <> 0 q = r \ nr tmp = t t = nt nt = tmp - q * nt tmp = r r = nr nr = tmp - q * nr Loop If r > 1 Then mul_inv = "a is not invertible" Else If t < 0 Then t = t + n mul_inv = t End If End Function Public Sub mi() Debug.Print mul_inv(42, 2017) Debug.Print mul_inv(40, 1) Debug.Print mul_inv(52, -217) Debug.Print mul_inv(-486, 217) Debug.Print mul_inv(40, 2018) End Sub
Ensure the translated VB code behaves exactly like the original C snippet.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <err.h> char response[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n" "<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>" "<style>body { background-color: #111 }" "h1 { font-size:4cm; text-align: center; color: black;" " text-shadow: 0 0 2mm red}</style></head>" "<body><h1>Goodbye, world!</h1></body></html>\r\n"; int main() { int one = 1, client_fd; struct sockaddr_in svr_addr, cli_addr; socklen_t sin_len = sizeof(cli_addr); int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) err(1, "can't open socket"); setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); int port = 8080; svr_addr.sin_family = AF_INET; svr_addr.sin_addr.s_addr = INADDR_ANY; svr_addr.sin_port = htons(port); if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { close(sock); err(1, "Can't bind"); } listen(sock, 5); while (1) { client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); printf("got connection\n"); if (client_fd == -1) { perror("Can't accept"); continue; } write(client_fd, response, sizeof(response) - 1); close(client_fd); } }
Class HTTPSock Inherits TCPSocket Event Sub DataAvailable() Dim headers As New InternetHeaders headers.AppendHeader("Content-Length", Str(LenB("Goodbye, World!"))) headers.AppendHeader("Content-Type", "text/plain") headers.AppendHeader("Content-Encoding", "identity") headers.AppendHeader("Connection", "close") Dim data As String = "HTTP/1.1 200 OK" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + "Goodbye, World!" Me.Write(data) Me.Close End Sub End Class Class HTTPServ Inherits ServerSocket Event Sub AddSocket() As TCPSocket Return New HTTPSock End Sub End Class Class App Inherits Application Event Sub Run(Args() As String) Dim sock As New HTTPServ sock.Port = 8080 sock.Listen() While True App.DoEvents Wend End Sub End Class
Convert the following code from C to VB, ensuring the logic remains intact.
#include <stdio.h> #include <math.h> #define MAX_DIGITS 9 int digits[MAX_DIGITS]; void getDigits(int i) { int ix = 0; while (i > 0) { digits[ix++] = i % 10; i /= 10; } } int main() { int n, d, i, max, lastDigit, sum, dp; int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}; printf("Own digits power sums for N = 3 to 9 inclusive:\n"); for (n = 3; n < 10; ++n) { for (d = 2; d < 10; ++d) powers[d] *= d; i = (int)pow(10, n-1); max = i * 10; lastDigit = 0; while (i < max) { if (!lastDigit) { getDigits(i); sum = 0; for (d = 0; d < n; ++d) { dp = digits[d]; sum += powers[dp]; } } else if (lastDigit == 1) { sum++; } else { sum += powers[lastDigit] - powers[lastDigit-1]; } if (sum == i) { printf("%d\n", i); if (lastDigit == 0) printf("%d\n", i + 1); i += 10 - lastDigit; lastDigit = 0; } else if (sum > i) { i += 10 - lastDigit; lastDigit = 0; } else if (lastDigit < 9) { i++; lastDigit++; } else { i++; lastDigit = 0; } } } return 0; }
Option Strict On Option Explicit On Imports System.IO Module OwnDigitsPowerSum Public Sub Main Dim used(9) As Integer Dim check(9) As Integer Dim power(9, 9) As Long For i As Integer = 0 To 9 check(i) = 0 Next i For i As Integer = 1 To 9 power(1, i) = i Next i For j As Integer = 2 To 9 For i As Integer = 1 To 9 power(j, i) = power(j - 1, i) * i Next i Next j Dim lowestDigit(9) As Integer lowestDigit(1) = -1 lowestDigit(2) = -1 Dim p10 As Long = 100 For i As Integer = 3 To 9 For p As Integer = 2 To 9 Dim np As Long = power(i, p) * i If Not ( np < p10) Then Exit For lowestDigit(i) = p Next p p10 *= 10 Next i Dim maxZeros(9, 9) As Integer For i As Integer = 1 To 9 For j As Integer = 1 To 9 maxZeros(i, j) = 0 Next j Next i p10 = 1000 For w As Integer = 3 To 9 For d As Integer = lowestDigit(w) To 9 Dim nz As Integer = 9 Do If nz < 0 Then Exit Do Else Dim np As Long = power(w, d) * nz IF Not ( np > p10) Then Exit Do End If nz -= 1 Loop maxZeros(w, d) = If(nz > w, 0, w - nz) Next d p10 *= 10 Next w Dim numbers(100) As Long Dim nCount As Integer = 0 Dim tryCount As Integer = 0 Dim digits(9) As Integer For d As Integer = 1 To 9 digits(d) = 9 Next d For d As Integer = 0 To 8 used(d) = 0 Next d used(9) = 9 Dim width As Integer = 9 Dim last As Integer = width p10 = 100000000 Do While width > 2 tryCount += 1 Dim dps As Long = 0 check(0) = used(0) For i As Integer = 1 To 9 check(i) = used(i) If used(i) <> 0 Then dps += used(i) * power(width, i) End If Next i Dim n As Long = dps Do check(CInt(n Mod 10)) -= 1 n \= 10 Loop Until n <= 0 Dim reduceWidth As Boolean = dps <= p10 If Not reduceWidth Then Dim zCount As Integer = 0 For i As Integer = 0 To 9 If check(i) <> 0 Then Exit For zCount+= 1 Next i If zCount = 10 Then nCount += 1 numbers(nCount) = dps End If used(digits(last)) -= 1 digits(last) -= 1 If digits(last) = 0 Then If used(0) >= maxZeros(width, digits(1)) Then digits(last) = -1 End If End If If digits(last) >= 0 Then used(digits(last)) += 1 Else Dim prev As Integer = last Do prev -= 1 If prev < 1 Then Exit Do Else used(digits(prev)) -= 1 digits(prev) -= 1 IF digits(prev) >= 0 Then Exit Do End If Loop If prev > 0 Then If prev = 1 Then If digits(1) <= lowestDigit(width) Then prev = 0 End If End If If prev <> 0 Then used(digits(prev)) += 1 For i As Integer = prev + 1 To width digits(i) = digits(prev) used(digits(prev)) += 1 Next i End If End If If prev <= 0 Then reduceWidth = True End If End If End If If reduceWidth Then last -= 1 width = last If last > 0 Then For d As Integer = 1 To last digits(d) = 9 Next d For d As Integer = last + 1 To 9 digits(d) = -1 Next d For d As Integer = 0 To 8 used(d) = 0 Next d used(9) = last p10 \= 10 End If End If Loop Console.Out.WriteLine("Own digits power sums for N = 3 to 9 inclusive:") For i As Integer = nCount To 1 Step -1 Console.Out.WriteLine(numbers(i)) Next i Console.Out.WriteLine("Considered " & tryCount & " digit combinations") End Sub End Module
Generate a VB translation of this C snippet without changing its computational steps.
#include <stdio.h> #define ELEMENTS 10000000U void make_klarner_rado(unsigned int *dst, unsigned int n) { unsigned int i, i2 = 0, i3 = 0; unsigned int m, m2 = 1, m3 = 1; for (i = 0; i < n; ++i) { dst[i] = m = m2 < m3 ? m2 : m3; if (m2 == m) m2 = dst[i2++] << 1 | 1; if (m3 == m) m3 = dst[i3++] * 3 + 1; } } int main(void) { static unsigned int klarner_rado[ELEMENTS]; unsigned int i; make_klarner_rado(klarner_rado, ELEMENTS); for (i = 0; i < 99; ++i) printf("%u ", klarner_rado[i]); for (i = 100; i <= ELEMENTS; i *= 10) printf("%u\n", klarner_rado[i - 1]); return 0; }
Option Strict On Option Explicit On Imports System.IO Module KlarnerRado Private Const bitsWidth As Integer = 31 Private bitMask() As Integer = _ New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _ , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _ , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _ , 16777216, 33554432, 67108864, 134217728, 268435456 _ , 536870912, 1073741824 _ } Private Const maxElement As Integer = 1100000000 Private Function BitSet(bit As Integer, v As Integer) As Boolean Return (v And bitMask(bit - 1)) <> 0 End Function Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer Return b Or bitMask(bit - 1) End Function Public Sub Main Dim kr(maxElement \ bitsWidth) As Integer For i As Integer = 0 To kr.Count() - 1 kr(i) = 0 Next i Dim krCount As Integer = 0 Dim n21 As Integer = 3 Dim n31 As Integer = 4 Dim p10 As Integer = 1000 Dim iBit As Integer = 0 Dim iOverBw As Integer = 0 Dim p2Bit As Integer = 1 Dim p2OverBw As Integer = 0 Dim p3Bit As Integer = 1 Dim p3OverBw As Integer = 0 kr(0) = SetBit(1, kr(0)) Dim kri As Boolean = True Dim lastI As Integer = 0 For i As Integer = 1 To maxElement iBit += 1 If iBit > bitsWidth Then iBit = 1 iOverBw += 1 End If If i = n21 Then If BitSet(p2Bit, kr(p2OverBw)) Then kri = True End If p2Bit += 1 If p2Bit > bitsWidth Then p2Bit = 1 p2OverBw += 1 End If n21 += 2 End If If i = n31 Then If BitSet(p3Bit, kr(p3OverBw)) Then kri = True End If p3Bit += 1 If p3Bit > bitsWidth Then p3Bit = 1 p3OverBw += 1 End If n31 += 3 End If If kri Then lastI = i kr(iOverBw) = SetBit(iBit, kr(iOverBw)) krCount += 1 If krCount <= 100 Then Console.Out.Write(" " & i.ToString().PadLeft(3)) If krCount Mod 20 = 0 Then Console.Out.WriteLine() End If ElseIf krCount = p10 Then Console.Out.WriteLine("Element " & p10.ToString().PadLeft(10) & " is " & i.ToString().PadLeft(10)) p10 *= 10 End If kri = False End If Next i Console.Out.WriteLine("Element " & krCount.ToString().PadLeft(10) & " is " & lastI.ToString().PadLeft(10)) End Sub End Module
Keep all operations the same but rewrite the snippet in VB.
#include <stdio.h> #define ELEMENTS 10000000U void make_klarner_rado(unsigned int *dst, unsigned int n) { unsigned int i, i2 = 0, i3 = 0; unsigned int m, m2 = 1, m3 = 1; for (i = 0; i < n; ++i) { dst[i] = m = m2 < m3 ? m2 : m3; if (m2 == m) m2 = dst[i2++] << 1 | 1; if (m3 == m) m3 = dst[i3++] * 3 + 1; } } int main(void) { static unsigned int klarner_rado[ELEMENTS]; unsigned int i; make_klarner_rado(klarner_rado, ELEMENTS); for (i = 0; i < 99; ++i) printf("%u ", klarner_rado[i]); for (i = 100; i <= ELEMENTS; i *= 10) printf("%u\n", klarner_rado[i - 1]); return 0; }
Option Strict On Option Explicit On Imports System.IO Module KlarnerRado Private Const bitsWidth As Integer = 31 Private bitMask() As Integer = _ New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _ , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _ , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _ , 16777216, 33554432, 67108864, 134217728, 268435456 _ , 536870912, 1073741824 _ } Private Const maxElement As Integer = 1100000000 Private Function BitSet(bit As Integer, v As Integer) As Boolean Return (v And bitMask(bit - 1)) <> 0 End Function Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer Return b Or bitMask(bit - 1) End Function Public Sub Main Dim kr(maxElement \ bitsWidth) As Integer For i As Integer = 0 To kr.Count() - 1 kr(i) = 0 Next i Dim krCount As Integer = 0 Dim n21 As Integer = 3 Dim n31 As Integer = 4 Dim p10 As Integer = 1000 Dim iBit As Integer = 0 Dim iOverBw As Integer = 0 Dim p2Bit As Integer = 1 Dim p2OverBw As Integer = 0 Dim p3Bit As Integer = 1 Dim p3OverBw As Integer = 0 kr(0) = SetBit(1, kr(0)) Dim kri As Boolean = True Dim lastI As Integer = 0 For i As Integer = 1 To maxElement iBit += 1 If iBit > bitsWidth Then iBit = 1 iOverBw += 1 End If If i = n21 Then If BitSet(p2Bit, kr(p2OverBw)) Then kri = True End If p2Bit += 1 If p2Bit > bitsWidth Then p2Bit = 1 p2OverBw += 1 End If n21 += 2 End If If i = n31 Then If BitSet(p3Bit, kr(p3OverBw)) Then kri = True End If p3Bit += 1 If p3Bit > bitsWidth Then p3Bit = 1 p3OverBw += 1 End If n31 += 3 End If If kri Then lastI = i kr(iOverBw) = SetBit(iBit, kr(iOverBw)) krCount += 1 If krCount <= 100 Then Console.Out.Write(" " & i.ToString().PadLeft(3)) If krCount Mod 20 = 0 Then Console.Out.WriteLine() End If ElseIf krCount = p10 Then Console.Out.WriteLine("Element " & p10.ToString().PadLeft(10) & " is " & i.ToString().PadLeft(10)) p10 *= 10 End If kri = False End If Next i Console.Out.WriteLine("Element " & krCount.ToString().PadLeft(10) & " is " & lastI.ToString().PadLeft(10)) End Sub End Module
Please provide an equivalent version of this C code in VB.
int pancake_sort(int *list, unsigned int length) { if(length<2) return 0; int i,a,max_num_pos,moves; moves=0; for(i=length;i>1;i--) { max_num_pos=0; for(a=0;a<i;a++) { if(list[a]>list[max_num_pos]) max_num_pos=a; } if(max_num_pos==i-1) continue; if(max_num_pos) { moves++; do_flip(list, length, max_num_pos+1); } moves++; do_flip(list, length, i); } return moves; }
Public Sub printarray(A) For i = LBound(A) To UBound(A) Debug.Print A(i), Next Debug.Print End Sub Public Sub Flip(ByRef A, p1, p2, trace) If trace Then Debug.Print "we Cut = Int((p2 - p1 + 1) / 2) For i = 0 To Cut - 1 temp = A(i) A(i) = A(p2 - i) A(p2 - i) = temp Next End Sub Public Sub pancakesort(ByRef A(), Optional trace As Boolean = False) lb = LBound(A) ub = UBound(A) Length = ub - lb + 1 If Length <= 1 Then Exit Sub End If For i = ub To lb + 1 Step -1 P = lb Maximum = A(P) For j = lb + 1 To i If A(j) > Maximum Then P = j Maximum = A(j) End If Next j If P < i Then If P > 1 Then Flip A, lb, P, trace If trace Then printarray A End If Flip A, lb, i, trace If trace Then printarray A End If Next i End Sub Public Sub TestPancake(Optional trace As Boolean = False) Dim A() A = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0) Debug.Print "Initial array:" printarray A pancakesort A, trace Debug.Print "Final array:" printarray A End Sub
Write the same algorithm in VB as shown in this C implementation.
#include <stdio.h> #include <math.h> #include <string.h> #define N 2200 int main(int argc, char **argv){ int a,b,c,d; int r[N+1]; memset(r,0,sizeof(r)); for(a=1; a<=N; a++){ for(b=a; b<=N; b++){ int aabb; if(a&1 && b&1) continue; aabb=a*a + b*b; for(c=b; c<=N; c++){ int aabbcc=aabb + c*c; d=(int)sqrt((float)aabbcc); if(aabbcc == d*d && d<=N) r[d]=1; } } } for(a=1; a<=N; a++) if(!r[a]) printf("%d ",a); printf("\n"); }
Const n = 2200 Public Sub pq() Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3 Dim l(n) As Boolean, l_add(9680000) As Boolean For x = 1 To n x2 = x * x For y = x To n l_add(x2 + y * y) = True Next y Next x For x = 1 To n s1 = s s = s + 2 s2 = s For y = x + 1 To n If l_add(s1) Then l(y) = True s1 = s1 + s2 s2 = s2 + 2 Next Next For x = 1 To n If Not l(x) Then Debug.Print x; Next Debug.Print End Sub
Convert the following code from C to VB, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { int trial, secs_tot=0, steps_tot=0; int sbeh, slen, wiz, secs; time_t t; srand((unsigned) time(&t)); printf( "Seconds steps behind steps ahead\n" ); for( trial=1;trial<=10000;trial++ ) { sbeh = 0; slen = 100; secs = 0; while(sbeh<slen) { sbeh+=1; for(wiz=1;wiz<=5;wiz++) { if(rand()%slen < sbeh) sbeh+=1; slen+=1; } secs+=1; if(trial==1&&599<secs&&secs<610) printf("%d %d %d\n", secs, sbeh, slen-sbeh ); } secs_tot+=secs; steps_tot+=slen; } printf( "Average secs taken: %f\n", secs_tot/10000.0 ); printf( "Average final length of staircase: %f\n", steps_tot/10000.0 ); return 0; }
Option Explicit Randomize Timer Function pad(s,n) If n<0 Then pad= right(space(-n) & s ,-n) Else pad= left(s& space(n),n) End If End Function Sub print(s) On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub Function Rounds(maxsecs,wiz,a) Dim mystep,maxstep,toend,j,i,x,d If IsArray(a) Then d=True: print "seconds behind pending" maxstep=100 For j=1 To maxsecs For i=1 To wiz If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1 maxstep=maxstep+1 Next mystep=mystep+1 If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function If d Then If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8) End If Next Rounds=Array(maxsecs,maxstep) End Function Dim n,r,a,sumt,sums,ntests,t,maxsecs ntests=10000 maxsecs=7000 t=timer a=Array(600,609) For n=1 To ntests r=Rounds(maxsecs,5,a) If r(0)<>maxsecs Then sumt=sumt+r(0) sums=sums+r(1) End if a="" Next print vbcrlf & "Done " & ntests & " tests in " & Timer-t & " seconds" print "escaped in " & sumt/ntests & " seconds with " & sums/ntests & " stairs"
Rewrite the snippet below in VB so it works the same as the original C code.
#include<stdio.h> long long seed; long long random(){ seed = seed * seed / 1000 % 1000000; return seed; } int main(){ seed = 675248; for(int i=1;i<=5;i++) printf("%lld\n",random()); return 0; }
Option Explicit Dim seed As Long Sub Main() Dim i As Integer seed = 675248 For i = 1 To 5 Debug.Print Rand Next i End Sub Function Rand() As Variant Dim s As String s = CStr(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End Function
Port the provided C code into VB while preserving the original functionality.
#include<stdio.h> long long seed; long long random(){ seed = seed * seed / 1000 % 1000000; return seed; } int main(){ seed = 675248; for(int i=1;i<=5;i++) printf("%lld\n",random()); return 0; }
Option Explicit Dim seed As Long Sub Main() Dim i As Integer seed = 675248 For i = 1 To 5 Debug.Print Rand Next i End Sub Function Rand() As Variant Dim s As String s = CStr(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End Function
Preserve the algorithm and functionality while converting the code from C to VB.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define strcomp(X, Y) strcasecmp(X, Y) struct option { const char *name, *value; int flag; }; struct option updlist[] = { { "NEEDSPEELING", NULL }, { "SEEDSREMOVED", "" }, { "NUMBEROFBANANAS", "1024" }, { "NUMBEROFSTRAWBERRIES", "62000" }, { NULL, NULL } }; int output_opt(FILE *to, struct option *opt) { if (opt->value == NULL) return fprintf(to, "; %s\n", opt->name); else if (opt->value[0] == 0) return fprintf(to, "%s\n", opt->name); else return fprintf(to, "%s %s\n", opt->name, opt->value); } int update(FILE *from, FILE *to, struct option *updlist) { char line_buf[256], opt_name[128]; int i; for (;;) { size_t len, space_span, span_to_hash; if (fgets(line_buf, sizeof line_buf, from) == NULL) break; len = strlen(line_buf); space_span = strspn(line_buf, "\t "); span_to_hash = strcspn(line_buf, "#"); if (space_span == span_to_hash) goto line_out; if (space_span == len) goto line_out; if ((sscanf(line_buf, "; %127s", opt_name) == 1) || (sscanf(line_buf, "%127s", opt_name) == 1)) { int flag = 0; for (i = 0; updlist[i].name; i++) { if (strcomp(updlist[i].name, opt_name) == 0) { if (output_opt(to, &updlist[i]) < 0) return -1; updlist[i].flag = 1; flag = 1; } } if (flag == 0) goto line_out; } else line_out: if (fprintf(to, "%s", line_buf) < 0) return -1; continue; } { for (i = 0; updlist[i].name; i++) { if (!updlist[i].flag) if (output_opt(to, &updlist[i]) < 0) return -1; } } return feof(from) ? 0 : -1; } int main(void) { if (update(stdin, stdout, updlist) < 0) { fprintf(stderr, "failed\n"); return (EXIT_FAILURE); } return 0; }
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objParamLookup = CreateObject("Scripting.Dictionary") With objParamLookup .Add "FAVOURITEFRUIT", "banana" .Add "NEEDSPEELING", "" .Add "SEEDSREMOVED", "" .Add "NUMBEROFBANANAS", "1024" .Add "NUMBEROFSTRAWBERRIES", "62000" End With Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\IN_config.txt",1) Output = "" Isnumberofstrawberries = False With objInFile Do Until .AtEndOfStream line = .ReadLine If Left(line,1) = "#" Or line = "" Then Output = Output & line & vbCrLf ElseIf Left(line,1) = " " And InStr(line,"#") Then Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf ElseIf Replace(Replace(line,";","")," ","") <> "" Then If InStr(1,line,"FAVOURITEFRUIT",1) Then Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf ElseIf InStr(1,line,"NEEDSPEELING",1) Then Output = Output & "; " & "NEEDSPEELING" & vbCrLf ElseIf InStr(1,line,"SEEDSREMOVED",1) Then Output = Output & "SEEDSREMOVED" & vbCrLf ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If End If Loop If Isnumberofstrawberries = False Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If .Close End With Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\OUT_config.txt",2,True) With objOutFile .Write Output .Close End With Set objFSO = Nothing Set objParamLookup = Nothing
Port the provided C code into VB while preserving the original functionality.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define strcomp(X, Y) strcasecmp(X, Y) struct option { const char *name, *value; int flag; }; struct option updlist[] = { { "NEEDSPEELING", NULL }, { "SEEDSREMOVED", "" }, { "NUMBEROFBANANAS", "1024" }, { "NUMBEROFSTRAWBERRIES", "62000" }, { NULL, NULL } }; int output_opt(FILE *to, struct option *opt) { if (opt->value == NULL) return fprintf(to, "; %s\n", opt->name); else if (opt->value[0] == 0) return fprintf(to, "%s\n", opt->name); else return fprintf(to, "%s %s\n", opt->name, opt->value); } int update(FILE *from, FILE *to, struct option *updlist) { char line_buf[256], opt_name[128]; int i; for (;;) { size_t len, space_span, span_to_hash; if (fgets(line_buf, sizeof line_buf, from) == NULL) break; len = strlen(line_buf); space_span = strspn(line_buf, "\t "); span_to_hash = strcspn(line_buf, "#"); if (space_span == span_to_hash) goto line_out; if (space_span == len) goto line_out; if ((sscanf(line_buf, "; %127s", opt_name) == 1) || (sscanf(line_buf, "%127s", opt_name) == 1)) { int flag = 0; for (i = 0; updlist[i].name; i++) { if (strcomp(updlist[i].name, opt_name) == 0) { if (output_opt(to, &updlist[i]) < 0) return -1; updlist[i].flag = 1; flag = 1; } } if (flag == 0) goto line_out; } else line_out: if (fprintf(to, "%s", line_buf) < 0) return -1; continue; } { for (i = 0; updlist[i].name; i++) { if (!updlist[i].flag) if (output_opt(to, &updlist[i]) < 0) return -1; } } return feof(from) ? 0 : -1; } int main(void) { if (update(stdin, stdout, updlist) < 0) { fprintf(stderr, "failed\n"); return (EXIT_FAILURE); } return 0; }
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objParamLookup = CreateObject("Scripting.Dictionary") With objParamLookup .Add "FAVOURITEFRUIT", "banana" .Add "NEEDSPEELING", "" .Add "SEEDSREMOVED", "" .Add "NUMBEROFBANANAS", "1024" .Add "NUMBEROFSTRAWBERRIES", "62000" End With Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\IN_config.txt",1) Output = "" Isnumberofstrawberries = False With objInFile Do Until .AtEndOfStream line = .ReadLine If Left(line,1) = "#" Or line = "" Then Output = Output & line & vbCrLf ElseIf Left(line,1) = " " And InStr(line,"#") Then Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf ElseIf Replace(Replace(line,";","")," ","") <> "" Then If InStr(1,line,"FAVOURITEFRUIT",1) Then Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf ElseIf InStr(1,line,"NEEDSPEELING",1) Then Output = Output & "; " & "NEEDSPEELING" & vbCrLf ElseIf InStr(1,line,"SEEDSREMOVED",1) Then Output = Output & "SEEDSREMOVED" & vbCrLf ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If End If Loop If Isnumberofstrawberries = False Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If .Close End With Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\OUT_config.txt",2,True) With objOutFile .Write Output .Close End With Set objFSO = Nothing Set objParamLookup = Nothing
Translate the given C code snippet into VB without altering its behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include "wren.h" struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; char *ptr = realloc(mem->memory, mem->size + realsize + 1); if(!ptr) { printf("not enough memory (realloc returned NULL)\n"); return 0; } mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } void C_bufferAllocate(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); ms->memory = malloc(1); ms->size = 0; } void C_bufferFinalize(void* data) { struct MemoryStruct *ms = (struct MemoryStruct *)data; free(ms->memory); } void C_curlAllocate(WrenVM* vm) { CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); *pcurl = curl_easy_init(); } void C_value(WrenVM* vm) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); wrenSetSlotString(vm, 0, ms->memory); } void C_easyPerform(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_perform(curl); } void C_easyCleanup(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); curl_easy_cleanup(curl); } void C_easySetOpt(WrenVM* vm) { CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); if (opt < 10000) { long lparam = (long)wrenGetSlotDouble(vm, 2); curl_easy_setopt(curl, opt, lparam); } else if (opt < 20000) { if (opt == CURLOPT_WRITEDATA) { struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); curl_easy_setopt(curl, opt, (void *)ms); } else if (opt == CURLOPT_URL) { const char *url = wrenGetSlotString(vm, 2); curl_easy_setopt(curl, opt, url); } } else if (opt < 30000) { if (opt == CURLOPT_WRITEFUNCTION) { curl_easy_setopt(curl, opt, &WriteMemoryCallback); } } } WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { WrenForeignClassMethods methods; methods.allocate = NULL; methods.finalize = NULL; if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { methods.allocate = C_bufferAllocate; methods.finalize = C_bufferFinalize; } else if (strcmp(className, "Curl") == 0) { methods.allocate = C_curlAllocate; } } return methods; } WrenForeignMethodFn bindForeignMethod( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { if (strcmp(module, "main") == 0) { if (strcmp(className, "Buffer") == 0) { if (!isStatic && strcmp(signature, "value") == 0) return C_value; } else if (strcmp(className, "Curl") == 0) { if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; } } return NULL; } static void writeFn(WrenVM* vm, const char* text) { printf("%s", text); } void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { switch (errorType) { case WREN_ERROR_COMPILE: printf("[%s line %d] [Error] %s\n", module, line, msg); break; case WREN_ERROR_STACK_TRACE: printf("[%s line %d] in %s\n", module, line, msg); break; case WREN_ERROR_RUNTIME: printf("[Runtime Error] %s\n", msg); break; } } char *readFile(const char *fileName) { FILE *f = fopen(fileName, "r"); fseek(f, 0, SEEK_END); long fsize = ftell(f); rewind(f); char *script = malloc(fsize + 1); fread(script, 1, fsize, f); fclose(f); script[fsize] = 0; return script; } static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { if( result.source) free((void*)result.source); } WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { WrenLoadModuleResult result = {0}; if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { result.onComplete = loadModuleComplete; char fullName[strlen(name) + 6]; strcpy(fullName, name); strcat(fullName, ".wren"); result.source = readFile(fullName); } return result; } int main(int argc, char **argv) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = &writeFn; config.errorFn = &errorFn; config.bindForeignClassFn = &bindForeignClass; config.bindForeignMethodFn = &bindForeignMethod; config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; const char* fileName = "rc_find_unimplemented_tasks.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { case WREN_RESULT_COMPILE_ERROR: printf("Compile Error!\n"); break; case WREN_RESULT_RUNTIME_ERROR: printf("Runtime Error!\n"); break; case WREN_RESULT_SUCCESS: break; } wrenFreeVM(vm); free(script); return 0; }
Set http= CreateObject("WinHttp.WinHttpRequest.5.1") Set oDic = WScript.CreateObject("scripting.dictionary") start="https://rosettacode.org" Const lang="VBScript" Dim oHF gettaskslist "about:/wiki/Category:Programming_Tasks" ,True print odic.Count gettaskslist "about:/wiki/Category:Draft_Programming_Tasks",True print "total tasks " & odic.Count gettaskslist "about:/wiki/Category:"&lang,False print "total tasks not in " & lang & " " &odic.Count & vbcrlf For Each d In odic.keys print d &vbTab & Replace(odic(d),"about:", start) next WScript.Quit(1) Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.echo " Please run this script with CScript": WScript.quit End Sub Function getpage(name) Set oHF=Nothing Set oHF = CreateObject("HTMLFILE") http.open "GET",name,False http.send oHF.write "<html><body></body></html>" oHF.body.innerHTML = http.responsetext Set getpage=Nothing End Function Sub gettaskslist(b,build) nextpage=b While nextpage <>"" nextpage=Replace(nextpage,"about:", start) WScript.Echo nextpage getpage(nextpage) Set xtoc = oHF.getElementbyId("mw-pages") nextpage="" For Each ch In xtoc.children If ch.innertext= "next page" Then nextpage=ch.attributes("href").value ElseIf ch.attributes("class").value="mw-content-ltr" Then Set ytoc=ch.children(0) Exit For End If Next For Each ch1 In ytoc.children For Each ch2 In ch1.children(1).children Set ch=ch2.children(0) If build Then odic.Add ch.innertext , ch.attributes("href").value else odic.Remove ch.innertext End if Next Next Wend End Sub
Port the provided C++ code into Java while preserving the original functionality.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
public class PrimeDigits { private static boolean primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; if (r != 2 && r != 3 && r != 5 && r != 7) { return false; } n /= 10; sum += r; } return sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
Port the following code from C++ to Java with equivalent syntax and logic.
#include <algorithm> #include <iostream> #include <sstream> #include <string> template <typename T> void demo_compare(const T &a, const T &b, const std::string &semantically) { std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ") << "exactly " << semantically << " equal." << std::endl; std::cout << a << " and " << b << " are " << ((a != b) ? "" : "not ") << semantically << "inequal." << std::endl; std::cout << a << " is " << ((a < b) ? "" : "not ") << semantically << " ordered before " << b << '.' << std::endl; std::cout << a << " is " << ((a > b) ? "" : "not ") << semantically << " ordered after " << b << '.' << std::endl; } int main(int argc, char *argv[]) { std::string a((argc > 1) ? argv[1] : "1.2.Foo"); std::string b((argc > 2) ? argv[2] : "1.3.Bar"); demo_compare<std::string>(a, b, "lexically"); std::transform(a.begin(), a.end(), a.begin(), ::tolower); std::transform(b.begin(), b.end(), b.begin(), ::tolower); demo_compare<std::string>(a, b, "lexically"); double numA, numB; std::istringstream(a) >> numA; std::istringstream(b) >> numB; demo_compare<double>(numA, numB, "numerically"); return (a == b); }
public class Compare { public static void compare (String A, String B) { if (A.equals(B)) System.debug(A + ' and ' + B + ' are lexically equal.'); else System.debug(A + ' and ' + B + ' are not lexically equal.'); if (A.equalsIgnoreCase(B)) System.debug(A + ' and ' + B + ' are case-insensitive lexically equal.'); else System.debug(A + ' and ' + B + ' are not case-insensitive lexically equal.'); if (A.compareTo(B) < 0) System.debug(A + ' is lexically before ' + B); else if (A.compareTo(B) > 0) System.debug(A + ' is lexically after ' + B); if (A.compareTo(B) >= 0) System.debug(A + ' is not lexically before ' + B); if (A.compareTo(B) <= 0) System.debug(A + ' is not lexically after ' + B); System.debug('The lexical relationship is: ' + A.compareTo(B)); } }
Port the provided C++ code into Java while preserving the original functionality.
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
import java.io.*; import java.nio.channels.*; import java.util.Date; public class TakeNotes { public static void main(String[] args) throws IOException { if (args.length > 0) { PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true)); ps.println(new Date()); ps.print("\t" + args[0]); for (int i = 1; i < args.length; i++) ps.print(" " + args[i]); ps.println(); ps.close(); } else { FileChannel fc = new FileInputStream("notes.txt").getChannel(); fc.transferTo(0, fc.size(), Channels.newChannel(System.out)); fc.close(); } } }
Write the same code in Java as shown below in C++.
#include <cmath> #include <iostream> #include <iomanip> #include <string.h> constexpr unsigned int N = 32u; double xval[N], t_sin[N], t_cos[N], t_tan[N]; constexpr unsigned int N2 = N * (N - 1u) / 2u; double r_sin[N2], r_cos[N2], r_tan[N2]; double ρ(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; unsigned int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, unsigned int n) { return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } inline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); } inline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); } inline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); } int main() { constexpr double step = .05; for (auto i = 0u; i < N; i++) { xval[i] = i * step; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (auto i = 0u; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = NAN; std::cout << std::setw(16) << std::setprecision(25) << 6 * i_sin(.5) << std::endl << 3 * i_cos(.5) << std::endl << 4 * i_tan(1.) << std::endl; return 0; }
import static java.lang.Math.*; public class Test { final static int N = 32; final static int N2 = (N * (N - 1) / 2); final static double STEP = 0.05; static double[] xval = new double[N]; static double[] t_sin = new double[N]; static double[] t_cos = new double[N]; static double[] t_tan = new double[N]; static double[] r_sin = new double[N2]; static double[] r_cos = new double[N2]; static double[] r_tan = new double[N2]; static double rho(double[] x, double[] y, double[] r, int i, int n) { if (n < 0) return 0; if (n == 0) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } static double thiele(double[] x, double[] y, double[] r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } public static void main(String[] args) { for (int i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (int i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN; System.out.printf("%16.14f%n", 6 * thiele(t_sin, xval, r_sin, 0.5, 0)); System.out.printf("%16.14f%n", 3 * thiele(t_cos, xval, r_cos, 0.5, 0)); System.out.printf("%16.14f%n", 4 * thiele(t_tan, xval, r_tan, 1.0, 0)); } }
Produce a language-to-language conversion: from C++ to Java, same semantics.
#include <cmath> #include <iostream> #include <iomanip> #include <string.h> constexpr unsigned int N = 32u; double xval[N], t_sin[N], t_cos[N], t_tan[N]; constexpr unsigned int N2 = N * (N - 1u) / 2u; double r_sin[N2], r_cos[N2], r_tan[N2]; double ρ(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; unsigned int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, unsigned int n) { return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } inline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); } inline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); } inline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); } int main() { constexpr double step = .05; for (auto i = 0u; i < N; i++) { xval[i] = i * step; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (auto i = 0u; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = NAN; std::cout << std::setw(16) << std::setprecision(25) << 6 * i_sin(.5) << std::endl << 3 * i_cos(.5) << std::endl << 4 * i_tan(1.) << std::endl; return 0; }
import static java.lang.Math.*; public class Test { final static int N = 32; final static int N2 = (N * (N - 1) / 2); final static double STEP = 0.05; static double[] xval = new double[N]; static double[] t_sin = new double[N]; static double[] t_cos = new double[N]; static double[] t_tan = new double[N]; static double[] r_sin = new double[N2]; static double[] r_cos = new double[N2]; static double[] r_tan = new double[N2]; static double rho(double[] x, double[] y, double[] r, int i, int n) { if (n < 0) return 0; if (n == 0) return y[i]; int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + rho(x, y, r, i + 1, n - 2); return r[idx]; } static double thiele(double[] x, double[] y, double[] r, double xin, int n) { if (n > N - 1) return 1; return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } public static void main(String[] args) { for (int i = 0; i < N; i++) { xval[i] = i * STEP; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (int i = 0; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN; System.out.printf("%16.14f%n", 6 * thiele(t_sin, xval, r_sin, 0.5, 0)); System.out.printf("%16.14f%n", 3 * thiele(t_cos, xval, r_cos, 0.5, 0)); System.out.printf("%16.14f%n", 4 * thiele(t_tan, xval, r_tan, 1.0, 0)); } }
Rewrite the snippet below in Java so it works the same as the original C++ code.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
import java.util.*; public class FWord { private String fWord0 = ""; private String fWord1 = ""; private String nextFWord () { final String result; if ( "".equals ( fWord1 ) ) result = "1"; else if ( "".equals ( fWord0 ) ) result = "0"; else result = fWord1 + fWord0; fWord0 = fWord1; fWord1 = result; return result; } public static double entropy ( final String source ) { final int length = source.length (); final Map < Character, Integer > counts = new HashMap < Character, Integer > (); double result = 0.0; for ( int i = 0; i < length; i++ ) { final char c = source.charAt ( i ); if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); else counts.put ( c, 1 ); } for ( final int count : counts.values () ) { final double proportion = ( double ) count / length; result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); } return result; } public static void main ( final String [] args ) { final FWord fWord = new FWord (); for ( int i = 0; i < 37; ) { final String word = fWord.nextFWord (); System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) ); } } }
Change the programming language of this snippet from C++ to Java without modifying what it does.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
import java.util.*; public class FWord { private String fWord0 = ""; private String fWord1 = ""; private String nextFWord () { final String result; if ( "".equals ( fWord1 ) ) result = "1"; else if ( "".equals ( fWord0 ) ) result = "0"; else result = fWord1 + fWord0; fWord0 = fWord1; fWord1 = result; return result; } public static double entropy ( final String source ) { final int length = source.length (); final Map < Character, Integer > counts = new HashMap < Character, Integer > (); double result = 0.0; for ( int i = 0; i < length; i++ ) { final char c = source.charAt ( i ); if ( counts.containsKey ( c ) ) counts.put ( c, counts.get ( c ) + 1 ); else counts.put ( c, 1 ); } for ( final int count : counts.values () ) { final double proportion = ( double ) count / length; result -= proportion * ( Math.log ( proportion ) / Math.log ( 2 ) ); } return result; } public static void main ( final String [] args ) { final FWord fWord = new FWord (); for ( int i = 0; i < 37; ) { final String word = fWord.nextFWord (); System.out.printf ( "%3d %10d %s %n", ++i, word.length (), entropy ( word ) ); } } }
Write the same code in Java as shown below in C++.
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(double a) { return normalize<double>(a, 400); } inline double m2m(double a) { return normalize<double>(a, 6400); } inline double r2r(double a) { return normalize<double>(a, 2*M_PI); } double d2g(double a) { return g2g(a * 10 / 9); } double d2m(double a) { return m2m(a * 160 / 9); } double d2r(double a) { return r2r(a * M_PI / 180); } double g2d(double a) { return d2d(a * 9 / 10); } double g2m(double a) { return m2m(a * 16); } double g2r(double a) { return r2r(a * M_PI / 200); } double m2d(double a) { return d2d(a * 9 / 160); } double m2g(double a) { return g2g(a / 16); } double m2r(double a) { return r2r(a * M_PI / 3200); } double r2d(double a) { return d2d(a * 180 / M_PI); } double r2g(double a) { return g2g(a * 200 / M_PI); } double r2m(double a) { return m2m(a * 3200 / M_PI); } void print(const std::vector<double> &values, const char *s, std::function<double(double)> f) { using namespace std; ostringstream out; out << " ┌───────────────────┐\n"; out << " │ " << setw(17) << s << " │\n"; out << "┌─────────────────┼───────────────────┤\n"; for (double i : values) out << "│ " << setw(15) << fixed << i << defaultfloat << " │ " << setw(17) << fixed << f(i) << defaultfloat << " │\n"; out << "└─────────────────┴───────────────────┘\n"; auto str = out.str(); boost::algorithm::replace_all(str, ".000000", " "); cout << str; } int main() { std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 }; print(values, "normalized (deg)", d2d); print(values, "normalized (grad)", g2g); print(values, "normalized (mil)", m2m); print(values, "normalized (rad)", r2r); print(values, "deg -> grad ", d2g); print(values, "deg -> mil ", d2m); print(values, "deg -> rad ", d2r); print(values, "grad -> deg ", g2d); print(values, "grad -> mil ", g2m); print(values, "grad -> rad ", g2r); print(values, "mil -> deg ", m2d); print(values, "mil -> grad ", m2g); print(values, "mil -> rad ", m2r); print(values, "rad -> deg ", r2d); print(values, "rad -> grad ", r2g); print(values, "rad -> mil ", r2m); return 0; }
import java.text.DecimalFormat; public class AnglesNormalizationAndConversion { public static void main(String[] args) { DecimalFormat formatAngle = new DecimalFormat("######0.000000"); DecimalFormat formatConv = new DecimalFormat("###0.0000"); System.out.printf(" degrees gradiens mils radians%n"); for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) { for ( String units : new String[] {"degrees", "gradiens", "mils", "radians"}) { double d = 0, g = 0, m = 0, r = 0; switch (units) { case "degrees": d = d2d(angle); g = d2g(d); m = d2m(d); r = d2r(d); break; case "gradiens": g = g2g(angle); d = g2d(g); m = g2m(g); r = g2r(g); break; case "mils": m = m2m(angle); d = m2d(m); g = m2g(m); r = m2r(m); break; case "radians": r = r2r(angle); d = r2d(r); g = r2g(r); m = r2m(r); break; } System.out.printf("%15s %8s = %10s %10s %10s %10s%n", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r)); } } } private static final double DEGREE = 360D; private static final double GRADIAN = 400D; private static final double MIL = 6400D; private static final double RADIAN = (2 * Math.PI); private static double d2d(double a) { return a % DEGREE; } private static double d2g(double a) { return a * (GRADIAN / DEGREE); } private static double d2m(double a) { return a * (MIL / DEGREE); } private static double d2r(double a) { return a * (RADIAN / 360); } private static double g2d(double a) { return a * (DEGREE / GRADIAN); } private static double g2g(double a) { return a % GRADIAN; } private static double g2m(double a) { return a * (MIL / GRADIAN); } private static double g2r(double a) { return a * (RADIAN / GRADIAN); } private static double m2d(double a) { return a * (DEGREE / MIL); } private static double m2g(double a) { return a * (GRADIAN / MIL); } private static double m2m(double a) { return a % MIL; } private static double m2r(double a) { return a * (RADIAN / MIL); } private static double r2d(double a) { return a * (DEGREE / RADIAN); } private static double r2g(double a) { return a * (GRADIAN / RADIAN); } private static double r2m(double a) { return a * (MIL / RADIAN); } private static double r2r(double a) { return a % RADIAN; } }
Rewrite the snippet below in Java so it works the same as the original C++ code.
#include <algorithm> #include <iostream> #include <string> #include <vector> std::string longestPath( const std::vector<std::string> & , char ) ; int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std::vector<std::string> myDirs ( dirs , dirs + 3 ) ; std::cout << "The longest common path of the given directories is " << longestPath( myDirs , '/' ) << "!\n" ; return 0 ; } std::string longestPath( const std::vector<std::string> & dirs , char separator ) { std::vector<std::string>::const_iterator vsi = dirs.begin( ) ; int maxCharactersCommon = vsi->length( ) ; std::string compareString = *vsi ; for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) { std::pair<std::string::const_iterator , std::string::const_iterator> p = std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ; if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) maxCharactersCommon = p.first - compareString.begin( ) ; } std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ; return compareString.substr( 0 , found ) ; }
public class CommonPath { public static String commonPath(String... paths){ String commonPath = ""; String[][] folders = new String[paths.length][]; for(int i = 0; i < paths.length; i++){ folders[i] = paths[i].split("/"); } for(int j = 0; j < folders[0].length; j++){ String thisFolder = folders[0][j]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
Write the same algorithm in Java as shown in this C++ implementation.
#include <algorithm> #include <iostream> #include <string> #include <vector> std::string longestPath( const std::vector<std::string> & , char ) ; int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std::vector<std::string> myDirs ( dirs , dirs + 3 ) ; std::cout << "The longest common path of the given directories is " << longestPath( myDirs , '/' ) << "!\n" ; return 0 ; } std::string longestPath( const std::vector<std::string> & dirs , char separator ) { std::vector<std::string>::const_iterator vsi = dirs.begin( ) ; int maxCharactersCommon = vsi->length( ) ; std::string compareString = *vsi ; for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) { std::pair<std::string::const_iterator , std::string::const_iterator> p = std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ; if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) maxCharactersCommon = p.first - compareString.begin( ) ; } std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ; return compareString.substr( 0 , found ) ; }
public class CommonPath { public static String commonPath(String... paths){ String commonPath = ""; String[][] folders = new String[paths.length][]; for(int i = 0; i < paths.length; i++){ folders[i] = paths[i].split("/"); } for(int j = 0; j < folders[0].length; j++){ String thisFolder = folders[0][j]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
Change the following C++ code into Java without altering its purpose.
#include <map> #include <iostream> #include <cmath> template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist; for (int i = 0; i < calls; ++i) ++dist[f()]; double mean = 1.0/dist.size(); bool good = true; for (distmap::iterator i = dist.begin(); i != dist.end(); ++i) { if (std::abs((1.0 * i->second)/calls - mean) > delta) { std::cout << "Relative frequency " << i->second/(1.0*calls) << " of result " << i->first << " deviates by more than " << delta << " from the expected value " << mean << "\n"; good = false; } } return good; }
import static java.lang.Math.abs; import java.util.*; import java.util.function.IntSupplier; public class Test { static void distCheck(IntSupplier f, int nRepeats, double delta) { Map<Integer, Integer> counts = new HashMap<>(); for (int i = 0; i < nRepeats; i++) counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1); double target = nRepeats / (double) counts.size(); int deltaCount = (int) (delta / 100.0 * target); counts.forEach((k, v) -> { if (abs(target - v) >= deltaCount) System.out.printf("distribution potentially skewed " + "for '%s': '%d'%n", k, v); }); counts.keySet().stream().sorted().forEach(k -> System.out.printf("%d %d%n", k, counts.get(k))); } public static void main(String[] a) { distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1); } }
Please provide an equivalent version of this C++ code in Java.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
Keep all operations the same but rewrite the snippet in Java.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
Produce a language-to-language conversion: from C++ to Java, same semantics.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Generate an equivalent Java version of this C++ code.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Preserve the algorithm and functionality while converting the code from C++ to Java.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
Rewrite this program in Java while keeping its functionality equivalent to the C++ version.
#include <string> int main() { int* p; p = new int; delete p; p = new int(2); delete p; std::string* p2; p2 = new std::string; delete p2; p = new int[10]; delete[] p; p2 = new std::string[10]; delete[] p2; }
Object foo = new Object(); int[] fooArray = new int[size]; int x = 0;
Rewrite the snippet below in Java so it works the same as the original C++ code.
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(i); } }
Write a version of this C++ function in Java with identical behavior.
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(i); } }
Please provide an equivalent version of this C++ code in Java.
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(i); } }
Convert this C++ block to Java, preserving its control flow and logic.
#include <iostream> #include <fstream> #include <cmath> using namespace std; string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; } double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; } int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
Convert this C++ block to Java, preserving its control flow and logic.
#include <iostream> #include <fstream> #include <cmath> using namespace std; string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; } double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; } int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class EntropyNarcissist { private static final String FILE_NAME = "src/EntropyNarcissist.java"; public static void main(String[] args) { System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME)); } private static double getEntropy(String fileName) { Map<Character,Integer> characterCount = new HashMap<>(); int length = 0; try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) { int c = 0; while ( (c = reader.read()) != -1 ) { characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2); length++; } } catch ( IOException e ) { throw new RuntimeException(e); } double entropy = 0; for ( char key : characterCount.keySet() ) { double fraction = (double) characterCount.get(key) / length; entropy -= fraction * Math.log(fraction); } return entropy / Math.log(2); } }
Convert this C++ snippet to Java and keep its semantics consistent.
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Can you help me rewrite this code in Java instead of C++, keeping it the same logically?
#include <cmath> #include <fstream> #include <iostream> #include <string> class peano_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::string& s); double x_; double y_; int angle_; int length_; }; void peano_curve::write(std::ostream& out, int size, int length, int order) { length_ = length; x_ = length; y_ = length; angle_ = 90; out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; std::string s = "L"; for (int i = 0; i < order; ++i) s = rewrite(s); execute(out, s); out << "'/>\n</svg>\n"; } std::string peano_curve::rewrite(const std::string& s) { std::string t; for (char c : s) { switch (c) { case 'L': t += "LFRFL-F-RFLFR+F+LFRFL"; break; case 'R': t += "RFLFR+F+LFRFL-F-RFLFR"; break; default: t += c; break; } } return t; } void peano_curve::line(std::ostream& out) { double theta = (3.14159265359 * angle_)/180.0; x_ += length_ * std::cos(theta); y_ += length_ * std::sin(theta); out << " L" << x_ << ',' << y_; } void peano_curve::execute(std::ostream& out, const std::string& s) { out << 'M' << x_ << ',' << y_; for (char c : s) { switch (c) { case 'F': line(out); break; case '+': angle_ = (angle_ + 90) % 360; break; case '-': angle_ = (angle_ - 90) % 360; break; } } } int main() { std::ofstream out("peano_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return 1; } peano_curve pc; pc.write(out, 656, 8, 4); return 0; }
import java.io.*; public class PeanoCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) { PeanoCurve s = new PeanoCurve(writer); final int length = 8; s.currentAngle = 90; s.currentX = length; s.currentY = length; s.lineLength = length; s.begin(656); s.execute(rewrite(4)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private PeanoCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY += length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = "L"; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'L') sb.append("LFRFL-F-RFLFR+F+LFRFL"); else if (ch == 'R') sb.append("RFLFR+F+LFRFL-F-RFLFR"); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final int ANGLE = 90; }
Convert this C++ block to Java, preserving its control flow and logic.
template<typename F> class fivetoseven { public: fivetoseven(F f): d5(f), rem(0), max(1) {} int operator()(); private: F d5; int rem, max; }; template<typename F> int fivetoseven<F>::operator()() { while (rem/7 == max/7) { while (max < 7) { int rand5 = d5()-1; max *= 5; rem = 5*rem + rand5; } int groups = max / 7; if (rem >= 7*groups) { rem -= 7*groups; max -= 7*groups; } } int result = rem % 7; rem /= 7; max /= 7; return result+1; } int d5() { return 5.0*std::rand()/(RAND_MAX + 1.0) + 1; } fivetoseven<int(*)()> d7(d5); int main() { srand(time(0)); test_distribution(d5, 1000000, 0.001); test_distribution(d7, 1000000, 0.001); }
import java.util.Random; public class SevenSidedDice { private static final Random rnd = new Random(); public static void main(String[] args) { SevenSidedDice now=new SevenSidedDice(); System.out.println("Random number from 1 to 7: "+now.seven()); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1+rnd.nextInt(5); } }
Rewrite this program in Java while keeping its functionality equivalent to the C++ version.
#include <array> #include <iostream> #include <vector> std::vector<std::pair<int, int>> connections = { {0, 2}, {0, 3}, {0, 4}, {1, 3}, {1, 4}, {1, 5}, {6, 2}, {6, 3}, {6, 4}, {7, 3}, {7, 4}, {7, 5}, {2, 3}, {3, 4}, {4, 5}, }; std::array<int, 8> pegs; int num = 0; void printSolution() { std::cout << "----- " << num++ << " -----\n"; std::cout << " " << pegs[0] << ' ' << pegs[1] << '\n'; std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\n'; std::cout << " " << pegs[6] << ' ' << pegs[7] << '\n'; std::cout << '\n'; } bool valid() { for (size_t i = 0; i < connections.size(); i++) { if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) { return false; } } return true; } void solution(int le, int ri) { if (le == ri) { if (valid()) { printSolution(); } } else { for (size_t i = le; i <= ri; i++) { std::swap(pegs[le], pegs[i]); solution(le + 1, ri); std::swap(pegs[le], pegs[i]); } } } int main() { pegs = { 1, 2, 3, 4, 5, 6, 7, 8 }; solution(0, pegs.size() - 1); return 0; }
import static java.lang.Math.abs; import java.util.*; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public class NoConnection { static int[][] links = { {2, 3, 4}, {3, 4, 5}, {2, 4}, {5}, {2, 3, 4}, {3, 4, 5}, }; static int[] pegs = new int[8]; public static void main(String[] args) { List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList()); do { Collections.shuffle(vals); for (int i = 0; i < pegs.length; i++) pegs[i] = vals.get(i); } while (!solved()); printResult(); } static boolean solved() { for (int i = 0; i < links.length; i++) for (int peg : links[i]) if (abs(pegs[i] - peg) == 1) return false; return true; } static void printResult() { System.out.printf(" %s %s%n", pegs[0], pegs[1]); System.out.printf("%s %s %s %s%n", pegs[2], pegs[3], pegs[4], pegs[5]); System.out.printf(" %s %s%n", pegs[6], pegs[7]); } }
Translate the given C++ code snippet into Java without altering its behavior.
#include <iomanip> #include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } bool is_magnanimous(unsigned int n) { for (unsigned int p = 10; n >= p; p *= 10) { if (!is_prime(n % p + n / p)) return false; } return true; } int main() { unsigned int count = 0, n = 0; std::cout << "First 45 magnanimous numbers:\n"; for (; count < 45; ++n) { if (is_magnanimous(n)) { if (count > 0) std::cout << (count % 15 == 0 ? "\n" : ", "); std::cout << std::setw(3) << n; ++count; } } std::cout << "\n\n241st through 250th magnanimous numbers:\n"; for (unsigned int i = 0; count < 250; ++n) { if (is_magnanimous(n)) { if (count++ >= 240) { if (i++ > 0) std::cout << ", "; std::cout << n; } } } std::cout << "\n\n391st through 400th magnanimous numbers:\n"; for (unsigned int i = 0; count < 400; ++n) { if (is_magnanimous(n)) { if (count++ >= 390) { if (i++ > 0) std::cout << ", "; std::cout << n; } } } std::cout << '\n'; return 0; }
import java.util.ArrayList; import java.util.List; public class MagnanimousNumbers { public static void main(String[] args) { runTask("Find and display the first 45 magnanimous numbers.", 1, 45); runTask("241st through 250th magnanimous numbers.", 241, 250); runTask("391st through 400th magnanimous numbers.", 391, 400); } private static void runTask(String message, int startN, int endN) { int count = 0; List<Integer> nums = new ArrayList<>(); for ( int n = 0 ; count < endN ; n++ ) { if ( isMagnanimous(n) ) { nums.add(n); count++; } } System.out.printf("%s%n", message); System.out.printf("%s%n%n", nums.subList(startN-1, endN)); } private static boolean isMagnanimous(long n) { if ( n >= 0 && n <= 9 ) { return true; } long q = 11; for ( long div = 10 ; q >= 10 ; div *= 10 ) { q = n / div; long r = n % div; if ( ! isPrime(q+r) ) { return false; } } return true; } private static final int MAX = 100_000; private static final boolean[] primes = new boolean[MAX]; private static boolean SIEVE_COMPLETE = false; private static final boolean isPrimeTrivial(long test) { if ( ! SIEVE_COMPLETE ) { sieve(); SIEVE_COMPLETE = true; } return primes[(int) test]; } private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } public static final boolean isPrime(long testValue) { if ( testValue == 2 ) return true; if ( testValue % 2 == 0 ) return false; if ( testValue <= MAX ) return isPrimeTrivial(testValue); long d = testValue-1; int s = 0; while ( d % 2 == 0 ) { s += 1; d /= 2; } if ( testValue < 1373565L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(3, s, d, testValue) ) { return false; } return true; } if ( testValue < 4759123141L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(7, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } return true; } if ( testValue < 10000000000000000L ) { if ( ! aSrp(3, s, d, testValue) ) { return false; } if ( ! aSrp(24251, s, d, testValue) ) { return false; } return true; } if ( ! aSrp(37, s, d, testValue) ) { return false; } if ( ! aSrp(47, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } if ( ! aSrp(73, s, d, testValue) ) { return false; } if ( ! aSrp(83, s, d, testValue) ) { return false; } return true; } private static final boolean aSrp(int a, int s, long d, long n) { long modPow = modPow(a, d, n); if ( modPow == 1 ) { return true; } int twoExpR = 1; for ( int r = 0 ; r < s ; r++ ) { if ( modPow(modPow, twoExpR, n) == n-1 ) { return true; } twoExpR *= 2; } return false; } private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE); public static final long modPow(long base, long exponent, long modulus) { long result = 1; while ( exponent > 0 ) { if ( exponent % 2 == 1 ) { if ( result > SQRT || base > SQRT ) { result = multiply(result, base, modulus); } else { result = (result * base) % modulus; } } exponent >>= 1; if ( base > SQRT ) { base = multiply(base, base, modulus); } else { base = (base * base) % modulus; } } return result; } public static final long multiply(long a, long b, long modulus) { long x = 0; long y = a % modulus; long t; while ( b > 0 ) { if ( b % 2 == 1 ) { t = x + y; x = (t > modulus ? t-modulus : t); } t = y << 1; y = (t > modulus ? t-modulus : t); b >>= 1; } return x % modulus; } }
Produce a functionally identical Java code for the snippet given in C++.
#include <iostream> #include <cstdint> #include <queue> #include <utility> #include <vector> #include <limits> template<typename integer> class prime_generator { public: integer next_prime(); integer count() const { return count_; } private: struct queue_item { queue_item(integer prime, integer multiple, unsigned int wheel_index) : prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {} integer prime_; integer multiple_; unsigned int wheel_index_; }; struct cmp { bool operator()(const queue_item& a, const queue_item& b) const { return a.multiple_ > b.multiple_; } }; static integer wheel_next(unsigned int& index) { integer offset = wheel_[index]; ++index; if (index == std::size(wheel_)) index = 0; return offset; } typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue; integer next_ = 11; integer count_ = 0; queue queue_; unsigned int wheel_index_ = 0; static const unsigned int wheel_[]; static const integer primes_[]; }; template<typename integer> const unsigned int prime_generator<integer>::wheel_[] = { 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10 }; template<typename integer> const integer prime_generator<integer>::primes_[] = { 2, 3, 5, 7 }; template<typename integer> integer prime_generator<integer>::next_prime() { if (count_ < std::size(primes_)) return primes_[count_++]; integer n = next_; integer prev = 0; while (!queue_.empty()) { queue_item item = queue_.top(); if (prev != 0 && prev != item.multiple_) n += wheel_next(wheel_index_); if (item.multiple_ > n) break; else if (item.multiple_ == n) { queue_.pop(); queue_item new_item(item); new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_); queue_.push(new_item); } else throw std::overflow_error("prime_generator: overflow!"); prev = item.multiple_; } if (std::numeric_limits<integer>::max()/n > n) queue_.emplace(n, n * n, wheel_index_); next_ = n + wheel_next(wheel_index_); ++count_; return n; } int main() { typedef uint32_t integer; prime_generator<integer> pgen; std::cout << "First 20 primes:\n"; for (int i = 0; i < 20; ++i) { integer p = pgen.next_prime(); if (i != 0) std::cout << ", "; std::cout << p; } std::cout << "\nPrimes between 100 and 150:\n"; for (int n = 0; ; ) { integer p = pgen.next_prime(); if (p > 150) break; if (p >= 100) { if (n != 0) std::cout << ", "; std::cout << p; ++n; } } int count = 0; for (;;) { integer p = pgen.next_prime(); if (p > 8000) break; if (p >= 7700) ++count; } std::cout << "\nNumber of primes between 7700 and 8000: " << count << '\n'; for (integer n = 10000; n <= 10000000; n *= 10) { integer prime; while (pgen.count() != n) prime = pgen.next_prime(); std::cout << n << "th prime: " << prime << '\n'; } return 0; }
import java.util.*; public class PrimeGenerator { private int limit_; private int index_ = 0; private int increment_; private int count_ = 0; private List<Integer> primes_ = new ArrayList<>(); private BitSet sieve_ = new BitSet(); private int sieveLimit_ = 0; public PrimeGenerator(int initialLimit, int increment) { limit_ = nextOddNumber(initialLimit); increment_ = increment; primes_.add(2); findPrimes(3); } public int nextPrime() { if (index_ == primes_.size()) { if (Integer.MAX_VALUE - increment_ < limit_) return 0; int start = limit_ + 2; limit_ = nextOddNumber(limit_ + increment_); primes_.clear(); findPrimes(start); } ++count_; return primes_.get(index_++); } public int count() { return count_; } private void findPrimes(int start) { index_ = 0; int newLimit = sqrt(limit_); for (int p = 3; p * p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p)); for (; q <= newLimit; q += 2*p) sieve_.set(q/2 - 1, true); } sieveLimit_ = newLimit; int count = (limit_ - start)/2 + 1; BitSet composite = new BitSet(count); for (int p = 3; p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start; q /= 2; for (; q >= 0 && q < count; q += p) composite.set(q, true); } for (int p = 0; p < count; ++p) { if (!composite.get(p)) primes_.add(p * 2 + start); } } private static int sqrt(int n) { return nextOddNumber((int)Math.sqrt(n)); } private static int nextOddNumber(int n) { return 1 + 2 * (n/2); } public static void main(String[] args) { PrimeGenerator pgen = new PrimeGenerator(20, 200000); System.out.println("First 20 primes:"); for (int i = 0; i < 20; ++i) { if (i > 0) System.out.print(", "); System.out.print(pgen.nextPrime()); } System.out.println(); System.out.println("Primes between 100 and 150:"); for (int i = 0; ; ) { int prime = pgen.nextPrime(); if (prime > 150) break; if (prime >= 100) { if (i++ != 0) System.out.print(", "); System.out.print(prime); } } System.out.println(); int count = 0; for (;;) { int prime = pgen.nextPrime(); if (prime > 8000) break; if (prime >= 7700) ++count; } System.out.println("Number of primes between 7700 and 8000: " + count); int n = 10000; for (;;) { int prime = pgen.nextPrime(); if (prime == 0) { System.out.println("Can't generate any more primes."); break; } if (pgen.count() == n) { System.out.println(n + "th prime: " + prime); n *= 10; } } } }
Produce a functionally identical Java code for the snippet given in C++.
#include <windows.h> #include <iostream> #include <string> using namespace std; enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C }; enum indexes { PLAYER, COMPUTER, DRAW }; class stats { public: stats() : _draw( 0 ) { ZeroMemory( _moves, sizeof( _moves ) ); ZeroMemory( _win, sizeof( _win ) ); } void draw() { _draw++; } void win( int p ) { _win[p]++; } void move( int p, int m ) { _moves[p][m]++; } int getMove( int p, int m ) { return _moves[p][m]; } string format( int a ) { char t[32]; wsprintf( t, "%.3d", a ); string d( t ); return d; } void print() { string d = format( _draw ), pw = format( _win[PLAYER] ), cw = format( _win[COMPUTER] ), pr = format( _moves[PLAYER][ROCK] ), cr = format( _moves[COMPUTER][ROCK] ), pp = format( _moves[PLAYER][PAPER] ), cp = format( _moves[COMPUTER][PAPER] ), ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ), pl = format( _moves[PLAYER][LIZARD] ), cl = format( _moves[COMPUTER][LIZARD] ), pk = format( _moves[PLAYER][SPOCK] ), ck = format( _moves[COMPUTER][SPOCK] ); system( "cls" ); cout << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |" << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << "| PLAYER | " << pw << " | | " << pr << " | " << pp << " | " << ps << " | " << pl << " | " << pk << " |" << endl; cout << "+----------+-------+ " << d << " +--------+---------+----------+--------+---------+" << endl; cout << "| COMPUTER | " << cw << " | | " << cr << " | " << cp << " | " << cs << " | " << cl << " | " << ck << " |" << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << endl << endl; system( "pause" ); } private: int _moves[2][MX_C], _win[2], _draw; }; class rps { private: int makeMove() { int total = 0, r, s; for( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) ); r = rand() % total; for( int i = ROCK; i < SCISSORS; i++ ) { s = statistics.getMove( PLAYER, i ); if( r < s ) return ( i + 1 ); r -= s; } return ROCK; } void printMove( int p, int m ) { if( p == COMPUTER ) cout << "My move: "; else cout << "Your move: "; switch( m ) { case ROCK: cout << "ROCK\n"; break; case PAPER: cout << "PAPER\n"; break; case SCISSORS: cout << "SCISSORS\n"; break; case LIZARD: cout << "LIZARD\n"; break; case SPOCK: cout << "SPOCK\n"; } } public: rps() { checker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1; checker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0; checker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1; checker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0; checker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2; } void play() { int p, r, m; while( true ) { cout << "What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? "; cin >> p; if( !p || p < 0 ) break; if( p > 0 && p < 6 ) { p--; cout << endl; printMove( PLAYER, p ); statistics.move( PLAYER, p ); m = makeMove(); statistics.move( COMPUTER, m ); printMove( COMPUTER, m ); r = checker[p][m]; switch( r ) { case DRAW: cout << endl << "DRAW!" << endl << endl; statistics.draw(); break; case COMPUTER: cout << endl << "I WIN!" << endl << endl; statistics.win( COMPUTER ); break; case PLAYER: cout << endl << "YOU WIN!" << endl << endl; statistics.win( PLAYER ); } system( "pause" ); } system( "cls" ); } statistics.print(); } private: stats statistics; int checker[MX_C][MX_C]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); rps game; game.play(); return 0; }
import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Random; public class RPS { public enum Item{ ROCK, PAPER, SCISSORS, ; public List<Item> losesToList; public boolean losesTo(Item other) { return losesToList.contains(other); } static { SCISSORS.losesToList = Arrays.asList(ROCK); ROCK.losesToList = Arrays.asList(PAPER); PAPER.losesToList = Arrays.asList(SCISSORS); } } public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{ for(Item item:Item.values()) put(item, 1); }}; private int totalThrows = Item.values().length; public static void main(String[] args){ RPS rps = new RPS(); rps.run(); } public void run() { Scanner in = new Scanner(System.in); System.out.print("Make your choice: "); while(in.hasNextLine()){ Item aiChoice = getAIChoice(); String input = in.nextLine(); Item choice; try{ choice = Item.valueOf(input.toUpperCase()); }catch (IllegalArgumentException ex){ System.out.println("Invalid choice"); continue; } counts.put(choice, counts.get(choice) + 1); totalThrows++; System.out.println("Computer chose: " + aiChoice); if(aiChoice == choice){ System.out.println("Tie!"); }else if(aiChoice.losesTo(choice)){ System.out.println("You chose...wisely. You win!"); }else{ System.out.println("You chose...poorly. You lose!"); } System.out.print("Make your choice: "); } } private static final Random rng = new Random(); private Item getAIChoice() { int rand = rng.nextInt(totalThrows); for(Map.Entry<Item, Integer> entry:counts.entrySet()){ Item item = entry.getKey(); int count = entry.getValue(); if(rand < count){ List<Item> losesTo = item.losesToList; return losesTo.get(rng.nextInt(losesTo.size())); } rand -= count; } return null; } }
Port the following code from C++ to Java with equivalent syntax and logic.
#include <iostream> int main() { int dim1, dim2; std::cin >> dim1 >> dim2; double* array_data = new double[dim1*dim2]; double** array = new double*[dim1]; for (int i = 0; i < dim1; ++i) array[i] = array_data + dim2*i; array[0][0] = 3.5; std::cout << array[0][0] << std::endl; delete[] array; delete[] array_data; return 0; }
import java.util.Scanner; public class twoDimArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int nbr1 = in.nextInt(); int nbr2 = in.nextInt(); double[][] array = new double[nbr1][nbr2]; array[0][0] = 42.0; System.out.println("The number at place [0 0] is " + array[0][0]); } }
Change the following C++ code into Java without altering its purpose.
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Change the following C++ code into Java without altering its purpose.
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Translate this program into Java but keep the logic exactly as in C++.
#include <iostream> #include <string> #include <vector> #include <map> #include <algorithm> #include <array> using namespace std; typedef array<pair<char, double>, 26> FreqArray; class VigenereAnalyser { private: array<double, 26> targets; array<double, 26> sortedTargets; FreqArray freq; FreqArray& frequency(const string& input) { for (char c = 'A'; c <= 'Z'; ++c) freq[c - 'A'] = make_pair(c, 0); for (size_t i = 0; i < input.size(); ++i) freq[input[i] - 'A'].second++; return freq; } double correlation(const string& input) { double result = 0.0; frequency(input); sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool { return u.second < v.second; }); for (size_t i = 0; i < 26; ++i) result += freq[i].second * sortedTargets[i]; return result; } public: VigenereAnalyser(const array<double, 26>& targetFreqs) { targets = targetFreqs; sortedTargets = targets; sort(sortedTargets.begin(), sortedTargets.end()); } pair<string, string> analyze(string input) { string cleaned; for (size_t i = 0; i < input.size(); ++i) { if (input[i] >= 'A' && input[i] <= 'Z') cleaned += input[i]; else if (input[i] >= 'a' && input[i] <= 'z') cleaned += input[i] + 'A' - 'a'; } size_t bestLength = 0; double bestCorr = -100.0; for (size_t i = 2; i < cleaned.size() / 20; ++i) { vector<string> pieces(i); for (size_t j = 0; j < cleaned.size(); ++j) pieces[j % i] += cleaned[j]; double corr = -0.5*i; for (size_t j = 0; j < i; ++j) corr += correlation(pieces[j]); if (corr > bestCorr) { bestLength = i; bestCorr = corr; } } if (bestLength == 0) return make_pair("Text is too short to analyze", ""); vector<string> pieces(bestLength); for (size_t i = 0; i < cleaned.size(); ++i) pieces[i % bestLength] += cleaned[i]; vector<FreqArray> freqs; for (size_t i = 0; i < bestLength; ++i) freqs.push_back(frequency(pieces[i])); string key = ""; for (size_t i = 0; i < bestLength; ++i) { sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool { return u.second > v.second; }); size_t m = 0; double mCorr = 0.0; for (size_t j = 0; j < 26; ++j) { double corr = 0.0; char c = 'A' + j; for (size_t k = 0; k < 26; ++k) { int d = (freqs[i][k].first - c + 26) % 26; corr += freqs[i][k].second * targets[d]; } if (corr > mCorr) { m = j; mCorr = corr; } } key += m + 'A'; } string result = ""; for (size_t i = 0; i < cleaned.size(); ++i) result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A'; return make_pair(result, key); } }; int main() { string input = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; array<double, 26> english = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074}; VigenereAnalyser va(english); pair<string, string> output = va.analyze(input); cout << "Key: " << output.second << endl << endl; cout << "Text: " << output.first << endl; }
public class Vig{ static String encodedMessage = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; final static double freq[] = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 }; public static void main(String[] args) { int lenghtOfEncodedMessage = encodedMessage.length(); char[] encoded = new char [lenghtOfEncodedMessage] ; char[] key = new char [lenghtOfEncodedMessage] ; encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0); int txt[] = new int[lenghtOfEncodedMessage]; int len = 0, j; double fit, best_fit = 1e100; for (j = 0; j < lenghtOfEncodedMessage; j++) if (Character.isUpperCase(encoded[j])) txt[len++] = encoded[j] - 'A'; for (j = 1; j < 30; j++) { fit = freq_every_nth(txt, len, j, key); System.out.printf("%f, key length: %2d ", fit, j); System.out.print(key); if (fit < best_fit) { best_fit = fit; System.out.print(" <--- best so far"); } System.out.print("\n"); } } static String decrypt(String text, final String key) { String res = ""; text = text.toUpperCase(); for (int i = 0, j = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < 'A' || c > 'Z') continue; res += (char)((c - key.charAt(j) + 26) % 26 + 'A'); j = ++j % key.length(); } return res; } static int best_match(final double []a, final double []b) { double sum = 0, fit, d, best_fit = 1e100; int i, rotate, best_rotate = 0; for (i = 0; i < 26; i++) sum += a[i]; for (rotate = 0; rotate < 26; rotate++) { fit = 0; for (i = 0; i < 26; i++) { d = a[(i + rotate) % 26] / sum - b[i]; fit += d * d / b[i]; } if (fit < best_fit) { best_fit = fit; best_rotate = rotate; } } return best_rotate; } static double freq_every_nth(final int []msg, int len, int interval, char[] key) { double sum, d, ret; double [] accu = new double [26]; double [] out = new double [26]; int i, j, rot; for (j = 0; j < interval; j++) { for (i = 0; i < 26; i++) out[i] = 0; for (i = j; i < len; i += interval) out[msg[i]]++; rot = best_match(out, freq); try{ key[j] = (char)(rot + 'A'); } catch (Exception e) { System.out.print(e.getMessage()); } for (i = 0; i < 26; i++) accu[i] += out[(i + rot) % 26]; } for (i = 0, sum = 0; i < 26; i++) sum += accu[i]; for (i = 0, ret = 0; i < 26; i++) { d = accu[i] / sum - freq[i]; ret += d * d / freq[i]; } key[interval] = '\0'; return ret; } }
Keep all operations the same but rewrite the snippet in Java.
#include <iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; class Gospers { cpp_int q, r, t, i, n; public: Gospers() : q{1}, r{0}, t{1}, i{1} { ++*this; } Gospers& operator++() { n = (q*(27*i-12)+5*r) / (5*t); while(n != (q*(675*i-216)+125*r)/(125*t)) { r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r); q = i*(2*i-1)*q; t = 3*(3*i+1)*(3*i+2)*t; i++; n = (q*(27*i-12)+5*r) / (5*t); } q = 10*q; r = 10*r-10*n*t; return *this; } int operator*() { return (int)n; } }; int main() { Gospers g; std::cout << *g << "."; for(;;) { std::cout << *++g; } }
import java.math.BigInteger ; public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ; BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ; public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } } public static void main(String[] args) { Pi p = new Pi() ; p.calcPiDigits() ; } }
Change the programming language of this snippet from C++ to Java without modifying what it does.
#include <iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; class Gospers { cpp_int q, r, t, i, n; public: Gospers() : q{1}, r{0}, t{1}, i{1} { ++*this; } Gospers& operator++() { n = (q*(27*i-12)+5*r) / (5*t); while(n != (q*(675*i-216)+125*r)/(125*t)) { r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r); q = i*(2*i-1)*q; t = 3*(3*i+1)*(3*i+2)*t; i++; n = (q*(27*i-12)+5*r) / (5*t); } q = 10*q; r = 10*r-10*n*t; return *this; } int operator*() { return (int)n; } }; int main() { Gospers g; std::cout << *g << "."; for(;;) { std::cout << *++g; } }
import java.math.BigInteger ; public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ; BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ; public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } } public static void main(String[] args) { Pi p = new Pi() ; p.calcPiDigits() ; } }
Convert this C++ block to Java, preserving its control flow and logic.
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
Change the following C++ code into Java without altering its purpose.
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
Translate this program into Java but keep the logic exactly as in C++.
#include <iostream> #include <functional> template <typename F> struct RecursiveFunc { std::function<F(RecursiveFunc)> o; }; template <typename A, typename B> std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) { RecursiveFunc<std::function<B(A)>> r = { std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) { return f(std::function<B(A)>([w](A x) { return w.o(w)(x); })); }) }; return r.o(r); } typedef std::function<int(int)> Func; typedef std::function<Func(Func)> FuncFunc; FuncFunc almost_fac = [](Func f) { return Func([f](int n) { if (n <= 1) return 1; return n * f(n - 1); }); }; FuncFunc almost_fib = [](Func f) { return Func([f](int n) { if (n <= 2) return 1; return f(n - 1) + f(n - 2); }); }; int main() { auto fib = Y(almost_fib); auto fac = Y(almost_fac); std::cout << "fib(10) = " << fib(10) << std::endl; std::cout << "fac(10) = " << fac(10) << std::endl; return 0; }
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
Keep all operations the same but rewrite the snippet in Java.
#include <algorithm> #include <array> #include <cstdint> #include <iostream> #include <tuple> std::tuple<int, int> minmax(const int * numbers, const std::size_t num) { const auto maximum = std::max_element(numbers, numbers + num); const auto minimum = std::min_element(numbers, numbers + num); return std::make_tuple(*minimum, *maximum) ; } int main( ) { const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}}; int min{}; int max{}; std::tie(min, max) = minmax(numbers.data(), numbers.size()); std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ; }
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class RReturnMultipleVals { public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; public static final Long K_1024 = 1024L; public static final String L = "L"; public static final String R = "R"; public static void main(String[] args) throws NumberFormatException{ Long nv_; String sv_; switch (args.length) { case 0: nv_ = K_1024; sv_ = K_lipsum; break; case 1: nv_ = Long.parseLong(args[0]); sv_ = K_lipsum; break; case 2: nv_ = Long.parseLong(args[0]); sv_ = args[1]; break; default: nv_ = Long.parseLong(args[0]); sv_ = args[1]; for (int ix = 2; ix < args.length; ++ix) { sv_ = sv_ + " " + args[ix]; } break; } RReturnMultipleVals lcl = new RReturnMultipleVals(); Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); System.out.println("Results extracted from a composite object:"); System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal()); List<Object> rvl = lcl.getPairFromList(nv_, sv_); System.out.println("Results extracted from a Java Colections \"List\" object:"); System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1)); Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); System.out.println("Results extracted from a Java Colections \"Map\" object:"); System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R)); } public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) { return new Pair<T, U>(vl_, vr_); } public List<Object> getPairFromList(Object nv_, Object sv_) { List<Object> rset = new ArrayList<Object>(); rset.add(nv_); rset.add(sv_); return rset; } public Map<String, Object> getPairFromMap(Object nv_, Object sv_) { Map<String, Object> rset = new HashMap<String, Object>(); rset.put(L, nv_); rset.put(R, sv_); return rset; } private static class Pair<L, R> { private L leftVal; private R rightVal; public Pair(L nv_, R sv_) { setLeftVal(nv_); setRightVal(sv_); } public void setLeftVal(L nv_) { leftVal = nv_; } public L getLeftVal() { return leftVal; } public void setRightVal(R sv_) { rightVal = sv_; } public R getRightVal() { return rightVal; } } }
Produce a language-to-language conversion: from C++ to Java, same semantics.
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
Change the programming language of this snippet from C++ to Java without modifying what it does.
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }