Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in C.
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); } } }
#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); } }
Port the following code from C# to C with equivalent syntax and logic.
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); } } } }
#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; }
Convert the following code from C# to C, ensuring the logic remains intact.
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))); } } }
#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; }
Produce a language-to-language conversion: from C# to C, same semantics.
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))); } } }
#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; }
Maintain the same structure and functionality when rewriting this code in C.
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)); } } }
#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; }
Translate this program into C but keep the logic exactly as in C#.
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)); } } }
#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; }
Port the following code from C# to C with equivalent syntax and logic.
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; } }
#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; }
Rewrite the snippet below in C so it works the same as the original C# code.
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 "); } } }
#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; }
Translate the given C# code snippet into C without altering its behavior.
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()); }
#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; }
Transform the following C# implementation into C, maintaining the same output and logic.
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 ) ); } }
#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; }
Ensure the translated C code behaves exactly like the original C# snippet.
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); } } } } }
#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; }
Port the provided C# code into C while preserving the original functionality.
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); } } } }
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']++; }
Write the same code in C as shown below in C#.
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); } } } }
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']++; }
Rewrite this program in C while keeping its functionality equivalent to the C# version.
string s = "12345"; s = (int.Parse(s) + 1).ToString(); using System.Numerics; string bis = "123456789012345678999999999"; bis = (BigInteger.Parse(bis) + 1).ToString();
#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; }
Produce a functionally identical C code for the snippet given in C#.
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; }
#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; }
Ensure the translated C code behaves exactly like the original C# snippet.
using System; using System.Linq; class Program { static void Main() { Console.WriteLine(new[] { 1, 2, 3 }.Average()); } }
#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; }
Please provide an equivalent version of this C# code in C.
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; } } }
#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; }
Generate an equivalent C version of this C# code.
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; } }
#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; }
Can you help me rewrite this code in C instead of C#, keeping it the same logically?
Using System; namespace HelloWorld { class Program { static void Main() { Console.Writeln("Hello World!"); } } }
const hello = "Hello world!\n" print(hello)
Can you help me rewrite this code in C instead of C#, keeping it the same logically?
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()); } }
#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; }
Generate a C translation of this C# snippet without changing its computational steps.
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; }
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; }
Preserve the algorithm and functionality while converting the code from C# to C.
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; }
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; }
Please provide an equivalent version of this C# code in C.
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; } } }
#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; }
Produce a language-to-language conversion: from C# to C, same semantics.
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";
#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); }
Generate an equivalent C version of this C# code.
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";
#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); }
Generate a C translation of this C# snippet without changing its computational steps.
var current = [head of list to traverse] while(current != null) { current = current.Next; }
struct link *first; struct link *iter; for(iter = first; iter != NULL; iter = iter->next) { }
Convert this C# block to C, preserving its control flow and logic.
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(); } }
#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; }
Write the same algorithm in C as shown in this C# implementation.
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(); } }
#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; }
Change the following C# code into C without altering its purpose.
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"); } } }
#include <stdio.h> int main() { remove("input.txt"); remove("/input.txt"); remove("docs"); remove("/docs"); return 0; }
Convert the following code from C# to C, ensuring the logic remains intact.
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()}"); } } }
#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; }
Change the programming language of this snippet from C# to C without modifying what it does.
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()}"); } } }
#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; }
Convert this C# snippet to C and keep its semantics consistent.
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); } } }
#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; }
Write a version of this VB function in Go with identical behavior.
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)
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) }
Convert this VB block to Go, preserving its control flow and logic.
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
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]) }
Translate the given VB code snippet into Go without altering its behavior.
$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$
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()) } }
Port the provided VB code into Go while preserving the original functionality.
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
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) }
Produce a language-to-language conversion: from VB to Go, same semantics.
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
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)) } }
Convert this VB block to Go, preserving its control flow and logic.
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
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) } }
Preserve the algorithm and functionality while converting the code from VB to Go.
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
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) }
Rewrite the snippet below in Go so it works the same as the original VB code.
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"))
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) }
Write the same algorithm in Go as shown in this VB implementation.
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
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 }
Change the following VB code into Go without altering its purpose.
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
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 }
Keep all operations the same but rewrite the snippet in Go.
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
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) }
Transform the following VB implementation into Go, maintaining the same output and logic.
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
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:]) } }
Produce a language-to-language conversion: from VB to Go, same semantics.
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
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:]) } }
Keep all operations the same but rewrite the snippet in Go.
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
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) }
Please provide an equivalent version of this VB code in Go.
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
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") }
Change the programming language of this snippet from VB to Go without modifying what it does.
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
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") }
Convert this VB block to Go, preserving its control flow and logic.
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
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() } }
Change the following VB code into Go without altering its purpose.
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
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() } }
Ensure the translated Go code behaves exactly like the original VB snippet.
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 }
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))) } }
Translate the given VB code snippet into Go without altering its behavior.
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 }
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))) } }
Rewrite the snippet below in Go so it works the same as the original VB code.
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
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) }) }) }
Write the same code in Go as shown below in VB.
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))
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]) }
Write the same code in Go as shown below in VB.
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))
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]) }
Change the programming language of this snippet from VB to Go without modifying what it does.
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))
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]) }
Convert this VB block to Go, preserving its control flow and logic.
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))
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]) }
Translate this program into Go but keep the logic exactly as in VB.
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
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("") }
Rewrite the snippet below in Go so it works the same as the original VB code.
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
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 } }
Generate a Go translation of this VB snippet without changing its computational steps.
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
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 } }
Maintain the same structure and functionality when rewriting this code in Go.
Public Sub create_file() Dim FileNumber As Integer FileNumber = FreeFile MkDir "docs" Open "docs\output.txt" For Output As #FreeFile Close #FreeFile MkDir "C:\docs" Open "C:\docs\output.txt" For Output As #FreeFile Close #FreeFile End Sub
package main import ( "fmt" "os" ) func createFile(fn string) { f, err := os.Create(fn) if err != nil { fmt.Println(err) return } fmt.Println("file", fn, "created!") f.Close() } func createDir(dn string) { err := os.Mkdir(dn, 0666) if err != nil { fmt.Println(err) return } fmt.Println("directory", dn, "created!") } func main() { createFile("input.txt") createFile("/input.txt") createDir("docs") createDir("/docs") }
Write the same algorithm in Go as shown in this VB implementation.
Public Sub create_file() Dim FileNumber As Integer FileNumber = FreeFile MkDir "docs" Open "docs\output.txt" For Output As #FreeFile Close #FreeFile MkDir "C:\docs" Open "C:\docs\output.txt" For Output As #FreeFile Close #FreeFile End Sub
package main import ( "fmt" "os" ) func createFile(fn string) { f, err := os.Create(fn) if err != nil { fmt.Println(err) return } fmt.Println("file", fn, "created!") f.Close() } func createDir(dn string) { err := os.Mkdir(dn, 0666) if err != nil { fmt.Println(err) return } fmt.Println("directory", dn, "created!") } func main() { createFile("input.txt") createFile("/input.txt") createDir("docs") createDir("/docs") }
Preserve the algorithm and functionality while converting the code from VB to Go.
b=_ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_ "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_ "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_ "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_ "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_ "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_ "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_ "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_ "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" s="SEQUENCE:" acnt=0:ccnt=0:gcnt=0:tcnt=0 for i=0 to len(b)-1 if (i mod 30)=0 then s = s & vbcrlf & right(" "& i+1,3)&": " if (i mod 5)=0 then s=s& " " m=mid(b,i+1,1) s=s & m select case m case "A":acnt=acnt+1 case "C":ccnt=ccnt+1 case "G":gcnt=gcnt+1 case "T":tcnt=tcnt+1 case else wscript.echo "error at ",i+1, m end select next wscript.echo s & vbcrlf wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt
package main import ( "fmt" "sort" ) func main() { dna := "" + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += 50 { k := i + 50 if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======") }
Can you help me rewrite this code in Go instead of VB, keeping it the same logically?
b=_ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_ "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_ "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_ "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_ "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_ "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_ "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_ "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_ "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" s="SEQUENCE:" acnt=0:ccnt=0:gcnt=0:tcnt=0 for i=0 to len(b)-1 if (i mod 30)=0 then s = s & vbcrlf & right(" "& i+1,3)&": " if (i mod 5)=0 then s=s& " " m=mid(b,i+1,1) s=s & m select case m case "A":acnt=acnt+1 case "C":ccnt=ccnt+1 case "G":gcnt=gcnt+1 case "T":tcnt=tcnt+1 case else wscript.echo "error at ",i+1, m end select next wscript.echo s & vbcrlf wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt
package main import ( "fmt" "sort" ) func main() { dna := "" + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += 50 { k := i + 50 if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======") }
Keep all operations the same but rewrite the snippet in Go.
Public Const HOLDON = False Public Const DIJKSTRASOLUTION = True Public Const X = 10 Public Const GETS = 0 Public Const PUTS = 1 Public Const EATS = 2 Public Const THKS = 5 Public Const FRSTFORK = 0 Public Const SCNDFORK = 1 Public Const SPAGHETI = 0 Public Const UNIVERSE = 1 Public Const MAXCOUNT = 100000 Public Const PHILOSOPHERS = 5 Public semaphore(PHILOSOPHERS - 1) As Integer Public positi0n(1, PHILOSOPHERS - 1) As Integer Public programcounter(PHILOSOPHERS - 1) As Long Public statistics(PHILOSOPHERS - 1, 5, 1) As Long Public names As Variant Private Sub init() names = [{"Aquinas","Babbage","Carroll","Derrida","Erasmus"}] For j = 0 To PHILOSOPHERS - 2 positi0n(0, j) = j + 1 positi0n(1, j) = j Next j If DIJKSTRASOLUTION Then positi0n(0, PHILOSOPHERS - 1) = j positi0n(1, PHILOSOPHERS - 1) = 0 Else positi0n(0, PHILOSOPHERS - 1) = 0 positi0n(1, PHILOSOPHERS - 1) = j End If End Sub Private Sub philosopher(subject As Integer, verb As Integer, objekt As Integer) statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1 If verb < 2 Then If semaphore(positi0n(objekt, subject)) <> verb Then If Not HOLDON Then semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt programcounter(subject) = 0 End If Else semaphore(positi0n(objekt, subject)) = 1 - verb programcounter(subject) = (programcounter(subject) + 1) Mod 6 End If Else programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6 End If End Sub Private Sub dine() Dim ph As Integer Do While TC < MAXCOUNT For ph = 0 To PHILOSOPHERS - 1 Select Case programcounter(ph) Case 0: philosopher ph, GETS, FRSTFORK Case 1: philosopher ph, GETS, SCNDFORK Case 2: philosopher ph, EATS, SPAGHETI Case 3: philosopher ph, PUTS, FRSTFORK Case 4: philosopher ph, PUTS, SCNDFORK Case 5: philosopher ph, THKS, UNIVERSE End Select TC = TC + 1 Next ph Loop End Sub Private Sub show() Debug.Print "Stats", "Gets", "Gets", "Eats", "Puts", "Puts", "Thinks" Debug.Print "", "First", "Second", "Spag-", "First", "Second", "About" Debug.Print "", "Fork", "Fork", "hetti", "Fork", "Fork", "Universe" For subject = 0 To PHILOSOPHERS - 1 Debug.Print names(subject + 1), For objekt = 0 To 1 Debug.Print statistics(subject, GETS, objekt), Next objekt Debug.Print statistics(subject, EATS, SPAGHETI), For objekt = 0 To 1 Debug.Print statistics(subject, PUTS, objekt), Next objekt Debug.Print statistics(subject, THKS, UNIVERSE) Next subject End Sub Public Sub main() init dine show End Sub
package main import ( "hash/fnv" "log" "math/rand" "os" "time" ) var ph = []string{"Aristotle", "Kant", "Spinoza", "Marx", "Russell"} const hunger = 3 const think = time.Second / 100 const eat = time.Second / 100 var fmt = log.New(os.Stdout, "", 0) var done = make(chan bool) type fork byte func philosopher(phName string, dominantHand, otherHand chan fork, done chan bool) { fmt.Println(phName, "seated") h := fnv.New64a() h.Write([]byte(phName)) rg := rand.New(rand.NewSource(int64(h.Sum64()))) rSleep := func(t time.Duration) { time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t)))) } for h := hunger; h > 0; h-- { fmt.Println(phName, "hungry") <-dominantHand <-otherHand fmt.Println(phName, "eating") rSleep(eat) dominantHand <- 'f' otherHand <- 'f' fmt.Println(phName, "thinking") rSleep(think) } fmt.Println(phName, "satisfied") done <- true fmt.Println(phName, "left the table") } func main() { fmt.Println("table empty") place0 := make(chan fork, 1) place0 <- 'f' placeLeft := place0 for i := 1; i < len(ph); i++ { placeRight := make(chan fork, 1) placeRight <- 'f' go philosopher(ph[i], placeLeft, placeRight, done) placeLeft = placeRight } go philosopher(ph[0], place0, placeLeft, done) for range ph { <-done } fmt.Println("table empty") }
Translate this program into Go but keep the logic exactly as in VB.
Dim fact() nn1=9 : nn2=12 lim=1499999 ReDim fact(nn2) fact(0)=1 For i=1 To nn2 fact(i)=fact(i-1)*i Next For base=nn1 To nn2 list="" For i=1 To lim s=0 t=i Do While t<>0 d=t Mod base s=s+fact(d) t=t\base Loop If s=i Then list=list &" "& i Next Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list Next
package main import ( "fmt" "strconv" ) func main() { var fact [12]uint64 fact[0] = 1 for n := uint64(1); n < 12; n++ { fact[n] = fact[n-1] * n } for b := 9; b <= 12; b++ { fmt.Printf("The factorions for base %d are:\n", b) for i := uint64(1); i < 1500000; i++ { digits := strconv.FormatUint(i, b) sum := uint64(0) for _, digit := range digits { if digit < 'a' { sum += fact[digit-'0'] } else { sum += fact[digit+10-'a'] } } if sum == i { fmt.Printf("%d ", i) } } fmt.Println("\n") } }
Translate this program into Go but keep the logic exactly as in VB.
Dim fact() nn1=9 : nn2=12 lim=1499999 ReDim fact(nn2) fact(0)=1 For i=1 To nn2 fact(i)=fact(i-1)*i Next For base=nn1 To nn2 list="" For i=1 To lim s=0 t=i Do While t<>0 d=t Mod base s=s+fact(d) t=t\base Loop If s=i Then list=list &" "& i Next Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list Next
package main import ( "fmt" "strconv" ) func main() { var fact [12]uint64 fact[0] = 1 for n := uint64(1); n < 12; n++ { fact[n] = fact[n-1] * n } for b := 9; b <= 12; b++ { fmt.Printf("The factorions for base %d are:\n", b) for i := uint64(1); i < 1500000; i++ { digits := strconv.FormatUint(i, b) sum := uint64(0) for _, digit := range digits { if digit < 'a' { sum += fact[digit-'0'] } else { sum += fact[digit+10-'a'] } } if sum == i { fmt.Printf("%d ", i) } } fmt.Println("\n") } }
Keep all operations the same but rewrite the snippet in Go.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " commandtable = Split(s, " ") Dim i As Integer For Each word In commandtable If Len(word) > 0 Then i = 1 Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z" i = i + 1 Loop command_table.Add Key:=word, Item:=i - 1 End If Next word For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
Ensure the translated Go code behaves exactly like the original VB snippet.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " commandtable = Split(s, " ") Dim i As Integer For Each word In commandtable If Len(word) > 0 Then i = 1 Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z" i = i + 1 Loop command_table.Add Key:=word, Item:=i - 1 End If Next word For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
Port the following code from VB to Go with equivalent syntax and logic.
Imports System.Text Module Module1 ReadOnly CODES As New Dictionary(Of Char, String) From { {"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"} } Function Encode(plainText As String, message As String) As String Dim pt = plainText.ToLower() Dim sb As New StringBuilder() For Each c In pt If "a" <= c AndAlso c <= "z" Then sb.Append(CODES(c)) Else sb.Append(CODES(" ")) End If Next Dim et = sb.ToString() Dim mg = message.ToLower() sb.Length = 0 Dim count = 0 For Each c In mg If "a" <= c AndAlso c <= "z" Then If et(count) = "A" Then sb.Append(c) Else sb.Append(Chr(Asc(c) - 32)) End If count += 1 If count = et.Length Then Exit For End If Else sb.Append(c) End If Next Return sb.ToString() End Function Function Decode(message As String) As String Dim sb As New StringBuilder For Each c In message If "a" <= c AndAlso c <= "z" Then sb.Append("A") ElseIf "A" <= c AndAlso c <= "Z" Then sb.Append("B") End If Next Dim et = sb.ToString() sb.Length = 0 For index = 0 To et.Length - 1 Step 5 Dim quintet = et.Substring(index, 5) Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key sb.Append(key) Next Return sb.ToString() End Function Sub Main() Dim plainText = "the quick brown fox jumps over the lazy dog" Dim message = "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." Dim cipherText = Encode(plainText, message) Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText) Dim decodedText = Decode(cipherText) Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText) End Sub End Module
package main import( "fmt" "strings" ) var codes = map[rune]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", } func baconEncode(plainText string, message string) string { pt := strings.ToLower(plainText) var sb []byte for _, c := range pt { if c >= 'a' && c <= 'z' { sb = append(sb, codes[c]...) } else { sb = append(sb, codes[' ']...) } } et := string(sb) mg := strings.ToLower(message) sb = nil var count = 0 for _, c := range mg { if c >= 'a' && c <= 'z' { if et[count] == 'A' { sb = append(sb, byte(c)) } else { sb = append(sb, byte(c - 32)) } count++ if count == len(et) { break } } else { sb = append(sb, byte(c)) } } return string(sb) } func baconDecode(message string) string { var sb []byte for _, c := range message { if c >= 'a' && c <= 'z' { sb = append(sb, 'A') } else if c >= 'A' && c <= 'Z' { sb = append(sb, 'B') } } et := string(sb) sb = nil for i := 0; i < len(et); i += 5 { quintet := et[i : i + 5] for k, v := range codes { if v == quintet { sb = append(sb, byte(k)) break } } } return string(sb) } func main() { plainText := "the quick brown fox jumps over the lazy dog" 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." cipherText := baconEncode(plainText, message) fmt.Printf("Cipher text ->\n\n%s\n", cipherText) decodedText := baconDecode(cipherText) fmt.Printf("\nHidden text ->\n\n%s\n", decodedText) }
Preserve the algorithm and functionality while converting the code from VB to Go.
Imports System.Text Module Module1 ReadOnly CODES As New Dictionary(Of Char, String) From { {"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"} } Function Encode(plainText As String, message As String) As String Dim pt = plainText.ToLower() Dim sb As New StringBuilder() For Each c In pt If "a" <= c AndAlso c <= "z" Then sb.Append(CODES(c)) Else sb.Append(CODES(" ")) End If Next Dim et = sb.ToString() Dim mg = message.ToLower() sb.Length = 0 Dim count = 0 For Each c In mg If "a" <= c AndAlso c <= "z" Then If et(count) = "A" Then sb.Append(c) Else sb.Append(Chr(Asc(c) - 32)) End If count += 1 If count = et.Length Then Exit For End If Else sb.Append(c) End If Next Return sb.ToString() End Function Function Decode(message As String) As String Dim sb As New StringBuilder For Each c In message If "a" <= c AndAlso c <= "z" Then sb.Append("A") ElseIf "A" <= c AndAlso c <= "Z" Then sb.Append("B") End If Next Dim et = sb.ToString() sb.Length = 0 For index = 0 To et.Length - 1 Step 5 Dim quintet = et.Substring(index, 5) Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key sb.Append(key) Next Return sb.ToString() End Function Sub Main() Dim plainText = "the quick brown fox jumps over the lazy dog" Dim message = "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." Dim cipherText = Encode(plainText, message) Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText) Dim decodedText = Decode(cipherText) Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText) End Sub End Module
package main import( "fmt" "strings" ) var codes = map[rune]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", } func baconEncode(plainText string, message string) string { pt := strings.ToLower(plainText) var sb []byte for _, c := range pt { if c >= 'a' && c <= 'z' { sb = append(sb, codes[c]...) } else { sb = append(sb, codes[' ']...) } } et := string(sb) mg := strings.ToLower(message) sb = nil var count = 0 for _, c := range mg { if c >= 'a' && c <= 'z' { if et[count] == 'A' { sb = append(sb, byte(c)) } else { sb = append(sb, byte(c - 32)) } count++ if count == len(et) { break } } else { sb = append(sb, byte(c)) } } return string(sb) } func baconDecode(message string) string { var sb []byte for _, c := range message { if c >= 'a' && c <= 'z' { sb = append(sb, 'A') } else if c >= 'A' && c <= 'Z' { sb = append(sb, 'B') } } et := string(sb) sb = nil for i := 0; i < len(et); i += 5 { quintet := et[i : i + 5] for k, v := range codes { if v == quintet { sb = append(sb, byte(k)) break } } } return string(sb) } func main() { plainText := "the quick brown fox jumps over the lazy dog" 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." cipherText := baconEncode(plainText, message) fmt.Printf("Cipher text ->\n\n%s\n", cipherText) decodedText := baconDecode(cipherText) fmt.Printf("\nHidden text ->\n\n%s\n", decodedText) }
Convert this VB block to Go, preserving its control flow and logic.
Function build_spiral(n) botcol = 0 : topcol = n - 1 botrow = 0 : toprow = n - 1 Dim matrix() ReDim matrix(topcol,toprow) dir = 0 : col = 0 : row = 0 For i = 0 To n*n-1 matrix(col,row) = i Select Case dir Case 0 If col < topcol Then col = col + 1 Else dir = 1 : row = row + 1 : botrow = botrow + 1 End If Case 1 If row < toprow Then row = row + 1 Else dir = 2 : col = col - 1 : topcol = topcol - 1 End If Case 2 If col > botcol Then col = col - 1 Else dir = 3 : row = row - 1 : toprow = toprow - 1 End If Case 3 If row > botrow Then row = row - 1 Else dir = 0 : col = col + 1 : botcol = botcol + 1 End If End Select Next For y = 0 To n-1 For x = 0 To n-1 WScript.StdOut.Write matrix(x,y) & vbTab Next WScript.StdOut.WriteLine Next End Function build_spiral(CInt(WScript.Arguments(0)))
package main import ( "fmt" "strconv" ) var n = 5 func main() { if n < 1 { return } top, left, bottom, right := 0, 0, n-1, n-1 sz := n * n a := make([]int, sz) i := 0 for left < right { for c := left; c <= right; c++ { a[top*n+c] = i i++ } top++ for r := top; r <= bottom; r++ { a[r*n+right] = i i++ } right-- if top == bottom { break } for c := right; c >= left; c-- { a[bottom*n+c] = i i++ } bottom-- for r := bottom; r >= top; r-- { a[r*n+left] = i i++ } left++ } a[top*n+left] = i w := len(strconv.Itoa(n*n - 1)) for i, e := range a { fmt.Printf("%*d ", w, e) if i%n == n-1 { fmt.Println("") } } }
Generate an equivalent Go version of this VB code.
Private Sub optional_parameters(theRange As String, _ Optional ordering As Integer = 0, _ Optional column As Integer = 1, _ Optional reverse As Integer = 1) ActiveSheet.Sort.SortFields.Clear ActiveSheet.Sort.SortFields.Add _ Key:=Range(theRange).Columns(column), _ SortOn:=SortOnValues, _ Order:=reverse, _ DataOption:=ordering With ActiveSheet.Sort .SetRange Range(theRange) .Header = xlGuess .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub Public Sub main() optional_parameters theRange:="A1:C4", ordering:=1, column:=2, reverse:=1 End Sub
type cell string type spec struct { less func(cell, cell) bool column int reverse bool } func newSpec() (s spec) { return } t.sort(newSpec()) s := newSpec s.reverse = true t.sort(s)
Write a version of this VB function in Go with identical behavior.
Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _ CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _ overlapped As Ptr) As Boolean Declare Function GetLastError Lib "Kernel32" () As Integer Declare Function CloseHandle Lib "kernel32" (hObject As Integer) As Boolean Const FILE_SHARE_READ = &h00000001 Const FILE_SHARE_WRITE = &h00000002 Const OPEN_EXISTING = 3 Dim fHandle As Integer = CreateFileW("C:\foo.txt", 0, FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0) If fHandle > 0 Then Dim mb As MemoryBlock = "Hello, World!" Dim bytesWritten As Integer If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then MsgBox("Error Number: " + Str(GetLastError)) End If Call CloseHandle(fHandle) Else MsgBox("Error Number: " + Str(GetLastError)) End If
package main import "C" import ( "fmt" "unsafe" ) func main() { go1 := "hello C" c1 := C.CString(go1) go1 = "" c2 := C.strdup(c1) C.free(unsafe.Pointer(c1)) go2 := C.GoString(c2) C.free(unsafe.Pointer(c2)) fmt.Println(go2) }
Change the programming language of this snippet from VB to Go without modifying what it does.
Module Module1 Class Frac Private ReadOnly num As Long Private ReadOnly denom As Long Public Shared ReadOnly ZERO = New Frac(0, 1) Public Shared ReadOnly ONE = New Frac(1, 1) Public Sub New(n As Long, d As Long) If d = 0 Then Throw New ArgumentException("d must not be zero") End If Dim nn = n Dim dd = d If nn = 0 Then dd = 1 ElseIf dd < 0 Then nn = -nn dd = -dd End If Dim g = Math.Abs(Gcd(nn, dd)) If g > 1 Then nn /= g dd /= g End If num = nn denom = dd End Sub Private Shared Function Gcd(a As Long, b As Long) As Long If b = 0 Then Return a Else Return Gcd(b, a Mod b) End If End Function Public Shared Operator -(self As Frac) As Frac Return New Frac(-self.num, self.denom) End Operator Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom) End Operator Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac Return lhs + -rhs End Operator Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom) End Operator Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x < y End Operator Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x > y End Operator Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom End Operator Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom End Operator Public Overrides Function ToString() As String If denom = 1 Then Return num.ToString Else Return String.Format("{0}/{1}", num, denom) End If End Function Public Overrides Function Equals(obj As Object) As Boolean Dim frac = CType(obj, Frac) Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom End Function End Class Function Bernoulli(n As Integer) As Frac If n < 0 Then Throw New ArgumentException("n may not be negative or zero") End If Dim a(n + 1) As Frac For m = 0 To n a(m) = New Frac(1, m + 1) For j = m To 1 Step -1 a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1) Next Next If n <> 1 Then Return a(0) Else Return -a(0) End If End Function Function Binomial(n As Integer, k As Integer) As Integer If n < 0 OrElse k < 0 OrElse n < k Then Throw New ArgumentException() End If If n = 0 OrElse k = 0 Then Return 1 End If Dim num = 1 For i = k + 1 To n num *= i Next Dim denom = 1 For i = 2 To n - k denom *= i Next Return num \ denom End Function Function FaulhaberTriangle(p As Integer) As Frac() Dim coeffs(p + 1) As Frac For i = 1 To p + 1 coeffs(i - 1) = Frac.ZERO Next Dim q As New Frac(1, p + 1) Dim sign = -1 For j = 0 To p sign *= -1 coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j) Next Return coeffs End Function Sub Main() For i = 1 To 10 Dim coeffs = FaulhaberTriangle(i - 1) For Each coeff In coeffs Console.Write("{0,5} ", coeff) Next Console.WriteLine() Next End Sub End Module
package main import ( "fmt" "math/big" ) func bernoulli(n uint) *big.Rat { a := make([]big.Rat, n+1) z := new(big.Rat) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) } } if n != 1 { return &a[0] } a[0].Neg(&a[0]) return &a[0] } func binomial(n, k int) int64 { if n <= 0 || k <= 0 || n < k { return 1 } var num, den int64 = 1, 1 for i := k + 1; i <= n; i++ { num *= int64(i) } for i := 2; i <= n-k; i++ { den *= int64(i) } return num / den } func faulhaberTriangle(p int) []big.Rat { coeffs := make([]big.Rat, p+1) q := big.NewRat(1, int64(p)+1) t := new(big.Rat) u := new(big.Rat) sign := -1 for j := range coeffs { sign *= -1 d := &coeffs[p-j] t.SetInt64(int64(sign)) u.SetInt64(binomial(p+1, j)) d.Mul(q, t) d.Mul(d, u) d.Mul(d, bernoulli(uint(j))) } return coeffs } func main() { for i := 0; i < 10; i++ { coeffs := faulhaberTriangle(i) for _, coeff := range coeffs { fmt.Printf("%5s ", coeff.RatString()) } fmt.Println() } fmt.Println() k := 17 cc := faulhaberTriangle(k) n := int64(1000) nn := big.NewRat(n, 1) np := big.NewRat(1, 1) sum := new(big.Rat) tmp := new(big.Rat) for _, c := range cc { np.Mul(np, nn) tmp.Set(np) tmp.Mul(tmp, &c) sum.Add(sum, tmp) } fmt.Println(sum.RatString()) }
Maintain the same structure and functionality when rewriting this code in Go.
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
package main import ( "fmt" "os" ) func main() { for i, x := range os.Args[1:] { fmt.Printf("the argument #%d is %s\n", i, x) } }
Translate this program into Go but keep the logic exactly as in VB.
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
package main import ( "fmt" "os" ) func main() { for i, x := range os.Args[1:] { fmt.Printf("the argument #%d is %s\n", i, x) } }
Preserve the algorithm and functionality while converting the code from VB to Go.
Const wheel="ndeokgelw" Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub Dim oDic Set oDic = WScript.CreateObject("scripting.dictionary") Dim cnt(127) Dim fso Set fso = WScript.CreateObject("Scripting.Filesystemobject") Set ff=fso.OpenTextFile("unixdict.txt") i=0 print "reading words of 3 or more letters" While Not ff.AtEndOfStream x=LCase(ff.ReadLine) If Len(x)>=3 Then If Not odic.exists(x) Then oDic.Add x,0 End If Wend print "remaining words: "& oDic.Count & vbcrlf ff.Close Set ff=Nothing Set fso=Nothing Set re=New RegExp print "removing words with chars not in the wheel" re.pattern="[^"& wheel &"]" For Each w In oDic.Keys If re.test(w) Then oDic.remove(w) Next print "remaining words: "& oDic.Count & vbcrlf print "ensuring the mandatory letter "& Mid(wheel,5,1) & " is present" re.Pattern=Mid(wheel,5,1) For Each w In oDic.Keys If Not re.test(w) Then oDic.remove(w) Next print "remaining words: "& oDic.Count & vbcrlf print "checking number of chars" Dim nDic Set nDic = WScript.CreateObject("scripting.dictionary") For i=1 To Len(wheel) x=Mid(wheel,i,1) If nDic.Exists(x) Then a=nDic(x) nDic(x)=Array(a(0)+1,0) Else nDic.add x,Array(1,0) End If Next For Each w In oDic.Keys For Each c In nDic.Keys ndic(c)=Array(nDic(c)(0),0) Next For ii = 1 To len(w) c=Mid(w,ii,1) a=nDic(c) If (a(0)=a(1)) Then oDic.Remove(w):Exit For End If nDic(c)=Array(a(0),a(1)+1) Next Next print "Remaining words "& oDic.count For Each w In oDic.Keys print w Next
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { b, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } letters := "deegklnow" wordsAll := bytes.Split(b, []byte{'\n'}) var words [][]byte for _, word := range wordsAll { word = bytes.TrimSpace(word) le := len(word) if le > 2 && le < 10 { words = append(words, word) } } var found []string for _, word := range words { le := len(word) if bytes.IndexByte(word, 'k') >= 0 { lets := letters ok := true for i := 0; i < le; i++ { c := word[i] ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c }) if ix < len(lets) && lets[ix] == c { lets = lets[0:ix] + lets[ix+1:] } else { ok = false break } } if ok { found = append(found, string(word)) } } } fmt.Println("The following", len(found), "words are the solutions to the puzzle:") fmt.Println(strings.Join(found, "\n")) mostFound := 0 var mostWords9 []string var mostLetters []byte var words9 [][]byte for _, word := range words { if len(word) == 9 { words9 = append(words9, word) } } for _, word9 := range words9 { letterBytes := make([]byte, len(word9)) copy(letterBytes, word9) sort.Slice(letterBytes, func(i, j int) bool { return letterBytes[i] < letterBytes[j] }) distinctBytes := []byte{letterBytes[0]} for _, b := range letterBytes[1:] { if b != distinctBytes[len(distinctBytes)-1] { distinctBytes = append(distinctBytes, b) } } distinctLetters := string(distinctBytes) for _, letter := range distinctLetters { found := 0 letterByte := byte(letter) for _, word := range words { le := len(word) if bytes.IndexByte(word, letterByte) >= 0 { lets := string(letterBytes) ok := true for i := 0; i < le; i++ { c := word[i] ix := sort.Search(len(lets), func(i int) bool { return lets[i] >= c }) if ix < len(lets) && lets[ix] == c { lets = lets[0:ix] + lets[ix+1:] } else { ok = false break } } if ok { found = found + 1 } } } if found > mostFound { mostFound = found mostWords9 = []string{string(word9)} mostLetters = []byte{letterByte} } else if found == mostFound { mostWords9 = append(mostWords9, string(word9)) mostLetters = append(mostLetters, letterByte) } } } fmt.Println("\nMost words found =", mostFound) fmt.Println("Nine letter words producing this total:") for i := 0; i < len(mostWords9); i++ { fmt.Println(mostWords9[i], "with central letter", string(mostLetters[i])) } }
Change the following VB code into Go without altering its purpose.
DEFINT A(1 to 4) = {1, 2, 3, 4} DEFINT B(1 to 4) = {10, 20, 30, 40} Redim A(1 to 8) as integer MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
package main import "fmt" func main() { a := []int{1, 2, 3} b := []int{7, 12, 60} c := append(a, b...) fmt.Println(c) i := []interface{}{1, 2, 3} j := []interface{}{"Crosby", "Stills", "Nash", "Young"} k := append(i, j...) fmt.Println(k) l := [...]int{1, 2, 3} m := [...]int{7, 12, 60} var n [len(l) + len(m)]int copy(n[:], l[:]) copy(n[len(l):], m[:]) fmt.Println(n) }
Preserve the algorithm and functionality while converting the code from VB to Go.
Public Sub text() Debug.Print InputBox("Input a string") Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long") End Sub
package main import "fmt" func main() { var s string var i int if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 { fmt.Println("good") } else { fmt.Println("wrong") } }
Convert the following code from VB to Go, ensuring the logic remains intact.
Option Explicit Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
package main import ( "encoding/binary" "log" "math" "os" "strings" ) func main() { const ( sampleRate = 44100 duration = 8 dataLength = sampleRate * duration hdrSize = 44 fileLen = dataLength + hdrSize - 8 ) buf1 := make([]byte, 1) buf2 := make([]byte, 2) buf4 := make([]byte, 4) var sb strings.Builder sb.WriteString("RIFF") binary.LittleEndian.PutUint32(buf4, fileLen) sb.Write(buf4) sb.WriteString("WAVE") sb.WriteString("fmt ") binary.LittleEndian.PutUint32(buf4, 16) sb.Write(buf4) binary.LittleEndian.PutUint16(buf2, 1) sb.Write(buf2) sb.Write(buf2) binary.LittleEndian.PutUint32(buf4, sampleRate) sb.Write(buf4) sb.Write(buf4) sb.Write(buf2) binary.LittleEndian.PutUint16(buf2, 8) sb.Write(buf2) sb.WriteString("data") binary.LittleEndian.PutUint32(buf4, dataLength) sb.Write(buf4) wavhdr := []byte(sb.String()) f, err := os.Create("notes.wav") if err != nil { log.Fatal(err) } defer f.Close() f.Write(wavhdr) freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3} for j := 0; j < duration; j++ { freq := freqs[j] omega := 2 * math.Pi * freq for i := 0; i < dataLength/duration; i++ { y := 32 * math.Sin(omega*float64(i)/float64(sampleRate)) buf1[0] = byte(math.Round(y)) f.Write(buf1) } } }
Translate the given VB code snippet into Go without altering its behavior.
Option Explicit Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
package main import ( "encoding/binary" "log" "math" "os" "strings" ) func main() { const ( sampleRate = 44100 duration = 8 dataLength = sampleRate * duration hdrSize = 44 fileLen = dataLength + hdrSize - 8 ) buf1 := make([]byte, 1) buf2 := make([]byte, 2) buf4 := make([]byte, 4) var sb strings.Builder sb.WriteString("RIFF") binary.LittleEndian.PutUint32(buf4, fileLen) sb.Write(buf4) sb.WriteString("WAVE") sb.WriteString("fmt ") binary.LittleEndian.PutUint32(buf4, 16) sb.Write(buf4) binary.LittleEndian.PutUint16(buf2, 1) sb.Write(buf2) sb.Write(buf2) binary.LittleEndian.PutUint32(buf4, sampleRate) sb.Write(buf4) sb.Write(buf4) sb.Write(buf2) binary.LittleEndian.PutUint16(buf2, 8) sb.Write(buf2) sb.WriteString("data") binary.LittleEndian.PutUint32(buf4, dataLength) sb.Write(buf4) wavhdr := []byte(sb.String()) f, err := os.Create("notes.wav") if err != nil { log.Fatal(err) } defer f.Close() f.Write(wavhdr) freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3} for j := 0; j < duration; j++ { freq := freqs[j] omega := 2 * math.Pi * freq for i := 0; i < dataLength/duration; i++ { y := 32 * math.Sin(omega*float64(i)/float64(sampleRate)) buf1[0] = byte(math.Round(y)) f.Write(buf1) } } }
Transform the following VB implementation into Go, maintaining the same output and logic.
Option Explicit Const maxWeight = 400 Dim DataList As Variant Dim xList(64, 3) As Variant Dim nItems As Integer Dim s As String, xss As String Dim xwei As Integer, xval As Integer, nn As Integer Sub Main() Dim i As Integer, j As Integer DataList = Array("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, "book", 30, 10, _ "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _ "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50) nItems = (UBound(DataList) + 1) / 3 j = 0 For i = 1 To nItems xList(i, 1) = DataList(j) xList(i, 2) = DataList(j + 1) xList(i, 3) = DataList(j + 2) j = j + 3 Next i s = "" For i = 1 To nItems s = s & Chr(i) Next nn = 0 Call ChoiceBin(1, "") For i = 1 To Len(xss) j = Asc(Mid(xss, i, 1)) Debug.Print xList(j, 1) Next i Debug.Print "count=" & Len(xss), "weight=" & xwei, "value=" & xval End Sub Private Sub ChoiceBin(n As String, ss As String) Dim r As String Dim i As Integer, j As Integer, iwei As Integer, ival As Integer Dim ipct As Integer If n = Len(s) + 1 Then iwei = 0: ival = 0 For i = 1 To Len(ss) j = Asc(Mid(ss, i, 1)) iwei = iwei + xList(j, 2) ival = ival + xList(j, 3) Next If iwei <= maxWeight And ival > xval Then xss = ss: xwei = iwei: xval = ival End If Else r = Mid(s, n, 1) Call ChoiceBin(n + 1, ss & r) Call ChoiceBin(n + 1, ss) End If End Sub
package main import "fmt" type item struct { string w, v int } var wants = []item{ {"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}, } const maxWt = 400 func main() { items, w, v := m(len(wants)-1, maxWt) fmt.Println(items) fmt.Println("weight:", w) fmt.Println("value:", v) } func m(i, w int) ([]string, int, int) { if i < 0 || w == 0 { return nil, 0, 0 } else if wants[i].w > w { return m(i-1, w) } i0, w0, v0 := m(i-1, w) i1, w1, v1 := m(i-1, w-wants[i].w) v1 += wants[i].v if v1 > v0 { return append(i1, wants[i].string), w1 + wants[i].w, v1 } return i0, w0, v0 }
Translate the given VB code snippet into Go without altering its behavior.
Imports System.Math Module Module1 Const MAXPRIME = 99 Const MAXPARENT = 99 Const NBRCHILDREN = 547100 Public Primes As New Collection() Public PrimesR As New Collection() Public Ancestors As New Collection() Public Parents(MAXPARENT + 1) As Integer Public CptDescendants(MAXPARENT + 1) As Integer Public Children(NBRCHILDREN) As ChildStruct Public iChildren As Integer Public Delimiter As String = ", " Public Structure ChildStruct Public Child As Long Public pLower As Integer Public pHigher As Integer End Structure Sub Main() Dim Parent As Short Dim Sum As Short Dim i As Short Dim TotDesc As Integer = 0 Dim MidPrime As Integer If GetPrimes(Primes, MAXPRIME) = vbFalse Then Return End If For i = Primes.Count To 1 Step -1 PrimesR.Add(Primes.Item(i)) Next MidPrime = PrimesR.Item(1) / 2 For Each Prime In PrimesR Parents(Prime) = InsertChild(Parents(Prime), Prime) CptDescendants(Prime) += 1 If Prime > MidPrime Then Continue For End If For Parent = 1 To MAXPARENT Sum = Parent + Prime If Sum > MAXPARENT Then Exit For End If If Parents(Parent) Then InsertPreorder(Parents(Parent), Sum, Prime) CptDescendants(Sum) += CptDescendants(Parent) End If Next Next RemoveFalseChildren() If MAXPARENT > MAXPRIME Then If GetPrimes(Primes, MAXPARENT) = vbFalse Then Return End If End If FileOpen(1, "Ancestors.txt", OpenMode.Output) For Parent = 1 To MAXPARENT GetAncestors(Parent) PrintLine(1, "[" & Parent.ToString & "] Level: " & Ancestors.Count.ToString) If Ancestors.Count Then Print(1, "Ancestors: " & Ancestors.Item(1).ToString) For i = 2 To Ancestors.Count Print(1, ", " & Ancestors.Item(i).ToString) Next PrintLine(1) Ancestors.Clear() Else PrintLine(1, "Ancestors: None") End If If CptDescendants(Parent) Then PrintLine(1, "Descendants: " & CptDescendants(Parent).ToString) Delimiter = "" PrintDescendants(Parents(Parent)) PrintLine(1) TotDesc += CptDescendants(Parent) Else PrintLine(1, "Descendants: None") End If PrintLine(1) Next Primes.Clear() PrimesR.Clear() PrintLine(1, "Total descendants " & TotDesc.ToString) PrintLine(1) FileClose(1) End Sub Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short) Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime) If Children(_index).pLower Then InsertPreorder(Children(_index).pLower, _sum, _prime) End If If Children(_index).pHigher Then InsertPreorder(Children(_index).pHigher, _sum, _prime) End If Return Nothing End Function Function InsertChild(_index As Integer, _child As Long) As Integer If _index Then If _child <= Children(_index).Child Then Children(_index).pLower = InsertChild(Children(_index).pLower, _child) Else Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child) End If Else iChildren += 1 _index = iChildren Children(_index).Child = _child Children(_index).pLower = 0 Children(_index).pHigher = 0 End If Return _index End Function Function RemoveFalseChildren() Dim Exclusions As New Collection Exclusions.Add(4) For Each Prime In Primes Exclusions.Add(Prime) Next For Each ex In Exclusions Parents(ex) = Children(Parents(ex)).pHigher CptDescendants(ex) -= 1 Next Exclusions.Clear() Return Nothing End Function Function GetAncestors(_child As Short) Dim Child As Short = _child Dim Parent As Short = 0 For Each Prime In Primes If Child = 1 Then Exit For End If While Child Mod Prime = 0 Child /= Prime Parent += Prime End While Next If Parent = _child Or _child = 1 Then Return Nothing End If GetAncestors(Parent) Ancestors.Add(Parent) Return Nothing End Function Function PrintDescendants(_index As Integer) If Children(_index).pLower Then PrintDescendants(Children(_index).pLower) End If Print(1, Delimiter.ToString & Children(_index).Child.ToString) Delimiter = ", " If Children(_index).pHigher Then PrintDescendants(Children(_index).pHigher) End If Return Nothing End Function Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean Dim Value As Integer = 3 Dim Max As Integer Dim Prime As Integer If _maxPrime < 2 Then Return vbFalse End If _primes.Add(2) While Value <= _maxPrime Max = Floor(Sqrt(Value)) For Each Prime In _primes If Prime > Max Then _primes.Add(Value) Exit For End If If Value Mod Prime = 0 Then Exit For End If Next Value += 2 End While Return vbTrue End Function End Module
package main import ( "fmt" "sort" ) func getPrimes(max int) []int { if max < 2 { return []int{} } lprimes := []int{2} outer: for x := 3; x <= max; x += 2 { for _, p := range lprimes { if x%p == 0 { continue outer } } lprimes = append(lprimes, x) } return lprimes } func main() { const maxSum = 99 descendants := make([][]int64, maxSum+1) ancestors := make([][]int, maxSum+1) for i := 0; i <= maxSum; i++ { descendants[i] = []int64{} ancestors[i] = []int{} } primes := getPrimes(maxSum) for _, p := range primes { descendants[p] = append(descendants[p], int64(p)) for s := 1; s < len(descendants)-p; s++ { temp := make([]int64, len(descendants[s])) for i := 0; i < len(descendants[s]); i++ { temp[i] = int64(p) * descendants[s][i] } descendants[s+p] = append(descendants[s+p], temp...) } } for _, p := range append(primes, 4) { le := len(descendants[p]) if le == 0 { continue } descendants[p][le-1] = 0 descendants[p] = descendants[p][:le-1] } total := 0 for s := 1; s <= maxSum; s++ { x := descendants[s] sort.Slice(x, func(i, j int) bool { return x[i] < x[j] }) total += len(descendants[s]) index := 0 for ; index < len(descendants[s]); index++ { if descendants[s][index] > int64(maxSum) { break } } for _, d := range descendants[s][:index] { ancestors[d] = append(ancestors[s], s) } if (s >= 21 && s <= 45) || (s >= 47 && s <= 73) || (s >= 75 && s < maxSum) { continue } temp := fmt.Sprintf("%v", ancestors[s]) fmt.Printf("%2d: %d Ancestor(s): %-14s", s, len(ancestors[s]), temp) le := len(descendants[s]) if le <= 10 { fmt.Printf("%5d Descendant(s): %v\n", le, descendants[s]) } else { fmt.Printf("%5d Descendant(s): %v\b ...]\n", le, descendants[s][:10]) } } fmt.Println("\nTotal descendants", total) }
Generate an equivalent Go version of this VB code.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
package main import "fmt" type pair [2]int func cart2(a, b []int) []pair { p := make([]pair, len(a)*len(b)) i := 0 for _, a := range a { for _, b := range b { p[i] = pair{a, b} i++ } } return p } func main() { fmt.Println(cart2([]int{1, 2}, []int{3, 4})) fmt.Println(cart2([]int{3, 4}, []int{1, 2})) fmt.Println(cart2([]int{1, 2}, nil)) fmt.Println(cart2(nil, []int{1, 2})) }
Generate a Go translation of this VB snippet without changing its computational steps.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
package main import "fmt" type pair [2]int func cart2(a, b []int) []pair { p := make([]pair, len(a)*len(b)) i := 0 for _, a := range a { for _, b := range b { p[i] = pair{a, b} i++ } } return p } func main() { fmt.Println(cart2([]int{1, 2}, []int{3, 4})) fmt.Println(cart2([]int{3, 4}, []int{1, 2})) fmt.Println(cart2([]int{1, 2}, nil)) fmt.Println(cart2(nil, []int{1, 2})) }
Keep all operations the same but rewrite the snippet in Go.
dim _proper_divisors(100) sub proper_divisors(n) dim i dim _proper_divisors_count = 0 if n <> 1 then for i = 1 to (n \ 2) if n %% i = 0 then _proper_divisors_count = _proper_divisors_count + 1 _proper_divisors(_proper_divisors_count) = i end if next end if return _proper_divisors_count end sub sub show_proper_divisors(n, tabbed) dim cnt = proper_divisors(n) print str$(n) + ":"; tab(4);"(" + str$(cnt) + " items) "; dim j for j = 1 to cnt if tabbed then print str$(_proper_divisors(j)), else print str$(_proper_divisors(j)); end if if (j < cnt) then print ","; next print end sub dim i for i = 1 to 10 show_proper_divisors(i, false) next dim c dim maxindex = 0 dim maxlength = 0 for t = 1 to 20000 c = proper_divisors(t) if c > maxlength then maxindex = t maxlength = c end if next print "A maximum at "; show_proper_divisors(maxindex, false)
package main import ( "fmt" "strconv" ) func listProperDivisors(limit int) { if limit < 1 { return } width := len(strconv.Itoa(limit)) for i := 1; i <= limit; i++ { fmt.Printf("%*d -> ", width, i) if i == 1 { fmt.Println("(None)") continue } for j := 1; j <= i/2; j++ { if i%j == 0 { fmt.Printf(" %d", j) } } fmt.Println() } } func countProperDivisors(n int) int { if n < 2 { return 0 } count := 0 for i := 1; i <= n/2; i++ { if n%i == 0 { count++ } } return count } func main() { fmt.Println("The proper divisors of the following numbers are :\n") listProperDivisors(10) fmt.Println() maxCount := 0 most := []int{1} for n := 2; n <= 20000; n++ { count := countProperDivisors(n) if count == maxCount { most = append(most, n) } else if count > maxCount { maxCount = count most = most[0:1] most[0] = n } } fmt.Print("The following number(s) <= 20000 have the most proper divisors, ") fmt.Println("namely", maxCount, "\b\n") for _, n := range most { fmt.Println(n) } }
Change the following VB code into Go without altering its purpose.
Module XMLOutput Sub Main() Dim charRemarks As New Dictionary(Of String, String) charRemarks.Add("April", "Bubbly: I charRemarks.Add("Tam O charRemarks.Add("Emily", "Short & shrift") Dim xml = <CharacterRemarks> <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %> </CharacterRemarks> Console.WriteLine(xml) End Sub End Module
package main import ( "encoding/xml" "fmt" ) func xRemarks(r CharacterRemarks) (string, error) { b, err := xml.MarshalIndent(r, "", " ") return string(b), err } type CharacterRemarks struct { Character []crm } type crm struct { Name string `xml:"name,attr"` Remark string `xml:",chardata"` } func main() { x, err := xRemarks(CharacterRemarks{[]crm{ {`April`, `Bubbly: I'm > Tam and <= Emily`}, {`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`}, {`Emily`, `Short & shrift`}, }}) if err != nil { x = err.Error() } fmt.Println(x) }
Change the programming language of this snippet from VB to Go without modifying what it does.
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlLine .HasLegend = False .HasTitle = True .ChartTitle.Text = "Time" .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(1).Values = y .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds" End With End Sub Public Sub main() x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}] y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}] plot_coordinate_pairs x, y End Sub
package main import ( "fmt" "log" "os/exec" ) var ( x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0} ) func main() { g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() if err != nil { log.Fatal(err) } if err = g.Start(); err != nil { log.Fatal(err) } fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d %f\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
Produce a functionally identical Go code for the snippet given in VB.
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlLine .HasLegend = False .HasTitle = True .ChartTitle.Text = "Time" .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(1).Values = y .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds" End With End Sub Public Sub main() x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}] y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}] plot_coordinate_pairs x, y End Sub
package main import ( "fmt" "log" "os/exec" ) var ( x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0} ) func main() { g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() if err != nil { log.Fatal(err) } if err = g.Start(); err != nil { log.Fatal(err) } fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d %f\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
Produce a language-to-language conversion: from VB to Go, same semantics.
text = "I need more coffee!!!" Set regex = New RegExp regex.Global = True regex.Pattern = "\s" If regex.Test(text) Then WScript.StdOut.Write regex.Replace(text,vbCrLf) Else WScript.StdOut.Write "No matching pattern" End If
package main import "fmt" import "regexp" func main() { str := "I am the original string" matched, _ := regexp.MatchString(".*string$", str) if matched { fmt.Println("ends with 'string'") } pattern := regexp.MustCompile("original") result := pattern.ReplaceAllString(str, "modified") fmt.Println(result) }
Can you help me rewrite this code in Go instead of VB, keeping it the same logically?
text = "I need more coffee!!!" Set regex = New RegExp regex.Global = True regex.Pattern = "\s" If regex.Test(text) Then WScript.StdOut.Write regex.Replace(text,vbCrLf) Else WScript.StdOut.Write "No matching pattern" End If
package main import "fmt" import "regexp" func main() { str := "I am the original string" matched, _ := regexp.MatchString(".*string$", str) if matched { fmt.Println("ends with 'string'") } pattern := regexp.MustCompile("original") result := pattern.ReplaceAllString(str, "modified") fmt.Println(result) }
Rewrite this program in Go while keeping its functionality equivalent to the VB version.
Set dict = CreateObject("Scripting.Dictionary") os = Array("Windows", "Linux", "MacOS") owner = Array("Microsoft", "Linus Torvalds", "Apple") For n = 0 To 2 dict.Add os(n), owner(n) Next MsgBox dict.Item("Linux") MsgBox dict.Item("MacOS") MsgBox dict.Item("Windows")
package main import "fmt" func main() { keys := []string{"a", "b", "c"} vals := []int{1, 2, 3} hash := map[string]int{} for i, key := range keys { hash[key] = vals[i] } fmt.Println(hash) }
Port the following code from VB to Go with equivalent syntax and logic.
Public Class Main Inherits System.Windows.Forms.Form Public Sub New() Me.FormBorderStyle = FormBorderStyle.None Me.WindowState = FormWindowState.Maximized End Sub Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load Dim Index As Integer Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White} Dim Height = (Me.ClientSize.Height / 4) + 1 For y = 1 To 4 Dim Top = Me.ClientSize.Height / 4 * (y - 1) For x = 0 To Me.ClientSize.Width Step y If Index = 6 Then Index = 0 Else Index += 1 Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)}) Next Next End Sub End Class
package main import "github.com/fogleman/gg" var palette = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func pinstripe(dc *gg.Context) { w := dc.Width() h := dc.Height() / 4 for b := 1; b <= 4; b++ { for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 { dc.SetHexColor(palette[ci%8]) y := h * (b - 1) dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h)) dc.Fill() } } } func main() { dc := gg.NewContext(900, 600) pinstripe(dc) dc.SavePNG("color_pinstripe.png") }
Produce a language-to-language conversion: from VB to Go, same semantics.
Function cocktailShakerSort(ByVal A As Variant) As Variant beginIdx = LBound(A) endIdx = UBound(A) - 1 Do While beginIdx <= endIdx newBeginIdx = endIdx newEndIdx = beginIdx For ii = beginIdx To endIdx If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newEndIdx = ii End If Next ii endIdx = newEndIdx - 1 For ii = endIdx To beginIdx Step -1 If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newBeginIdx = ii End If Next ii beginIdx = newBeginIdx + 1 Loop cocktailShakerSort = A End Function Public Sub main() Dim B(20) As Variant For i = LBound(B) To UBound(B) B(i) = Int(Rnd() * 100) Next i Debug.Print Join(B, ", ") Debug.Print Join(cocktailShakerSort(B), ", ") End Sub
package main import ( "fmt" "math/rand" "time" ) func cocktailShakerSort(a []int) { var begin = 0 var end = len(a) - 2 for begin <= end { newBegin := end newEnd := begin for i := begin; i <= end; i++ { if a[i] > a[i+1] { a[i+1], a[i] = a[i], a[i+1] newEnd = i } } end = newEnd - 1 for i := end; i >= begin; i-- { if a[i] > a[i+1] { a[i+1], a[i] = a[i], a[i+1] newBegin = i } } begin = newBegin + 1 } } func cocktailSort(a []int) { last := len(a) - 1 for { swapped := false for i := 0; i < last; i++ { if a[i] > a[i+1] { a[i], a[i+1] = a[i+1], a[i] swapped = true } } if !swapped { return } swapped = false for i := last - 1; i >= 0; i-- { if a[i] > a[i+1] { a[i], a[i+1] = a[i+1], a[i] swapped = true } } if !swapped { return } } } func main() { a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170} fmt.Println("Original array:", a) b := make([]int, len(a)) copy(b, a) cocktailSort(a) fmt.Println("Cocktail sort :", a) cocktailShakerSort(b) fmt.Println("C/Shaker sort :", b) rand.Seed(time.Now().UnixNano()) fmt.Println("\nRelative speed of the two sorts") fmt.Println(" N x faster (CSS v CS)") fmt.Println("----- -------------------") const runs = 10 for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} { sum := 0.0 for i := 1; i <= runs; i++ { nums := make([]int, n) for i := 0; i < n; i++ { rn := rand.Intn(100000) if i%2 == 1 { rn = -rn } nums[i] = rn } nums2 := make([]int, n) copy(nums2, nums) start := time.Now() cocktailSort(nums) elapsed := time.Since(start) start2 := time.Now() cocktailShakerSort(nums2) elapsed2 := time.Since(start2) sum += float64(elapsed) / float64(elapsed2) } fmt.Printf(" %2dk %0.3f\n", n/1000, sum/runs) } }
Please provide an equivalent version of this VB code in Go.
Function cocktailShakerSort(ByVal A As Variant) As Variant beginIdx = LBound(A) endIdx = UBound(A) - 1 Do While beginIdx <= endIdx newBeginIdx = endIdx newEndIdx = beginIdx For ii = beginIdx To endIdx If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newEndIdx = ii End If Next ii endIdx = newEndIdx - 1 For ii = endIdx To beginIdx Step -1 If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newBeginIdx = ii End If Next ii beginIdx = newBeginIdx + 1 Loop cocktailShakerSort = A End Function Public Sub main() Dim B(20) As Variant For i = LBound(B) To UBound(B) B(i) = Int(Rnd() * 100) Next i Debug.Print Join(B, ", ") Debug.Print Join(cocktailShakerSort(B), ", ") End Sub
package main import ( "fmt" "math/rand" "time" ) func cocktailShakerSort(a []int) { var begin = 0 var end = len(a) - 2 for begin <= end { newBegin := end newEnd := begin for i := begin; i <= end; i++ { if a[i] > a[i+1] { a[i+1], a[i] = a[i], a[i+1] newEnd = i } } end = newEnd - 1 for i := end; i >= begin; i-- { if a[i] > a[i+1] { a[i+1], a[i] = a[i], a[i+1] newBegin = i } } begin = newBegin + 1 } } func cocktailSort(a []int) { last := len(a) - 1 for { swapped := false for i := 0; i < last; i++ { if a[i] > a[i+1] { a[i], a[i+1] = a[i+1], a[i] swapped = true } } if !swapped { return } swapped = false for i := last - 1; i >= 0; i-- { if a[i] > a[i+1] { a[i], a[i+1] = a[i+1], a[i] swapped = true } } if !swapped { return } } } func main() { a := []int{21, 4, -9, 62, -7, 107, -62, 4, 0, -170} fmt.Println("Original array:", a) b := make([]int, len(a)) copy(b, a) cocktailSort(a) fmt.Println("Cocktail sort :", a) cocktailShakerSort(b) fmt.Println("C/Shaker sort :", b) rand.Seed(time.Now().UnixNano()) fmt.Println("\nRelative speed of the two sorts") fmt.Println(" N x faster (CSS v CS)") fmt.Println("----- -------------------") const runs = 10 for _, n := range []int{1000, 2000, 4000, 8000, 10000, 20000} { sum := 0.0 for i := 1; i <= runs; i++ { nums := make([]int, n) for i := 0; i < n; i++ { rn := rand.Intn(100000) if i%2 == 1 { rn = -rn } nums[i] = rn } nums2 := make([]int, n) copy(nums2, nums) start := time.Now() cocktailSort(nums) elapsed := time.Since(start) start2 := time.Now() cocktailShakerSort(nums2) elapsed2 := time.Since(start2) sum += float64(elapsed) / float64(elapsed2) } fmt.Printf(" %2dk %0.3f\n", n/1000, sum/runs) } }
Preserve the algorithm and functionality while converting the code from VB to Go.
option explicit const dt = 0.15 const length=23 dim ans0:ans0=chr(27)&"[" dim Veloc,Accel,angle,olr,olc,r,c const r0=1 const c0=40 cls angle=0.7 while 1 wscript.sleep(50) Accel = -.9 * sin(Angle) Veloc = Veloc + Accel * dt Angle = Angle + Veloc * dt r = r0 + int(cos(Angle) * Length) c = c0+ int(2*sin(Angle) * Length) cls draw_line r,c,r0,c0 toxy r,c,"O" olr=r :olc=c wend sub cls() wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub sub toxy(r,c,s) wscript.StdOut.Write ans0 & r & ";" & c & "f" & s :end sub Sub draw_line(r1,c1, r2,c2) Dim x,y,xf,yf,dx,dy,sx,sy,err,err2 x =r1 : y =c1 xf=r2 : yf=c2 dx=Abs(xf-x) : dy=Abs(yf-y) If x<xf Then sx=+1: Else sx=-1 If y<yf Then sy=+1: Else sy=-1 err=dx-dy Do toxy x,y,"." If x=xf And y=yf Then Exit Do err2=err+err If err2>-dy Then err=err-dy: x=x+sx If err2< dx Then err=err+dx: y=y+sy Loop End Sub
package main import ( "github.com/google/gxui" "github.com/google/gxui/drivers/gl" "github.com/google/gxui/math" "github.com/google/gxui/themes/dark" omath "math" "time" ) const ( ANIMATION_WIDTH int = 480 ANIMATION_HEIGHT int = 320 BALL_RADIUS float32 = 25.0 METER_PER_PIXEL float64 = 1.0 / 20.0 PHI_ZERO float64 = omath.Pi * 0.5 ) var ( l float64 = float64(ANIMATION_HEIGHT) * 0.5 freq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL)) ) type Pendulum interface { GetPhi() float64 } type mathematicalPendulum struct { start time.Time } func (p *mathematicalPendulum) GetPhi() float64 { if (p.start == time.Time{}) { p.start = time.Now() } t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9) return PHI_ZERO * omath.Cos(t*freq) } type numericalPendulum struct { currentPhi float64 angAcc float64 angVel float64 lastTime time.Time } func (p *numericalPendulum) GetPhi() float64 { dt := 0.0 if (p.lastTime != time.Time{}) { dt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9) } p.lastTime = time.Now() p.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi) p.angVel += p.angAcc * dt p.currentPhi += p.angVel * dt return p.currentPhi } func draw(p Pendulum, canvas gxui.Canvas, x, y int) { attachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y} phi := p.GetPhi() ball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))} line := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}} canvas.DrawLines(line, gxui.DefaultPen) m := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)} rect := math.Rect{ball.Sub(m), ball.Add(m)} canvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow)) } func appMain(driver gxui.Driver) { theme := dark.CreateTheme(driver) window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum") window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50)) image := theme.CreateImage() ticker := time.NewTicker(time.Millisecond * 15) pendulum := &mathematicalPendulum{} pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}} go func() { for _ = range ticker.C { canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT}) canvas.Clear(gxui.White) draw(pendulum, canvas, 0, 0) draw(pendulum2, canvas, 0, ANIMATION_HEIGHT) canvas.Complete() driver.Call(func() { image.SetCanvas(canvas) }) } }() window.AddChild(image) window.OnClose(ticker.Stop) window.OnClose(driver.Terminate) } func main() { gl.StartDriver(appMain) }
Produce a functionally identical Go code for the snippet given in VB.
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
Maintain the same structure and functionality when rewriting this code in Go.
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
Ensure the translated Go code behaves exactly like the original VB snippet.
class playingcard dim suit dim pips end class class carddeck private suitnames private pipnames private cardno private deck(52) private nTop sub class_initialize dim suit dim pips suitnames = split("H,D,C,S",",") pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",") cardno = 0 for suit = 1 to 4 for pips = 1 to 13 set deck(cardno) = new playingcard deck(cardno).suit = suitnames(suit-1) deck(cardno).pips = pipnames(pips-1) cardno = cardno + 1 next next nTop = 0 end sub public sub showdeck dim a redim a(51-nTop) for i = nTop to 51 a(i) = deck(i).pips & deck(i).suit next wscript.echo join( a, ", ") end sub public sub shuffle dim r randomize timer for i = nTop to 51 r = int( rnd * ( 52 - nTop ) ) if r <> i then objswap deck(i),deck(r) end if next end sub public function deal() set deal = deck( nTop ) nTop = nTop + 1 end function public property get cardsRemaining cardsRemaining = 52 - nTop end property private sub objswap( a, b ) dim tmp set tmp = a set a = b set b = tmp end sub end class
package cards import ( "math/rand" ) type Suit uint8 const ( Spade Suit = 3 Heart Suit = 2 Diamond Suit = 1 Club Suit = 0 ) func (s Suit) String() string { const suites = "CDHS" return suites[s : s+1] } type Rank uint8 const ( Ace Rank = 1 Two Rank = 2 Three Rank = 3 Four Rank = 4 Five Rank = 5 Six Rank = 6 Seven Rank = 7 Eight Rank = 8 Nine Rank = 9 Ten Rank = 10 Jack Rank = 11 Queen Rank = 12 King Rank = 13 ) func (r Rank) String() string { const ranks = "A23456789TJQK" return ranks[r-1 : r] } type Card uint8 func NewCard(r Rank, s Suit) Card { return Card(13*uint8(s) + uint8(r-1)) } func (c Card) RankSuit() (Rank, Suit) { return Rank(c%13 + 1), Suit(c / 13) } func (c Card) Rank() Rank { return Rank(c%13 + 1) } func (c Card) Suit() Suit { return Suit(c / 13) } func (c Card) String() string { return c.Rank().String() + c.Suit().String() } type Deck []Card func NewDeck() Deck { d := make(Deck, 52) for i := range d { d[i] = Card(i) } return d } func (d Deck) String() string { s := "" for i, c := range d { switch { case i == 0: case i%13 == 0: s += "\n" default: s += " " } s += c.String() } return s } func (d Deck) Shuffle() { for i := range d { j := rand.Intn(i + 1) d[i], d[j] = d[j], d[i] } } func (d Deck) Contains(tc Card) bool { for _, c := range d { if c == tc { return true } } return false } func (d *Deck) AddDeck(decks ...Deck) { for _, o := range decks { *d = append(*d, o...) } } func (d *Deck) AddCard(c Card) { *d = append(*d, c) } func (d *Deck) Draw(n int) Deck { old := *d *d = old[n:] return old[:n:n] } func (d *Deck) DrawCard() (Card, bool) { if len(*d) == 0 { return 0, false } old := *d *d = old[1:] return old[0], true } func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) { for i := 0; i < cards; i++ { for j := range hands { if len(*d) == 0 { return hands, false } hands[j] = append(hands[j], (*d)[0]) *d = (*d)[1:] } } return hands, true }