Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert the following code from C to C#, ensuring the logic remains intact.
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
Produce a functionally identical C# code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
Keep all operations the same but rewrite the snippet in C#.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
Produce a functionally identical C# code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
Translate this program into C# but keep the logic exactly as in C.
#include <stdio.h> long fib(long x) { long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); }; if (x < 0) { printf("Bad argument: fib(%ld)\n", x); return -1; } return fib_i(x); } long fib_i(long n) { printf("This is not the fib you are looking for\n"); return -1; } int main() { long x; for (x = -1; x < 4; x ++) printf("fib %ld = %ld\n", x, fib(x)); printf("calling fib_i from outside fib:\n"); fib_i(3); return 0; }
static int Fib(int n) { if (n < 0) throw new ArgumentException("Must be non negativ", "n"); Func<int, int> fib = null; fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p; return fib(n); }
Port the provided C code into C# while preserving the original functionality.
#include <stdio.h> int main() { FILE *fh = fopen("output.txt", "w"); fclose(fh); return 0; }
using System; using System.IO; class Program { static void Main(string[] args) { File.Create("output.txt"); File.Create(@"\output.txt"); Directory.CreateDirectory("docs"); Directory.CreateDirectory(@"\docs"); } }
Generate an equivalent C# version of this C code.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef const char * (*Responder)( int p1); typedef struct sDelegate { Responder operation; } *Delegate; Delegate NewDelegate( Responder rspndr ) { Delegate dl = malloc(sizeof(struct sDelegate)); dl->operation = rspndr; return dl; } const char *DelegateThing(Delegate dl, int p1) { return (dl->operation)? (*dl->operation)(p1) : NULL; } typedef struct sDelegator { int param; char *phrase; Delegate delegate; } *Delegator; const char * defaultResponse( int p1) { return "default implementation"; } static struct sDelegate defaultDel = { &defaultResponse }; Delegator NewDelegator( int p, char *phrase) { Delegator d = malloc(sizeof(struct sDelegator)); d->param = p; d->phrase = phrase; d->delegate = &defaultDel; return d; } const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy) { const char *rtn; if (delroy) { rtn = DelegateThing(delroy, p1); if (!rtn) { rtn = DelegateThing(theDelegator->delegate, p1); } } else rtn = DelegateThing(theDelegator->delegate, p1); printf("%s\n", theDelegator->phrase ); return rtn; } const char *thing1( int p1) { printf("We're in thing1 with value %d\n" , p1); return "delegate implementation"; } int main() { Delegate del1 = NewDelegate(&thing1); Delegate del2 = NewDelegate(NULL); Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby."); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, NULL)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del1)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del2)); return 0; }
using System; interface IOperable { string Operate(); } class Inoperable { } class Operable : IOperable { public string Operate() { return "Delegate implementation."; } } class Delegator : IOperable { object Delegate; public string Operate() { var operable = Delegate as IOperable; return operable != null ? operable.Operate() : "Default implementation."; } static void Main() { var delegator = new Delegator(); foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() }) { delegator.Delegate = @delegate; Console.WriteLine(delegator.Operate()); } } }
Change the following C code into C# without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef const char * (*Responder)( int p1); typedef struct sDelegate { Responder operation; } *Delegate; Delegate NewDelegate( Responder rspndr ) { Delegate dl = malloc(sizeof(struct sDelegate)); dl->operation = rspndr; return dl; } const char *DelegateThing(Delegate dl, int p1) { return (dl->operation)? (*dl->operation)(p1) : NULL; } typedef struct sDelegator { int param; char *phrase; Delegate delegate; } *Delegator; const char * defaultResponse( int p1) { return "default implementation"; } static struct sDelegate defaultDel = { &defaultResponse }; Delegator NewDelegator( int p, char *phrase) { Delegator d = malloc(sizeof(struct sDelegator)); d->param = p; d->phrase = phrase; d->delegate = &defaultDel; return d; } const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy) { const char *rtn; if (delroy) { rtn = DelegateThing(delroy, p1); if (!rtn) { rtn = DelegateThing(theDelegator->delegate, p1); } } else rtn = DelegateThing(theDelegator->delegate, p1); printf("%s\n", theDelegator->phrase ); return rtn; } const char *thing1( int p1) { printf("We're in thing1 with value %d\n" , p1); return "delegate implementation"; } int main() { Delegate del1 = NewDelegate(&thing1); Delegate del2 = NewDelegate(NULL); Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby."); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, NULL)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del1)); printf("Delegator returns %s\n\n", Delegator_Operation( theDelegator, 3, del2)); return 0; }
using System; interface IOperable { string Operate(); } class Inoperable { } class Operable : IOperable { public string Operate() { return "Delegate implementation."; } } class Delegator : IOperable { object Delegate; public string Operate() { var operable = Delegate as IOperable; return operable != null ? operable.Operate() : "Default implementation."; } static void Main() { var delegator = new Delegator(); foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() }) { delegator.Delegate = @delegate; Console.WriteLine(delegator.Operate()); } } }
Write a version of this C function in C# with identical behavior.
#include <stdio.h> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; unsigned int p; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; } total *= sum; } if (n > 1) { total *= n + 1; } return total; } int main() { const unsigned int limit = 100; unsigned int n; printf("Sum of divisors for the first %d positive integers:\n", limit); for (n = 1; n <= limit; ++n) { printf("%4d", divisor_sum(n)); if (n % 10 == 0) { printf("\n"); } } return 0; }
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } int main() { const unsigned int limit = 100; std::cout << "Sum of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(4) << divisor_sum(n); if (n % 10 == 0) std::cout << '\n'; } }
Produce a language-to-language conversion: from C to C#, same semantics.
#include <stdio.h> #include <string.h> #include <stdlib.h> char *codes[] = { "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", "BBAAA", "BBAAB", "BBBAA" }; char *get_code(const char c) { if (c >= 97 && c <= 122) return codes[c - 97]; return codes[26]; } char get_char(const char *code) { int i; if (!strcmp(codes[26], code)) return ' '; for (i = 0; i < 26; ++i) { if (strcmp(codes[i], code) == 0) return 97 + i; } printf("\nCode \"%s\" is invalid\n", code); exit(1); } void str_tolower(char s[]) { int i; for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]); } char *bacon_encode(char plain_text[], char message[]) { int i, count; int plen = strlen(plain_text), mlen = strlen(message); int elen = 5 * plen; char c; char *p, *et, *mt; et = malloc(elen + 1); str_tolower(plain_text); for (i = 0, p = et; i < plen; ++i, p += 5) { c = plain_text[i]; strncpy(p, get_code(c), 5); } *++p = '\0'; str_tolower(message); mt = calloc(mlen + 1, 1); for (i = 0, count = 0; i < mlen; ++i) { c = message[i]; if (c >= 'a' && c <= 'z') { if (et[count] == 'A') mt[i] = c; else mt[i] = c - 32; if (++count == elen) break; } else mt[i] = c; } free(et); return mt; } char *bacon_decode(char cipher_text[]) { int i, count, clen = strlen(cipher_text); int plen; char *p, *ct, *pt; char c, quintet[6]; ct = calloc(clen + 1, 1); for (i = 0, count = 0; i < clen; ++i) { c = cipher_text[i]; if (c >= 'a' && c <= 'z') ct[count++] = 'A'; else if (c >= 'A' && c <= 'Z') ct[count++] = 'B'; } plen = strlen(ct) / 5; pt = malloc(plen + 1); for (i = 0, p = ct; i < plen; ++i, p += 5) { strncpy(quintet, p, 5); quintet[5] = '\0'; pt[i] = get_char(quintet); } pt[plen] = '\0'; free(ct); return pt; } int main() { char plain_text[] = "the quick brown fox jumps over the lazy dog"; char message[] = "bacon's cipher is a method of steganography created by francis bacon." "this task is to implement a program for encryption and decryption of " "plaintext using the simple alphabet of the baconian cipher or some " "other kind of representation of this alphabet (make anything signify anything). " "the baconian alphabet may optionally be extended to encode all lower " "case characters individually and/or adding a few punctuation characters " "such as the space."; char *cipher_text, *hidden_text; cipher_text = bacon_encode(plain_text, message); printf("Cipher text ->\n\n%s\n", cipher_text); hidden_text = bacon_decode(cipher_text); printf("\nHidden text ->\n\n%s\n", hidden_text); free(cipher_text); free(hidden_text); return 0; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaconCipher { class Program { private static Dictionary<char, string> codes = new Dictionary<char, string> { {'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" }, {'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" }, {'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" }, {'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" }, {'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" }, {'z', "BBAAB" }, {' ', "BBBAA" }, }; private static string Encode(string plainText, string message) { string pt = plainText.ToLower(); StringBuilder sb = new StringBuilder(); foreach (char c in pt) { if ('a' <= c && c <= 'z') sb.Append(codes[c]); else sb.Append(codes[' ']); } string et = sb.ToString(); string mg = message.ToLower(); sb.Length = 0; int count = 0; foreach (char c in mg) { if ('a' <= c && c <= 'z') { if (et[count] == 'A') sb.Append(c); else sb.Append((char)(c - 32)); count++; if (count == et.Length) break; } else sb.Append(c); } return sb.ToString(); } private static string Decode(string message) { StringBuilder sb = new StringBuilder(); foreach (char c in message) { if ('a' <= c && c <= 'z') sb.Append('A'); else if ('A' <= c && c <= 'Z') sb.Append('B'); } string et = sb.ToString(); sb.Length = 0; for (int i = 0; i < et.Length; i += 5) { string quintet = et.Substring(i, 5); char key = codes.Where(a => a.Value == quintet).First().Key; sb.Append(key); } return sb.ToString(); } static void Main(string[] args) { string plainText = "the quick brown fox jumps over the lazy dog"; string message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; string cipherText = Encode(plainText, message); Console.WriteLine("Cipher text ->\n{0}", cipherText); string decodedText = Decode(cipherText); Console.WriteLine("\nHidden text ->\n{0}", decodedText); } } }
Can you help me rewrite this code in C# instead of C, keeping it the same logically?
#include <stdio.h> #include <string.h> #include <stdlib.h> char *codes[] = { "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", "BBAAA", "BBAAB", "BBBAA" }; char *get_code(const char c) { if (c >= 97 && c <= 122) return codes[c - 97]; return codes[26]; } char get_char(const char *code) { int i; if (!strcmp(codes[26], code)) return ' '; for (i = 0; i < 26; ++i) { if (strcmp(codes[i], code) == 0) return 97 + i; } printf("\nCode \"%s\" is invalid\n", code); exit(1); } void str_tolower(char s[]) { int i; for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]); } char *bacon_encode(char plain_text[], char message[]) { int i, count; int plen = strlen(plain_text), mlen = strlen(message); int elen = 5 * plen; char c; char *p, *et, *mt; et = malloc(elen + 1); str_tolower(plain_text); for (i = 0, p = et; i < plen; ++i, p += 5) { c = plain_text[i]; strncpy(p, get_code(c), 5); } *++p = '\0'; str_tolower(message); mt = calloc(mlen + 1, 1); for (i = 0, count = 0; i < mlen; ++i) { c = message[i]; if (c >= 'a' && c <= 'z') { if (et[count] == 'A') mt[i] = c; else mt[i] = c - 32; if (++count == elen) break; } else mt[i] = c; } free(et); return mt; } char *bacon_decode(char cipher_text[]) { int i, count, clen = strlen(cipher_text); int plen; char *p, *ct, *pt; char c, quintet[6]; ct = calloc(clen + 1, 1); for (i = 0, count = 0; i < clen; ++i) { c = cipher_text[i]; if (c >= 'a' && c <= 'z') ct[count++] = 'A'; else if (c >= 'A' && c <= 'Z') ct[count++] = 'B'; } plen = strlen(ct) / 5; pt = malloc(plen + 1); for (i = 0, p = ct; i < plen; ++i, p += 5) { strncpy(quintet, p, 5); quintet[5] = '\0'; pt[i] = get_char(quintet); } pt[plen] = '\0'; free(ct); return pt; } int main() { char plain_text[] = "the quick brown fox jumps over the lazy dog"; char message[] = "bacon's cipher is a method of steganography created by francis bacon." "this task is to implement a program for encryption and decryption of " "plaintext using the simple alphabet of the baconian cipher or some " "other kind of representation of this alphabet (make anything signify anything). " "the baconian alphabet may optionally be extended to encode all lower " "case characters individually and/or adding a few punctuation characters " "such as the space."; char *cipher_text, *hidden_text; cipher_text = bacon_encode(plain_text, message); printf("Cipher text ->\n\n%s\n", cipher_text); hidden_text = bacon_decode(cipher_text); printf("\nHidden text ->\n\n%s\n", hidden_text); free(cipher_text); free(hidden_text); return 0; }
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Write a version of this C function in C# with identical behavior.
#include <stdio.h> #include <string.h> #include <stdlib.h> char *codes[] = { "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", "BBAAA", "BBAAB", "BBBAA" }; char *get_code(const char c) { if (c >= 97 && c <= 122) return codes[c - 97]; return codes[26]; } char get_char(const char *code) { int i; if (!strcmp(codes[26], code)) return ' '; for (i = 0; i < 26; ++i) { if (strcmp(codes[i], code) == 0) return 97 + i; } printf("\nCode \"%s\" is invalid\n", code); exit(1); } void str_tolower(char s[]) { int i; for (i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]); } char *bacon_encode(char plain_text[], char message[]) { int i, count; int plen = strlen(plain_text), mlen = strlen(message); int elen = 5 * plen; char c; char *p, *et, *mt; et = malloc(elen + 1); str_tolower(plain_text); for (i = 0, p = et; i < plen; ++i, p += 5) { c = plain_text[i]; strncpy(p, get_code(c), 5); } *++p = '\0'; str_tolower(message); mt = calloc(mlen + 1, 1); for (i = 0, count = 0; i < mlen; ++i) { c = message[i]; if (c >= 'a' && c <= 'z') { if (et[count] == 'A') mt[i] = c; else mt[i] = c - 32; if (++count == elen) break; } else mt[i] = c; } free(et); return mt; } char *bacon_decode(char cipher_text[]) { int i, count, clen = strlen(cipher_text); int plen; char *p, *ct, *pt; char c, quintet[6]; ct = calloc(clen + 1, 1); for (i = 0, count = 0; i < clen; ++i) { c = cipher_text[i]; if (c >= 'a' && c <= 'z') ct[count++] = 'A'; else if (c >= 'A' && c <= 'Z') ct[count++] = 'B'; } plen = strlen(ct) / 5; pt = malloc(plen + 1); for (i = 0, p = ct; i < plen; ++i, p += 5) { strncpy(quintet, p, 5); quintet[5] = '\0'; pt[i] = get_char(quintet); } pt[plen] = '\0'; free(ct); return pt; } int main() { char plain_text[] = "the quick brown fox jumps over the lazy dog"; char message[] = "bacon's cipher is a method of steganography created by francis bacon." "this task is to implement a program for encryption and decryption of " "plaintext using the simple alphabet of the baconian cipher or some " "other kind of representation of this alphabet (make anything signify anything). " "the baconian alphabet may optionally be extended to encode all lower " "case characters individually and/or adding a few punctuation characters " "such as the space."; char *cipher_text, *hidden_text; cipher_text = bacon_encode(plain_text, message); printf("Cipher text ->\n\n%s\n", cipher_text); hidden_text = bacon_decode(cipher_text); printf("\nHidden text ->\n\n%s\n", hidden_text); free(cipher_text); free(hidden_text); return 0; }
#include <iostream> #include <algorithm> #include <vector> #include <bitset> #include <string> class bacon { public: bacon() { int x = 0; for( ; x < 9; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 20; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); bAlphabet.push_back( bAlphabet.back() ); for( ; x < 24; x++ ) bAlphabet.push_back( std::bitset<5>( x ).to_string() ); } std::string encode( std::string txt ) { std::string r; size_t z; for( std::string::iterator i = txt.begin(); i != txt.end(); i++ ) { z = toupper( *i ); if( z < 'A' || z > 'Z' ) continue; r.append( bAlphabet.at( ( *i & 31 ) - 1 ) ); } return r; } std::string decode( std::string txt ) { size_t len = txt.length(); while( len % 5 != 0 ) len--; if( len != txt.length() ) txt = txt.substr( 0, len ); std::string r; for( size_t i = 0; i < len; i += 5 ) { r.append( 1, 'A' + std::distance( bAlphabet.begin(), std::find( bAlphabet.begin(), bAlphabet.end(), txt.substr( i, 5 ) ) ) ); } return r; } private: std::vector<std::string> bAlphabet; };
Transform the following C implementation into C#, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> #define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j] int main(int c, char **v) { int i, j, m = 0, n = 0; if (c >= 2) m = atoi(v[1]); if (c >= 3) n = atoi(v[2]); if (m <= 0) m = 5; if (n <= 0) n = m; int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n); s[0] = (int*)(s + m); for (i = 1; i < m; i++) s[i] = s[i - 1] + n; int dx = 1, dy = 0, val = 0, t; for (i = j = 0; valid(i, j); i += dy, j += dx ) { for (; valid(i, j); j += dx, i += dy) s[i][j] = ++val; j -= dx; i -= dy; t = dy; dy = dx; dx = -t; } for (t = 2; val /= 10; t++); for(i = 0; i < m; i++) for(j = 0; j < n || !putchar('\n'); j++) printf("%*d", t, s[i][j]); return 0; }
public int[,] Spiral(int n) { int[,] result = new int[n, n]; int pos = 0; int count = n; int value = -n; int sum = -1; do { value = -1 * value / n; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } value *= n; count--; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } } while (count > 0); return result; } public void PrintArray(int[,] array) { int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1; for (int i = 0; i < array.GetLength(0); i++) { for (int j = 0; j < array.GetLength(1); j++) { Console.Write(array[i, j].ToString().PadLeft(n, ' ')); } Console.WriteLine(); } }
Generate an equivalent C# version of this C code.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int binomial(int n, int k) { int num, denom, i; if (n < 0 || k < 0 || n < k) return -1; if (n == 0 || k == 0) return 1; num = 1; for (i = k + 1; i <= n; ++i) { num = num * i; } denom = 1; for (i = 2; i <= n - k; ++i) { denom *= i; } return num / denom; } int gcd(int a, int b) { int temp; while (b != 0) { temp = a % b; a = b; b = temp; } return a; } typedef struct tFrac { int num, denom; } Frac; Frac makeFrac(int n, int d) { Frac result; int g; if (d == 0) { result.num = 0; result.denom = 0; return result; } if (n == 0) { d = 1; } else if (d < 0) { n = -n; d = -d; } g = abs(gcd(n, d)); if (g > 1) { n = n / g; d = d / g; } result.num = n; result.denom = d; return result; } Frac negateFrac(Frac f) { return makeFrac(-f.num, f.denom); } Frac subFrac(Frac lhs, Frac rhs) { return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom); } Frac multFrac(Frac lhs, Frac rhs) { return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom); } bool equalFrac(Frac lhs, Frac rhs) { return (lhs.num == rhs.num) && (lhs.denom == rhs.denom); } bool lessFrac(Frac lhs, Frac rhs) { return (lhs.num * rhs.denom) < (rhs.num * lhs.denom); } void printFrac(Frac f) { char buffer[7]; int len; if (f.denom != 1) { snprintf(buffer, 7, "%d/%d", f.num, f.denom); } else { snprintf(buffer, 7, "%d", f.num); } len = 7 - strlen(buffer); while (len-- > 0) { putc(' ', stdout); } printf(buffer); } Frac bernoulli(int n) { Frac a[16]; int j, m; if (n < 0) { a[0].num = 0; a[0].denom = 0; return a[0]; } for (m = 0; m <= n; ++m) { a[m] = makeFrac(1, m + 1); for (j = m; j >= 1; --j) { a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1)); } } if (n != 1) { return a[0]; } return negateFrac(a[0]); } void faulhaber(int p) { Frac q, *coeffs; int j, sign; coeffs = malloc(sizeof(Frac)*(p + 1)); q = makeFrac(1, p + 1); sign = -1; for (j = 0; j <= p; ++j) { sign = -1 * sign; coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j)); } for (j = 0; j <= p; ++j) { printFrac(coeffs[j]); } printf("\n"); free(coeffs); } int main() { int i; for (i = 0; i < 10; ++i) { faulhaber(i); } return 0; }
using System; namespace FaulhabersTriangle { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { throw new ArgumentException("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.Abs(Gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } private static long Gcd(long a, long b) { if (b == 0) { return a; } return Gcd(b, a % b); } public static Frac operator -(Frac self) { return new Frac(-self.num, self.denom); } public static Frac operator +(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom); } public static Frac operator -(Frac lhs, Frac rhs) { return lhs + -rhs; } public static Frac operator *(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom); } public static bool operator <(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x < y; } public static bool operator >(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x > y; } public static bool operator ==(Frac lhs, Frac rhs) { return lhs.num == rhs.num && lhs.denom == rhs.denom; } public static bool operator !=(Frac lhs, Frac rhs) { return lhs.num != rhs.num || lhs.denom != rhs.denom; } public override string ToString() { if (denom == 1) { return num.ToString(); } return string.Format("{0}/{1}", num, denom); } public override bool Equals(object obj) { var frac = obj as Frac; return frac != null && num == frac.num && denom == frac.denom; } public override int GetHashCode() { var hashCode = 1317992671; hashCode = hashCode * -1521134295 + num.GetHashCode(); hashCode = hashCode * -1521134295 + denom.GetHashCode(); return hashCode; } } class Program { static Frac Bernoulli(int n) { if (n < 0) { throw new ArgumentException("n may not be negative or zero"); } Frac[] a = new Frac[n + 1]; for (int m = 0; m <= n; m++) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1); } } if (n != 1) return a[0]; return -a[0]; } static int Binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw new ArgumentException(); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num = num * i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom = denom * i; } return num / denom; } static Frac[] FaulhaberTriangle(int p) { Frac[] coeffs = new Frac[p + 1]; for (int i = 0; i < p + 1; i++) { coeffs[i] = Frac.ZERO; } Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j); } return coeffs; } static void Main(string[] args) { for (int i = 0; i < 10; i++) { Frac[] coeffs = FaulhaberTriangle(i); foreach (Frac coeff in coeffs) { Console.Write("{0,5} ", coeff); } Console.WriteLine(); } } } }
Produce a language-to-language conversion: from C to C#, same semantics.
#include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
Preserve the algorithm and functionality while converting the code from C to C#.
#include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; (void) printf("This program is named %s.\n", argv[0]); for (i = 1; i < argc; ++i) (void) printf("the argument #%d is %s\n", i, argv[i]); return EXIT_SUCCESS; }
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
Maintain the same structure and functionality when rewriting this code in C#.
#include <stdlib.h> #include <stdio.h> #include <string.h> #define ARRAY_CONCAT(TYPE, A, An, B, Bn) \ (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE)); void *array_concat(const void *a, size_t an, const void *b, size_t bn, size_t s) { char *p = malloc(s * (an + bn)); memcpy(p, a, an*s); memcpy(p + an*s, b, bn*s); return p; } const int a[] = { 1, 2, 3, 4, 5 }; const int b[] = { 6, 7, 8, 9, 0 }; int main(void) { unsigned int i; int *c = ARRAY_CONCAT(int, a, 5, b, 5); for(i = 0; i < 10; i++) printf("%d\n", c[i]); free(c); return EXIT_SUCCCESS; }
using System; namespace RosettaCode { class Program { static void Main(string[] args) { int[] a = { 1, 2, 3 }; int[] b = { 4, 5, 6 }; int[] c = new int[a.Length + b.Length]; a.CopyTo(c, 0); b.CopyTo(c, a.Length); foreach(int n in c) { Console.WriteLine(n.ToString()); } } } }
Produce a functionally identical C# code for the snippet given in C.
#include <stdio.h> #include <stdlib.h> int main(void) { char str[BUFSIZ]; puts("Enter a string: "); fgets(str, sizeof(str), stdin); long num; char buf[BUFSIZ]; do { puts("Enter 75000: "); fgets(buf, sizeof(buf), stdin); num = strtol(buf, NULL, 10); } while (num != 75000); return EXIT_SUCCESS; }
using System; namespace C_Sharp_Console { class example { static void Main() { string word; int num; Console.Write("Enter an integer: "); num = Console.Read(); Console.Write("Enter a String: "); word = Console.ReadLine(); } } }
Generate a C# translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; int weight; int value; } item_t; item_t items[] = { {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"beer", 52, 10}, {"suntan cream", 11, 70}, {"camera", 32, 30}, {"T-shirt", 24, 15}, {"trousers", 48, 10}, {"umbrella", 73, 40}, {"waterproof trousers", 42, 70}, {"waterproof overclothes", 43, 75}, {"note-case", 22, 80}, {"sunglasses", 7, 20}, {"towel", 18, 12}, {"socks", 4, 50}, {"book", 30, 10}, }; int *knapsack (item_t *items, int n, int w) { int i, j, a, b, *mm, **m, *s; mm = calloc((n + 1) * (w + 1), sizeof (int)); m = malloc((n + 1) * sizeof (int *)); m[0] = mm; for (i = 1; i <= n; i++) { m[i] = &mm[i * (w + 1)]; for (j = 0; j <= w; j++) { if (items[i - 1].weight > j) { m[i][j] = m[i - 1][j]; } else { a = m[i - 1][j]; b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value; m[i][j] = a > b ? a : b; } } } s = calloc(n, sizeof (int)); for (i = n, j = w; i > 0; i--) { if (m[i][j] > m[i - 1][j]) { s[i - 1] = 1; j -= items[i - 1].weight; } } free(mm); free(m); return s; } int main () { int i, n, tw = 0, tv = 0, *s; n = sizeof (items) / sizeof (item_t); s = knapsack(items, n, 400); for (i = 0; i < n; i++) { if (s[i]) { printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value); tw += items[i].weight; tv += items[i].value; } } printf("%-22s %5d %5d\n", "totals:", tw, tv); return 0; }
using System; using System.Collections.Generic; namespace Tests_With_Framework_4 { class Bag : IEnumerable<Bag.Item> { List<Item> items; const int MaxWeightAllowed = 400; public Bag() { items = new List<Item>(); } void AddItem(Item i) { if ((TotalWeight + i.Weight) <= MaxWeightAllowed) items.Add(i); } public void Calculate(List<Item> items) { foreach (Item i in Sorte(items)) { AddItem(i); } } List<Item> Sorte(List<Item> inputItems) { List<Item> choosenItems = new List<Item>(); for (int i = 0; i < inputItems.Count; i++) { int j = -1; if (i == 0) { choosenItems.Add(inputItems[i]); } if (i > 0) { if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j)) { choosenItems.Add(inputItems[i]); } } } return choosenItems; } bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd) { if (!(lastBound < 0)) { if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV ) { indxToAdd = lastBound; } return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd); } if (indxToAdd > -1) { choosenItems.Insert(indxToAdd, knapsackItems[i]); return true; } return false; } #region IEnumerable<Item> Members IEnumerator<Item> IEnumerable<Item>.GetEnumerator() { foreach (Item i in items) yield return i; } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return items.GetEnumerator(); } #endregion public int TotalWeight { get { var sum = 0; foreach (Item i in this) { sum += i.Weight; } return sum; } } public class Item { public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return Weight-Value; } } public override string ToString() { return "Name : " + Name + " Wieght : " + Weight + " Value : " + Value + " ResultWV : " + ResultWV; } } } class Program { static void Main(string[] args) {List<Bag.Item> knapsackItems = new List<Bag.Item>(); knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 }); knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 }); knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 }); knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 }); knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 }); knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 }); knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 }); knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 }); knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 }); knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 }); knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 }); Bag b = new Bag(); b.Calculate(knapsackItems); b.All(x => { Console.WriteLine(x); return true; }); Console.WriteLine(b.Sum(x => x.Weight)); Console.ReadKey(); } } }
Can you help me rewrite this code in C# instead of C, keeping it the same logically?
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; int weight; int value; } item_t; item_t items[] = { {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"beer", 52, 10}, {"suntan cream", 11, 70}, {"camera", 32, 30}, {"T-shirt", 24, 15}, {"trousers", 48, 10}, {"umbrella", 73, 40}, {"waterproof trousers", 42, 70}, {"waterproof overclothes", 43, 75}, {"note-case", 22, 80}, {"sunglasses", 7, 20}, {"towel", 18, 12}, {"socks", 4, 50}, {"book", 30, 10}, }; int *knapsack (item_t *items, int n, int w) { int i, j, a, b, *mm, **m, *s; mm = calloc((n + 1) * (w + 1), sizeof (int)); m = malloc((n + 1) * sizeof (int *)); m[0] = mm; for (i = 1; i <= n; i++) { m[i] = &mm[i * (w + 1)]; for (j = 0; j <= w; j++) { if (items[i - 1].weight > j) { m[i][j] = m[i - 1][j]; } else { a = m[i - 1][j]; b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value; m[i][j] = a > b ? a : b; } } } s = calloc(n, sizeof (int)); for (i = n, j = w; i > 0; i--) { if (m[i][j] > m[i - 1][j]) { s[i - 1] = 1; j -= items[i - 1].weight; } } free(mm); free(m); return s; } int main () { int i, n, tw = 0, tv = 0, *s; n = sizeof (items) / sizeof (item_t); s = knapsack(items, n, 400); for (i = 0; i < n; i++) { if (s[i]) { printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value); tw += items[i].weight; tv += items[i].value; } } printf("%-22s %5d %5d\n", "totals:", tw, tv); return 0; }
using System; using System.Collections.Generic; namespace Tests_With_Framework_4 { class Bag : IEnumerable<Bag.Item> { List<Item> items; const int MaxWeightAllowed = 400; public Bag() { items = new List<Item>(); } void AddItem(Item i) { if ((TotalWeight + i.Weight) <= MaxWeightAllowed) items.Add(i); } public void Calculate(List<Item> items) { foreach (Item i in Sorte(items)) { AddItem(i); } } List<Item> Sorte(List<Item> inputItems) { List<Item> choosenItems = new List<Item>(); for (int i = 0; i < inputItems.Count; i++) { int j = -1; if (i == 0) { choosenItems.Add(inputItems[i]); } if (i > 0) { if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j)) { choosenItems.Add(inputItems[i]); } } } return choosenItems; } bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd) { if (!(lastBound < 0)) { if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV ) { indxToAdd = lastBound; } return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd); } if (indxToAdd > -1) { choosenItems.Insert(indxToAdd, knapsackItems[i]); return true; } return false; } #region IEnumerable<Item> Members IEnumerator<Item> IEnumerable<Item>.GetEnumerator() { foreach (Item i in items) yield return i; } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return items.GetEnumerator(); } #endregion public int TotalWeight { get { var sum = 0; foreach (Item i in this) { sum += i.Weight; } return sum; } } public class Item { public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return Weight-Value; } } public override string ToString() { return "Name : " + Name + " Wieght : " + Weight + " Value : " + Value + " ResultWV : " + ResultWV; } } } class Program { static void Main(string[] args) {List<Bag.Item> knapsackItems = new List<Bag.Item>(); knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 }); knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 }); knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 }); knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 }); knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 }); knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 }); knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 }); knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 }); knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 }); knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 }); knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 }); Bag b = new Bag(); b.Calculate(knapsackItems); b.All(x => { Console.WriteLine(x); return true; }); Console.WriteLine(b.Sum(x => x.Weight)); Console.ReadKey(); } } }
Translate this program into C# but keep the logic exactly as in C.
#include<string.h> #include<stdlib.h> #include<stdio.h> void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){ int i,j; if(times==numSets){ printf("("); for(i=0;i<times;i++){ printf("%d,",currentSet[i]); } printf("\b),"); } else{ for(j=0;j<setLengths[times];j++){ currentSet[times] = sets[times][j]; cartesianProduct(sets,setLengths,currentSet,numSets,times+1); } } } void printSets(int** sets, int* setLengths, int numSets){ int i,j; printf("\nNumber of sets : %d",numSets); for(i=0;i<numSets+1;i++){ printf("\nSet %d : ",i+1); for(j=0;j<setLengths[i];j++){ printf(" %d ",sets[i][j]); } } } void processInputString(char* str){ int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0; char *token,*holder,*holderToken; for(i=0;str[i]!=00;i++) if(str[i]=='x') numSets++; if(numSets==0){ printf("\n%s",str); return; } currentSet = (int*)calloc(sizeof(int),numSets + 1); setLengths = (int*)calloc(sizeof(int),numSets + 1); sets = (int**)malloc((numSets + 1)*sizeof(int*)); token = strtok(str,"x"); while(token!=NULL){ holder = (char*)malloc(strlen(token)*sizeof(char)); j = 0; for(i=0;token[i]!=00;i++){ if(token[i]>='0' && token[i]<='9') holder[j++] = token[i]; else if(token[i]==',') holder[j++] = ' '; } holder[j] = 00; setLength = 0; for(i=0;holder[i]!=00;i++) if(holder[i]==' ') setLength++; if(setLength==0 && strlen(holder)==0){ printf("\n{}"); return; } setLengths[counter] = setLength+1; sets[counter] = (int*)malloc((1+setLength)*sizeof(int)); k = 0; start = 0; for(l=0;holder[l]!=00;l++){ if(holder[l+1]==' '||holder[l+1]==00){ holderToken = (char*)malloc((l+1-start)*sizeof(char)); strncpy(holderToken,holder + start,l+1-start); sets[counter][k++] = atoi(holderToken); start = l+2; } } counter++; token = strtok(NULL,"x"); } printf("\n{"); cartesianProduct(sets,setLengths,currentSet,numSets + 1,0); printf("\b}"); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]); else processInputString(argV[1]); return 0; }
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
Write the same code in C# as shown below in C.
#include<string.h> #include<stdlib.h> #include<stdio.h> void cartesianProduct(int** sets, int* setLengths, int* currentSet, int numSets, int times){ int i,j; if(times==numSets){ printf("("); for(i=0;i<times;i++){ printf("%d,",currentSet[i]); } printf("\b),"); } else{ for(j=0;j<setLengths[times];j++){ currentSet[times] = sets[times][j]; cartesianProduct(sets,setLengths,currentSet,numSets,times+1); } } } void printSets(int** sets, int* setLengths, int numSets){ int i,j; printf("\nNumber of sets : %d",numSets); for(i=0;i<numSets+1;i++){ printf("\nSet %d : ",i+1); for(j=0;j<setLengths[i];j++){ printf(" %d ",sets[i][j]); } } } void processInputString(char* str){ int **sets, *currentSet, *setLengths, setLength, numSets = 0, i,j,k,l,start,counter=0; char *token,*holder,*holderToken; for(i=0;str[i]!=00;i++) if(str[i]=='x') numSets++; if(numSets==0){ printf("\n%s",str); return; } currentSet = (int*)calloc(sizeof(int),numSets + 1); setLengths = (int*)calloc(sizeof(int),numSets + 1); sets = (int**)malloc((numSets + 1)*sizeof(int*)); token = strtok(str,"x"); while(token!=NULL){ holder = (char*)malloc(strlen(token)*sizeof(char)); j = 0; for(i=0;token[i]!=00;i++){ if(token[i]>='0' && token[i]<='9') holder[j++] = token[i]; else if(token[i]==',') holder[j++] = ' '; } holder[j] = 00; setLength = 0; for(i=0;holder[i]!=00;i++) if(holder[i]==' ') setLength++; if(setLength==0 && strlen(holder)==0){ printf("\n{}"); return; } setLengths[counter] = setLength+1; sets[counter] = (int*)malloc((1+setLength)*sizeof(int)); k = 0; start = 0; for(l=0;holder[l]!=00;l++){ if(holder[l+1]==' '||holder[l+1]==00){ holderToken = (char*)malloc((l+1-start)*sizeof(char)); strncpy(holderToken,holder + start,l+1-start); sets[counter][k++] = atoi(holderToken); start = l+2; } } counter++; token = strtok(NULL,"x"); } printf("\n{"); cartesianProduct(sets,setLengths,currentSet,numSets + 1,0); printf("\b}"); } int main(int argC,char* argV[]) { if(argC!=2) printf("Usage : %s <Set product expression enclosed in double quotes>",argV[0]); else processInputString(argV[1]); return 0; }
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
Convert the following code from C to C#, ensuring the logic remains intact.
#include <stdlib.h> #include <stdio.h> #include <math.h> typedef double (*Class2Func)(double); double functionA( double v) { return v*v*v; } double functionB(double v) { return exp(log(v)/3); } double Function1( Class2Func f2, double val ) { return f2(val); } Class2Func WhichFunc( int idx) { return (idx < 4) ? &functionA : &functionB; } Class2Func funcListA[] = {&functionA, &sin, &cos, &tan }; Class2Func funcListB[] = {&functionB, &asin, &acos, &atan }; double InvokeComposed( Class2Func f1, Class2Func f2, double val ) { return f1(f2(val)); } typedef struct sComposition { Class2Func f1; Class2Func f2; } *Composition; Composition Compose( Class2Func f1, Class2Func f2) { Composition comp = malloc(sizeof(struct sComposition)); comp->f1 = f1; comp->f2 = f2; return comp; } double CallComposed( Composition comp, double val ) { return comp->f1( comp->f2(val) ); } int main(int argc, char *argv[]) { int ix; Composition c; printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0)); for (ix=0; ix<4; ix++) { c = Compose(funcListA[ix], funcListB[ix]); printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9)); } return 0; }
using System; class Program { static void Main(string[] args) { var cube = new Func<double, double>(x => Math.Pow(x, 3.0)); var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0)); var functionTuples = new[] { (forward: Math.Sin, backward: Math.Asin), (forward: Math.Cos, backward: Math.Acos), (forward: cube, backward: croot) }; foreach (var ft in functionTuples) { Console.WriteLine(ft.backward(ft.forward(0.5))); } } }
Change the following C code into C# without altering its purpose.
#include <stdio.h> #include <stdbool.h> int proper_divisors(const int n, bool print_flag) { int count = 0; for (int i = 1; i < n; ++i) { if (n % i == 0) { count++; if (print_flag) printf("%d ", i); } } if (print_flag) printf("\n"); return count; } int main(void) { for (int i = 1; i <= 10; ++i) { printf("%d: ", i); proper_divisors(i, true); } int max = 0; int max_i = 1; for (int i = 1; i <= 20000; ++i) { int v = proper_divisors(i, false); if (v >= max) { max = v; max_i = i; } } printf("%d with %d divisors\n", max_i, max); return 0; }
namespace RosettaCode.ProperDivisors { using System; using System.Collections.Generic; using System.Linq; internal static class Program { private static IEnumerable<int> ProperDivisors(int number) { return Enumerable.Range(1, number / 2) .Where(divisor => number % divisor == 0); } private static void Main() { foreach (var number in Enumerable.Range(1, 10)) { Console.WriteLine("{0}: {{{1}}}", number, string.Join(", ", ProperDivisors(number))); } var record = Enumerable.Range(1, 20000).Select(number => new { Number = number, Count = ProperDivisors(number).Count() }).OrderByDescending(currentRecord => currentRecord.Count).First(); Console.WriteLine("{0}: {1}", record.Number, record.Count); } } }
Write the same code in C# as shown below in C.
#include <stdio.h> #include <stdbool.h> int proper_divisors(const int n, bool print_flag) { int count = 0; for (int i = 1; i < n; ++i) { if (n % i == 0) { count++; if (print_flag) printf("%d ", i); } } if (print_flag) printf("\n"); return count; } int main(void) { for (int i = 1; i <= 10; ++i) { printf("%d: ", i); proper_divisors(i, true); } int max = 0; int max_i = 1; for (int i = 1; i <= 20000; ++i) { int v = proper_divisors(i, false); if (v >= max) { max = v; max_i = i; } } printf("%d with %d divisors\n", max_i, max); return 0; }
namespace RosettaCode.ProperDivisors { using System; using System.Collections.Generic; using System.Linq; internal static class Program { private static IEnumerable<int> ProperDivisors(int number) { return Enumerable.Range(1, number / 2) .Where(divisor => number % divisor == 0); } private static void Main() { foreach (var number in Enumerable.Range(1, 10)) { Console.WriteLine("{0}: {{{1}}}", number, string.Join(", ", ProperDivisors(number))); } var record = Enumerable.Range(1, 20000).Select(number => new { Number = number, Count = ProperDivisors(number).Count() }).OrderByDescending(currentRecord => currentRecord.Count).First(); Console.WriteLine("{0}: {1}", record.Number, record.Count); } } }
Write a version of this C function in C# with identical behavior.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libxml/parser.h> #include <libxml/tree.h> const char *names[] = { "April", "Tam O'Shanter", "Emily", NULL }; const char *remarks[] = { "Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift", NULL }; int main() { xmlDoc *doc = NULL; xmlNode *root = NULL, *node; const char **next; int a; doc = xmlNewDoc("1.0"); root = xmlNewNode(NULL, "CharacterRemarks"); xmlDocSetRootElement(doc, root); for(next = names, a = 0; *next != NULL; next++, a++) { node = xmlNewNode(NULL, "Character"); (void)xmlNewProp(node, "name", *next); xmlAddChild(node, xmlNewText(remarks[a])); xmlAddChild(root, node); } xmlElemDump(stdout, doc, root); xmlFreeDoc(doc); xmlCleanupParser(); return EXIT_SUCCESS; }
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; class Program { static string CreateXML(Dictionary<string, string> characterRemarks) { var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key))); var xml = new XElement("CharacterRemarks", remarks); return xml.ToString(); } static void Main(string[] args) { var characterRemarks = new Dictionary<string, string> { { "April", "Bubbly: I'm > Tam and <= Emily" }, { "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" }, { "Emily", "Short & shrift" } }; string xml = CreateXML(characterRemarks); Console.WriteLine(xml); } }
Rewrite the snippet below in C# so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <regex.h> #include <string.h> int main() { regex_t preg; regmatch_t substmatch[1]; const char *tp = "string$"; const char *t1 = "this is a matching string"; const char *t2 = "this is not a matching string!"; const char *ss = "istyfied"; regcomp(&preg, "string$", REG_EXTENDED); printf("'%s' %smatched with '%s'\n", t1, (regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp); printf("'%s' %smatched with '%s'\n", t2, (regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp); regfree(&preg); regcomp(&preg, "a[a-z]+", REG_EXTENDED); if ( regexec(&preg, t1, 1, substmatch, 0) == 0 ) { char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) + (strlen(t1) - substmatch[0].rm_eo) + 2); memcpy(ns, t1, substmatch[0].rm_so+1); memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss)); memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo], strlen(&t1[substmatch[0].rm_eo])); ns[ substmatch[0].rm_so + strlen(ss) + strlen(&t1[substmatch[0].rm_eo]) ] = 0; printf("mod string: '%s'\n", ns); free(ns); } else { printf("the string '%s' is the same: no matching!\n", t1); } regfree(&preg); return 0; }
using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string str = "I am a string"; if (new Regex("string$").IsMatch(str)) { Console.WriteLine("Ends with string."); } str = new Regex(" a ").Replace(str, " another "); Console.WriteLine(str); } }
Generate an equivalent C# version of this C code.
#include <stdio.h> int main(){ int bounds[ 2 ] = {1, 100}; char input[ 2 ] = " "; int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] ); do{ switch( input[ 0 ] ){ case 'H': bounds[ 1 ] = choice; break; case 'L': bounds[ 0 ] = choice; break; case 'Y': printf( "\nAwwwright\n" ); return 0; } choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Is the number %d? (Y/H/L) ", choice ); }while( scanf( "%1s", input ) == 1 ); return 0; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication1 { class RealisticGuess { private int max; private int min; private int guess; public void Start() { Console.Clear(); string input; try { Console.WriteLine("Please enter the lower boundary"); input = Console.ReadLine(); min = Convert.ToInt32(input); Console.WriteLine("Please enter the upper boundary"); input = Console.ReadLine(); max = Convert.ToInt32(input); } catch (FormatException) { Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again."); Console.ReadKey(true); Start(); } Console.WriteLine("Think of a number between {0} and {1}.", min, max); Thread.Sleep(2500); Console.WriteLine("Ready?"); Console.WriteLine("Press any key to begin."); Console.ReadKey(true); Guess(min, max); } public void Guess(int min, int max) { int counter = 1; string userAnswer; bool correct = false; Random rand = new Random(); while (correct == false) { guess = rand.Next(min, max); Console.Clear(); Console.WriteLine("{0}", guess); Console.WriteLine("Is this number correct? {Y/N}"); userAnswer = Console.ReadLine(); if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N") { Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'"); Console.WriteLine("Is the number correct? {Y/N}"); userAnswer = Console.ReadLine(); } if (userAnswer == "y" || userAnswer == "Y") { correct = true; } if (userAnswer == "n" || userAnswer == "N") { counter++; if (max == min) { Console.WriteLine("Error: Range Intersect. Press enter to restart the game."); Console.ReadKey(true); Guess(1, 101); } Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); userAnswer = Console.ReadLine(); if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H") { Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'"); Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); userAnswer = Console.ReadLine(); } if (userAnswer == "l" || userAnswer == "L") { max = guess; } if (userAnswer == "h" || userAnswer == "H") { min = guess; } } } if (correct == true) { EndAndLoop(counter); } } public void EndAndLoop(int iterations) { string userChoice; bool loop = false; Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations); while (loop == false) { Console.WriteLine("Would you like to play again? {Y/N}"); userChoice = Console.ReadLine(); if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n") { Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit."); } if (userChoice == "Y" || userChoice == "y") { Start(); } if (userChoice == "N" || userChoice == "n") { Environment.Exit(1); } } } } class Program { static void Main(string[] args) { Console.Title = "Random Number"; RealisticGuess game = new RealisticGuess(); game.Start(); } } }
Please provide an equivalent version of this C code in C#.
#include <stdio.h> int main(){ int bounds[ 2 ] = {1, 100}; char input[ 2 ] = " "; int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] ); do{ switch( input[ 0 ] ){ case 'H': bounds[ 1 ] = choice; break; case 'L': bounds[ 0 ] = choice; break; case 'Y': printf( "\nAwwwright\n" ); return 0; } choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Is the number %d? (Y/H/L) ", choice ); }while( scanf( "%1s", input ) == 1 ); return 0; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication1 { class RealisticGuess { private int max; private int min; private int guess; public void Start() { Console.Clear(); string input; try { Console.WriteLine("Please enter the lower boundary"); input = Console.ReadLine(); min = Convert.ToInt32(input); Console.WriteLine("Please enter the upper boundary"); input = Console.ReadLine(); max = Convert.ToInt32(input); } catch (FormatException) { Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again."); Console.ReadKey(true); Start(); } Console.WriteLine("Think of a number between {0} and {1}.", min, max); Thread.Sleep(2500); Console.WriteLine("Ready?"); Console.WriteLine("Press any key to begin."); Console.ReadKey(true); Guess(min, max); } public void Guess(int min, int max) { int counter = 1; string userAnswer; bool correct = false; Random rand = new Random(); while (correct == false) { guess = rand.Next(min, max); Console.Clear(); Console.WriteLine("{0}", guess); Console.WriteLine("Is this number correct? {Y/N}"); userAnswer = Console.ReadLine(); if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N") { Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'"); Console.WriteLine("Is the number correct? {Y/N}"); userAnswer = Console.ReadLine(); } if (userAnswer == "y" || userAnswer == "Y") { correct = true; } if (userAnswer == "n" || userAnswer == "N") { counter++; if (max == min) { Console.WriteLine("Error: Range Intersect. Press enter to restart the game."); Console.ReadKey(true); Guess(1, 101); } Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); userAnswer = Console.ReadLine(); if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H") { Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'"); Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); userAnswer = Console.ReadLine(); } if (userAnswer == "l" || userAnswer == "L") { max = guess; } if (userAnswer == "h" || userAnswer == "H") { min = guess; } } } if (correct == true) { EndAndLoop(counter); } } public void EndAndLoop(int iterations) { string userChoice; bool loop = false; Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations); while (loop == false) { Console.WriteLine("Would you like to play again? {Y/N}"); userChoice = Console.ReadLine(); if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n") { Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit."); } if (userChoice == "Y" || userChoice == "y") { Start(); } if (userChoice == "N" || userChoice == "n") { Environment.Exit(1); } } } } class Program { static void Main(string[] args) { Console.Title = "Random Number"; RealisticGuess game = new RealisticGuess(); game.Start(); } } }
Keep all operations the same but rewrite the snippet in C#.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define KeyType const char * #define ValType int #define HASH_SIZE 4096 unsigned strhashkey( const char * key, int max) { unsigned h=0; unsigned hl, hr; while(*key) { h += *key; hl= 0x5C5 ^ (h&0xfff00000 )>>18; hr =(h&0x000fffff ); h = hl ^ hr ^ *key++; } return h % max; } typedef struct sHme { KeyType key; ValType value; struct sHme *link; } *MapEntry; typedef struct he { MapEntry first, last; } HashElement; HashElement hash[HASH_SIZE]; typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc); typedef void (*ValCopyF)(ValType *vdest, ValType vsrc); typedef unsigned (*KeyHashF)( KeyType key, int upperBound ); typedef int (*KeyCmprF)(KeyType key1, KeyType key2); void HashAddH( KeyType key, ValType value, KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { (*copyVal)(&m_ent->value, value); } else { MapEntry last; MapEntry hme = malloc(sizeof(struct sHme)); (*copyKey)(&hme->key, key); (*copyVal)(&hme->value, value); hme->link = NULL; last = hash[hix].last; if (last) { last->link = hme; } else hash[hix].first = hme; hash[hix].last = hme; } } int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { *val = m_ent->value; } return (m_ent != NULL); } void copyStr(const char**dest, const char *src) { *dest = strdup(src); } void copyInt( int *dest, int src) { *dest = src; } int strCompare( const char *key1, const char *key2) { return strcmp(key1, key2) == 0; } void HashAdd( KeyType key, ValType value ) { HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare); } int HashGet(ValType *val, KeyType key) { return HashGetH( val, key, &strhashkey, &strCompare); } int main() { static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" }; static int valuList[] = {1,43,640, 747, 42, 42}; int ix; for (ix=0; ix<6; ix++) { HashAdd(keyList[ix], valuList[ix]); } return 0; }
static class Program { static void Main() { System.Collections.Hashtable h = new System.Collections.Hashtable(); string[] keys = { "foo", "bar", "val" }; string[] values = { "little", "miss", "muffet" }; System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length."); for (int i = 0; i < keys.Length; i++) { h.Add(keys[i], values[i]); } } }
Translate the given C code snippet into C# without altering its behavior.
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
using System; public class Program { static void Main() { PrintBins(new [] { 23, 37, 43, 53, 67, 83 }, 95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55 ); Console.WriteLine(); PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 }, 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202, 253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534, 622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458, 945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759, 898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527, 736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621, 892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749); } static void PrintBins(int[] limits, params int[] data) { int[] bins = Bins(limits, data); Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}"); for (int i = 0; i < limits.Length-1; i++) { Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}"); } Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}"); } static int[] Bins(int[] limits, params int[] data) { Array.Sort(limits); int[] bins = new int[limits.Length + 1]; foreach (int n in data) { int i = Array.BinarySearch(limits, n); i = i < 0 ? ~i : i+1; bins[i]++; } return bins; } }
Transform the following C implementation into C#, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
using System; public class Program { static void Main() { PrintBins(new [] { 23, 37, 43, 53, 67, 83 }, 95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55 ); Console.WriteLine(); PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 }, 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202, 253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534, 622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458, 945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759, 898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527, 736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621, 892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749); } static void PrintBins(int[] limits, params int[] data) { int[] bins = Bins(limits, data); Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}"); for (int i = 0; i < limits.Length-1; i++) { Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}"); } Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}"); } static int[] Bins(int[] limits, params int[] data) { Array.Sort(limits); int[] bins = new int[limits.Length + 1]; foreach (int n in data) { int i = Array.BinarySearch(limits, n); i = i < 0 ? ~i : i+1; bins[i]++; } return bins; } }
Keep all operations the same but rewrite the snippet in C#.
#include <stdio.h> #include <stdlib.h> size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
using System; public class Program { static void Main() { PrintBins(new [] { 23, 37, 43, 53, 67, 83 }, 95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55 ); Console.WriteLine(); PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 }, 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202, 253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534, 622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458, 945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759, 898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527, 736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621, 892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749); } static void PrintBins(int[] limits, params int[] data) { int[] bins = Bins(limits, data); Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}"); for (int i = 0; i < limits.Length-1; i++) { Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}"); } Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}"); } static int[] Bins(int[] limits, params int[] data) { Array.Sort(limits); int[] bins = new int[limits.Length + 1]; foreach (int n in data) { int i = Array.BinarySearch(limits, n); i = i < 0 ? ~i : i+1; bins[i]++; } return bins; } }
Ensure the translated C# code behaves exactly like the original C snippet.
#include <stdlib.h> #include <math.h> #include <GL/glut.h> #include <GL/gl.h> #include <sys/time.h> #define length 5 #define g 9.8 double alpha, accl, omega = 0, E; struct timeval tv; double elappsed() { struct timeval now; gettimeofday(&now, 0); int ret = (now.tv_sec - tv.tv_sec) * 1000000 + now.tv_usec - tv.tv_usec; tv = now; return ret / 1.e6; } void resize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); } void render() { double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha); resize(640, 320); glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_LINES); glVertex2d(320, 0); glVertex2d(x, y); glEnd(); glFlush(); double us = elappsed(); alpha += (omega + us * accl / 2) * us; omega += accl * us; if (length * g * (1 - cos(alpha)) >= E) { alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g); omega = 0; } accl = -g / length * sin(alpha); } void init_gfx(int *c, char **v) { glutInit(c, v); glutInitDisplayMode(GLUT_RGB); glutInitWindowSize(640, 320); glutIdleFunc(render); glutCreateWindow("Pendulum"); } int main(int c, char **v) { alpha = 4 * atan2(1, 1) / 2.1; E = length * g * (1 - cos(alpha)); accl = -g / length * sin(alpha); omega = 0; gettimeofday(&tv, 0); init_gfx(&c, v); glutMainLoop(); return 0; }
using System; using System.Drawing; using System.Windows.Forms; class CSharpPendulum { Form _form; Timer _timer; double _angle = Math.PI / 2, _angleAccel, _angleVelocity = 0, _dt = 0.1; int _length = 50; [STAThread] static void Main() { var p = new CSharpPendulum(); } public CSharpPendulum() { _form = new Form() { Text = "Pendulum", Width = 200, Height = 200 }; _timer = new Timer() { Interval = 30 }; _timer.Tick += delegate(object sender, EventArgs e) { int anchorX = (_form.Width / 2) - 12, anchorY = _form.Height / 4, ballX = anchorX + (int)(Math.Sin(_angle) * _length), ballY = anchorY + (int)(Math.Cos(_angle) * _length); _angleAccel = -9.81 / _length * Math.Sin(_angle); _angleVelocity += _angleAccel * _dt; _angle += _angleVelocity * _dt; Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height); Graphics g = Graphics.FromImage(dblBuffer); Graphics f = Graphics.FromHwnd(_form.Handle); g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY)); g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7); g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14); f.Clear(Color.White); f.DrawImage(dblBuffer, new Point(0, 0)); }; _timer.Start(); Application.Run(_form); } }
Convert this C block to C#, preserving its control flow and logic.
#include <stdlib.h> #include <math.h> #include <GL/glut.h> #include <GL/gl.h> #include <sys/time.h> #define length 5 #define g 9.8 double alpha, accl, omega = 0, E; struct timeval tv; double elappsed() { struct timeval now; gettimeofday(&now, 0); int ret = (now.tv_sec - tv.tv_sec) * 1000000 + now.tv_usec - tv.tv_usec; tv = now; return ret / 1.e6; } void resize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glOrtho(0, w, h, 0, -1, 1); } void render() { double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha); resize(640, 320); glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_LINES); glVertex2d(320, 0); glVertex2d(x, y); glEnd(); glFlush(); double us = elappsed(); alpha += (omega + us * accl / 2) * us; omega += accl * us; if (length * g * (1 - cos(alpha)) >= E) { alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g); omega = 0; } accl = -g / length * sin(alpha); } void init_gfx(int *c, char **v) { glutInit(c, v); glutInitDisplayMode(GLUT_RGB); glutInitWindowSize(640, 320); glutIdleFunc(render); glutCreateWindow("Pendulum"); } int main(int c, char **v) { alpha = 4 * atan2(1, 1) / 2.1; E = length * g * (1 - cos(alpha)); accl = -g / length * sin(alpha); omega = 0; gettimeofday(&tv, 0); init_gfx(&c, v); glutMainLoop(); return 0; }
using System; using System.Drawing; using System.Windows.Forms; class CSharpPendulum { Form _form; Timer _timer; double _angle = Math.PI / 2, _angleAccel, _angleVelocity = 0, _dt = 0.1; int _length = 50; [STAThread] static void Main() { var p = new CSharpPendulum(); } public CSharpPendulum() { _form = new Form() { Text = "Pendulum", Width = 200, Height = 200 }; _timer = new Timer() { Interval = 30 }; _timer.Tick += delegate(object sender, EventArgs e) { int anchorX = (_form.Width / 2) - 12, anchorY = _form.Height / 4, ballX = anchorX + (int)(Math.Sin(_angle) * _length), ballY = anchorY + (int)(Math.Cos(_angle) * _length); _angleAccel = -9.81 / _length * Math.Sin(_angle); _angleVelocity += _angleAccel * _dt; _angle += _angleVelocity * _dt; Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height); Graphics g = Graphics.FromImage(dblBuffer); Graphics f = Graphics.FromHwnd(_form.Handle); g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY)); g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7); g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14); f.Clear(Color.White); f.DrawImage(dblBuffer, new Point(0, 0)); }; _timer.Start(); Application.Run(_form); } }
Transform the following C implementation into C#, maintaining the same output and logic.
#include <stdio.h> int max (int *a, int n, int i, int j, int k) { int m = i; if (j < n && a[j] > a[m]) { m = j; } if (k < n && a[k] > a[m]) { m = k; } return m; } void downheap (int *a, int n, int i) { while (1) { int j = max(a, n, i, 2 * i + 1, 2 * i + 2); if (j == i) { break; } int t = a[i]; a[i] = a[j]; a[j] = t; i = j; } } void heapsort (int *a, int n) { int i; for (i = (n - 2) / 2; i >= 0; i--) { downheap(a, n, i); } for (i = 0; i < n; i++) { int t = a[n - i - 1]; a[n - i - 1] = a[0]; a[0] = t; downheap(a, n - i - 1, 0); } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); heapsort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
using System; using System.Collections.Generic; using System.Text; public class HeapSortClass { public static void HeapSort<T>(T[] array) { HeapSort<T>(array, 0, array.Length, Comparer<T>.Default); } public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer) { HeapSort<T>(array, offset, length, comparer.Compare); } public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison) { for (int i = 0; i < length; i++) { int index = i; T item = array[offset + i]; while (index > 0 && comparison(array[offset + (index - 1) / 2], item) < 0) { int top = (index - 1) / 2; array[offset + index] = array[offset + top]; index = top; } array[offset + index] = item; } for (int i = length - 1; i > 0; i--) { T last = array[offset + i]; array[offset + i] = array[offset]; int index = 0; while (index * 2 + 1 < i) { int left = index * 2 + 1, right = left + 1; if (right < i && comparison(array[offset + left], array[offset + right]) < 0) { if (comparison(last, array[offset + right]) > 0) break; array[offset + index] = array[offset + right]; index = right; } else { if (comparison(last, array[offset + left]) > 0) break; array[offset + index] = array[offset + left]; index = left; } } array[offset + index] = last; } } static void Main() { byte[] r = {5, 4, 1, 2}; HeapSort(r); string[] s = { "-", "D", "a", "33" }; HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase); } }
Convert the following code from C to C#, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> #include <locale.h> int locale_ok = 0; wchar_t s_suits[] = L"♠♥♦♣"; const char *s_suits_ascii[] = { "S", "H", "D", "C" }; const char *s_nums[] = { "WHAT", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "OVERFLOW" }; typedef struct { int suit, number, _s; } card_t, *card; typedef struct { int n; card_t cards[52]; } deck_t, *deck; void show_card(card c) { if (locale_ok) printf(" %lc%s", s_suits[c->suit], s_nums[c->number]); else printf(" %s%s", s_suits_ascii[c->suit], s_nums[c->number]); } deck new_deck() { int i, j, k; deck d = malloc(sizeof(deck_t)); d->n = 52; for (i = k = 0; i < 4; i++) for (j = 1; j <= 13; j++, k++) { d->cards[k].suit = i; d->cards[k].number = j; } return d; } void show_deck(deck d) { int i; printf("%d cards:", d->n); for (i = 0; i < d->n; i++) show_card(d->cards + i); printf("\n"); } int cmp_card(const void *a, const void *b) { int x = ((card)a)->_s, y = ((card)b)->_s; return x < y ? -1 : x > y; } card deal_card(deck d) { if (!d->n) return 0; return d->cards + --d->n; } void shuffle_deck(deck d) { int i; for (i = 0; i < d->n; i++) d->cards[i]._s = rand(); qsort(d->cards, d->n, sizeof(card_t), cmp_card); } int main() { int i, j; deck d = new_deck(); locale_ok = (0 != setlocale(LC_CTYPE, "")); printf("New deck, "); show_deck(d); printf("\nShuffle and deal to three players:\n"); shuffle_deck(d); for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) show_card(deal_card(d)); printf("\n"); } printf("Left in deck "); show_deck(d); return 0; }
using System; using System.Linq; using System.Collections.Generic; public struct Card { public Card(string rank, string suit) : this() { Rank = rank; Suit = suit; } public string Rank { get; } public string Suit { get; } public override string ToString() => $"{Rank} of {Suit}"; } public class Deck : IEnumerable<Card> { static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" }; static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" }; readonly List<Card> cards; public Deck() { cards = (from suit in suits from rank in ranks select new Card(rank, suit)).ToList(); } public int Count => cards.Count; public void Shuffle() { var random = new Random(); for (int i = 0; i < cards.Count; i++) { int r = random.Next(i, cards.Count); var temp = cards[i]; cards[i] = cards[r]; cards[r] = temp; } } public Card Deal() { int last = cards.Count - 1; Card card = cards[last]; cards.RemoveAt(last); return card; } public IEnumerator<Card> GetEnumerator() { for (int i = cards.Count - 1; i >= 0; i--) yield return cards[i]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); }
Convert the following code from C to C#, ensuring the logic remains intact.
char foo() { char array[5] = {3,6,9,12,15}; return array[2]; }
int[] numbers = new int[10];
Convert the following code from C to C#, ensuring the logic remains intact.
char foo() { char array[5] = {3,6,9,12,15}; return array[2]; }
int[] numbers = new int[10];
Produce a functionally identical C# code for the snippet given in C.
#include <stdio.h> int main() { int i, j, dim, d; int depth = 3; for (i = 0, dim = 1; i < depth; i++, dim *= 3); for (i = 0; i < dim; i++) { for (j = 0; j < dim; j++) { for (d = dim / 3; d; d /= 3) if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1) break; printf(d ? " " : "##"); } printf("\n"); } return 0; }
using System; using System.Collections.Generic; using System.Linq; class Program { static List<string> NextCarpet(List<string> carpet) { return carpet.Select(x => x + x + x) .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x)) .Concat(carpet.Select(x => x + x + x)).ToList(); } static List<string> SierpinskiCarpet(int n) { return Enumerable.Range(1, n).Aggregate(new List<string> { "#" }, (carpet, _) => NextCarpet(carpet)); } static void Main(string[] args) { foreach (string s in SierpinskiCarpet(3)) Console.WriteLine(s); } }
Preserve the algorithm and functionality while converting the code from C to C#.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> bool is_sorted(int *a, int n) { while ( --n >= 1 ) { if ( a[n] < a[n-1] ) return false; } return true; } void shuffle(int *a, int n) { int i, t, r; for(i=0; i < n; i++) { t = a[i]; r = rand() % n; a[i] = a[r]; a[r] = t; } } void bogosort(int *a, int n) { while ( !is_sorted(a, n) ) shuffle(a, n); } int main() { int numbers[] = { 1, 10, 9, 7, 3, 0 }; int i; bogosort(numbers, 6); for (i=0; i < 6; i++) printf("%d ", numbers[i]); printf("\n"); }
using System; using System.Collections.Generic; namespace RosettaCode.BogoSort { public static class BogoSorter { public static void Sort<T>(List<T> list) where T:IComparable { while (!list.isSorted()) { list.Shuffle(); } } private static bool isSorted<T>(this IList<T> list) where T:IComparable { if(list.Count<=1) return true; for (int i = 1 ; i < list.Count; i++) if(list[i].CompareTo(list[i-1])<0) return false; return true; } private static void Shuffle<T>(this IList<T> list) { Random rand = new Random(); for (int i = 0; i < list.Count; i++) { int swapIndex = rand.Next(list.Count); T temp = list[swapIndex]; list[swapIndex] = list[i]; list[i] = temp; } } } class TestProgram { static void Main() { List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 }; BogoSorter.Sort(testList); foreach (int i in testList) Console.Write(i + " "); } } }
Translate the given C code snippet into C# without altering its behavior.
#include <ctime> #include <cstdint> extern "C" { int64_t from date(const char* string) { struct tm tmInfo = {0}; strptime(string, "%Y-%m-%d", &tmInfo); return mktime(&tmInfo); } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization; public static class MergeAndAggregateDatasets { public static void Main() { string patientsCsv = @" PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz"; string visitsCsv = @" PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3"; string format = "yyyy-MM-dd"; var formatProvider = new DateTimeFormat(format).FormatProvider; var patients = ParseCsv( patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries), line => (PatientId: int.Parse(line[0]), LastName: line[1])); var visits = ParseCsv( visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries), line => ( PatientId: int.Parse(line[0]), VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?), Score: double.TryParse(line[2], out double score) ? score : default(double?) ) ); var results = patients.GroupJoin(visits, p => p.PatientId, v => v.PatientId, (p, vs) => ( p.PatientId, p.LastName, LastVisit: vs.Max(v => v.VisitDate), ScoreSum: vs.Sum(v => v.Score), ScoreAvg: vs.Average(v => v.Score) ) ).OrderBy(r => r.PatientId); Console.WriteLine("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |"); foreach (var r in results) { Console.WriteLine($"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? "",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |"); } } private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor) { for (int i = 1; i < contents.Length; i++) { var line = contents[i].Split(','); yield return constructor(line); } } }
Transform the following C implementation into C#, maintaining the same output and logic.
#include <stdio.h> #include <math.h> typedef double (*deriv_f)(double, double); #define FMT " %7.3f" void ivp_euler(deriv_f f, double y, int step, int end_t) { int t = 0; printf(" Step %2d: ", (int)step); do { if (t % 10 == 0) printf(FMT, y); y += step * f(t, y); } while ((t += step) <= end_t); printf("\n"); } void analytic() { double t; printf(" Time: "); for (t = 0; t <= 100; t += 10) printf(" %7g", t); printf("\nAnalytic: "); for (t = 0; t <= 100; t += 10) printf(FMT, 20 + 80 * exp(-0.07 * t)); printf("\n"); } double cooling(double t, double temp) { return -0.07 * (temp - 20); } int main() { analytic(); ivp_euler(cooling, 100, 2, 100); ivp_euler(cooling, 100, 5, 100); ivp_euler(cooling, 100, 10, 100); return 0; }
using System; namespace prog { class MainClass { const float T0 = 100f; const float TR = 20f; const float k = 0.07f; readonly static float[] delta_t = {2.0f,5.0f,10.0f}; const int n = 100; public delegate float func(float t); static float NewtonCooling(float t) { return -k * (t-TR); } public static void Main (string[] args) { func f = new func(NewtonCooling); for(int i=0; i<delta_t.Length; i++) { Console.WriteLine("delta_t = " + delta_t[i]); Euler(f,T0,n,delta_t[i]); } } public static void Euler(func f, float y, int n, float h) { for(float x=0; x<=n; x+=h) { Console.WriteLine("\t" + x + "\t" + y); y += h * f(y); } } } }
Write a version of this C function in C# with identical behavior.
#include <math.h> #include <stdio.h> #include <assert.h> int nonsqr(int n) { return n + (int)(0.5 + sqrt(n)); } int main() { int i; for (i = 1; i < 23; i++) printf("%d ", nonsqr(i)); printf("\n"); for (i = 1; i < 1000000; i++) { double j = sqrt(nonsqr(i)); assert(j != floor(j)); } return 0; }
using System; using System.Diagnostics; namespace sons { class Program { static void Main(string[] args) { for (int i = 1; i < 23; i++) Console.WriteLine(nonsqr(i)); for (int i = 1; i < 1000000; i++) { double j = Math.Sqrt(nonsqr(i)); Debug.Assert(j != Math.Floor(j),"Square"); } } static int nonsqr(int i) { return (int)(i + Math.Floor(0.5 + Math.Sqrt(i))); } } }
Generate an equivalent C# version of this C code.
#include <math.h> #include <stdio.h> #include <assert.h> int nonsqr(int n) { return n + (int)(0.5 + sqrt(n)); } int main() { int i; for (i = 1; i < 23; i++) printf("%d ", nonsqr(i)); printf("\n"); for (i = 1; i < 1000000; i++) { double j = sqrt(nonsqr(i)); assert(j != floor(j)); } return 0; }
using System; using System.Diagnostics; namespace sons { class Program { static void Main(string[] args) { for (int i = 1; i < 23; i++) Console.WriteLine(nonsqr(i)); for (int i = 1; i < 1000000; i++) { double j = Math.Sqrt(nonsqr(i)); Debug.Assert(j != Math.Floor(j),"Square"); } } static int nonsqr(int i) { return (int)(i + Math.Floor(0.5 + Math.Sqrt(i))); } } }
Port the following code from C to C# with equivalent syntax and logic.
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> void putm(char* string, size_t m) { while(*string && m--) putchar(*string++); } int main(void) { char string[] = "Programs for other encodings (such as 8-bit ASCII, or EUC-JP)." int n = 3; int m = 4; char knownCharacter = '('; char knownSubstring[] = "encodings"; putm(string+n-1, m ); putchar('\n'); puts(string+n+1); putchar('\n'); putm(string, strlen(string)-1); putchar('\n'); putm(strchr(string, knownCharacter), m ); putchar('\n'); putm(strstr(string, knownSubstring), m ); putchar('\n'); return EXIT_SUCCESS; }
using System; namespace SubString { class Program { static void Main(string[] args) { string s = "0123456789"; const int n = 3; const int m = 2; const char c = '3'; const string z = "345"; Console.WriteLine(s.Substring(n, m)); Console.WriteLine(s.Substring(n, s.Length - n)); Console.WriteLine(s.Substring(0, s.Length - 1)); Console.WriteLine(s.Substring(s.IndexOf(c), m)); Console.WriteLine(s.Substring(s.IndexOf(z), m)); } } }
Change the following C code into C# without altering its purpose.
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> void putm(char* string, size_t m) { while(*string && m--) putchar(*string++); } int main(void) { char string[] = "Programs for other encodings (such as 8-bit ASCII, or EUC-JP)." int n = 3; int m = 4; char knownCharacter = '('; char knownSubstring[] = "encodings"; putm(string+n-1, m ); putchar('\n'); puts(string+n+1); putchar('\n'); putm(string, strlen(string)-1); putchar('\n'); putm(strchr(string, knownCharacter), m ); putchar('\n'); putm(strstr(string, knownSubstring), m ); putchar('\n'); return EXIT_SUCCESS; }
using System; namespace SubString { class Program { static void Main(string[] args) { string s = "0123456789"; const int n = 3; const int m = 2; const char c = '3'; const string z = "345"; Console.WriteLine(s.Substring(n, m)); Console.WriteLine(s.Substring(n, s.Length - n)); Console.WriteLine(s.Substring(0, s.Length - 1)); Console.WriteLine(s.Substring(s.IndexOf(c), m)); Console.WriteLine(s.Substring(s.IndexOf(z), m)); } } }
Convert the following code from C to C#, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> int number_of_digits(int x){ int NumberOfDigits; for(NumberOfDigits=0;x!=0;NumberOfDigits++){ x=x/10; } return NumberOfDigits; } int* convert_array(char array[], int NumberOfElements) { int *convertedArray=malloc(NumberOfElements*sizeof(int)); int originalElement, convertedElement; for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++) { convertedArray[convertedElement]=atoi(&array[originalElement]); originalElement+=number_of_digits(convertedArray[convertedElement])+1; } return convertedArray; } int isSorted(int array[], int numberOfElements){ int sorted=1; for(int counter=0;counter<numberOfElements;counter++){ if(counter!=0 && array[counter-1]>array[counter]) sorted--; } return sorted; } int main(int argc, char* argv[]) { int* convertedArray; convertedArray=convert_array(*(argv+1), argc-1); if(isSorted(convertedArray, argc-1)==1) printf("Did you forgot to turn on your brain?! This array is already sorted!\n"); else if(argc-1<=10) printf("Am I really supposed to sort this? Sort it by yourself!\n"); else printf("Am I really supposed to sort this? Bhahahaha!\n"); free(convertedArray); return 0; }
using System; class Program { public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T> { T[] originalArray = (T[]) array.Clone(); Array.Sort(array); for (var i = 0; i < originalArray.Length; i++) { if (!Equals(originalArray[i], array[i])) { return false; } } return true; } }
Port the following code from C to C# with equivalent syntax and logic.
#include <stdio.h> int is_leap_year(unsigned year) { return !(year & (year % 100 ? 3 : 15)); } int main(void) { const unsigned test_case[] = { 1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100 }; const unsigned n = sizeof test_case / sizeof test_case[0]; for (unsigned i = 0; i != n; ++i) { unsigned year = test_case[i]; printf("%u is %sa leap year.\n", year, is_leap_year(year) ? "" : "not "); } return 0; }
using System; class Program { static void Main() { foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year }) { Console.WriteLine("{0} is {1}a leap year.", year, DateTime.IsLeapYear(year) ? string.Empty : "not "); } } }
Write a version of this C function in C# with identical behavior.
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int compareStrings(const void *a, const void *b) { const char **aa = (const char **)a; const char **bb = (const char **)b; return strcmp(*aa, *bb); } void lexOrder(int n, int *ints) { char **strs; int i, first = 1, last = n, k = n, len; if (n < 1) { first = n; last = 1; k = 2 - n; } strs = malloc(k * sizeof(char *)); for (i = first; i <= last; ++i) { if (i >= 1) len = (int)log10(i) + 2; else if (i == 0) len = 2; else len = (int)log10(-i) + 3; strs[i-first] = malloc(len); sprintf(strs[i-first], "%d", i); } qsort(strs, k, sizeof(char *), compareStrings); for (i = 0; i < k; ++i) { ints[i] = atoi(strs[i]); free(strs[i]); } free(strs); } int main() { int i, j, k, n, *ints; int numbers[5] = {0, 5, 13, 21, -22}; printf("In lexicographical order:\n\n"); for (i = 0; i < 5; ++i) { k = n = numbers[i]; if (k < 1) k = 2 - k; ints = malloc(k * sizeof(int)); lexOrder(n, ints); printf("%3d: [", n); for (j = 0; j < k; ++j) { printf("%d ", ints[j]); } printf("\b]\n"); free(ints); } return 0; }
using static System.Console; using static System.Linq.Enumerable; public class Program { public static void Main() { foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($"{n}: {string.Join(", ", LexOrder(n))}"); } public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString()); }
Generate a C# translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <string.h> const char *ones[] = { 0, "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char *tens[] = { 0, "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; const char *llions[] = { 0, "thousand", "million", "billion", "trillion", }; const int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3; int say_hundred(const char *s, int len, int depth, int has_lead) { int c[3], i; for (i = -3; i < 0; i++) { if (len + i >= 0) c[i + 3] = s[len + i] - '0'; else c[i + 3] = 0; } if (!(c[0] + c[1] + c[2])) return 0; if (c[0]) { printf("%s hundred", ones[c[0]]); has_lead = 1; } if (has_lead && (c[1] || c[2])) printf((!depth || c[0]) && (!c[0] || !c[1]) ? "and " : c[0] ? " " : ""); if (c[1] < 2) { if (c[1] || c[2]) printf("%s", ones[c[1] * 10 + c[2]]); } else { if (c[1]) { printf("%s", tens[c[1]]); if (c[2]) putchar('-'); } if (c[2]) printf("%s", ones[c[2]]); } return 1; } int say_maxillion(const char *s, int len, int depth, int has_lead) { int n = len / 3, r = len % 3; if (!r) { n--; r = 3; } const char *e = s + r; do { if (say_hundred(s, r, n, has_lead) && n) { has_lead = 1; printf(" %s", llions[n]); if (!depth) printf(", "); else printf(" "); } s = e; e += 3; } while (r = 3, n--); return 1; } void say_number(const char *s) { int len, i, got_sign = 0; while (*s == ' ') s++; if (*s < '0' || *s > '9') { if (*s == '-') got_sign = -1; else if (*s == '+') got_sign = 1; else goto nan; s++; } else got_sign = 1; while (*s == '0') { s++; if (*s == '\0') { printf("zero\n"); return; } } len = strlen(s); if (!len) goto nan; for (i = 0; i < len; i++) { if (s[i] < '0' || s[i] > '9') { printf("(not a number)"); return; } } if (got_sign == -1) printf("minus "); int n = len / maxillion; int r = len % maxillion; if (!r) { r = maxillion; n--; } const char *end = s + len - n * maxillion; int has_lead = 0; do { if ((has_lead = say_maxillion(s, r, n, has_lead))) { for (i = 0; i < n; i++) printf(" %s", llions[maxillion / 3]); if (n) printf(", "); } n--; r = maxillion; s = end; end += r; } while (n >= 0); printf("\n"); return; nan: printf("not a number\n"); return; } int main() { say_number("-42"); say_number("1984"); say_number("10000"); say_number("1024"); say_number("1001001001001"); say_number("123456789012345678901234567890123456789012345678900000001"); return 0; }
using System; class NumberNamer { static readonly string[] incrementsOfOne = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; static readonly string[] incrementsOfTen = { "", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" }; const string millionName = "million", thousandName = "thousand", hundredName = "hundred", andName = "and"; public static string GetName( int i ) { string output = ""; if( i >= 1000000 ) { output += ParseTriplet( i / 1000000 ) + " " + millionName; i %= 1000000; if( i == 0 ) return output; } if( i >= 1000 ) { if( output.Length > 0 ) { output += ", "; } output += ParseTriplet( i / 1000 ) + " " + thousandName; i %= 1000; if( i == 0 ) return output; } if( output.Length > 0 ) { output += ", "; } output += ParseTriplet( i ); return output; } static string ParseTriplet( int i ) { string output = ""; if( i >= 100 ) { output += incrementsOfOne[i / 100] + " " + hundredName; i %= 100; if( i == 0 ) return output; } if( output.Length > 0 ) { output += " " + andName + " "; } if( i >= 20 ) { output += incrementsOfTen[i / 10]; i %= 10; if( i == 0 ) return output; } if( output.Length > 0 ) { output += " "; } output += incrementsOfOne[i]; return output; } } class Program { static void Main( string[] args ) { Console.WriteLine( NumberNamer.GetName( 1 ) ); Console.WriteLine( NumberNamer.GetName( 234 ) ); Console.WriteLine( NumberNamer.GetName( 31337 ) ); Console.WriteLine( NumberNamer.GetName( 987654321 ) ); } }
Transform the following C implementation into C#, maintaining the same output and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> int cmp(const int* a, const int* b) { return *b - *a; } void compareAndReportStringsLength(const char* strings[], const int n) { if (n > 0) { char* has_length = "has length"; char* predicate_max = "and is the longest string"; char* predicate_min = "and is the shortest string"; char* predicate_ave = "and is neither the longest nor the shortest string"; int* si = malloc(2 * n * sizeof(int)); if (si != NULL) { for (int i = 0; i < n; i++) { si[2 * i] = strlen(strings[i]); si[2 * i + 1] = i; } qsort(si, n, 2 * sizeof(int), cmp); int max = si[0]; int min = si[2 * (n - 1)]; for (int i = 0; i < n; i++) { int length = si[2 * i]; char* string = strings[si[2 * i + 1]]; char* predicate; if (length == max) predicate = predicate_max; else if (length == min) predicate = predicate_min; else predicate = predicate_ave; printf("\"%s\" %s %d %s\n", string, has_length, length, predicate); } free(si); } else { fputs("unable allocate memory buffer", stderr); } } } int main(int argc, char* argv[]) { char* list[] = { "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(list, 4); return EXIT_SUCCESS; }
using System; using System.Collections.Generic; namespace example { class Program { static void Main(string[] args) { var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(strings); } private static void compareAndReportStringsLength(string[] strings) { if (strings.Length > 0) { char Q = '"'; string hasLength = " has length "; string predicateMax = " and is the longest string"; string predicateMin = " and is the shortest string"; string predicateAve = " and is neither the longest nor the shortest string"; string predicate; (int, int)[] li = new (int, int)[strings.Length]; for (int i = 0; i < strings.Length; i++) li[i] = (strings[i].Length, i); Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1); int maxLength = li[0].Item1; int minLength = li[strings.Length - 1].Item1; for (int i = 0; i < strings.Length; i++) { int length = li[i].Item1; string str = strings[li[i].Item2]; if (length == maxLength) predicate = predicateMax; else if (length == minLength) predicate = predicateMin; else predicate = predicateAve; Console.WriteLine(Q + str + Q + hasLength + length + predicate); } } } } }
Ensure the translated C# code behaves exactly like the original C snippet.
int frequency[26]; int ch; FILE* txt_file = fopen ("a_text_file.txt", "rt"); for (ch = 0; ch < 26; ch++) frequency[ch] = 0; while (1) { ch = fgetc(txt_file); if (ch == EOF) break; if ('a' <= ch && ch <= 'z') frequency[ch-'a']++; else if ('A' <= ch && ch <= 'Z') frequency[ch-'A']++; }
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Program { static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items) { var dictionary = new SortedDictionary<TItem, int>(); foreach (var item in items) { if (dictionary.ContainsKey(item)) { dictionary[item]++; } else { dictionary[item] = 1; } } return dictionary; } static void Main(string[] arguments) { var file = arguments.FirstOrDefault(); if (File.Exists(file)) { var text = File.ReadAllText(file); foreach (var entry in GetFrequencies(text)) { Console.WriteLine("{0}: {1}", entry.Key, entry.Value); } } } }
Produce a language-to-language conversion: from C to C#, same semantics.
int frequency[26]; int ch; FILE* txt_file = fopen ("a_text_file.txt", "rt"); for (ch = 0; ch < 26; ch++) frequency[ch] = 0; while (1) { ch = fgetc(txt_file); if (ch == EOF) break; if ('a' <= ch && ch <= 'z') frequency[ch-'a']++; else if ('A' <= ch && ch <= 'Z') frequency[ch-'A']++; }
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Program { static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items) { var dictionary = new SortedDictionary<TItem, int>(); foreach (var item in items) { if (dictionary.ContainsKey(item)) { dictionary[item]++; } else { dictionary[item] = 1; } } return dictionary; } static void Main(string[] arguments) { var file = arguments.FirstOrDefault(); if (File.Exists(file)) { var text = File.ReadAllText(file); foreach (var entry in GetFrequencies(text)) { Console.WriteLine("{0}: {1}", entry.Key, entry.Value); } } } }
Rewrite the snippet below in C# so it works the same as the original C code.
#include <stdio.h> #include <string.h> #include <stdlib.h> char * incr(char *s) { int i, begin, tail, len; int neg = (*s == '-'); char tgt = neg ? '0' : '9'; if (!strcmp(s, "-1")) { s[0] = '0', s[1] = '\0'; return s; } len = strlen(s); begin = (*s == '-' || *s == '+') ? 1 : 0; for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--); if (tail < begin && !neg) { if (!begin) s = realloc(s, len + 2); s[0] = '1'; for (i = 1; i <= len - begin; i++) s[i] = '0'; s[len + 1] = '\0'; } else if (tail == begin && neg && s[1] == '1') { for (i = 1; i < len - begin; i++) s[i] = '9'; s[len - 1] = '\0'; } else { for (i = len - 1; i > tail; i--) s[i] = neg ? '9' : '0'; s[tail] += neg ? -1 : 1; } return s; } void string_test(const char *s) { char *ret = malloc(strlen(s)); strcpy(ret, s); printf("text: %s\n", ret); printf(" ->: %s\n", ret = incr(ret)); free(ret); } int main() { string_test("+0"); string_test("-1"); string_test("-41"); string_test("+41"); string_test("999"); string_test("+999"); string_test("109999999999999999999999999999999999999999"); string_test("-100000000000000000000000000000000000000000000"); return 0; }
string s = "12345"; s = (int.Parse(s) + 1).ToString(); using System.Numerics; string bis = "123456789012345678999999999"; bis = (BigInteger.Parse(bis) + 1).ToString();
Rewrite the snippet below in C# so it works the same as the original C code.
#include <string.h> #include <stdio.h> #include <stdlib.h> char *strip_chars(const char *string, const char *chars) { char * newstr = malloc(strlen(string) + 1); int counter = 0; for ( ; *string; string++) { if (!strchr(chars, *string)) { newstr[ counter ] = *string; ++ counter; } } newstr[counter] = 0; return newstr; } int main(void) { char *new = strip_chars("She was a soul stripper. She took my heart!", "aei"); printf("%s\n", new); free(new); return 0; }
using System; public static string RemoveCharactersFromString(string testString, string removeChars) { char[] charAry = removeChars.ToCharArray(); string returnString = testString; foreach (char c in charAry) { while (returnString.IndexOf(c) > -1) { returnString = returnString.Remove(returnString.IndexOf(c), 1); } } return returnString; }
Convert the following code from C to C#, ensuring the logic remains intact.
#include <stdio.h> double mean(double *v, int len) { double sum = 0; int i; for (i = 0; i < len; i++) sum += v[i]; return sum / len; } int main(void) { double v[] = {1, 2, 2.718, 3, 3.142}; int i, len; for (len = 5; len >= 0; len--) { printf("mean["); for (i = 0; i < len; i++) printf(i ? ", %g" : "%g", v[i]); printf("] = %g\n", mean(v, len)); } return 0; }
using System; using System.Linq; class Program { static void Main() { Console.WriteLine(new[] { 1, 2, 3 }.Average()); } }
Change the following C code into C# without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 100 int makehist(unsigned char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ unsigned char S[MAXLEN]; int len,*hist,histlen; double H; scanf("%[^\n]",S); len=strlen(S); hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
using System; using System.Collections.Generic; namespace Entropy { class Program { public static double logtwo(double num) { return Math.Log(num)/Math.Log(2); } public static void Main(string[] args) { label1: string input = Console.ReadLine(); double infoC=0; Dictionary<char,double> table = new Dictionary<char, double>(); foreach (char c in input) { if (table.ContainsKey(c)) table[c]++; else table.Add(c,1); } double freq; foreach (KeyValuePair<char,double> letter in table) { freq=letter.Value/input.Length; infoC+=freq*logtwo(freq); } infoC*=-1; Console.WriteLine("The Entropy of {0} is {1}",input,infoC); goto label1; } } }
Transform the following C implementation into C#, maintaining the same output and logic.
#include <stdlib.h> #include <stdio.h> #define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|" #define SEP '|' #define ESC '^' typedef char* Str; unsigned int ElQ( const char *s, char sep, char esc ); Str *Tokenize( char *s, char sep, char esc, unsigned int *q ); int main() { char s[] = STR_DEMO; unsigned int i, q; Str *list = Tokenize( s, SEP, ESC, &q ); if( list != NULL ) { printf( "\n Original string: %s\n\n", STR_DEMO ); printf( " %d tokens:\n\n", q ); for( i=0; i<q; ++i ) printf( " %4d. %s\n", i+1, list[i] ); free( list ); } return 0; } unsigned int ElQ( const char *s, char sep, char esc ) { unsigned int q, e; const char *p; for( e=0, q=1, p=s; *p; ++p ) { if( *p == esc ) e = !e; else if( *p == sep ) q += !e; else e = 0; } return q; } Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) { Str *list = NULL; *q = ElQ( s, sep, esc ); list = malloc( *q * sizeof(Str) ); if( list != NULL ) { unsigned int e, i; char *p; i = 0; list[i++] = s; for( e=0, p=s; *p; ++p ) { if( *p == esc ) { e = !e; } else if( *p == sep && !e ) { list[i++] = p+1; *p = '\0'; } else { e = 0; } } } return list; }
using System; using System.Text; using System.Collections.Generic; public class TokenizeAStringWithEscaping { public static void Main() { string testcase = "one^|uno||three^^^^|four^^^|^cuatro|"; foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) { Console.WriteLine(": " + token); } } } public static class Extensions { public static IEnumerable<string> Tokenize(this string input, char separator, char escape) { if (input == null) yield break; var buffer = new StringBuilder(); bool escaping = false; foreach (char c in input) { if (escaping) { buffer.Append(c); escaping = false; } else if (c == escape) { escaping = true; } else if (c == separator) { yield return buffer.Flush(); } else { buffer.Append(c); } } if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush(); } public static string Flush(this StringBuilder stringBuilder) { string result = stringBuilder.ToString(); stringBuilder.Clear(); return result; } }
Keep all operations the same but rewrite the snippet in C#.
const hello = "Hello world!\n" print(hello)
Using System; namespace HelloWorld { class Program { static void Main() { Console.Writeln("Hello World!"); } } }
Ensure the translated C# code behaves exactly like the original C snippet.
#include <stdlib.h> #include <string.h> #include <stdio.h> double* fwd_diff(double* x, unsigned int len, unsigned int order) { unsigned int i, j; double* y; if (order >= len) return 0; y = malloc(sizeof(double) * len); if (!order) { memcpy(y, x, sizeof(double) * len); return y; } for (j = 0; j < order; j++, x = y) for (i = 0, len--; i < len; i++) y[i] = x[i + 1] - x[i]; y = realloc(y, sizeof(double) * len); return y; } int main(void) { double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}; int i, len = sizeof(x) / sizeof(x[0]); y = fwd_diff(x, len, 1); for (i = 0; i < len - 1; i++) printf("%g ", y[i]); putchar('\n'); return 0; }
using System; using System.Collections.Generic; using System.Linq; class Program { static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u) { switch (order) { case 0u: return sequence; case 1u: return sequence.Skip(1).Zip(sequence, (next, current) => next - current); default: return ForwardDifference(ForwardDifference(sequence), order - 1u); } } static void Main() { IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 }; do { Console.WriteLine(string.Join(", ", sequence)); } while ((sequence = ForwardDifference(sequence)).Any()); } }
Produce a language-to-language conversion: from C to C#, same semantics.
int is_prime(unsigned int n) { unsigned int p; if (!(n & 1) || n < 2 ) return n == 2; for (p = 3; p <= n/p; p += 2) if (!(n % p)) return 0; return 1; }
static bool isPrime(int n) { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; }
Translate the given C code snippet into C# without altering its behavior.
int is_prime(unsigned int n) { unsigned int p; if (!(n & 1) || n < 2 ) return n == 2; for (p = 3; p <= n/p; p += 2) if (!(n % p)) return 0; return 1; }
static bool isPrime(int n) { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; }
Port the following code from C to C# with equivalent syntax and logic.
#include <stdio.h> #include <limits.h> static unsigned long gcd_ui(unsigned long x, unsigned long y) { unsigned long t; if (y < x) { t = x; x = y; y = t; } while (y > 0) { t = y; y = x % y; x = t; } return x; } unsigned long binomial(unsigned long n, unsigned long k) { unsigned long d, g, r = 1; if (k == 0) return 1; if (k == 1) return n; if (k >= n) return (k == n); if (k > n/2) k = n-k; for (d = 1; d <= k; d++) { if (r >= ULONG_MAX/n) { unsigned long nr, dr; g = gcd_ui(n, d); nr = n/g; dr = d/g; g = gcd_ui(r, dr); r = r/g; dr = dr/g; if (r >= ULONG_MAX/nr) return 0; r *= nr; r /= dr; n--; } else { r *= n--; r /= d; } } return r; } int main() { printf("%lu\n", binomial(5, 3)); printf("%lu\n", binomial(40, 19)); printf("%lu\n", binomial(67, 31)); return 0; }
using System; namespace BinomialCoefficients { class Program { static void Main(string[] args) { ulong n = 1000000, k = 3; ulong result = biCoefficient(n, k); Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result); Console.ReadLine(); } static int fact(int n) { if (n == 0) return 1; else return n * fact(n - 1); } static ulong biCoefficient(ulong n, ulong k) { if (k > n - k) { k = n - k; } ulong c = 1; for (uint i = 0; i < k; i++) { c = c * (n - i); c = c / (i + 1); } return c; } } }
Convert the following code from C to C#, ensuring the logic remains intact.
#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) int ar[10]; ar[0] = 1; ar[1] = 2; int* p; for (p=ar; p<(ar+cSize(ar)); p++) { printf("%d\n",*p); }
int[] intArray = new int[5] { 1, 2, 3, 4, 5 }; int[] intArray = new int[]{ 1, 2, 3, 4, 5 }; int[] intArray = { 1, 2, 3, 4, 5 }; string[] stringArr = new string[5]; stringArr[0] = "string";
Convert this C block to C#, preserving its control flow and logic.
#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) int ar[10]; ar[0] = 1; ar[1] = 2; int* p; for (p=ar; p<(ar+cSize(ar)); p++) { printf("%d\n",*p); }
int[] intArray = new int[5] { 1, 2, 3, 4, 5 }; int[] intArray = new int[]{ 1, 2, 3, 4, 5 }; int[] intArray = { 1, 2, 3, 4, 5 }; string[] stringArr = new string[5]; stringArr[0] = "string";
Write the same algorithm in C# as shown in this C implementation.
struct link *first; struct link *iter; for(iter = first; iter != NULL; iter = iter->next) { }
var current = [head of list to traverse] while(current != null) { current = current.Next; }
Produce a language-to-language conversion: from C to C#, same semantics.
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Convert the following code from C to C#, ensuring the logic remains intact.
#include <stdlib.h> #include <stdio.h> int main(void) { const int dimx = 800, dimy = 800; int i, j; FILE *fp = fopen("first.ppm", "wb"); (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy); for (j = 0; j < dimy; ++j) { for (i = 0; i < dimx; ++i) { static unsigned char color[3]; color[0] = i % 256; color[1] = j % 256; color[2] = (i * j) % 256; (void) fwrite(color, 1, 3, fp); } } (void) fclose(fp); return EXIT_SUCCESS; }
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
Maintain the same structure and functionality when rewriting this code in C#.
#include <stdio.h> int main() { remove("input.txt"); remove("/input.txt"); remove("docs"); remove("/docs"); return 0; }
using System; using System.IO; namespace DeleteFile { class Program { static void Main() { File.Delete("input.txt"); Directory.Delete("docs"); File.Delete("/input.txt"); Directory.Delete("/docs"); } } }
Translate this program into C# but keep the logic exactly as in C.
#include <stdlib.h> #include <stdio.h> #include <time.h> #define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\ (x) == 2 ? "Boomtime" :\ (x) == 3 ? "Pungenday" :\ (x) == 4 ? "Prickle-Prickle" :\ "Setting Orange") #define season( x ) ((x) == 0 ? "Chaos" :\ (x) == 1 ? "Discord" :\ (x) == 2 ? "Confusion" :\ (x) == 3 ? "Bureaucracy" :\ "The Aftermath") #define date( x ) ((x)%73 == 0 ? 73 : (x)%73) #define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100)) char * ddate( int y, int d ){ int dyear = 1166 + y; char * result = malloc( 100 * sizeof( char ) ); if( leap_year( y ) ){ if( d == 60 ){ sprintf( result, "St. Tib's Day, YOLD %d", dyear ); return result; } else if( d >= 60 ){ -- d; } } sprintf( result, "%s, %s %d, YOLD %d", day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear ); return result; } int day_of_year( int y, int m, int d ){ int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; for( ; m > 1; m -- ){ d += month_lengths[ m - 2 ]; if( m == 3 && leap_year( y ) ){ ++ d; } } return d; } int main( int argc, char * argv[] ){ time_t now; struct tm * now_time; int year, doy; if( argc == 1 ){ now = time( NULL ); now_time = localtime( &now ); year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1; } else if( argc == 4 ){ year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) ); } char * result = ddate( year, doy ); puts( result ); free( result ); return 0; }
using System; public static class DiscordianDate { static readonly string[] seasons = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" }; static readonly string[] weekdays = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" }; static readonly string[] apostles = { "Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" }; static readonly string[] holidays = { "Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux" }; public static string Discordian(this DateTime date) { string yold = $" in the YOLD {date.Year + 1166}."; int dayOfYear = date.DayOfYear; if (DateTime.IsLeapYear(date.Year)) { if (dayOfYear == 60) return "St. Tib's day" + yold; else if (dayOfYear > 60) dayOfYear--; } dayOfYear--; int seasonDay = dayOfYear % 73 + 1; int seasonNr = dayOfYear / 73; int weekdayNr = dayOfYear % 5; string holyday = ""; if (seasonDay == 5) holyday = $" Celebrate {apostles[seasonNr]}!"; else if (seasonDay == 50) holyday = $" Celebrate {holidays[seasonNr]}!"; return $"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}"; } public static void Main() { foreach (var (day, month, year) in new [] { (1, 1, 2010), (5, 1, 2010), (19, 2, 2011), (28, 2, 2012), (29, 2, 2012), (1, 3, 2012), (19, 3, 2013), (3, 5, 2014), (31, 5, 2015), (22, 6, 2016), (15, 7, 2016), (12, 8, 2017), (19, 9, 2018), (26, 9, 2018), (24, 10, 2019), (8, 12, 2020), (31, 12, 2020) }) { Console.WriteLine($"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}"); } } }
Change the programming language of this snippet from C to C# without modifying what it does.
#include <stdlib.h> #include <stdio.h> #include <time.h> #define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\ (x) == 2 ? "Boomtime" :\ (x) == 3 ? "Pungenday" :\ (x) == 4 ? "Prickle-Prickle" :\ "Setting Orange") #define season( x ) ((x) == 0 ? "Chaos" :\ (x) == 1 ? "Discord" :\ (x) == 2 ? "Confusion" :\ (x) == 3 ? "Bureaucracy" :\ "The Aftermath") #define date( x ) ((x)%73 == 0 ? 73 : (x)%73) #define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100)) char * ddate( int y, int d ){ int dyear = 1166 + y; char * result = malloc( 100 * sizeof( char ) ); if( leap_year( y ) ){ if( d == 60 ){ sprintf( result, "St. Tib's Day, YOLD %d", dyear ); return result; } else if( d >= 60 ){ -- d; } } sprintf( result, "%s, %s %d, YOLD %d", day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear ); return result; } int day_of_year( int y, int m, int d ){ int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; for( ; m > 1; m -- ){ d += month_lengths[ m - 2 ]; if( m == 3 && leap_year( y ) ){ ++ d; } } return d; } int main( int argc, char * argv[] ){ time_t now; struct tm * now_time; int year, doy; if( argc == 1 ){ now = time( NULL ); now_time = localtime( &now ); year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1; } else if( argc == 4 ){ year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) ); } char * result = ddate( year, doy ); puts( result ); free( result ); return 0; }
using System; public static class DiscordianDate { static readonly string[] seasons = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" }; static readonly string[] weekdays = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" }; static readonly string[] apostles = { "Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" }; static readonly string[] holidays = { "Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux" }; public static string Discordian(this DateTime date) { string yold = $" in the YOLD {date.Year + 1166}."; int dayOfYear = date.DayOfYear; if (DateTime.IsLeapYear(date.Year)) { if (dayOfYear == 60) return "St. Tib's day" + yold; else if (dayOfYear > 60) dayOfYear--; } dayOfYear--; int seasonDay = dayOfYear % 73 + 1; int seasonNr = dayOfYear / 73; int weekdayNr = dayOfYear % 5; string holyday = ""; if (seasonDay == 5) holyday = $" Celebrate {apostles[seasonNr]}!"; else if (seasonDay == 50) holyday = $" Celebrate {holidays[seasonNr]}!"; return $"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}"; } public static void Main() { foreach (var (day, month, year) in new [] { (1, 1, 2010), (5, 1, 2010), (19, 2, 2011), (28, 2, 2012), (29, 2, 2012), (1, 3, 2012), (19, 3, 2013), (3, 5, 2014), (31, 5, 2015), (22, 6, 2016), (15, 7, 2016), (12, 8, 2017), (19, 9, 2018), (26, 9, 2018), (24, 10, 2019), (8, 12, 2020), (31, 12, 2020) }) { Console.WriteLine($"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}"); } } }
Change the following C code into C# without altering its purpose.
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int randint(int n) { int r, rmax = RAND_MAX / n * n; while ((r = rand()) >= rmax); return r / (RAND_MAX / n); } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = 1 << randint(n); } } return count; } int main(void) { srand(time(0)); puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); double avg = (double)cnt / TIMES; double theory = expected(n); double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff); } return 0; }
public class AverageLoopLength { private static int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.Next(n); } var seen = new HashSet<double>(n); int current = 0; int length = 0; while (seen.Add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void Main(string[] args) { Console.WriteLine(" N average analytical (error)"); Console.WriteLine("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { var average = AverageLoopLength.average(i); var analytical = AverageLoopLength.analytical(i); Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100); } } }
Port the following code from Go to VB with equivalent syntax and logic.
package main import "fmt" func bitwise(a, b int16) { fmt.Printf("a: %016b\n", uint16(a)) fmt.Printf("b: %016b\n", uint16(b)) fmt.Printf("and: %016b\n", uint16(a&b)) fmt.Printf("or: %016b\n", uint16(a|b)) fmt.Printf("xor: %016b\n", uint16(a^b)) fmt.Printf("not: %016b\n", uint16(^a)) if b < 0 { fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).") return } ua := uint16(a) ub := uint32(b) fmt.Printf("shl: %016b\n", uint16(ua<<ub)) fmt.Printf("shr: %016b\n", uint16(ua>>ub)) fmt.Printf("las: %016b\n", uint16(a<<ub)) fmt.Printf("ras: %016b\n", uint16(a>>ub)) fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub)))) fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub))) } func main() { var a, b int16 = -460, 6 bitwise(a, b) }
Debug.Print Hex(&HF0F0 And &HFF00) Debug.Print Hex(&HF0F0 Or &HFF00) Debug.Print Hex(&HF0F0 Xor &HFF00) Debug.Print Hex(Not &HF0F0) Debug.Print Hex(&HF0F0 Eqv &HFF00) Debug.Print Hex(&HF0F0 Imp &HFF00)
Rewrite the snippet below in VB so it works the same as the original Go code.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) const sep = 512 const depth = 14 var s = math.Sqrt2 / 2 var sin = []float64{0, s, 1, s, 0, -s, -1, -s} var cos = []float64{1, s, 0, -s, -1, -s, 0, s} var p = color.NRGBA{64, 192, 96, 255} var b *image.NRGBA func main() { width := sep * 11 / 6 height := sep * 4 / 3 bounds := image.Rect(0, 0, width, height) b = image.NewNRGBA(bounds) draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src) dragon(14, 0, 1, sep, sep/2, sep*5/6) f, err := os.Create("dragon.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, b); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } } func dragon(n, a, t int, d, x, y float64) { if n <= 1 { x1 := int(x + .5) y1 := int(y + .5) x2 := int(x + d*cos[a] + .5) y2 := int(y + d*sin[a] + .5) xInc := 1 if x1 > x2 { xInc = -1 } yInc := 1 if y1 > y2 { yInc = -1 } for x, y := x1, y1; ; x, y = x+xInc, y+yInc { b.Set(x, y, p) if x == x2 { break } } return } d *= s a1 := (a - t) & 7 a2 := (a + t) & 7 dragon(n-1, a1, 1, d, x, y) dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1]) }
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: end sub public sub lt(i): ori=(ori + i*iang) 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 x=400:y=400:incr=100 ori=90*pi180 iang=90*pi180 clr=0 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 dragon(st,le,dir) if st=0 then x.fw le: exit sub x.rt dir dragon st-1, le/1.41421 ,1 x.rt dir*2 dragon st-1, le/1.41421 ,-1 x.rt dir end sub dim x set x=new turtle x.iangle=45 x.orient=45 x.incr=1 x.x=200:x.y=200 dragon 12,300,1 set x=nothing
Port the following code from Go to VB with equivalent syntax and logic.
package main import ( "bufio" "fmt" "log" "os" ) func init() { log.SetFlags(log.Lshortfile) } func main() { inputFile, err := os.Open("byline.go") if err != nil { log.Fatal("Error opening input file:", err) } defer inputFile.Close() scanner := bufio.NewScanner(inputFile) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(scanner.Err()) } }
$Include "Rapidq.inc" dim file as qfilestream if file.open("c:\A Test.txt", fmOpenRead) then while not File.eof print File.readline wend else print "Cannot read file" end if input "Press enter to exit: ";a$
Write a version of this Go function in VB with identical behavior.
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.next { r += " " + p.string } return r + "]" } func (list *dlList) insertTail(node *dlNode) { if list.tail == nil { list.head = node } else { list.tail.next = node } node.next = nil node.prev = list.tail list.tail = node } func (list *dlList) insertAfter(existing, insert *dlNode) { insert.prev = existing insert.next = existing.next existing.next.prev = insert existing.next = insert if existing == list.tail { list.tail = insert } } func main() { dll := &dlList{} fmt.Println(dll) a := &dlNode{string: "A"} dll.insertTail(a) dll.insertTail(&dlNode{string: "B"}) fmt.Println(dll) dll.insertAfter(a, &dlNode{string: "C"}) fmt.Println(dll) }
Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T) Dim node As New Node(Of T)(value) a.Next = node node.Previous = a b.Previous = node node.Next = b End Sub
Change the programming language of this snippet from Go to VB without modifying what it does.
package main import "fmt" func quickselect(list []int, k int) int { for { px := len(list) / 2 pv := list[px] last := len(list) - 1 list[px], list[last] = list[last], list[px] i := 0 for j := 0; j < last; j++ { if list[j] < pv { list[i], list[j] = list[j], list[i] i++ } } if i == k { return pv } if k < i { list = list[:i] } else { list[i], list[last] = list[last], list[i] list = list[i+1:] k -= i + 1 } } } func main() { for i := 0; ; i++ { v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4} if i == len(v) { return } fmt.Println(quickselect(v, i)) } }
Dim s As Variant Private Function quick_select(ByRef s As Variant, k As Integer) As Integer Dim left As Integer, right As Integer, pos As Integer Dim pivotValue As Integer, tmp As Integer left = 1: right = UBound(s) Do While left < right pivotValue = s(k) tmp = s(k) s(k) = s(right) s(right) = tmp pos = left For i = left To right If s(i) < pivotValue Then tmp = s(i) s(i) = s(pos) s(pos) = tmp pos = pos + 1 End If Next i tmp = s(right) s(right) = s(pos) s(pos) = tmp If pos = k Then Exit Do End If If pos < k Then left = pos + 1 Else right = pos - 1 End If Loop quick_select = s(k) End Function Public Sub main() Dim r As Integer, i As Integer s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}] For i = 1 To 10 r = quick_select(s, i) Debug.Print IIf(i < 10, r & ", ", "" & r); Next i End Sub
Ensure the translated VB code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/big" "strconv" ) func main () { s := strconv.FormatInt(26, 16) fmt.Println(s) i, err := strconv.ParseInt("1a", 16, 64) if err == nil { fmt.Println(i) } b, ok := new(big.Int).SetString("1a", 16) if ok { fmt.Println(b) } }
Private Function to_base(ByVal number As Long, base As Integer) As String Dim digits As String, result As String Dim i As Integer, digit As Integer digits = "0123456789abcdefghijklmnopqrstuvwxyz" Do While number > 0 digit = number Mod base result = Mid(digits, digit + 1, 1) & result number = number \ base Loop to_base = result End Function Private Function from_base(number As String, base As Integer) As Long Dim digits As String, result As Long Dim i As Integer digits = "0123456789abcdefghijklmnopqrstuvwxyz" result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1) For i = 2 To Len(number) result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1) Next i from_base = result End Function Public Sub Non_decimal_radices_Convert() Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16) End Sub
Port the following code from Go to VB with equivalent syntax and logic.
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Rewrite this program in VB while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "hash/crc32" ) func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
dim crctbl(255) const crcc =&hEDB88320 sub gencrctable for i= 0 to 255 k=i for j=1 to 8 if k and 1 then k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) k=k xor crcc else k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) end if next crctbl(i)=k next end sub function crc32 (buf) dim r,r1,i r=&hffffffff for i=1 to len(buf) r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0) r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) next crc32=r xor &hffffffff end function gencrctable wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))
Change the following Go code into VB without altering its purpose.
package main import ( "bytes" "encoding/csv" "fmt" "html/template" "strings" ) var c = `Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!` func main() { if h, err := csvToHtml(c); err != nil { fmt.Println(err) } else { fmt.Print(h) } } func csvToHtml(c string) (string, error) { data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll() if err != nil { return "", err } var b strings.Builder err = template.Must(template.New("").Parse(`<table> {{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr> {{end}}</table> `)).Execute(&b, data) return b.String(), err }
Public Sub CSV_TO_HTML() input_ = "Character,Speech\n" & _ "The multitude,The messiah! Show us the messiah!\n" & _ "Brians mother,<angry>Now you listen here! He "he "The multitude,Who are you?\n" & _ "Brians mother,I "The multitude,Behold his mother! Behold his mother!" Debug.Print "<table>" & vbCrLf & "<tr><td>" For i = 1 To Len(input_) Select Case Mid(input_, i, 1) Case "\" If Mid(input_, i + 1, 1) = "n" Then Debug.Print "</td></tr>" & vbCrLf & "<tr><td>"; i = i + 1 Else Debug.Print Mid(input_, i, 1); End If Case ",": Debug.Print "</td><td>"; Case "<": Debug.Print "&lt;"; Case ">": Debug.Print "&gt;"; Case "&": Debug.Print "&amp;"; Case Else: Debug.Print Mid(input_, i, 1); End Select Next i Debug.Print "</td></tr>" & vbCrLf & "</table>" End Sub
Maintain the same structure and functionality when rewriting this code in VB.
package main import ( "bytes" "encoding/csv" "fmt" "html/template" "strings" ) var c = `Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!` func main() { if h, err := csvToHtml(c); err != nil { fmt.Println(err) } else { fmt.Print(h) } } func csvToHtml(c string) (string, error) { data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll() if err != nil { return "", err } var b strings.Builder err = template.Must(template.New("").Parse(`<table> {{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr> {{end}}</table> `)).Execute(&b, data) return b.String(), err }
Public Sub CSV_TO_HTML() input_ = "Character,Speech\n" & _ "The multitude,The messiah! Show us the messiah!\n" & _ "Brians mother,<angry>Now you listen here! He "he "The multitude,Who are you?\n" & _ "Brians mother,I "The multitude,Behold his mother! Behold his mother!" Debug.Print "<table>" & vbCrLf & "<tr><td>" For i = 1 To Len(input_) Select Case Mid(input_, i, 1) Case "\" If Mid(input_, i + 1, 1) = "n" Then Debug.Print "</td></tr>" & vbCrLf & "<tr><td>"; i = i + 1 Else Debug.Print Mid(input_, i, 1); End If Case ",": Debug.Print "</td><td>"; Case "<": Debug.Print "&lt;"; Case ">": Debug.Print "&gt;"; Case "&": Debug.Print "&amp;"; Case Else: Debug.Print Mid(input_, i, 1); End Select Next i Debug.Print "</td></tr>" & vbCrLf & "</table>" End Sub
Rewrite this program in VB while keeping its functionality equivalent to the Go version.
package main import "fmt" type picnicBasket struct { nServings int corkscrew bool } func (b *picnicBasket) happy() bool { return b.nServings > 1 && b.corkscrew } func newPicnicBasket(nPeople int) *picnicBasket { return &picnicBasket{nPeople, nPeople > 0} } func main() { var pb picnicBasket pbl := picnicBasket{} pbp := &picnicBasket{} pbn := new(picnicBasket) forTwo := newPicnicBasket(2) forToo := &picnicBasket{nServings: 2, corkscrew: true} fmt.Println(pb.nServings, pb.corkscrew) fmt.Println(pbl.nServings, pbl.corkscrew) fmt.Println(pbp) fmt.Println(pbn) fmt.Println(forTwo) fmt.Println(forToo) }
Class NumberContainer Private TheNumber As Integer Sub Constructor(InitialNumber As Integer) TheNumber = InitialNumber End Sub Function Number() As Integer Return TheNumber End Function Sub Number(Assigns NewNumber As Integer) TheNumber = NewNumber End Sub End Class
Rewrite this program in VB while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
Module Module1 ReadOnly max As ULong = 1000000 Function Kaprekar(n As ULong) As Boolean If n = 1 Then Return True Dim sq = n * n Dim sq_str = Str(sq) Dim l = Len(sq_str) For x = l - 1 To 1 Step -1 If sq_str(x) = "0" Then l = l - 1 Else Exit For End If Next For x = 1 To l - 1 Dim p2 = Val(Mid(sq_str, x + 1)) If p2 > n Then Continue For End If Dim p1 = Val(Left(sq_str, x)) If p1 > n Then Return False If (p1 + p2) = n Then Return True Next Return False End Function Sub Main() Dim count = 0 Console.WriteLine("Kaprekar numbers below 10000") For n = 1 To max - 1 If Kaprekar(n) Then count = count + 1 If n < 10000 Then Console.WriteLine("{0,2} {1,4}", count, n) End If End If Next Console.WriteLine() Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max) End Sub End Module
Change the following Go code into VB without altering its purpose.
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
Module Module1 ReadOnly max As ULong = 1000000 Function Kaprekar(n As ULong) As Boolean If n = 1 Then Return True Dim sq = n * n Dim sq_str = Str(sq) Dim l = Len(sq_str) For x = l - 1 To 1 Step -1 If sq_str(x) = "0" Then l = l - 1 Else Exit For End If Next For x = 1 To l - 1 Dim p2 = Val(Mid(sq_str, x + 1)) If p2 > n Then Continue For End If Dim p1 = Val(Left(sq_str, x)) If p1 > n Then Return False If (p1 + p2) = n Then Return True Next Return False End Function Sub Main() Dim count = 0 Console.WriteLine("Kaprekar numbers below 10000") For n = 1 To max - 1 If Kaprekar(n) Then count = count + 1 If n < 10000 Then Console.WriteLine("{0,2} {1,4}", count, n) End If End If Next Console.WriteLine() Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max) End Sub End Module
Rewrite the snippet below in VB so it works the same as the original Go code.
package main import ( "fmt" "log" "strings" ) func compress(uncompressed string) []int { dictSize := 256 dictionary := make(map[string]int, dictSize) for i := 0; i < dictSize; i++ { dictionary[string([]byte{byte(i)})] = i } var result []int var w []byte for i := 0; i < len(uncompressed); i++ { c := uncompressed[i] wc := append(w, c) if _, ok := dictionary[string(wc)]; ok { w = wc } else { result = append(result, dictionary[string(w)]) dictionary[string(wc)] = dictSize dictSize++ wc[0] = c w = wc[:1] } } if len(w) > 0 { result = append(result, dictionary[string(w)]) } return result } type BadSymbolError int func (e BadSymbolError) Error() string { return fmt.Sprint("Bad compressed symbol ", int(e)) } func decompress(compressed []int) (string, error) { dictSize := 256 dictionary := make(map[int][]byte, dictSize) for i := 0; i < dictSize; i++ { dictionary[i] = []byte{byte(i)} } var result strings.Builder var w []byte for _, k := range compressed { var entry []byte if x, ok := dictionary[k]; ok { entry = x[:len(x):len(x)] } else if k == dictSize && len(w) > 0 { entry = append(w, w[0]) } else { return result.String(), BadSymbolError(k) } result.Write(entry) if len(w) > 0 { w = append(w, entry[0]) dictionary[dictSize] = w dictSize++ } w = entry } return result.String(), nil } func main() { compressed := compress("TOBEORNOTTOBEORTOBEORNOT") fmt.Println(compressed) decompressed, err := decompress(compressed) if err != nil { log.Fatal(err) } fmt.Println(decompressed) }
Option Explicit Const numchars=127 Function LZWCompress(si) Dim oDict, intMaxCode, i,z,ii,ss,strCurrent,strNext,j Set oDict = CreateObject("Scripting.Dictionary") ReDim a(Len(si)) intMaxCode = numchars For i = 0 To numchars oDict.Add Chr(i), i Next strCurrent = Left(si,1) j=0 For ii=2 To Len(si) strNext = Mid(si,ii,1) ss=strCurrent & strNext If oDict.Exists(ss) Then strCurrent = ss Else a(j)=oDict.Item(strCurrent) :j=j+1 intMaxCode = intMaxCode + 1 oDict.Add ss, intMaxCode strCurrent = strNext End If Next a(j)=oDict.Item(strCurrent) ReDim preserve a(j) LZWCompress=a Set oDict = Nothing End Function Function lzwUncompress(sc) Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j s="" reDim dict(1000) intMaxCode = numchars For i = 0 To numchars : dict(i)= Chr(i) : Next intCurrent=sc(0) For j=1 To UBound(sc) ss=dict(intCurrent) s= s & ss intMaxCode = intMaxCode + 1 intnext=sc(j) If intNext<intMaxCode Then dict(intMaxCode)=ss & Left(dict(intNext), 1) Else dict(intMaxCode)=ss & Left(ss, 1) End If intCurrent = intNext Next s= s & dict(intCurrent) lzwUncompress=s End function Sub printvec(a) Dim s,i,x s="(" For i=0 To UBound (a) s=s & x & a(i) x=", " Next WScript.echo s &")" End sub Dim a,b b="TOBEORNOTTOBEORTOBEORNOT" WScript.Echo b a=LZWCompress (b) printvec(a) WScript.echo lzwUncompress (a ) wscript.quit 1
Can you help me rewrite this code in VB instead of Go, keeping it the same logically?
package main import "fmt" var ffr, ffs func(int) int func init() { r := []int{0, 1} s := []int{0, 2} ffr = func(n int) int { for len(r) <= n { nrk := len(r) - 1 rNxt := r[nrk] + s[nrk] r = append(r, rNxt) for sn := r[nrk] + 2; sn < rNxt; sn++ { s = append(s, sn) } s = append(s, rNxt+1) } return r[n] } ffs = func(n int) int { for len(s) <= n { ffr(len(r)) } return s[n] } } func main() { for n := 1; n <= 10; n++ { fmt.Printf("r(%d): %d\n", n, ffr(n)) } var found [1001]int for n := 1; n <= 40; n++ { found[ffr(n)]++ } for n := 1; n <= 960; n++ { found[ffs(n)]++ } for i := 1; i <= 1000; i++ { if found[i] != 1 { fmt.Println("task 4: FAIL") return } } fmt.Println("task 4: PASS") }
Private Function ffr(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j Next i ffr = R(n) Set R = Nothing Set S = Nothing End Function Private Function ffs(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j If S.Count >= n Then Exit For Next i ffs = S(n) Set R = Nothing Set S = Nothing End Function Public Sub main() Dim i As Long Debug.Print "The first ten values of R are:" For i = 1 To 10 Debug.Print ffr(i); Next i Debug.Print Dim x As New Collection For i = 1 To 1000 x.Add i, CStr(i) Next i For i = 1 To 40 x.Remove CStr(ffr(i)) Next i For i = 1 To 960 x.Remove CStr(ffs(i)) Next i Debug.Print "The first 40 values of ffr plus the first 960 values of ffs " Debug.Print "include all the integers from 1 to 1000 exactly once is "; Format(x.Count = 0) End Sub
Generate an equivalent VB version of this Go code.
package main import "fmt" var ffr, ffs func(int) int func init() { r := []int{0, 1} s := []int{0, 2} ffr = func(n int) int { for len(r) <= n { nrk := len(r) - 1 rNxt := r[nrk] + s[nrk] r = append(r, rNxt) for sn := r[nrk] + 2; sn < rNxt; sn++ { s = append(s, sn) } s = append(s, rNxt+1) } return r[n] } ffs = func(n int) int { for len(s) <= n { ffr(len(r)) } return s[n] } } func main() { for n := 1; n <= 10; n++ { fmt.Printf("r(%d): %d\n", n, ffr(n)) } var found [1001]int for n := 1; n <= 40; n++ { found[ffr(n)]++ } for n := 1; n <= 960; n++ { found[ffs(n)]++ } for i := 1; i <= 1000; i++ { if found[i] != 1 { fmt.Println("task 4: FAIL") return } } fmt.Println("task 4: PASS") }
Private Function ffr(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j Next i ffr = R(n) Set R = Nothing Set S = Nothing End Function Private Function ffs(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j If S.Count >= n Then Exit For Next i ffs = S(n) Set R = Nothing Set S = Nothing End Function Public Sub main() Dim i As Long Debug.Print "The first ten values of R are:" For i = 1 To 10 Debug.Print ffr(i); Next i Debug.Print Dim x As New Collection For i = 1 To 1000 x.Add i, CStr(i) Next i For i = 1 To 40 x.Remove CStr(ffr(i)) Next i For i = 1 To 960 x.Remove CStr(ffs(i)) Next i Debug.Print "The first 40 values of ffr plus the first 960 values of ffs " Debug.Print "include all the integers from 1 to 1000 exactly once is "; Format(x.Count = 0) End Sub
Write a version of this Go function in VB with identical behavior.
package main import ( "fmt" "log" ) func ms(n int) (int, []int) { M := func(x int) int { return (x + n - 1) % n } if n <= 0 || n&1 == 0 { n = 5 log.Println("forcing size", n) } m := make([]int, n*n) i, j := 0, n/2 for k := 1; k <= n*n; k++ { m[i*n+j] = k if m[M(i)*n+M(j)] != 0 { i = (i + 1) % n } else { i, j = M(i), M(j) } } return n, m } func main() { n, m := ms(5) i := 2 for j := 1; j <= n*n; j *= 10 { i++ } f := fmt.Sprintf("%%%dd", i) for i := 0; i < n; i++ { for j := 0; j < n; j++ { fmt.Printf(f, m[i*n+j]) } fmt.Println() } }
Sub magicsquare() Const n = 9 Dim i As Integer, j As Integer, v As Integer Debug.Print "The square order is: " & n For i = 1 To n For j = 1 To n Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1 Next j Next i Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2 End Sub
Ensure the translated VB code behaves exactly like the original Go snippet.
package main import ( "fmt" "log" ) func ms(n int) (int, []int) { M := func(x int) int { return (x + n - 1) % n } if n <= 0 || n&1 == 0 { n = 5 log.Println("forcing size", n) } m := make([]int, n*n) i, j := 0, n/2 for k := 1; k <= n*n; k++ { m[i*n+j] = k if m[M(i)*n+M(j)] != 0 { i = (i + 1) % n } else { i, j = M(i), M(j) } } return n, m } func main() { n, m := ms(5) i := 2 for j := 1; j <= n*n; j *= 10 { i++ } f := fmt.Sprintf("%%%dd", i) for i := 0; i < n; i++ { for j := 0; j < n; j++ { fmt.Printf(f, m[i*n+j]) } fmt.Println() } }
Sub magicsquare() Const n = 9 Dim i As Integer, j As Integer, v As Integer Debug.Print "The square order is: " & n For i = 1 To n For j = 1 To n Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1 Next j Next i Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2 End Sub
Write a version of this Go function in VB with identical behavior.
package main import ( "fmt" "math" ) func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] } func main() { show(Fib1000(), "First 1000 Fibonacci numbers") } func show(c []float64, title string) { var f [9]int for _, v := range c { f[fmt.Sprintf("%g", v)[0]-'1']++ } fmt.Println(title) fmt.Println("Digit Observed Predicted") for i, n := range f { fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)), math.Log10(1+1/float64(i+1))) } }
Sub BenfordLaw() Dim BenResult(1 To 9) As Long BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%" For Each c In Selection.Cells If InStr(1, "-0123456789", Left(c, 1)) > 0 Then For i = 1 To 9 If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For Next End If Next Total= Application.Sum(BenResult) biggest= Len(CStr(BenResult(1))) txt = "# | Values | Real | Expected " & vbCrLf For i = 1 To 9 If BenResult(i) > 0 Then txt = txt & "#" & i & " | " & vbTab txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab txt = txt & Format(Split(BENref, "|")(i - 1), " ##0.0%") & vbCrLf End If Next MsgBox txt, vbOKOnly, "Finish" End Sub }
Can you help me rewrite this code in VB instead of Go, keeping it the same logically?
package main import ( "fmt" "math" ) func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] } func main() { show(Fib1000(), "First 1000 Fibonacci numbers") } func show(c []float64, title string) { var f [9]int for _, v := range c { f[fmt.Sprintf("%g", v)[0]-'1']++ } fmt.Println(title) fmt.Println("Digit Observed Predicted") for i, n := range f { fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)), math.Log10(1+1/float64(i+1))) } }
Sub BenfordLaw() Dim BenResult(1 To 9) As Long BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%" For Each c In Selection.Cells If InStr(1, "-0123456789", Left(c, 1)) > 0 Then For i = 1 To 9 If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For Next End If Next Total= Application.Sum(BenResult) biggest= Len(CStr(BenResult(1))) txt = "# | Values | Real | Expected " & vbCrLf For i = 1 To 9 If BenResult(i) > 0 Then txt = txt & "#" & i & " | " & vbTab txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab txt = txt & Format(Split(BENref, "|")(i - 1), " ##0.0%") & vbCrLf End If Next MsgBox txt, vbOKOnly, "Finish" End Sub }
Port the following code from Go to VB with equivalent syntax and logic.
package main import "fmt" func main() { for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} { f, ok := arFib(n) if ok { fmt.Printf("fib %d = %d\n", n, f) } else { fmt.Println("fib undefined for negative numbers") } } } func arFib(n int) (int, bool) { switch { case n < 0: return 0, false case n < 2: return n, true } return yc(func(recurse fn) fn { return func(left, term1, term2 int) int { if left == 0 { return term1+term2 } return recurse(left-1, term1+term2, term1) } })(n-2, 1, 0), true } type fn func(int, int, int) int type ff func(fn) fn type fx func(fx) fn func yc(f ff) fn { return func(x fx) fn { return x(x) }(func(x fx) fn { return f(func(a1, a2, a3 int) int { return x(x)(a1, a2, a3) }) }) }
Sub Main() Debug.Print F(-10) Debug.Print F(10) End Sub Private Function F(N As Long) As Variant If N < 0 Then F = "Error. Negative argument" ElseIf N <= 1 Then F = N Else F = F(N - 1) + F(N - 2) End If End Function
Change the programming language of this snippet from Go to VB without modifying what it does.
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
Produce a functionally identical VB code for the snippet given in Go.
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
Convert this Go snippet to VB and keep its semantics consistent.
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
Generate a VB translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
Change the following Go code into VB without altering its purpose.
package main import ( "bufio" "os" ) func main() { in := bufio.NewReader(os.Stdin) var blankLine = "\n" var printLongest func(string) string printLongest = func(candidate string) (longest string) { longest = candidate s, err := in.ReadString('\n') defer func() { recover() defer func() { recover() }() _ = blankLine[0] func() { defer func() { recover() }() _ = s[len(longest)] longest = s }() longest = printLongest(longest) func() { defer func() { recover() os.Stdout.WriteString(s) }() _ = longest[len(s)] s = "" }() }() _ = err.(error) os.Stdout.WriteString(blankLine) blankLine = "" return } printLongest("") }
Set objfso = CreateObject("Scripting.FileSystemObject") Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\input.txt",1) list = "" previous_line = "" l = Len(previous_line) Do Until objfile.AtEndOfStream current_line = objfile.ReadLine If Mid(current_line,l+1,1) <> "" Then list = current_line & vbCrLf previous_line = current_line l = Len(previous_line) ElseIf Mid(current_line,l,1) <> "" And Mid(current_line,(l+1),1) = "" Then list = list & current_line & vbCrLf End If Loop WScript.Echo list objfile.Close Set objfso = Nothing
Maintain the same structure and functionality when rewriting this code in VB.
package turing type Symbol byte type Motion byte const ( Left Motion = 'L' Right Motion = 'R' Stay Motion = 'N' ) type Tape struct { data []Symbol pos, left int blank Symbol } func NewTape(blank Symbol, start int, data []Symbol) *Tape { t := &Tape{ data: data, blank: blank, } if start < 0 { t.Left(-start) } t.Right(start) return t } func (t *Tape) Stay() {} func (t *Tape) Data() []Symbol { return t.data[t.left:] } func (t *Tape) Read() Symbol { return t.data[t.pos] } func (t *Tape) Write(s Symbol) { t.data[t.pos] = s } func (t *Tape) Dup() *Tape { t2 := &Tape{ data: make([]Symbol, len(t.Data())), blank: t.blank, } copy(t2.data, t.Data()) t2.pos = t.pos - t.left return t2 } func (t *Tape) String() string { s := "" for i := t.left; i < len(t.data); i++ { b := t.data[i] if i == t.pos { s += "[" + string(b) + "]" } else { s += " " + string(b) + " " } } return s } func (t *Tape) Move(a Motion) { switch a { case Left: t.Left(1) case Right: t.Right(1) case Stay: t.Stay() } } const minSz = 16 func (t *Tape) Left(n int) { t.pos -= n if t.pos < 0 { var sz int for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 { } newd := make([]Symbol, sz) newl := len(newd) - cap(t.data[t.left:]) n := copy(newd[newl:], t.data[t.left:]) t.data = newd[:newl+n] t.pos += newl - t.left t.left = newl } if t.pos < t.left { if t.blank != 0 { for i := t.pos; i < t.left; i++ { t.data[i] = t.blank } } t.left = t.pos } } func (t *Tape) Right(n int) { t.pos += n if t.pos >= cap(t.data) { var sz int for sz = minSz; t.pos >= sz; sz <<= 1 { } newd := make([]Symbol, sz) n := copy(newd[t.left:], t.data[t.left:]) t.data = newd[:t.left+n] } if i := len(t.data); t.pos >= i { t.data = t.data[:t.pos+1] if t.blank != 0 { for ; i < len(t.data); i++ { t.data[i] = t.blank } } } } type State string type Rule struct { State Symbol Write Symbol Motion Next State } func (i *Rule) key() key { return key{i.State, i.Symbol} } func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} } type key struct { State Symbol } type action struct { write Symbol Motion next State } type Machine struct { tape *Tape start, state State transition map[key]action l func(string, ...interface{}) } func NewMachine(rules []Rule) *Machine { m := &Machine{transition: make(map[key]action, len(rules))} if len(rules) > 0 { m.start = rules[0].State } for _, r := range rules { m.transition[r.key()] = r.action() } return m } func (m *Machine) Run(input *Tape) (int, *Tape) { m.tape = input.Dup() m.state = m.start for cnt := 0; ; cnt++ { if m.l != nil { m.l("%3d %4s: %v\n", cnt, m.state, m.tape) } sym := m.tape.Read() act, ok := m.transition[key{m.state, sym}] if !ok { return cnt, m.tape } m.tape.Write(act.write) m.tape.Move(act.Motion) m.state = act.next } }
Option Base 1 Public Enum sett name_ = 1 initState endState blank rules End Enum Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant Private Sub init() incrementer = Array("Simple incrementer", _ "q0", _ "qf", _ "B", _ Array( _ Array("q0", "1", "1", "right", "q0"), _ Array("q0", "B", "1", "stay", "qf"))) threeStateBB = Array("Three-state busy beaver", _ "a", _ "halt", _ "0", _ Array( _ Array("a", "0", "1", "right", "b"), _ Array("a", "1", "1", "left", "c"), _ Array("b", "0", "1", "left", "a"), _ Array("b", "1", "1", "right", "b"), _ Array("c", "0", "1", "left", "b"), _ Array("c", "1", "1", "stay", "halt"))) fiveStateBB = Array("Five-state busy beaver", _ "A", _ "H", _ "0", _ Array( _ Array("A", "0", "1", "right", "B"), _ Array("A", "1", "1", "left", "C"), _ Array("B", "0", "1", "right", "C"), _ Array("B", "1", "1", "right", "B"), _ Array("C", "0", "1", "right", "D"), _ Array("C", "1", "0", "left", "E"), _ Array("D", "0", "1", "left", "A"), _ Array("D", "1", "1", "left", "D"), _ Array("E", "0", "1", "stay", "H"), _ Array("E", "1", "0", "left", "A"))) End Sub Private Sub show(state As String, headpos As Long, tape As Collection) Debug.Print " "; state; String$(7 - Len(state), " "); "| "; For p = 1 To tape.Count Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " "); Next p Debug.Print End Sub Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0) Dim state As String: state = machine(initState) Dim headpos As Long: headpos = 1 Dim counter As Long, rule As Variant Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=") If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------" Do While True If headpos > tape.Count Then tape.Add machine(blank) Else If headpos < 1 Then tape.Add machine(blank), Before:=1 headpos = 1 End If End If If Not countOnly Then show state, headpos, tape For i = LBound(machine(rules)) To UBound(machine(rules)) rule = machine(rules)(i) If rule(1) = state And rule(2) = tape(headpos) Then tape.Remove headpos If headpos > tape.Count Then tape.Add rule(3) Else tape.Add rule(3), Before:=headpos End If If rule(4) = "left" Then headpos = headpos - 1 If rule(4) = "right" Then headpos = headpos + 1 state = rule(5) Exit For End If Next i counter = counter + 1 If counter Mod 100000 = 0 Then Debug.Print counter DoEvents DoEvents End If If state = machine(endState) Then Exit Do Loop DoEvents If countOnly Then Debug.Print "Steps taken: ", counter Else show state, headpos, tape Debug.Print End If End Sub Public Sub main() init Dim tap As New Collection tap.Add "1": tap.Add "1": tap.Add "1" UTM incrementer, tap Set tap = New Collection UTM threeStateBB, tap Set tap = New Collection UTM fiveStateBB, tap, countOnly:=-1 End Sub