Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write a version of this Python function in Go with identical behavior.
def isExt(fileName, extensions): return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
Convert this Python block to Go, preserving its control flow and logic.
from __future__ import division, print_function from itertools import permutations, combinations, product, \ chain from pprint import pprint as pp from fractions import Fraction as F import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input from itertools import izip_longest as zip_longest else: from itertools import zip_longest def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def ask4(): 'get four random digits >0 from the player' digits = '' while len(digits) != 4 or not all(d in '123456789' for d in digits): digits = input('Enter the digits to solve for: ') digits = ''.join(digits.strip().split()) return list(digits) def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def solve(digits): digilen = len(digits) exprlen = 2 * digilen - 1 digiperm = sorted(set(permutations(digits))) opcomb = list(product('+-*/', repeat=digilen-1)) brackets = ( [()] + [(x,y) for x in range(0, exprlen, 2) for y in range(x+4, exprlen+2, 2) if (x,y) != (0,exprlen+1)] + [(0, 3+1, 4+2, 7+3)] ) for d in digiperm: for ops in opcomb: if '/' in ops: d2 = [('F(%s)' % i) for i in d] else: d2 = d ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue=''))) for b in brackets: exp = ex[::] for insertpoint, bracket in zip(b, '()'*(len(b)//2)): exp.insert(insertpoint, bracket) txt = ''.join(exp) try: num = eval(txt) except ZeroDivisionError: continue if num == 24: if '/' in ops: exp = [ (term if not term.startswith('F(') else term[2]) for term in exp ] ans = ' '.join(exp).rstrip() print ("Solution found:",ans) return ans print ("No solution found for:", ' '.join(digits)) return '!' def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer == '?': solve(digits) answer = '!' if answer.lower() == 'q': break if answer == '!': digits = choose4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if answer == '!!': digits = ask4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: if '/' in answer: answer = ''.join( (('F(%s)' % char) if char in '123456789' else char) for char in answer ) ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") main()
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op == op_num { return fmt.Sprintf("%d", x.value.num) } var bl1, br1, bl2, br2, opstr string switch { case x.left.op == op_num: case x.left.op >= x.op: case x.left.op == op_add && x.op == op_sub: bl1, br1 = "", "" default: bl1, br1 = "(", ")" } if x.right.op == op_num || x.op < x.right.op { bl2, br2 = "", "" } else { bl2, br2 = "(", ")" } switch { case x.op == op_add: opstr = " + " case x.op == op_sub: opstr = " - " case x.op == op_mul: opstr = " * " case x.op == op_div: opstr = " / " } return bl1 + x.left.String() + br1 + opstr + bl2 + x.right.String() + br2 } func expr_eval(x *Expr) (f frac) { if x.op == op_num { return x.value } l, r := expr_eval(x.left), expr_eval(x.right) switch x.op { case op_add: f.num = l.num*r.denom + l.denom*r.num f.denom = l.denom * r.denom return case op_sub: f.num = l.num*r.denom - l.denom*r.num f.denom = l.denom * r.denom return case op_mul: f.num = l.num * r.num f.denom = l.denom * r.denom return case op_div: f.num = l.num * r.denom f.denom = l.denom * r.num return } return } func solve(ex_in []*Expr) bool { if len(ex_in) == 1 { f := expr_eval(ex_in[0]) if f.denom != 0 && f.num == f.denom*goal { fmt.Println(ex_in[0].String()) return true } return false } var node Expr ex := make([]*Expr, len(ex_in)-1) for i := range ex { copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)]) ex[i] = &node for j := i + 1; j < len(ex_in); j++ { node.left = ex_in[i] node.right = ex_in[j] for o := op_add; o <= op_div; o++ { node.op = o if solve(ex) { return true } } node.left = ex_in[j] node.right = ex_in[i] node.op = op_sub if solve(ex) { return true } node.op = op_div if solve(ex) { return true } if j < len(ex) { ex[j] = ex_in[j] } } ex[i] = ex_in[i] } return false } func main() { cards := make([]*Expr, n_cards) rand.Seed(time.Now().Unix()) for k := 0; k < 10; k++ { for i := 0; i < n_cards; i++ { cards[i] = &Expr{op_num, nil, nil, frac{rand.Intn(digit_range-1) + 1, 1}} fmt.Printf(" %d", cards[i].value.num) } fmt.Print(": ") if !solve(cards) { fmt.Println("No solution") } } }
Maintain the same structure and functionality when rewriting this code in Go.
from __future__ import division, print_function from itertools import permutations, combinations, product, \ chain from pprint import pprint as pp from fractions import Fraction as F import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input from itertools import izip_longest as zip_longest else: from itertools import zip_longest def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def ask4(): 'get four random digits >0 from the player' digits = '' while len(digits) != 4 or not all(d in '123456789' for d in digits): digits = input('Enter the digits to solve for: ') digits = ''.join(digits.strip().split()) return list(digits) def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def solve(digits): digilen = len(digits) exprlen = 2 * digilen - 1 digiperm = sorted(set(permutations(digits))) opcomb = list(product('+-*/', repeat=digilen-1)) brackets = ( [()] + [(x,y) for x in range(0, exprlen, 2) for y in range(x+4, exprlen+2, 2) if (x,y) != (0,exprlen+1)] + [(0, 3+1, 4+2, 7+3)] ) for d in digiperm: for ops in opcomb: if '/' in ops: d2 = [('F(%s)' % i) for i in d] else: d2 = d ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue=''))) for b in brackets: exp = ex[::] for insertpoint, bracket in zip(b, '()'*(len(b)//2)): exp.insert(insertpoint, bracket) txt = ''.join(exp) try: num = eval(txt) except ZeroDivisionError: continue if num == 24: if '/' in ops: exp = [ (term if not term.startswith('F(') else term[2]) for term in exp ] ans = ' '.join(exp).rstrip() print ("Solution found:",ans) return ans print ("No solution found for:", ' '.join(digits)) return '!' def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer == '?': solve(digits) answer = '!' if answer.lower() == 'q': break if answer == '!': digits = choose4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if answer == '!!': digits = ask4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: if '/' in answer: answer = ''.join( (('F(%s)' % char) if char in '123456789' else char) for char in answer ) ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") main()
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op == op_num { return fmt.Sprintf("%d", x.value.num) } var bl1, br1, bl2, br2, opstr string switch { case x.left.op == op_num: case x.left.op >= x.op: case x.left.op == op_add && x.op == op_sub: bl1, br1 = "", "" default: bl1, br1 = "(", ")" } if x.right.op == op_num || x.op < x.right.op { bl2, br2 = "", "" } else { bl2, br2 = "(", ")" } switch { case x.op == op_add: opstr = " + " case x.op == op_sub: opstr = " - " case x.op == op_mul: opstr = " * " case x.op == op_div: opstr = " / " } return bl1 + x.left.String() + br1 + opstr + bl2 + x.right.String() + br2 } func expr_eval(x *Expr) (f frac) { if x.op == op_num { return x.value } l, r := expr_eval(x.left), expr_eval(x.right) switch x.op { case op_add: f.num = l.num*r.denom + l.denom*r.num f.denom = l.denom * r.denom return case op_sub: f.num = l.num*r.denom - l.denom*r.num f.denom = l.denom * r.denom return case op_mul: f.num = l.num * r.num f.denom = l.denom * r.denom return case op_div: f.num = l.num * r.denom f.denom = l.denom * r.num return } return } func solve(ex_in []*Expr) bool { if len(ex_in) == 1 { f := expr_eval(ex_in[0]) if f.denom != 0 && f.num == f.denom*goal { fmt.Println(ex_in[0].String()) return true } return false } var node Expr ex := make([]*Expr, len(ex_in)-1) for i := range ex { copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)]) ex[i] = &node for j := i + 1; j < len(ex_in); j++ { node.left = ex_in[i] node.right = ex_in[j] for o := op_add; o <= op_div; o++ { node.op = o if solve(ex) { return true } } node.left = ex_in[j] node.right = ex_in[i] node.op = op_sub if solve(ex) { return true } node.op = op_div if solve(ex) { return true } if j < len(ex) { ex[j] = ex_in[j] } } ex[i] = ex_in[i] } return false } func main() { cards := make([]*Expr, n_cards) rand.Seed(time.Now().Unix()) for k := 0; k < 10; k++ { for i := 0; i < n_cards; i++ { cards[i] = &Expr{op_num, nil, nil, frac{rand.Intn(digit_range-1) + 1, 1}} fmt.Printf(" %d", cards[i].value.num) } fmt.Print(": ") if !solve(cards) { fmt.Println("No solution") } } }
Translate the given Python code snippet into Go without altering its behavior.
import threading import time import random def worker(workernum, barrier): sleeptime = random.random() print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum)) barrier.wait() sleeptime = random.random() print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum)) barrier = threading.Barrier(3) w1 = threading.Thread(target=worker, args=((1,barrier))) w2 = threading.Thread(target=worker, args=((2,barrier))) w3 = threading.Thread(target=worker, args=((3,barrier))) w1.start() w2.start() w3.start()
package main import ( "log" "math/rand" "sync" "time" ) func worker(part string) { log.Println(part, "worker begins part") time.Sleep(time.Duration(rand.Int63n(1e6))) log.Println(part, "worker completes part") wg.Done() } var ( partList = []string{"A", "B", "C", "D"} nAssemblies = 3 wg sync.WaitGroup ) func main() { rand.Seed(time.Now().UnixNano()) for c := 1; c <= nAssemblies; c++ { log.Println("begin assembly cycle", c) wg.Add(len(partList)) for _, part := range partList { go worker(part) } wg.Wait() log.Println("assemble. cycle", c, "complete") } }
Translate this program into Go but keep the logic exactly as in Python.
import threading import time import random def worker(workernum, barrier): sleeptime = random.random() print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum)) barrier.wait() sleeptime = random.random() print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum)) barrier = threading.Barrier(3) w1 = threading.Thread(target=worker, args=((1,barrier))) w2 = threading.Thread(target=worker, args=((2,barrier))) w3 = threading.Thread(target=worker, args=((3,barrier))) w1.start() w2.start() w3.start()
package main import ( "log" "math/rand" "sync" "time" ) func worker(part string) { log.Println(part, "worker begins part") time.Sleep(time.Duration(rand.Int63n(1e6))) log.Println(part, "worker completes part") wg.Done() } var ( partList = []string{"A", "B", "C", "D"} nAssemblies = 3 wg sync.WaitGroup ) func main() { rand.Seed(time.Now().UnixNano()) for c := 1; c <= nAssemblies; c++ { log.Println("begin assembly cycle", c) wg.Add(len(partList)) for _, part := range partList { go worker(part) } wg.Wait() log.Println("assemble. cycle", c, "complete") } }
Port the following code from Python to Go with equivalent syntax and logic.
def tobits(n, _group=8, _sep='_', _pad=False): 'Express n as binary bits with separator' bits = '{0:b}'.format(n)[::-1] if _pad: bits = '{0:0{1}b}'.format(n, ((_group+len(bits)-1)//_group)*_group)[::-1] answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] answer = '0'*(len(_sep)-1) + answer else: answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] return answer def tovlq(n): return tobits(n, _group=7, _sep='1_', _pad=True) def toint(vlq): return int(''.join(vlq.split('_1')), 2) def vlqsend(vlq): for i, byte in enumerate(vlq.split('_')[::-1]): print('Sent byte {0:3}: {1:
package main import ( "fmt" "encoding/binary" ) func main() { buf := make([]byte, binary.MaxVarintLen64) for _, x := range []int64{0x200000, 0x1fffff} { v := buf[:binary.PutVarint(buf, x)] fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v) x, _ = binary.Varint(v) fmt.Println(x, "decoded") } }
Convert this Python snippet to Go and keep its semantics consistent.
import pyaudio chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 p = pyaudio.PyAudio() stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) data = stream.read(chunk) print [ord(i) for i in data]
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) name := "" for name == "" { fmt.Print("Enter output file name (without extension) : ") scanner.Scan() name = scanner.Text() check(scanner.Err()) } name += ".wav" rate := 0 for rate < 2000 || rate > 192000 { fmt.Print("Enter sampling rate in Hz (2000 to 192000) : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) rate, _ = strconv.Atoi(input) } rateS := strconv.Itoa(rate) dur := 0.0 for dur < 5 || dur > 30 { fmt.Print("Enter duration in seconds (5 to 30)  : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) dur, _ = strconv.ParseFloat(input, 64) } durS := strconv.FormatFloat(dur, 'f', -1, 64) fmt.Println("OK, start speaking now...") args := []string{"-r", rateS, "-f", "S16_LE", "-d", durS, name} cmd := exec.Command("arecord", args...) err := cmd.Run() check(err) fmt.Printf("'%s' created on disk and will now be played back...\n", name) cmd = exec.Command("aplay", name) err = cmd.Run() check(err) fmt.Println("Play-back completed.") }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
import argh import hashlib import sys @argh.arg('filename', nargs='?', default=None) def main(filename, block_size=1024*1024): if filename: fin = open(filename, 'rb') else: fin = sys.stdin stack = [] block = fin.read(block_size) while block: node = (0, hashlib.sha256(block).digest()) stack.append(node) while len(stack) >= 2 and stack[-2][0] == stack[-1][0]: a = stack[-2] b = stack[-1] l = a[0] stack[-2:] = [(l+1, hashlib.sha256(a[1] + b[1]).digest())] block = fin.read(block_size) while len(stack) > 1: a = stack[-2] b = stack[-1] al = a[0] bl = b[0] stack[-2:] = [(max(al, bl)+1, hashlib.sha256(a[1] + b[1]).digest())] print(stack[0][1].hex()) argh.dispatch_command(main)
package main import ( "crypto/sha256" "fmt" "io" "log" "os" ) func main() { const blockSize = 1024 f, err := os.Open("title.png") if err != nil { log.Fatal(err) } defer f.Close() var hashes [][]byte buffer := make([]byte, blockSize) h := sha256.New() for { bytesRead, err := f.Read(buffer) if err != nil { if err != io.EOF { log.Fatal(err) } break } h.Reset() h.Write(buffer[:bytesRead]) hashes = append(hashes, h.Sum(nil)) } buffer = make([]byte, 64) for len(hashes) > 1 { var hashes2 [][]byte for i := 0; i < len(hashes); i += 2 { if i < len(hashes)-1 { copy(buffer, hashes[i]) copy(buffer[32:], hashes[i+1]) h.Reset() h.Write(buffer) hashes2 = append(hashes2, h.Sum(nil)) } else { hashes2 = append(hashes2, hashes[i]) } } hashes = hashes2 } fmt.Printf("%x", hashes[0]) fmt.Println() }
Please provide an equivalent version of this Python code in Go.
s = "alphaBETA" print s.upper() print s.lower() print s.swapcase() print "fOo bAR".capitalize() print "fOo bAR".title() import string print string.capwords("fOo bAR")
package main import ( "fmt" "strings" "unicode" "unicode/utf8" ) func main() { show("alphaBETA") show("alpha BETA") show("DŽLjnj") show("o'hare O'HARE o’hare don't") } func show(s string) { fmt.Println("\nstring: ", s, " len:", utf8.RuneCountInString(s), "runes") fmt.Println("All upper case: ", strings.ToUpper(s)) fmt.Println("All lower case: ", strings.ToLower(s)) fmt.Println("All title case: ", strings.ToTitle(s)) fmt.Println("Title words: ", strings.Title(s)) fmt.Println("Swapping case: ", strings.Map(unicode.SimpleFold, s)) }
Convert this Python block to Go, preserving its control flow and logic.
from javax.swing import JOptionPane def to_int(n, default=0): try: return int(n) except ValueError: return default number = to_int(JOptionPane.showInputDialog ("Enter an Integer")) println(number) a_string = JOptionPane.showInputDialog ("Enter a String") println(a_string)
package main import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" ) func validateInput(window *gtk.Window, str1, str2 string) bool { n, err := strconv.ParseFloat(str2, 64) if len(str1) == 0 || err != nil || n != 75000 { dialog := gtk.MessageDialogNew( window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, "Invalid input", ) dialog.Run() dialog.Destroy() return false } return true } func check(err error, msg string) { if err != nil { log.Fatal(msg, err) } } func main() { rand.Seed(time.Now().UnixNano()) gtk.Init(nil) window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL) check(err, "Unable to create window:") window.SetTitle("Rosetta Code") window.SetPosition(gtk.WIN_POS_CENTER) window.Connect("destroy", func() { gtk.MainQuit() }) vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1) check(err, "Unable to create vertical box:") vbox.SetBorderWidth(1) hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create first horizontal box:") hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1) check(err, "Unable to create second horizontal box:") label, err := gtk.LabelNew("Enter a string and the number 75000 \n") check(err, "Unable to create label:") sel, err := gtk.LabelNew("String: ") check(err, "Unable to create string entry label:") nel, err := gtk.LabelNew("Number: ") check(err, "Unable to create number entry label:") se, err := gtk.EntryNew() check(err, "Unable to create string entry:") ne, err := gtk.EntryNew() check(err, "Unable to create number entry:") hbox1.PackStart(sel, false, false, 2) hbox1.PackStart(se, false, false, 2) hbox2.PackStart(nel, false, false, 2) hbox2.PackStart(ne, false, false, 2) ab, err := gtk.ButtonNewWithLabel("Accept") check(err, "Unable to create accept button:") ab.Connect("clicked", func() { str1, _ := se.GetText() str2, _ := ne.GetText() if validateInput(window, str1, str2) { window.Destroy() } }) vbox.Add(label) vbox.Add(hbox1) vbox.Add(hbox2) vbox.Add(ab) window.Add(vbox) window.ShowAll() gtk.Main() }
Write the same algorithm in Go as shown in this Python implementation.
t = { 'x': 20, 'y': 30, 'a': 60 } def setup(): size(450, 400) background(0, 0, 200) stroke(-1) sc(7, 400, -60) def sc(o, l, a, s = t, X = 'x', Y = 'y', A = 'a', HALF = .5): if o: o -= 1 l *= HALF sc(o, l, -a)[A] += a sc(o, l, a)[A] += a sc(o, l, -a) else: x, y = s[X], s[Y] s[X] += cos(radians(s[A])) * l s[Y] += sin(radians(s[A])) * l line(x, y, s[X], s[Y]) return s
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) iy = 1.0 theta = 0 ) var cx, cy, h float64 func arrowhead(order int, length float64) { if order&1 == 0 { curve(order, length, 60) } else { turn(60) curve(order, length, -60) } drawLine(length) } func drawLine(length float64) { dc.LineTo(cx-width/2+h, (height-cy)*iy+2*h) rads := gg.Radians(float64(theta)) cx += length * math.Cos(rads) cy += length * math.Sin(rads) } func turn(angle int) { theta = (theta + angle) % 360 } func curve(order int, length float64, angle int) { if order == 0 { drawLine(length) } else { curve(order-1, length/2, -angle) turn(angle) curve(order-1, length/2, angle) turn(angle) curve(order-1, length/2, -angle) } } func main() { dc.SetRGB(0, 0, 0) dc.Clear() order := 6 if order&1 == 0 { iy = -1 } cx, cy = width/2, height h = cx / 2 arrowhead(order, cx) dc.SetRGB255(255, 0, 255) dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("sierpinski_arrowhead_curve.png") }
Port the provided Python code into Go while preserving the original functionality.
import fileinput import sys nodata = 0; nodata_max=-1; nodata_maxline=[]; tot_file = 0 num_file = 0 infiles = sys.argv[1:] for line in fileinput.input(): tot_line=0; num_line=0; field = line.split() date = field[0] data = [float(f) for f in field[1::2]] flags = [int(f) for f in field[2::2]] for datum, flag in zip(data, flags): if flag<1: nodata += 1 else: if nodata_max==nodata and nodata>0: nodata_maxline.append(date) if nodata_max<nodata and nodata>0: nodata_max=nodata nodata_maxline=[date] nodata=0; tot_line += datum num_line += 1 tot_file += tot_line num_file += num_line print "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f" % ( date, len(data) -num_line, num_line, tot_line, tot_line/num_line if (num_line>0) else 0) print "" print "File(s) = %s" % (", ".join(infiles),) print "Total = %10.3f" % (tot_file,) print "Readings = %6i" % (num_file,) print "Average = %10.3f" % (tot_file / num_file,) print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % ( nodata_max, ", ".join(nodata_maxline))
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) const ( filename = "readings.txt" readings = 24 fields = readings*2 + 1 ) func main() { file, err := os.Open(filename) if err != nil { log.Fatal(err) } defer file.Close() var ( badRun, maxRun int badDate, maxDate string fileSum float64 fileAccept int ) endBadRun := func() { if badRun > maxRun { maxRun = badRun maxDate = badDate } badRun = 0 } s := bufio.NewScanner(file) for s.Scan() { f := strings.Fields(s.Text()) if len(f) != fields { log.Fatal("unexpected format,", len(f), "fields.") } var accept int var sum float64 for i := 1; i < fields; i += 2 { flag, err := strconv.Atoi(f[i+1]) if err != nil { log.Fatal(err) } if flag <= 0 { if badRun++; badRun == 1 { badDate = f[0] } } else { endBadRun() value, err := strconv.ParseFloat(f[i], 64) if err != nil { log.Fatal(err) } sum += value accept++ } } fmt.Printf("Line: %s Reject %2d Accept: %2d Line_tot:%9.3f", f[0], readings-accept, accept, sum) if accept > 0 { fmt.Printf(" Line_avg:%8.3f\n", sum/float64(accept)) } else { fmt.Println() } fileSum += sum fileAccept += accept } if err := s.Err(); err != nil { log.Fatal(err) } endBadRun() fmt.Println("\nFile =", filename) fmt.Printf("Total = %.3f\n", fileSum) fmt.Println("Readings = ", fileAccept) if fileAccept > 0 { fmt.Printf("Average =  %.3f\n", fileSum/float64(fileAccept)) } if maxRun == 0 { fmt.Println("\nAll data valid.") } else { fmt.Printf("\nMax data gap = %d, beginning on line %s.\n", maxRun, maxDate) } }
Rewrite the snippet below in Go so it works the same as the original Python code.
>>> import hashlib >>> >>> tests = ( (b"", 'd41d8cd98f00b204e9800998ecf8427e'), (b"a", '0cc175b9c0f1b6a831c399e269772661'), (b"abc", '900150983cd24fb0d6963f7d28e17f72'), (b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'), (b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'), (b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'), (b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') ) >>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden >>>
package main import ( "crypto/md5" "fmt" ) func main() { for _, p := range [][2]string{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"}, {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"}, {"d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" + "123456789012345678901234567890123456789012345678901234567890"}, {"e38ca1d920c4b8b8d3946b2c72f01680", "The quick brown fox jumped over the lazy dog's back"}, } { validate(p[0], p[1]) } } var h = md5.New() func validate(check, s string) { h.Reset() h.Write([]byte(s)) sum := fmt.Sprintf("%x", h.Sum(nil)) if sum != check { fmt.Println("MD5 fail") fmt.Println(" for string,", s) fmt.Println(" expected: ", check) fmt.Println(" got: ", sum) } }
Preserve the algorithm and functionality while converting the code from Python to Go.
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length %i' % slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to %i' % new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s if __name__ == '__main__': for n in range(1, 11): print('%s: %r' % aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s: %r' % aliquot(n))
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
Maintain the same structure and functionality when rewriting this code in Go.
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length %i' % slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to %i' % new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s if __name__ == '__main__': for n in range(1, 11): print('%s: %r' % aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s: %r' % aliquot(n))
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
Write the same algorithm in Go as shown in this Python implementation.
import datetime def mt(): datime1="March 7 2009 7:30pm EST" formatting = "%B %d %Y %I:%M%p " datime2 = datime1[:-3] tdelta = datetime.timedelta(hours=12) s3 = datetime.datetime.strptime(datime2, formatting) datime2 = s3+tdelta print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:] mt()
package main import ( "fmt" "time" ) const taskDate = "March 7 2009 7:30pm EST" const taskFormat = "January 2 2006 3:04pm MST" func main() { if etz, err := time.LoadLocation("US/Eastern"); err == nil { time.Local = etz } fmt.Println("Input: ", taskDate) t, err := time.Parse(taskFormat, taskDate) if err != nil { fmt.Println(err) return } t = t.Add(12 * time.Hour) fmt.Println("+12 hrs: ", t) if _, offset := t.Zone(); offset == 0 { fmt.Println("No time zone info.") return } atz, err := time.LoadLocation("US/Arizona") if err == nil { fmt.Println("+12 hrs in Arizona:", t.In(atz)) } }
Port the following code from Python to Go with equivalent syntax and logic.
from time import sleep from threading import Timer def sleepsort(values): sleepsort.result = [] def add1(x): sleepsort.result.append(x) mx = values[0] for v in values: if mx < v: mx = v Timer(v, add1, [v]).start() sleep(mx+1) return sleepsort.result if __name__ == '__main__': x = [3,2,4,7,3,6,9,1] if sleepsort(x) == sorted(x): print('sleep sort worked for:',x) else: print('sleep sort FAILED for:',x)
package main import ( "fmt" "log" "os" "strconv" "time" ) func main() { out := make(chan uint64) for _, a := range os.Args[1:] { i, err := strconv.ParseUint(a, 10, 64) if err != nil { log.Fatal(err) } go func(n uint64) { time.Sleep(time.Duration(n) * time.Millisecond) out <- n }(i) } for _ = range os.Args[1:] { fmt.Println(<-out) } }
Convert the following code from Python to Go, ensuring the logic remains intact.
from random import randint def do_scan(mat): for row in mat: for item in row: print item, if item == 20: print return print print mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)] do_scan(mat)
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) values := make([][]int, 10) for i := range values { values[i] = make([]int, 10) for j := range values[i] { values[i][j] = rand.Intn(20) + 1 } } outerLoop: for i, row := range values { fmt.Printf("%3d)", i) for _, value := range row { fmt.Printf(" %3d", value) if value == 20 { break outerLoop } } fmt.Printf("\n") } fmt.Printf("\n") }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
from fractions import gcd def pt1(maxperimeter=100): trips = [] for a in range(1, maxperimeter): aa = a*a for b in range(a, maxperimeter-a+1): bb = b*b for c in range(b, maxperimeter-b-a+1): cc = c*c if a+b+c > maxperimeter or cc > aa + bb: break if aa + bb == cc: trips.append((a,b,c, gcd(a, b) == 1)) return trips def pytrip(trip=(3,4,5),perim=100, prim=1): a0, b0, c0 = a, b, c = sorted(trip) t, firstprim = set(), prim>0 while a + b + c <= perim: t.add((a, b, c, firstprim>0)) a, b, c, firstprim = a+a0, b+b0, c+c0, False t2 = set() for a, b, c, firstprim in t: a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7 if a5 - b5 + c7 <= perim: t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim) if a5 + b5 + c7 <= perim: t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim) if -a5 + b5 + c7 <= perim: t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim) return t | t2 def pt2(maxperimeter=100): trips = pytrip((3,4,5), maxperimeter, 1) return trips def printit(maxperimeter=100, pt=pt1): trips = pt(maxperimeter) print(" Up to a perimeter of %i there are %i triples, of which %i are primitive" % (maxperimeter, len(trips), len([prim for a,b,c,prim in trips if prim]))) for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)): print(algo.__doc__) for maxperimeter in range(mn, mx+1, mn): printit(maxperimeter, algo)
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
Keep all operations the same but rewrite the snippet in Go.
from fractions import gcd def pt1(maxperimeter=100): trips = [] for a in range(1, maxperimeter): aa = a*a for b in range(a, maxperimeter-a+1): bb = b*b for c in range(b, maxperimeter-b-a+1): cc = c*c if a+b+c > maxperimeter or cc > aa + bb: break if aa + bb == cc: trips.append((a,b,c, gcd(a, b) == 1)) return trips def pytrip(trip=(3,4,5),perim=100, prim=1): a0, b0, c0 = a, b, c = sorted(trip) t, firstprim = set(), prim>0 while a + b + c <= perim: t.add((a, b, c, firstprim>0)) a, b, c, firstprim = a+a0, b+b0, c+c0, False t2 = set() for a, b, c, firstprim in t: a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7 if a5 - b5 + c7 <= perim: t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim) if a5 + b5 + c7 <= perim: t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim) if -a5 + b5 + c7 <= perim: t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim) return t | t2 def pt2(maxperimeter=100): trips = pytrip((3,4,5), maxperimeter, 1) return trips def printit(maxperimeter=100, pt=pt1): trips = pt(maxperimeter) print(" Up to a perimeter of %i there are %i triples, of which %i are primitive" % (maxperimeter, len(trips), len([prim for a,b,c,prim in trips if prim]))) for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)): print(algo.__doc__) for maxperimeter in range(mn, mx+1, mn): printit(maxperimeter, algo)
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'] unique = list(set(items))
package main import "fmt" func uniq(list []int) []int { unique_set := make(map[int]bool, len(list)) for _, x := range list { unique_set[x] = true } result := make([]int, 0, len(unique_set)) for x := range unique_set { result = append(result, x) } return result } func main() { fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) }
Rewrite the snippet below in Go so it works the same as the original Python code.
def lookandsay(number): result = "" repeat = number[0] number = number[1:]+" " times = 1 for actual in number: if actual != repeat: result += str(times)+repeat times = 1 repeat = actual else: times += 1 return result num = "1" for i in range(10): print num num = lookandsay(num)
package main import ( "fmt" "strconv" ) func lss(s string) (r string) { c := s[0] nc := 1 for i := 1; i < len(s); i++ { d := s[i] if d == c { nc++ continue } r += strconv.Itoa(nc) + string(c) c = d nc = 1 } return r + strconv.Itoa(nc) + string(c) } func main() { s := "1" fmt.Println(s) for i := 0; i < 8; i++ { s = lss(s) fmt.Println(s) } }
Generate an equivalent Go version of this Python code.
from math import gcd def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) if __name__ == '__main__': def is_prime(n): return φ(n) == n - 1 for n in range(1, 26): print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}") count = 0 for n in range(1, 10_000 + 1): count += is_prime(n) if n in {100, 1000, 10_000}: print(f"Primes up to {n}: {count}")
package main import "fmt" func gcd(n, k int) int { if n < k || k < 1 { panic("Need n >= k and k >= 1") } s := 1 for n&1 == 0 && k&1 == 0 { n >>= 1 k >>= 1 s <<= 1 } t := n if n&1 != 0 { t = -k } for t != 0 { for t&1 == 0 { t >>= 1 } if t > 0 { n = t } else { k = -t } t = n - k } return n * s } func totient(n int) int { tot := 0 for k := 1; k <= n; k++ { if gcd(n, k) == 1 { tot++ } } return tot } func main() { fmt.Println(" n phi prime") fmt.Println("---------------") count := 0 for n := 1; n <= 25; n++ { tot := totient(n) isPrime := n-1 == tot if isPrime { count++ } fmt.Printf("%2d %2d %t\n", n, tot, isPrime) } fmt.Println("\nNumber of primes up to 25 =", count) for n := 26; n <= 100000; n++ { tot := totient(n) if tot == n-1 { count++ } if n == 100 || n == 1000 || n%10000 == 0 { fmt.Printf("\nNumber of primes up to %-6d = %d\n", n, count) } } }
Change the programming language of this snippet from Python to Go without modifying what it does.
if x == 0: foo() elif x == 1: bar() elif x == 2: baz() else: qux() match x: 0 => foo() 1 => bar() 2 => baz() _ => qux() (a) ? b : c
if booleanExpression { statements }
Please provide an equivalent version of this Python code in Go.
from fractions import Fraction def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,' '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,' '13 / 11, 15 / 14, 15 / 2, 55 / 1'): flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')] n = Fraction(n) while True: yield n.numerator for f in flist: if (n * f).denominator == 1: break else: break n *= f if __name__ == '__main__': n, m = 2, 15 print('First %i members of fractran(%i):\n ' % (m, n) + ', '.join(str(f) for f,i in zip(fractran(n), range(m))))
package main import ( "fmt" "log" "math/big" "os" "strconv" "strings" ) func compile(src string) ([]big.Rat, bool) { s := strings.Fields(src) r := make([]big.Rat, len(s)) for i, s1 := range s { if _, ok := r[i].SetString(s1); !ok { return nil, false } } return r, true } func exec(p []big.Rat, n *big.Int, limit int) { var q, r big.Int rule: for i := 0; i < limit; i++ { fmt.Printf("%d ", n) for j := range p { q.QuoRem(n, p[j].Denom(), &r) if r.BitLen() == 0 { n.Mul(&q, p[j].Num()) continue rule } } break } fmt.Println() } func usage() { log.Fatal("usage: ft <limit> <n> <prog>") } func main() { if len(os.Args) != 4 { usage() } limit, err := strconv.Atoi(os.Args[1]) if err != nil { usage() } var n big.Int _, ok := n.SetString(os.Args[2], 10) if !ok { usage() } p, ok := compile(os.Args[3]) if !ok { usage() } exec(p, &n, limit) }
Please provide an equivalent version of this Python code in Go.
>>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] >>> def stoogesort(L, i=0, j=None): if j is None: j = len(L) - 1 if L[j] < L[i]: L[i], L[j] = L[j], L[i] if j - i > 1: t = (j - i + 1) // 3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L >>> stoogesort(data) [-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) stoogesort(a) fmt.Println("after: ", a) fmt.Println("nyuk nyuk nyuk") } func stoogesort(a []int) { last := len(a) - 1 if a[last] < a[0] { a[0], a[last] = a[last], a[0] } if last > 1 { t := len(a) / 3 stoogesort(a[:len(a)-t]) stoogesort(a[t:]) stoogesort(a[:len(a)-t]) } }
Preserve the algorithm and functionality while converting the code from Python to Go.
import sys, os import random import time def print_there(x, y, text): sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text)) sys.stdout.flush() class Ball(): def __init__(self): self.x = 0 self.y = 0 def update(self): self.x += random.randint(0,1) self.y += 1 def fall(self): self.y +=1 class Board(): def __init__(self, width, well_depth, N): self.balls = [] self.fallen = [0] * (width + 1) self.width = width self.well_depth = well_depth self.N = N self.shift = 4 def update(self): for ball in self.balls: if ball.y < self.width: ball.update() elif ball.y < self.width + self.well_depth - self.fallen[ball.x]: ball.fall() elif ball.y == self.width + self.well_depth - self.fallen[ball.x]: self.fallen[ball.x] += 1 else: pass def balls_on_board(self): return len(self.balls) - sum(self.fallen) def add_ball(self): if(len(self.balls) <= self.N): self.balls.append(Ball()) def print_board(self): for y in range(self.width + 1): for x in range(y): print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, " def print_ball(self, ball): if ball.y <= self.width: x = self.width - ball.y + 2*ball.x + self.shift else: x = 2*ball.x + self.shift y = ball.y + 1 print_there(y, x, "*") def print_all(self): print(chr(27) + "[2J") self.print_board(); for ball in self.balls: self.print_ball(ball) def main(): board = Board(width = 15, well_depth = 5, N = 10) board.add_ball() while(board.balls_on_board() > 0): board.print_all() time.sleep(0.25) board.update() board.print_all() time.sleep(0.25) board.update() board.add_ball() if __name__=="__main__": main()
package main import ( "fmt" "math/rand" "time" ) const boxW = 41 const boxH = 37 const pinsBaseW = 19 const nMaxBalls = 55 const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 const ( empty = ' ' ball = 'o' wall = '|' corner = '+' floor = '-' pin = '.' ) type Ball struct{ x, y int } func newBall(x, y int) *Ball { if box[y][x] != empty { panic("Tried to create a new ball in a non-empty cell. Program terminated.") } b := Ball{x, y} box[y][x] = ball return &b } func (b *Ball) doStep() { if b.y <= 0 { return } cell := box[b.y-1][b.x] switch cell { case empty: box[b.y][b.x] = empty b.y-- box[b.y][b.x] = ball case pin: box[b.y][b.x] = empty b.y-- if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty { b.x += rand.Intn(2)*2 - 1 box[b.y][b.x] = ball return } else if box[b.y][b.x-1] == empty { b.x++ } else { b.x-- } box[b.y][b.x] = ball default: } } type Cell = byte var box [boxH][boxW]Cell func initializeBox() { box[0][0] = corner box[0][boxW-1] = corner for i := 1; i < boxW-1; i++ { box[0][i] = floor } for i := 0; i < boxW; i++ { box[boxH-1][i] = box[0][i] } for r := 1; r < boxH-1; r++ { box[r][0] = wall box[r][boxW-1] = wall } for i := 1; i < boxH-1; i++ { for j := 1; j < boxW-1; j++ { box[i][j] = empty } } for nPins := 1; nPins <= pinsBaseW; nPins++ { for p := 0; p < nPins; p++ { box[boxH-2-nPins][centerH+1-nPins+p*2] = pin } } } func drawBox() { for r := boxH - 1; r >= 0; r-- { for c := 0; c < boxW; c++ { fmt.Printf("%c", box[r][c]) } fmt.Println() } } func main() { rand.Seed(time.Now().UnixNano()) initializeBox() var balls []*Ball for i := 0; i < nMaxBalls+boxH; i++ { fmt.Println("\nStep", i, ":") if i < nMaxBalls { balls = append(balls, newBall(centerH, boxH-2)) } drawBox() for _, b := range balls { b.doStep() } } }
Change the programming language of this snippet from Python to Go without modifying what it does.
import sys, os import random import time def print_there(x, y, text): sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text)) sys.stdout.flush() class Ball(): def __init__(self): self.x = 0 self.y = 0 def update(self): self.x += random.randint(0,1) self.y += 1 def fall(self): self.y +=1 class Board(): def __init__(self, width, well_depth, N): self.balls = [] self.fallen = [0] * (width + 1) self.width = width self.well_depth = well_depth self.N = N self.shift = 4 def update(self): for ball in self.balls: if ball.y < self.width: ball.update() elif ball.y < self.width + self.well_depth - self.fallen[ball.x]: ball.fall() elif ball.y == self.width + self.well_depth - self.fallen[ball.x]: self.fallen[ball.x] += 1 else: pass def balls_on_board(self): return len(self.balls) - sum(self.fallen) def add_ball(self): if(len(self.balls) <= self.N): self.balls.append(Ball()) def print_board(self): for y in range(self.width + 1): for x in range(y): print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, " def print_ball(self, ball): if ball.y <= self.width: x = self.width - ball.y + 2*ball.x + self.shift else: x = 2*ball.x + self.shift y = ball.y + 1 print_there(y, x, "*") def print_all(self): print(chr(27) + "[2J") self.print_board(); for ball in self.balls: self.print_ball(ball) def main(): board = Board(width = 15, well_depth = 5, N = 10) board.add_ball() while(board.balls_on_board() > 0): board.print_all() time.sleep(0.25) board.update() board.print_all() time.sleep(0.25) board.update() board.add_ball() if __name__=="__main__": main()
package main import ( "fmt" "math/rand" "time" ) const boxW = 41 const boxH = 37 const pinsBaseW = 19 const nMaxBalls = 55 const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 const ( empty = ' ' ball = 'o' wall = '|' corner = '+' floor = '-' pin = '.' ) type Ball struct{ x, y int } func newBall(x, y int) *Ball { if box[y][x] != empty { panic("Tried to create a new ball in a non-empty cell. Program terminated.") } b := Ball{x, y} box[y][x] = ball return &b } func (b *Ball) doStep() { if b.y <= 0 { return } cell := box[b.y-1][b.x] switch cell { case empty: box[b.y][b.x] = empty b.y-- box[b.y][b.x] = ball case pin: box[b.y][b.x] = empty b.y-- if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty { b.x += rand.Intn(2)*2 - 1 box[b.y][b.x] = ball return } else if box[b.y][b.x-1] == empty { b.x++ } else { b.x-- } box[b.y][b.x] = ball default: } } type Cell = byte var box [boxH][boxW]Cell func initializeBox() { box[0][0] = corner box[0][boxW-1] = corner for i := 1; i < boxW-1; i++ { box[0][i] = floor } for i := 0; i < boxW; i++ { box[boxH-1][i] = box[0][i] } for r := 1; r < boxH-1; r++ { box[r][0] = wall box[r][boxW-1] = wall } for i := 1; i < boxH-1; i++ { for j := 1; j < boxW-1; j++ { box[i][j] = empty } } for nPins := 1; nPins <= pinsBaseW; nPins++ { for p := 0; p < nPins; p++ { box[boxH-2-nPins][centerH+1-nPins+p*2] = pin } } } func drawBox() { for r := boxH - 1; r >= 0; r-- { for c := 0; c < boxW; c++ { fmt.Printf("%c", box[r][c]) } fmt.Println() } } func main() { rand.Seed(time.Now().UnixNano()) initializeBox() var balls []*Ball for i := 0; i < nMaxBalls+boxH; i++ { fmt.Println("\nStep", i, ":") if i < nMaxBalls { balls = append(balls, newBall(centerH, boxH-2)) } drawBox() for _, b := range balls { b.doStep() } } }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps': n = R-L if n < 2: return 0 swaps = 0 m = n//2 for i in range(m): if A[R-(i+1)] < A[L+i]: (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],) swaps += 1 if (n & 1) and (A[L+m] < A[L+m-1]): (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],) swaps += 1 return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R) def circle_sort(L:list)->'sort A in place, returning the number of swaps': swaps = 0 s = 1 while s: s = circle_sort_backend(L, 0, len(L)) swaps += s return swaps if __name__ == '__main__': from random import shuffle for i in range(309): L = list(range(i)) M = L[:] shuffle(L) N = L[:] circle_sort(L) if L != M: print(len(L)) print(N) print(L)
package main import "fmt" func circleSort(a []int, lo, hi, swaps int) int { if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- } if lo == hi { if a[lo] > a[hi+1] { a[lo], a[hi+1] = a[hi+1], a[lo] swaps++ } } swaps = circleSort(a, low, low+mid, swaps) swaps = circleSort(a, low+mid+1, high, swaps) return swaps } func main() { aa := [][]int{ {6, 7, 8, 9, 2, 5, 3, 4, 1}, {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}, } for _, a := range aa { fmt.Printf("Original: %v\n", a) for circleSort(a, 0, len(a)-1, 0) != 0 { } fmt.Printf("Sorted  : %v\n\n", a) } }
Write the same code in Go as shown below in Python.
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps': n = R-L if n < 2: return 0 swaps = 0 m = n//2 for i in range(m): if A[R-(i+1)] < A[L+i]: (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],) swaps += 1 if (n & 1) and (A[L+m] < A[L+m-1]): (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],) swaps += 1 return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R) def circle_sort(L:list)->'sort A in place, returning the number of swaps': swaps = 0 s = 1 while s: s = circle_sort_backend(L, 0, len(L)) swaps += s return swaps if __name__ == '__main__': from random import shuffle for i in range(309): L = list(range(i)) M = L[:] shuffle(L) N = L[:] circle_sort(L) if L != M: print(len(L)) print(N) print(L)
package main import "fmt" func circleSort(a []int, lo, hi, swaps int) int { if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- } if lo == hi { if a[lo] > a[hi+1] { a[lo], a[hi+1] = a[hi+1], a[lo] swaps++ } } swaps = circleSort(a, low, low+mid, swaps) swaps = circleSort(a, low+mid+1, high, swaps) return swaps } func main() { aa := [][]int{ {6, 7, 8, 9, 2, 5, 3, 4, 1}, {2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}, } for _, a := range aa { fmt.Printf("Original: %v\n", a) for circleSort(a, 0, len(a)-1, 0) != 0 { } fmt.Printf("Sorted  : %v\n\n", a) } }
Port the provided Python code into Go while preserving the original functionality.
import os from PIL import Image def imgsave(path, arr): w, h = len(arr), len(arr[0]) img = Image.new('1', (w, h)) for x in range(w): for y in range(h): img.putpixel((x, y), arr[x][y]) img.save(path) def get_shape(mat): return len(mat), len(mat[0]) def kron(matrix1, matrix2): final_list = [] count = len(matrix2) for elem1 in matrix1: for i in range(count): sub_list = [] for num1 in elem1: for num2 in matrix2[i]: sub_list.append(num1 * num2) final_list.append(sub_list) return final_list def kronpow(mat): matrix = mat while True: yield matrix matrix = kron(mat, matrix) def fractal(name, mat, order=6): path = os.path.join('fractals', name) os.makedirs(path, exist_ok=True) fgen = kronpow(mat) print(name) for i in range(order): p = os.path.join(path, f'{i}.jpg') print('Calculating n =', i, end='\t', flush=True) mat = next(fgen) imgsave(p, mat) x, y = get_shape(mat) print('Saved as', x, 'x', y, 'image', p) test1 = [ [0, 1, 0], [1, 1, 1], [0, 1, 0] ] test2 = [ [1, 1, 1], [1, 0, 1], [1, 1, 1] ] test3 = [ [1, 0, 1], [0, 1, 0], [1, 0, 1] ] fractal('test1', test1) fractal('test2', test2) fractal('test3', test3)
package main import "fmt" type matrix [][]int func (m1 matrix) kroneckerProduct(m2 matrix) matrix { m := len(m1) n := len(m1[0]) p := len(m2) q := len(m2[0]) rtn := m * p ctn := n * q r := make(matrix, rtn) for i := range r { r[i] = make([]int, ctn) } for i := 0; i < m; i++ { for j := 0; j < n; j++ { for k := 0; k < p; k++ { for l := 0; l < q; l++ { r[p*i+k][q*j+l] = m1[i][j] * m2[k][l] } } } } return r } func (m matrix) kroneckerPower(n int) matrix { pow := m for i := 1; i < n; i++ { pow = pow.kroneckerProduct(m) } return pow } func (m matrix) print(text string) { fmt.Println(text, "fractal :\n") for i := range m { for j := range m[0] { if m[i][j] == 1 { fmt.Print("*") } else { fmt.Print(" ") } } fmt.Println() } fmt.Println() } func main() { m1 := matrix{{0, 1, 0}, {1, 1, 1}, {0, 1, 0}} m1.kroneckerPower(4).print("Vivsek") m2 := matrix{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}} m2.kroneckerPower(4).print("Sierpinski carpet") }
Translate this program into Go but keep the logic exactly as in Python.
def readconf(fn): ret = {} with file(fn) as fp: for line in fp: line = line.strip() if not line or line.startswith(' boolval = True if line.startswith(';'): line = line.lstrip(';') if len(line.split()) != 1: continue boolval = False bits = line.split(None, 1) if len(bits) == 1: k = bits[0] v = boolval else: k, v = bits ret[k.lower()] = v return ret if __name__ == '__main__': import sys conf = readconf(sys.argv[1]) for k, v in sorted(conf.items()): print k, '=', v
package config import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" ) var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") ) type varError struct { err error n string t VarType } func (err *varError) Error() string { return fmt.Sprintf("%v: (%q, %v)", err.err, err.n, err.t) } type VarType int const ( Bool VarType = 1 + iota Array String ) func (t VarType) String() string { switch t { case Bool: return "Bool" case Array: return "Array" case String: return "String" } panic("Unknown VarType") } type confvar struct { Type VarType Val interface{} } type Config struct { m map[string]confvar } func Parse(r io.Reader) (c *Config, err error) { c = new(Config) c.m = make(map[string]confvar) buf, err := ioutil.ReadAll(r) if err != nil { return } lines := bytes.Split(buf, []byte{'\n'}) for _, line := range lines { line = bytes.TrimSpace(line) if len(line) == 0 { continue } switch line[0] { case '#', ';': continue } parts := bytes.SplitN(line, []byte{' '}, 2) nam := string(bytes.ToLower(parts[0])) if len(parts) == 1 { c.m[nam] = confvar{Bool, true} continue } if strings.Contains(string(parts[1]), ",") { tmpB := bytes.Split(parts[1], []byte{','}) for i := range tmpB { tmpB[i] = bytes.TrimSpace(tmpB[i]) } tmpS := make([]string, 0, len(tmpB)) for i := range tmpB { tmpS = append(tmpS, string(tmpB[i])) } c.m[nam] = confvar{Array, tmpS} continue } c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))} } return } func (c *Config) Bool(name string) (bool, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return false, nil } if c.m[name].Type != Bool { return false, &varError{EBADTYPE, name, Bool} } v, ok := c.m[name].Val.(bool) if !ok { return false, &varError{EBADVAL, name, Bool} } return v, nil } func (c *Config) Array(name string) ([]string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return nil, &varError{ENONE, name, Array} } if c.m[name].Type != Array { return nil, &varError{EBADTYPE, name, Array} } v, ok := c.m[name].Val.([]string) if !ok { return nil, &varError{EBADVAL, name, Array} } return v, nil } func (c *Config) String(name string) (string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return "", &varError{ENONE, name, String} } if c.m[name].Type != String { return "", &varError{EBADTYPE, name, String} } v, ok := c.m[name].Val.(string) if !ok { return "", &varError{EBADVAL, name, String} } return v, nil }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
def readconf(fn): ret = {} with file(fn) as fp: for line in fp: line = line.strip() if not line or line.startswith(' boolval = True if line.startswith(';'): line = line.lstrip(';') if len(line.split()) != 1: continue boolval = False bits = line.split(None, 1) if len(bits) == 1: k = bits[0] v = boolval else: k, v = bits ret[k.lower()] = v return ret if __name__ == '__main__': import sys conf = readconf(sys.argv[1]) for k, v in sorted(conf.items()): print k, '=', v
package config import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" ) var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") ) type varError struct { err error n string t VarType } func (err *varError) Error() string { return fmt.Sprintf("%v: (%q, %v)", err.err, err.n, err.t) } type VarType int const ( Bool VarType = 1 + iota Array String ) func (t VarType) String() string { switch t { case Bool: return "Bool" case Array: return "Array" case String: return "String" } panic("Unknown VarType") } type confvar struct { Type VarType Val interface{} } type Config struct { m map[string]confvar } func Parse(r io.Reader) (c *Config, err error) { c = new(Config) c.m = make(map[string]confvar) buf, err := ioutil.ReadAll(r) if err != nil { return } lines := bytes.Split(buf, []byte{'\n'}) for _, line := range lines { line = bytes.TrimSpace(line) if len(line) == 0 { continue } switch line[0] { case '#', ';': continue } parts := bytes.SplitN(line, []byte{' '}, 2) nam := string(bytes.ToLower(parts[0])) if len(parts) == 1 { c.m[nam] = confvar{Bool, true} continue } if strings.Contains(string(parts[1]), ",") { tmpB := bytes.Split(parts[1], []byte{','}) for i := range tmpB { tmpB[i] = bytes.TrimSpace(tmpB[i]) } tmpS := make([]string, 0, len(tmpB)) for i := range tmpB { tmpS = append(tmpS, string(tmpB[i])) } c.m[nam] = confvar{Array, tmpS} continue } c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))} } return } func (c *Config) Bool(name string) (bool, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return false, nil } if c.m[name].Type != Bool { return false, &varError{EBADTYPE, name, Bool} } v, ok := c.m[name].Val.(bool) if !ok { return false, &varError{EBADVAL, name, Bool} } return v, nil } func (c *Config) Array(name string) ([]string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return nil, &varError{ENONE, name, Array} } if c.m[name].Type != Array { return nil, &varError{EBADTYPE, name, Array} } v, ok := c.m[name].Val.([]string) if !ok { return nil, &varError{EBADVAL, name, Array} } return v, nil } func (c *Config) String(name string) (string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return "", &varError{ENONE, name, String} } if c.m[name].Type != String { return "", &varError{EBADTYPE, name, String} } v, ok := c.m[name].Val.(string) if !ok { return "", &varError{EBADVAL, name, String} } return v, nil }
Write the same algorithm in Go as shown in this Python implementation.
strings = "here are Some sample strings to be sorted".split() def mykey(x): return -len(x), x.upper() print sorted(strings, key=mykey)
package main import ( "fmt" "sort" "strings" ) type sortable []string func (s sortable) Len() int { return len(s) } func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortable) Less(i, j int) bool { a, b := s[i], s[j] if len(a) != len(b) { return len(a) > len(b) } return strings.ToLower(a) < strings.ToLower(b) } func main() { var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") fmt.Println(s, "(original)") sort.Sort(s) fmt.Println(s, "(sorted)") }
Preserve the algorithm and functionality while converting the code from Python to Go.
import random def is_Prime(n): if n!=int(n): return False n=int(n) if n==0 or n==1 or n==4 or n==6 or n==8 or n==9: return False if n==2 or n==3 or n==5 or n==7: return True s = 0 d = n-1 while d%2==0: d>>=1 s+=1 assert(2**s * d == n-1) def trial_composite(a): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True for i in range(8): a = random.randrange(2, n) if trial_composite(a): return False return True def isPrime(n: int) -> bool: if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True def rotations(n: int)-> set((int,)): a = str(n) return set(int(a[i:] + a[:i]) for i in range(len(a))) def isCircular(n: int) -> bool: return all(isPrime(int(o)) for o in rotations(n)) from itertools import product def main(): result = [2, 3, 5, 7] first = '137' latter = '1379' for i in range(1, 6): s = set(int(''.join(a)) for a in product(first, *((latter,) * i))) while s: a = s.pop() b = rotations(a) if isCircular(a): result.append(min(b)) s -= b result.sort() return result assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main() repunit = lambda n: int('1' * n) def repmain(n: int) -> list: result = [] i = 2 while len(result) < n: if is_Prime(repunit(i)): result.append(i) i += 1 return result assert [2, 19, 23, 317, 1031] == repmain(5)
package main import ( "fmt" big "github.com/ncw/gmp" "strings" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func repunit(n int) *big.Int { ones := strings.Repeat("1", n) b, _ := new(big.Int).SetString(ones, 10) return b } var circs = []int{} func alreadyFound(n int) bool { for _, i := range circs { if i == n { return true } } return false } func isCircular(n int) bool { nn := n pow := 1 for nn > 0 { pow *= 10 nn /= 10 } nn = n for { nn *= 10 f := nn / pow nn += f * (1 - pow) if alreadyFound(nn) { return false } if nn == n { break } if !isPrime(nn) { return false } } return true } func main() { fmt.Println("The first 19 circular primes are:") digits := [4]int{1, 3, 7, 9} q := []int{1, 2, 3, 5, 7, 9} fq := []int{1, 2, 3, 5, 7, 9} count := 0 for { f := q[0] fd := fq[0] if isPrime(f) && isCircular(f) { circs = append(circs, f) count++ if count == 19 { break } } copy(q, q[1:]) q = q[:len(q)-1] copy(fq, fq[1:]) fq = fq[:len(fq)-1] if f == 2 || f == 5 { continue } for _, d := range digits { if d >= fd { q = append(q, f*10+d) fq = append(fq, fd) } } } fmt.Println(circs) fmt.Println("\nThe next 4 circular primes, in repunit format, are:") count = 0 var rus []string for i := 7; count < 4; i++ { if repunit(i).ProbablyPrime(10) { count++ rus = append(rus, fmt.Sprintf("R(%d)", i)) } } fmt.Println(rus) fmt.Println("\nThe following repunits are probably circular primes:") for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} { fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10)) } }
Port the following code from Python to Go with equivalent syntax and logic.
txt = "Hello, world! " left = True def draw(): global txt background(128) text(txt, 10, height / 2) if frameCount % 10 == 0: if (left): txt = rotate(txt, 1) else: txt = rotate(txt, -1) println(txt) def mouseReleased(): global left left = not left def rotate(text, startIdx): rotated = text[startIdx:] + text[:startIdx] return rotated
package main import ( "log" "time" "github.com/gdamore/tcell" ) const ( msg = "Hello World! " x0, y0 = 8, 3 shiftsPerSecond = 4 clicksToExit = 5 ) func main() { s, err := tcell.NewScreen() if err != nil { log.Fatal(err) } if err = s.Init(); err != nil { log.Fatal(err) } s.Clear() s.EnableMouse() tick := time.Tick(time.Second / shiftsPerSecond) click := make(chan bool) go func() { for { em, ok := s.PollEvent().(*tcell.EventMouse) if !ok || em.Buttons()&0xFF == tcell.ButtonNone { continue } mx, my := em.Position() if my == y0 && mx >= x0 && mx < x0+len(msg) { click <- true } } }() for inc, shift, clicks := 1, 0, 0; ; { select { case <-tick: shift = (shift + inc) % len(msg) for i, r := range msg { s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0) } s.Show() case <-click: clicks++ if clicks == clicksToExit { s.Fini() return } inc = len(msg) - inc } } }
Change the following Python code into Go without altering its purpose.
txt = "Hello, world! " left = True def draw(): global txt background(128) text(txt, 10, height / 2) if frameCount % 10 == 0: if (left): txt = rotate(txt, 1) else: txt = rotate(txt, -1) println(txt) def mouseReleased(): global left left = not left def rotate(text, startIdx): rotated = text[startIdx:] + text[:startIdx] return rotated
package main import ( "log" "time" "github.com/gdamore/tcell" ) const ( msg = "Hello World! " x0, y0 = 8, 3 shiftsPerSecond = 4 clicksToExit = 5 ) func main() { s, err := tcell.NewScreen() if err != nil { log.Fatal(err) } if err = s.Init(); err != nil { log.Fatal(err) } s.Clear() s.EnableMouse() tick := time.Tick(time.Second / shiftsPerSecond) click := make(chan bool) go func() { for { em, ok := s.PollEvent().(*tcell.EventMouse) if !ok || em.Buttons()&0xFF == tcell.ButtonNone { continue } mx, my := em.Position() if my == y0 && mx >= x0 && mx < x0+len(msg) { click <- true } } }() for inc, shift, clicks := 1, 0, 0; ; { select { case <-tick: shift = (shift + inc) % len(msg) for i, r := range msg { s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0) } s.Show() case <-click: clicks++ if clicks == clicksToExit { s.Fini() return } inc = len(msg) - inc } } }
Produce a language-to-language conversion: from Python to Go, same semantics.
from math import log def getDigit(num, base, digit_num): return (num // base ** digit_num) % base def makeBlanks(size): return [ [] for i in range(size) ] def split(a_list, base, digit_num): buckets = makeBlanks(base) for num in a_list: buckets[getDigit(num, base, digit_num)].append(num) return buckets def merge(a_list): new_list = [] for sublist in a_list: new_list.extend(sublist) return new_list def maxAbs(a_list): return max(abs(num) for num in a_list) def split_by_sign(a_list): buckets = [[], []] for num in a_list: if num < 0: buckets[0].append(num) else: buckets[1].append(num) return buckets def radixSort(a_list, base): passes = int(round(log(maxAbs(a_list), base)) + 1) new_list = list(a_list) for digit_num in range(passes): new_list = merge(split(new_list, base, digit_num)) return merge(split_by_sign(new_list))
package main import ( "bytes" "encoding/binary" "fmt" ) type word int32 const wordLen = 4 const highBit = -1 << 31 var data = []word{170, 45, 75, -90, -802, 24, 2, 66} func main() { buf := bytes.NewBuffer(nil) ds := make([][]byte, len(data)) for i, x := range data { binary.Write(buf, binary.LittleEndian, x^highBit) b := make([]byte, wordLen) buf.Read(b) ds[i] = b } bins := make([][][]byte, 256) for i := 0; i < wordLen; i++ { for _, b := range ds { bins[b[i]] = append(bins[b[i]], b) } j := 0 for k, bs := range bins { copy(ds[j:], bs) j += len(bs) bins[k] = bs[:0] } } fmt.Println("original:", data) var w word for i, b := range ds { buf.Write(b) binary.Read(buf, binary.LittleEndian, &w) data[i] = w^highBit } fmt.Println("sorted: ", data) }
Write a version of this Python function in Go with identical behavior.
[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
package main import "fmt" type ( seq []int sofs []seq ) func newSeq(start, end int) seq { if end < start { end = start } s := make(seq, end-start+1) for i := 0; i < len(s); i++ { s[i] = start + i } return s } func newSofs() sofs { return sofs{seq{}} } func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs { var s2 sofs for _, t := range expr(s, in) { if pred(t) { s2 = append(s2, t) } } return s2 } func (s sofs) build(t seq) sofs { var u sofs for _, ss := range s { for _, tt := range t { uu := make(seq, len(ss)) copy(uu, ss) uu = append(uu, tt) u = append(u, uu) } } return u } func main() { pt := newSofs() in := newSeq(1, 20) expr := func(s sofs, t seq) sofs { return s.build(t).build(t).build(t) } pred := func(t seq) bool { if len(t) != 3 { return false } return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2] } pt = pt.listComp(in, expr, pred) fmt.Println(pt) }
Maintain the same structure and functionality when rewriting this code in Go.
def selection_sort(lst): for i, e in enumerate(lst): mn = min(range(i,len(lst)), key=lst.__getitem__) lst[i], lst[mn] = lst[mn], e return lst
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) selectionSort(a) fmt.Println("after: ", a) } func selectionSort(a []int) { last := len(a) - 1 for i := 0; i < last; i++ { aMin := a[i] iMin := i for j := i + 1; j < len(a); j++ { if a[j] < aMin { aMin = a[j] iMin = j } } a[i], a[iMin] = aMin, a[i] } }
Generate a Go translation of this Python snippet without changing its computational steps.
def jacobi(a, n): if n <= 0: raise ValueError("'n' must be a positive integer.") if n % 2 == 0: raise ValueError("'n' must be odd.") a %= n result = 1 while a != 0: while a % 2 == 0: a /= 2 n_mod_8 = n % 8 if n_mod_8 in (3, 5): result = -result a, n = n, a if a % 4 == 3 and n % 4 == 3: result = -result a %= n if n == 1: return result else: return 0
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { result = -result } } a, n = n, a if a%4 == 3 && n%4 == 3 { result = -result } a %= n } if n == 1 { return result } return 0 } func main() { fmt.Println("Using hand-coded version:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { fmt.Printf(" % d", jacobi(a, n)) } fmt.Println() } ba, bn := new(big.Int), new(big.Int) fmt.Println("\nUsing standard library function:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { ba.SetUint64(a) bn.SetUint64(n) fmt.Printf(" % d", big.Jacobi(ba, bn)) } fmt.Println() } }
Produce a language-to-language conversion: from Python to Go, same semantics.
def jacobi(a, n): if n <= 0: raise ValueError("'n' must be a positive integer.") if n % 2 == 0: raise ValueError("'n' must be odd.") a %= n result = 1 while a != 0: while a % 2 == 0: a /= 2 n_mod_8 = n % 8 if n_mod_8 in (3, 5): result = -result a, n = n, a if a % 4 == 3 and n % 4 == 3: result = -result a %= n if n == 1: return result else: return 0
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { result = -result } } a, n = n, a if a%4 == 3 && n%4 == 3 { result = -result } a %= n } if n == 1 { return result } return 0 } func main() { fmt.Println("Using hand-coded version:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { fmt.Printf(" % d", jacobi(a, n)) } fmt.Println() } ba, bn := new(big.Int), new(big.Int) fmt.Println("\nUsing standard library function:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { ba.SetUint64(a) bn.SetUint64(n) fmt.Printf(" % d", big.Jacobi(ba, bn)) } fmt.Println() } }
Write the same code in Go as shown below in Python.
from random import seed, random from time import time from operator import itemgetter from collections import namedtuple from math import sqrt from copy import deepcopy def sqd(p1, p2): return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2)) class KdNode(object): __slots__ = ("dom_elt", "split", "left", "right") def __init__(self, dom_elt, split, left, right): self.dom_elt = dom_elt self.split = split self.left = left self.right = right class Orthotope(object): __slots__ = ("min", "max") def __init__(self, mi, ma): self.min, self.max = mi, ma class KdTree(object): __slots__ = ("n", "bounds") def __init__(self, pts, bounds): def nk2(split, exset): if not exset: return None exset.sort(key=itemgetter(split)) m = len(exset) // 2 d = exset[m] while m + 1 < len(exset) and exset[m + 1][split] == d[split]: m += 1 d = exset[m] s2 = (split + 1) % len(d) return KdNode(d, split, nk2(s2, exset[:m]), nk2(s2, exset[m + 1:])) self.n = nk2(0, pts) self.bounds = bounds T3 = namedtuple("T3", "nearest dist_sqd nodes_visited") def find_nearest(k, t, p): def nn(kd, target, hr, max_dist_sqd): if kd is None: return T3([0.0] * k, float("inf"), 0) nodes_visited = 1 s = kd.split pivot = kd.dom_elt left_hr = deepcopy(hr) right_hr = deepcopy(hr) left_hr.max[s] = pivot[s] right_hr.min[s] = pivot[s] if target[s] <= pivot[s]: nearer_kd, nearer_hr = kd.left, left_hr further_kd, further_hr = kd.right, right_hr else: nearer_kd, nearer_hr = kd.right, right_hr further_kd, further_hr = kd.left, left_hr n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd) nearest = n1.nearest dist_sqd = n1.dist_sqd nodes_visited += n1.nodes_visited if dist_sqd < max_dist_sqd: max_dist_sqd = dist_sqd d = (pivot[s] - target[s]) ** 2 if d > max_dist_sqd: return T3(nearest, dist_sqd, nodes_visited) d = sqd(pivot, target) if d < dist_sqd: nearest = pivot dist_sqd = d max_dist_sqd = dist_sqd n2 = nn(further_kd, target, further_hr, max_dist_sqd) nodes_visited += n2.nodes_visited if n2.dist_sqd < dist_sqd: nearest = n2.nearest dist_sqd = n2.dist_sqd return T3(nearest, dist_sqd, nodes_visited) return nn(t.n, p, t.bounds, float("inf")) def show_nearest(k, heading, kd, p): print(heading + ":") print("Point: ", p) n = find_nearest(k, kd, p) print("Nearest neighbor:", n.nearest) print("Distance: ", sqrt(n.dist_sqd)) print("Nodes visited: ", n.nodes_visited, "\n") def random_point(k): return [random() for _ in range(k)] def random_points(k, n): return [random_point(k) for _ in range(n)] if __name__ == "__main__": seed(1) P = lambda *coords: list(coords) kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)], Orthotope(P(0, 0), P(10, 10))) show_nearest(2, "Wikipedia example data", kd1, P(9, 2)) N = 400000 t0 = time() kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1))) t1 = time() text = lambda *parts: "".join(map(str, parts)) show_nearest(2, text("k-d tree with ", N, " random 3D points (generation time: ", t1-t0, "s)"), kd2, random_point(3))
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt point split int left, right *kdNode } type kdTree struct { n *kdNode bounds hyperRect } type hyperRect struct { min, max point } func (hr hyperRect) copy() hyperRect { return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} } func newKd(pts []point, bounds hyperRect) kdTree { var nk2 func([]point, int) *kdNode nk2 = func(exset []point, split int) *kdNode { if len(exset) == 0 { return nil } sort.Sort(part{exset, split}) m := len(exset) / 2 d := exset[m] for m+1 < len(exset) && exset[m+1][split] == d[split] { m++ } s2 := split + 1 if s2 == len(d) { s2 = 0 } return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} } return kdTree{nk2(pts, 0), bounds} } type part struct { pts []point dPart int } func (p part) Len() int { return len(p.pts) } func (p part) Less(i, j int) bool { return p.pts[i][p.dPart] < p.pts[j][p.dPart] } func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { return nn(t.n, p, t.bounds, math.Inf(1)) } func nn(kd *kdNode, target point, hr hyperRect, maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { if kd == nil { return nil, math.Inf(1), 0 } nodesVisited++ s := kd.split pivot := kd.domElt leftHr := hr.copy() rightHr := hr.copy() leftHr.max[s] = pivot[s] rightHr.min[s] = pivot[s] targetInLeft := target[s] <= pivot[s] var nearerKd, furtherKd *kdNode var nearerHr, furtherHr hyperRect if targetInLeft { nearerKd, nearerHr = kd.left, leftHr furtherKd, furtherHr = kd.right, rightHr } else { nearerKd, nearerHr = kd.right, rightHr furtherKd, furtherHr = kd.left, leftHr } var nv int nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) nodesVisited += nv if distSqd < maxDistSqd { maxDistSqd = distSqd } d := pivot[s] - target[s] d *= d if d > maxDistSqd { return } if d = pivot.sqd(target); d < distSqd { nearest = pivot distSqd = d maxDistSqd = distSqd } tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) nodesVisited += nv if tempSqd < distSqd { nearest = tempNearest distSqd = tempSqd } return } func main() { rand.Seed(time.Now().Unix()) kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}}, hyperRect{point{0, 0}, point{10, 10}}) showNearest("WP example data", kd, point{9, 2}) kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}}) showNearest("1000 random 3d points", kd, randomPt(3)) } func randomPt(dim int) point { p := make(point, dim) for d := range p { p[d] = rand.Float64() } return p } func randomPts(dim, n int) []point { p := make([]point, n) for i := range p { p[i] = randomPt(dim) } return p } func showNearest(heading string, kd kdTree, p point) { fmt.Println() fmt.Println(heading) fmt.Println("point: ", p) nn, ssq, nv := kd.nearest(p) fmt.Println("nearest neighbor:", nn) fmt.Println("distance: ", math.Sqrt(ssq)) fmt.Println("nodes visited: ", nv) }
Convert this Python block to Go, preserving its control flow and logic.
from random import seed, random from time import time from operator import itemgetter from collections import namedtuple from math import sqrt from copy import deepcopy def sqd(p1, p2): return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2)) class KdNode(object): __slots__ = ("dom_elt", "split", "left", "right") def __init__(self, dom_elt, split, left, right): self.dom_elt = dom_elt self.split = split self.left = left self.right = right class Orthotope(object): __slots__ = ("min", "max") def __init__(self, mi, ma): self.min, self.max = mi, ma class KdTree(object): __slots__ = ("n", "bounds") def __init__(self, pts, bounds): def nk2(split, exset): if not exset: return None exset.sort(key=itemgetter(split)) m = len(exset) // 2 d = exset[m] while m + 1 < len(exset) and exset[m + 1][split] == d[split]: m += 1 d = exset[m] s2 = (split + 1) % len(d) return KdNode(d, split, nk2(s2, exset[:m]), nk2(s2, exset[m + 1:])) self.n = nk2(0, pts) self.bounds = bounds T3 = namedtuple("T3", "nearest dist_sqd nodes_visited") def find_nearest(k, t, p): def nn(kd, target, hr, max_dist_sqd): if kd is None: return T3([0.0] * k, float("inf"), 0) nodes_visited = 1 s = kd.split pivot = kd.dom_elt left_hr = deepcopy(hr) right_hr = deepcopy(hr) left_hr.max[s] = pivot[s] right_hr.min[s] = pivot[s] if target[s] <= pivot[s]: nearer_kd, nearer_hr = kd.left, left_hr further_kd, further_hr = kd.right, right_hr else: nearer_kd, nearer_hr = kd.right, right_hr further_kd, further_hr = kd.left, left_hr n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd) nearest = n1.nearest dist_sqd = n1.dist_sqd nodes_visited += n1.nodes_visited if dist_sqd < max_dist_sqd: max_dist_sqd = dist_sqd d = (pivot[s] - target[s]) ** 2 if d > max_dist_sqd: return T3(nearest, dist_sqd, nodes_visited) d = sqd(pivot, target) if d < dist_sqd: nearest = pivot dist_sqd = d max_dist_sqd = dist_sqd n2 = nn(further_kd, target, further_hr, max_dist_sqd) nodes_visited += n2.nodes_visited if n2.dist_sqd < dist_sqd: nearest = n2.nearest dist_sqd = n2.dist_sqd return T3(nearest, dist_sqd, nodes_visited) return nn(t.n, p, t.bounds, float("inf")) def show_nearest(k, heading, kd, p): print(heading + ":") print("Point: ", p) n = find_nearest(k, kd, p) print("Nearest neighbor:", n.nearest) print("Distance: ", sqrt(n.dist_sqd)) print("Nodes visited: ", n.nodes_visited, "\n") def random_point(k): return [random() for _ in range(k)] def random_points(k, n): return [random_point(k) for _ in range(n)] if __name__ == "__main__": seed(1) P = lambda *coords: list(coords) kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)], Orthotope(P(0, 0), P(10, 10))) show_nearest(2, "Wikipedia example data", kd1, P(9, 2)) N = 400000 t0 = time() kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1))) t1 = time() text = lambda *parts: "".join(map(str, parts)) show_nearest(2, text("k-d tree with ", N, " random 3D points (generation time: ", t1-t0, "s)"), kd2, random_point(3))
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt point split int left, right *kdNode } type kdTree struct { n *kdNode bounds hyperRect } type hyperRect struct { min, max point } func (hr hyperRect) copy() hyperRect { return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} } func newKd(pts []point, bounds hyperRect) kdTree { var nk2 func([]point, int) *kdNode nk2 = func(exset []point, split int) *kdNode { if len(exset) == 0 { return nil } sort.Sort(part{exset, split}) m := len(exset) / 2 d := exset[m] for m+1 < len(exset) && exset[m+1][split] == d[split] { m++ } s2 := split + 1 if s2 == len(d) { s2 = 0 } return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} } return kdTree{nk2(pts, 0), bounds} } type part struct { pts []point dPart int } func (p part) Len() int { return len(p.pts) } func (p part) Less(i, j int) bool { return p.pts[i][p.dPart] < p.pts[j][p.dPart] } func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { return nn(t.n, p, t.bounds, math.Inf(1)) } func nn(kd *kdNode, target point, hr hyperRect, maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { if kd == nil { return nil, math.Inf(1), 0 } nodesVisited++ s := kd.split pivot := kd.domElt leftHr := hr.copy() rightHr := hr.copy() leftHr.max[s] = pivot[s] rightHr.min[s] = pivot[s] targetInLeft := target[s] <= pivot[s] var nearerKd, furtherKd *kdNode var nearerHr, furtherHr hyperRect if targetInLeft { nearerKd, nearerHr = kd.left, leftHr furtherKd, furtherHr = kd.right, rightHr } else { nearerKd, nearerHr = kd.right, rightHr furtherKd, furtherHr = kd.left, leftHr } var nv int nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) nodesVisited += nv if distSqd < maxDistSqd { maxDistSqd = distSqd } d := pivot[s] - target[s] d *= d if d > maxDistSqd { return } if d = pivot.sqd(target); d < distSqd { nearest = pivot distSqd = d maxDistSqd = distSqd } tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) nodesVisited += nv if tempSqd < distSqd { nearest = tempNearest distSqd = tempSqd } return } func main() { rand.Seed(time.Now().Unix()) kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}}, hyperRect{point{0, 0}, point{10, 10}}) showNearest("WP example data", kd, point{9, 2}) kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}}) showNearest("1000 random 3d points", kd, randomPt(3)) } func randomPt(dim int) point { p := make(point, dim) for d := range p { p[d] = rand.Float64() } return p } func randomPts(dim, n int) []point { p := make([]point, n) for i := range p { p[i] = randomPt(dim) } return p } func showNearest(heading string, kd kdTree, p point) { fmt.Println() fmt.Println(heading) fmt.Println("point: ", p) nn, ssq, nv := kd.nearest(p) fmt.Println("nearest neighbor:", nn) fmt.Println("distance: ", math.Sqrt(ssq)) fmt.Println("nodes visited: ", nv) }
Convert this Python block to Go, preserving its control flow and logic.
def square(n): return n * n numbers = [1, 3, 5, 7] squares1 = [square(n) for n in numbers] squares2a = map(square, numbers) squares2b = map(lambda x: x*x, numbers) squares3 = [n * n for n in numbers] isquares1 = (n * n for n in numbers) import itertools isquares2 = itertools.imap(square, numbers)
package main import "fmt" func main() { for _, i := range []int{1, 2, 3, 4, 5} { fmt.Println(i * i) } }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
def square(n): return n * n numbers = [1, 3, 5, 7] squares1 = [square(n) for n in numbers] squares2a = map(square, numbers) squares2b = map(lambda x: x*x, numbers) squares3 = [n * n for n in numbers] isquares1 = (n * n for n in numbers) import itertools isquares2 = itertools.imap(square, numbers)
package main import "fmt" func main() { for _, i := range []int{1, 2, 3, 4, 5} { fmt.Println(i * i) } }
Ensure the translated Go code behaves exactly like the original Python snippet.
>>> class Borg(object): __state = {} def __init__(self): self.__dict__ = self.__state >>> b1 = Borg() >>> b2 = Borg() >>> b1 is b2 False >>> b1.datum = range(5) >>> b1.datum [0, 1, 2, 3, 4] >>> b2.datum [0, 1, 2, 3, 4] >>> b1.datum is b2.datum True >>>
package main import ( "log" "math/rand" "sync" "time" ) var ( instance string once sync.Once ) func claim(color string, w *sync.WaitGroup) { time.Sleep(time.Duration(rand.Intn(1e8))) log.Println("trying to claim", color) once.Do(func() { instance = color }) log.Printf("tried %s. instance: %s", color, instance) w.Done() } func main() { rand.Seed(time.Now().Unix()) var w sync.WaitGroup w.Add(2) go claim("red", &w) go claim("blue", &w) w.Wait() log.Println("after trying both, instance =", instance) }
Produce a functionally identical Go code for the snippet given in Python.
>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999 >>> from math import fsum >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0
package main import ( "fmt" "math" ) type interval struct { lower, upper float64 } func stepAway(x float64) interval { return interval { math.Nextafter(x, math.Inf(-1)), math.Nextafter(x, math.Inf(1))} } func safeAdd(a, b float64) interval { return stepAway(a + b) } func main() { a, b := 1.2, .03 fmt.Println(a, b, safeAdd(a, b)) }
Write the same algorithm in Go as shown in this Python implementation.
>>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie' >>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG) The three dogs are named Benjamin , Samba , and Bernie >>>
package dogs import "fmt" var dog = "Salt" var Dog = "Pepper" var DOG = "Mustard" func PackageSees() map[*string]int { fmt.Println("Package sees:", dog, Dog, DOG) return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1} }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
>>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie' >>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG) The three dogs are named Benjamin , Samba , and Bernie >>>
package dogs import "fmt" var dog = "Salt" var Dog = "Pepper" var DOG = "Mustard" func PackageSees() map[*string]int { fmt.Println("Package sees:", dog, Dog, DOG) return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1} }
Write the same algorithm in Go as shown in this Python implementation.
for i in xrange(10, -1, -1): print i
for i := 10; i >= 0; i-- { fmt.Println(i) }
Generate a Go translation of this Python snippet without changing its computational steps.
with open(filename, 'w') as f: f.write(data)
import "io/ioutil" func main() { ioutil.WriteFile("path/to/your.file", []byte("data"), 0644) }
Convert this Python block to Go, preserving its control flow and logic.
for i in 1..5: for j in 1..i: stdout.write("*") echo("")
package main import "fmt" func main() { for i := 1; i <= 5; i++ { for j := 1; j <= i; j++ { fmt.Printf("*") } fmt.Printf("\n") } }
Generate an equivalent Go version of this Python code.
for i in 1..5: for j in 1..i: stdout.write("*") echo("")
package main import "fmt" func main() { for i := 1; i <= 5; i++ { for j := 1; j <= i; j++ { fmt.Printf("*") } fmt.Printf("\n") } }
Write a version of this Python function in Go with identical behavior.
from itertools import count from pprint import pformat import re import heapq def pal_part_gen(odd=True): for i in count(1): fwd = str(i) rev = fwd[::-1][1:] if odd else fwd[::-1] yield int(fwd + rev) def pal_ordered_gen(): yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False)) def is_gapful(x): return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0) if __name__ == '__main__': start = 100 for mx, last in [(20, 20), (100, 15), (1_000, 10)]: print(f"\nLast {last} of the first {mx} binned-by-last digit " f"gapful numbers >= {start}") bin = {i: [] for i in range(1, 10)} gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i)) while any(len(val) < mx for val in bin.values()): g = next(gen) val = bin[g % 10] if len(val) < mx: val.append(g) b = {k:v[-last:] for k, v in bin.items()} txt = pformat(b, width=220) print('', re.sub(r"[{},\[\]]", '', txt))
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func ord(n uint) string { var suffix string if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) { suffix = "th" } else { switch n % 10 { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" default: suffix = "th" } } return fmt.Sprintf("%s%s", commatize(n), suffix) } func main() { const max = 10_000_000 data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14}, {1e6, 1e6, 16}, {1e7, 1e7, 18}} results := make(map[uint][]uint64) for _, d := range data { for i := d[0]; i <= d[1]; i++ { results[i] = make([]uint64, 9) } } var p uint64 outer: for d := uint64(1); d < 10; d++ { count := uint(0) pow := uint64(1) fl := d * 11 for nd := 3; nd < 20; nd++ { slim := (d + 1) * pow for s := d * pow; s < slim; s++ { e := reverse(s) mlim := uint64(1) if nd%2 == 1 { mlim = 10 } for m := uint64(0); m < mlim; m++ { if nd%2 == 0 { p = s*pow*10 + e } else { p = s*pow*100 + m*pow*10 + e } if p%fl == 0 { count++ if _, ok := results[count]; ok { results[count][d-1] = p } if count == max { continue outer } } } } if nd%2 == 1 { pow *= 10 } } } for _, d := range data { if d[0] != d[1] { fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1])) } else { fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0])) } for i := 1; i <= 9; i++ { fmt.Printf("%d: ", i) for j := d[0]; j <= d[1]; j++ { fmt.Printf("%*d ", d[2], results[j][i-1]) } fmt.Println() } fmt.Println() } }
Change the following Python code into Go without altering its purpose.
from itertools import count from pprint import pformat import re import heapq def pal_part_gen(odd=True): for i in count(1): fwd = str(i) rev = fwd[::-1][1:] if odd else fwd[::-1] yield int(fwd + rev) def pal_ordered_gen(): yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False)) def is_gapful(x): return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0) if __name__ == '__main__': start = 100 for mx, last in [(20, 20), (100, 15), (1_000, 10)]: print(f"\nLast {last} of the first {mx} binned-by-last digit " f"gapful numbers >= {start}") bin = {i: [] for i in range(1, 10)} gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i)) while any(len(val) < mx for val in bin.values()): g = next(gen) val = bin[g % 10] if len(val) < mx: val.append(g) b = {k:v[-last:] for k, v in bin.items()} txt = pformat(b, width=220) print('', re.sub(r"[{},\[\]]", '', txt))
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func ord(n uint) string { var suffix string if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) { suffix = "th" } else { switch n % 10 { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" default: suffix = "th" } } return fmt.Sprintf("%s%s", commatize(n), suffix) } func main() { const max = 10_000_000 data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14}, {1e6, 1e6, 16}, {1e7, 1e7, 18}} results := make(map[uint][]uint64) for _, d := range data { for i := d[0]; i <= d[1]; i++ { results[i] = make([]uint64, 9) } } var p uint64 outer: for d := uint64(1); d < 10; d++ { count := uint(0) pow := uint64(1) fl := d * 11 for nd := 3; nd < 20; nd++ { slim := (d + 1) * pow for s := d * pow; s < slim; s++ { e := reverse(s) mlim := uint64(1) if nd%2 == 1 { mlim = 10 } for m := uint64(0); m < mlim; m++ { if nd%2 == 0 { p = s*pow*10 + e } else { p = s*pow*100 + m*pow*10 + e } if p%fl == 0 { count++ if _, ok := results[count]; ok { results[count][d-1] = p } if count == max { continue outer } } } } if nd%2 == 1 { pow *= 10 } } } for _, d := range data { if d[0] != d[1] { fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1])) } else { fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0])) } for i := 1; i <= 9; i++ { fmt.Printf("%d: ", i) for j := d[0]; j <= d[1]; j++ { fmt.Printf("%*d ", d[2], results[j][i-1]) } fmt.Println() } fmt.Println() } }
Write the same algorithm in Go as shown in this Python implementation.
import turtle as t def sier(n,length): if n == 0: return for i in range(3): sier(n - 1, length / 2) t.fd(length) t.rt(120)
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color.Gray{0} gWhite := color.Gray{255} draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src) for y := 0; y < width; y++ { for x := 0; x < width; x++ { if x&y == 0 { im.SetGray(x, y, gBlack) } } } f, err := os.Create("sierpinski.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, im); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
import turtle as t def sier(n,length): if n == 0: return for i in range(3): sier(n - 1, length / 2) t.fd(length) t.rt(120)
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color.Gray{0} gWhite := color.Gray{255} draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src) for y := 0; y < width; y++ { for x := 0; x < width; x++ { if x&y == 0 { im.SetGray(x, y, gBlack) } } } f, err := os.Create("sierpinski.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, im); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
Convert this Python snippet to Go and keep its semantics consistent.
from itertools import accumulate, chain, takewhile def primeSums(): return ( x for x in enumerate( accumulate( chain([(0, 0)], primes()), lambda a, p: (p, p + a[1]) ) ) if isPrime(x[1][1]) ) def main(): for x in takewhile( lambda t: 1000 > t[1][0], primeSums() ): print(f'{x[0]} -> {x[1][1]}') def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n if __name__ == '__main__': main()
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPrime(sum) { c++ fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum)) } } fmt.Println() fmt.Println(c, "such prime sums found") }
Rewrite the snippet below in Go so it works the same as the original Python code.
from itertools import accumulate, chain, takewhile def primeSums(): return ( x for x in enumerate( accumulate( chain([(0, 0)], primes()), lambda a, p: (p, p + a[1]) ) ) if isPrime(x[1][1]) ) def main(): for x in takewhile( lambda t: 1000 > t[1][0], primeSums() ): print(f'{x[0]} -> {x[1][1]}') def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n if __name__ == '__main__': main()
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPrime(sum) { c++ fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum)) } } fmt.Println() fmt.Println(c, "such prime sums found") }
Please provide an equivalent version of this Python code in Go.
from itertools import chain def main(): print( sorted(nub(concat([ [5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9] ]))) ) def concat(xs): return list(chain(*xs)) def nub(xs): return list(dict.fromkeys(xs)) if __name__ == '__main__': main()
package main import ( "fmt" "sort" ) func distinctSortedUnion(ll [][]int) []int { var res []int for _, l := range ll { res = append(res, l...) } set := make(map[int]bool) for _, e := range res { set[e] = true } res = res[:0] for key := range set { res = append(res, key) } sort.Ints(res) return res } func main() { ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}} fmt.Println("Distinct sorted union of", ll, "is:") fmt.Println(distinctSortedUnion(ll)) }
Transform the following Python implementation into Go, maintaining the same output and logic.
from itertools import chain def main(): print( sorted(nub(concat([ [5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9] ]))) ) def concat(xs): return list(chain(*xs)) def nub(xs): return list(dict.fromkeys(xs)) if __name__ == '__main__': main()
package main import ( "fmt" "sort" ) func distinctSortedUnion(ll [][]int) []int { var res []int for _, l := range ll { res = append(res, l...) } set := make(map[int]bool) for _, e := range res { set[e] = true } res = res[:0] for key := range set { res = append(res, key) } sort.Ints(res) return res } func main() { ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}} fmt.Println("Distinct sorted union of", ll, "is:") fmt.Println(distinctSortedUnion(ll)) }
Generate a Go translation of this Python snippet without changing its computational steps.
from itertools import chain def main(): print( sorted(nub(concat([ [5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9] ]))) ) def concat(xs): return list(chain(*xs)) def nub(xs): return list(dict.fromkeys(xs)) if __name__ == '__main__': main()
package main import ( "fmt" "sort" ) func distinctSortedUnion(ll [][]int) []int { var res []int for _, l := range ll { res = append(res, l...) } set := make(map[int]bool) for _, e := range res { set[e] = true } res = res[:0] for key := range set { res = append(res, key) } sort.Ints(res) return res } func main() { ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}} fmt.Println("Distinct sorted union of", ll, "is:") fmt.Println(distinctSortedUnion(ll)) }
Transform the following Python implementation into Go, maintaining the same output and logic.
def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else []
package main import "fmt" const ( m = iota c cm cmc ) func ncs(s []int) [][]int { if len(s) < 3 { return nil } return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...) } var skip = []int{m, cm, cm, cmc} var incl = []int{c, c, cmc, cmc} func n2(ss, tail []int, seq int) [][]int { if len(tail) == 0 { if seq != cmc { return nil } return [][]int{ss} } return append(n2(append([]int{}, ss...), tail[1:], skip[seq]), n2(append(ss, tail[0]), tail[1:], incl[seq])...) } func main() { ss := ncs([]int{1, 2, 3, 4}) fmt.Println(len(ss), "non-continuous subsequences:") for _, s := range ss { fmt.Println(" ", s) } }
Generate an equivalent Go version of this Python code.
def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else []
package main import "fmt" const ( m = iota c cm cmc ) func ncs(s []int) [][]int { if len(s) < 3 { return nil } return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...) } var skip = []int{m, cm, cm, cmc} var incl = []int{c, c, cmc, cmc} func n2(ss, tail []int, seq int) [][]int { if len(tail) == 0 { if seq != cmc { return nil } return [][]int{ss} } return append(n2(append([]int{}, ss...), tail[1:], skip[seq]), n2(append(ss, tail[0]), tail[1:], incl[seq])...) } func main() { ss := ncs([]int{1, 2, 3, 4}) fmt.Println(len(ss), "non-continuous subsequences:") for _, s := range ss { fmt.Println(" ", s) } }
Write the same code in Go as shown below in Python.
from functools import wraps from turtle import * def memoize(obj): cache = obj.cache = {} @wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer @memoize def fibonacci_word(n): assert n > 0 if n == 1: return "1" if n == 2: return "0" return fibonacci_word(n - 1) + fibonacci_word(n - 2) def draw_fractal(word, step): for i, c in enumerate(word, 1): forward(step) if c == "0": if i % 2 == 0: left(90) else: right(90) def main(): n = 25 step = 1 width = 1050 height = 1050 w = fibonacci_word(n) setup(width=width, height=height) speed(0) setheading(90) left(90) penup() forward(500) right(90) backward(500) pendown() tracer(10000) hideturtle() draw_fractal(w, step) getscreen().getcanvas().postscript(file="fibonacci_word_fractal.eps") exitonclick() if __name__ == '__main__': main()
package main import ( "github.com/fogleman/gg" "strings" ) func wordFractal(i int) string { if i < 2 { if i == 1 { return "1" } return "" } var f1 strings.Builder f1.WriteString("1") var f2 strings.Builder f2.WriteString("0") for j := i - 2; j >= 1; j-- { tmp := f2.String() f2.WriteString(f1.String()) f1.Reset() f1.WriteString(tmp) } return f2.String() } func draw(dc *gg.Context, x, y, dx, dy float64, wf string) { for i, c := range wf { dc.DrawLine(x, y, x+dx, y+dy) x += dx y += dy if c == '0' { tx := dx dx = dy if i%2 == 0 { dx = -dy } dy = -tx if i%2 == 0 { dy = tx } } } } func main() { dc := gg.NewContext(450, 620) dc.SetRGB(0, 0, 0) dc.Clear() wf := wordFractal(23) draw(dc, 20, 20, 1, 0, wf) dc.SetRGB(0, 1, 0) dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("fib_wordfractal.png") }
Write the same code in Go as shown below in Python.
primes = [2, 3, 5, 7, 11, 13, 17, 19] def count_twin_primes(limit: int) -> int: global primes if limit > primes[-1]: ram_limit = primes[-1] + 90000000 - len(primes) reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1 while reasonable_limit < limit: ram_limit = primes[-1] + 90000000 - len(primes) if ram_limit > primes[-1]: reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) else: reasonable_limit = min(limit, primes[-1] ** 2) sieve = list({x for prime in primes for x in range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)}) primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit] count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y]) return count def test(limit: int): count = count_twin_primes(limit) print(f"Number of twin prime pairs less than {limit} is {count}\n") test(10) test(100) test(1000) test(10000) test(100000) test(1000000) test(10000000) test(100000000)
package main import "fmt" func sieve(limit uint64) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := uint64(3) for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { c := sieve(1e10 - 1) limit := 10 start := 3 twins := 0 for i := 1; i < 11; i++ { for i := start; i < limit; i += 2 { if !c[i] && !c[i-2] { twins++ } } fmt.Printf("Under %14s there are %10s pairs of twin primes.\n", commatize(limit), commatize(twins)) start = limit + 1 limit *= 10 } }
Produce a language-to-language conversion: from Python to Go, same semantics.
import random class IDAStar: def __init__(self, h, neighbours): self.h = h self.neighbours = neighbours self.FOUND = object() def solve(self, root, is_goal, max_cost=None): self.is_goal = is_goal self.path = [root] self.is_in_path = {root} self.path_descrs = [] self.nodes_evaluated = 0 bound = self.h(root) while True: t = self._search(0, bound) if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated if t is None: return None bound = t def _search(self, g, bound): self.nodes_evaluated += 1 node = self.path[-1] f = g + self.h(node) if f > bound: return f if self.is_goal(node): return self.FOUND m = None for cost, n, descr in self.neighbours(node): if n in self.is_in_path: continue self.path.append(n) self.is_in_path.add(n) self.path_descrs.append(descr) t = self._search(g + cost, bound) if t == self.FOUND: return self.FOUND if m is None or (t is not None and t < m): m = t self.path.pop() self.path_descrs.pop() self.is_in_path.remove(n) return m def slide_solved_state(n): return tuple(i % (n*n) for i in range(1, n*n+1)) def slide_randomize(p, neighbours): for _ in range(len(p) ** 2): _, p, _ = random.choice(list(neighbours(p))) return p def slide_neighbours(n): movelist = [] for gap in range(n*n): x, y = gap % n, gap // n moves = [] if x > 0: moves.append(-1) if x < n-1: moves.append(+1) if y > 0: moves.append(-n) if y < n-1: moves.append(+n) movelist.append(moves) def neighbours(p): gap = p.index(0) l = list(p) for m in movelist[gap]: l[gap] = l[gap + m] l[gap + m] = 0 yield (1, tuple(l), (l[gap], m)) l[gap + m] = l[gap] l[gap] = 0 return neighbours def slide_print(p): n = int(round(len(p) ** 0.5)) l = len(str(n*n)) for i in range(0, len(p), n): print(" ".join("{:>{}}".format(x, l) for x in p[i:i+n])) def encode_cfg(cfg, n): r = 0 b = n.bit_length() for i in range(len(cfg)): r |= cfg[i] << (b*i) return r def gen_wd_table(n): goal = [[0] * i + [n] + [0] * (n - 1 - i) for i in range(n)] goal[-1][-1] = n - 1 goal = tuple(sum(goal, [])) table = {} to_visit = [(goal, 0, n-1)] while to_visit: cfg, cost, e = to_visit.pop(0) enccfg = encode_cfg(cfg, n) if enccfg in table: continue table[enccfg] = cost for d in [-1, 1]: if 0 <= e + d < n: for c in range(n): if cfg[n*(e+d) + c] > 0: ncfg = list(cfg) ncfg[n*(e+d) + c] -= 1 ncfg[n*e + c] += 1 to_visit.append((tuple(ncfg), cost + 1, e+d)) return table def slide_wd(n, goal): wd = gen_wd_table(n) goals = {i : goal.index(i) for i in goal} b = n.bit_length() def h(p): ht = 0 vt = 0 d = 0 for i, c in enumerate(p): if c == 0: continue g = goals[c] xi, yi = i % n, i // n xg, yg = g % n, g // n ht += 1 << (b*(n*yi+yg)) vt += 1 << (b*(n*xi+xg)) if yg == yi: for k in range(i + 1, i - i%n + n): if p[k] and goals[p[k]] // n == yi and goals[p[k]] < g: d += 2 if xg == xi: for k in range(i + n, n * n, n): if p[k] and goals[p[k]] % n == xi and goals[p[k]] < g: d += 2 d += wd[ht] + wd[vt] return d return h if __name__ == "__main__": solved_state = slide_solved_state(4) neighbours = slide_neighbours(4) is_goal = lambda p: p == solved_state tests = [ (15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2), ] slide_solver = IDAStar(slide_wd(4, solved_state), neighbours) for p in tests: path, moves, cost, num_eval = slide_solver.solve(p, is_goal, 80) slide_print(p) print(", ".join({-1: "Left", 1: "Right", -4: "Up", 4: "Down"}[move[1]] for move in moves)) print(cost, num_eval)
package main import "fmt" var ( Nr = [16]int{3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3} Nc = [16]int{3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2} ) var ( n, _n int N0, N3, N4 [85]int N2 [85]uint64 ) const ( i = 1 g = 8 e = 2 l = 4 ) func fY() bool { if N2[n] == 0x123456789abcdef0 { return true } if N4[n] <= _n { return fN() } return false } func fZ(w int) bool { if w&i > 0 { fI() if fY() { return true } n-- } if w&g > 0 { fG() if fY() { return true } n-- } if w&e > 0 { fE() if fY() { return true } n-- } if w&l > 0 { fL() if fY() { return true } n-- } return false } func fN() bool { switch N0[n] { case 0: switch N3[n] { case 'l': return fZ(i) case 'u': return fZ(e) default: return fZ(i + e) } case 3: switch N3[n] { case 'r': return fZ(i) case 'u': return fZ(l) default: return fZ(i + l) } case 1, 2: switch N3[n] { case 'l': return fZ(i + l) case 'r': return fZ(i + e) case 'u': return fZ(e + l) default: return fZ(l + e + i) } case 12: switch N3[n] { case 'l': return fZ(g) case 'd': return fZ(e) default: return fZ(e + g) } case 15: switch N3[n] { case 'r': return fZ(g) case 'd': return fZ(l) default: return fZ(g + l) } case 13, 14: switch N3[n] { case 'l': return fZ(g + l) case 'r': return fZ(e + g) case 'd': return fZ(e + l) default: return fZ(g + e + l) } case 4, 8: switch N3[n] { case 'l': return fZ(i + g) case 'u': return fZ(g + e) case 'd': return fZ(i + e) default: return fZ(i + g + e) } case 7, 11: switch N3[n] { case 'd': return fZ(i + l) case 'u': return fZ(g + l) case 'r': return fZ(i + g) default: return fZ(i + g + l) } default: switch N3[n] { case 'd': return fZ(i + e + l) case 'l': return fZ(i + g + l) case 'r': return fZ(i + g + e) case 'u': return fZ(g + e + l) default: return fZ(i + g + e + l) } } } func fI() { g := (11 - N0[n]) * 4 a := N2[n] & uint64(15<<uint(g)) N0[n+1] = N0[n] + 4 N2[n+1] = N2[n] - a + (a << 16) N3[n+1] = 'd' N4[n+1] = N4[n] cond := Nr[a>>uint(g)] <= N0[n]/4 if !cond { N4[n+1]++ } n++ } func fG() { g := (19 - N0[n]) * 4 a := N2[n] & uint64(15<<uint(g)) N0[n+1] = N0[n] - 4 N2[n+1] = N2[n] - a + (a >> 16) N3[n+1] = 'u' N4[n+1] = N4[n] cond := Nr[a>>uint(g)] >= N0[n]/4 if !cond { N4[n+1]++ } n++ } func fE() { g := (14 - N0[n]) * 4 a := N2[n] & uint64(15<<uint(g)) N0[n+1] = N0[n] + 1 N2[n+1] = N2[n] - a + (a << 4) N3[n+1] = 'r' N4[n+1] = N4[n] cond := Nc[a>>uint(g)] <= N0[n]%4 if !cond { N4[n+1]++ } n++ } func fL() { g := (16 - N0[n]) * 4 a := N2[n] & uint64(15<<uint(g)) N0[n+1] = N0[n] - 1 N2[n+1] = N2[n] - a + (a >> 4) N3[n+1] = 'l' N4[n+1] = N4[n] cond := Nc[a>>uint(g)] >= N0[n]%4 if !cond { N4[n+1]++ } n++ } func fifteenSolver(n int, g uint64) { N0[0] = n N2[0] = g N4[0] = 0 } func solve() { if fN() { fmt.Print("Solution found in ", n, " moves: ") for g := 1; g <= n; g++ { fmt.Printf("%c", N3[g]) } fmt.Println() } else { n = 0 _n++ solve() } } func main() { fifteenSolver(8, 0xfe169b4c0a73d852) solve() }
Write a version of this Python function in Go with identical behavior.
import cmath class Complex(complex): def __repr__(self): rp = '%7.5f' % self.real if not self.pureImag() else '' ip = '%7.5fj' % self.imag if not self.pureReal() else '' conj = '' if ( self.pureImag() or self.pureReal() or self.imag < 0.0 ) else '+' return '0.0' if ( self.pureImag() and self.pureReal() ) else rp + conj + ip def pureImag(self): return abs(self.real) < 0.000005 def pureReal(self): return abs(self.imag) < 0.000005 def croots(n): if n <= 0: return None return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n)) for nr in range(2, 11): print(nr, list(croots(nr)))
package main import ( "fmt" "math" "math/cmplx" ) func main() { for n := 2; n <= 5; n++ { fmt.Printf("%d roots of 1:\n", n) for _, r := range roots(n) { fmt.Printf(" %18.15f\n", r) } } } func roots(n int) []complex128 { r := make([]complex128, n) for i := 0; i < n; i++ { r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n)) } return r }
Convert this Python snippet to Go and keep its semantics consistent.
print 2**64*2**64
package main import "fmt" func d(b byte) byte { if b < '0' || b > '9' { panic("digit 0-9 expected") } return b - '0' } func add(x, y string) string { if len(y) > len(x) { x, y = y, x } b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { if i <= len(y) { c += d(y[len(y)-i]) } s := d(x[len(x)-i]) + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mulDigit(x string, y byte) string { if y == '0' { return "0" } y = d(y) b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { s := d(x[len(x)-i])*y + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mul(x, y string) string { result := mulDigit(x, y[len(y)-1]) for i, zeros := 2, ""; i <= len(y); i++ { zeros += "0" result = add(result, mulDigit(x, y[len(y)-i])+zeros) } return result } const n = "18446744073709551616" func main() { fmt.Println(mul(n, n)) }
Generate a Go translation of this Python snippet without changing its computational steps.
import math def solvePell(n): x = int(math.sqrt(n)) y, z, r = x, 1, x << 1 e1, e2 = 1, 0 f1, f2 = 0, 1 while True: y = r * z - y z = (n - y * y) // z r = (x + y) // z e1, e2 = e2, e1 + e2 * r f1, f2 = f2, f1 + f2 * r a, b = f2 * x + e2, f2 if a * a - n * b * b == 1: return a, b for n in [61, 109, 181, 277]: x, y = solvePell(n) print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))
package main import ( "fmt" "math/big" ) var big1 = new(big.Int).SetUint64(1) func solvePell(nn uint64) (*big.Int, *big.Int) { n := new(big.Int).SetUint64(nn) x := new(big.Int).Set(n) x.Sqrt(x) y := new(big.Int).Set(x) z := new(big.Int).SetUint64(1) r := new(big.Int).Lsh(x, 1) e1 := new(big.Int).SetUint64(1) e2 := new(big.Int) f1 := new(big.Int) f2 := new(big.Int).SetUint64(1) t := new(big.Int) u := new(big.Int) a := new(big.Int) b := new(big.Int) for { t.Mul(r, z) y.Sub(t, y) t.Mul(y, y) t.Sub(n, t) z.Quo(t, z) t.Add(x, y) r.Quo(t, z) u.Set(e1) e1.Set(e2) t.Mul(r, e2) e2.Add(t, u) u.Set(f1) f1.Set(f2) t.Mul(r, f2) f2.Add(t, u) t.Mul(x, f2) a.Add(e2, t) b.Set(f2) t.Mul(a, a) u.Mul(n, b) u.Mul(u, b) t.Sub(t, u) if t.Cmp(big1) == 0 { return a, b } } } func main() { ns := []uint64{61, 109, 181, 277} for _, n := range ns { x, y := solvePell(n) fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y) } }
Write a version of this Python function in Go with identical behavior.
import random digits = '123456789' size = 4 chosen = ''.join(random.sample(digits,size)) print % (size, size) guesses = 0 while True: guesses += 1 while True: guess = raw_input('\nNext guess [%i]: ' % guesses).strip() if len(guess) == size and \ all(char in digits for char in guess) \ and len(set(guess)) == size: break print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size if guess == chosen: print '\nCongratulations you guessed correctly in',guesses,'attempts' break bulls = cows = 0 for i in range(size): if guess[i] == chosen[i]: bulls += 1 elif guess[i] in chosen: cows += 1 print ' %i Bulls\n %i Cows' % (bulls, cows)
package main import ( "bufio" "bytes" "fmt" "math/rand" "os" "strings" "time" ) func main() { fmt.Println(`Cows and Bulls Guess four digit number of unique digits in the range 1 to 9. A correct digit but not in the correct place is a cow. A correct digit in the correct place is a bull.`) pat := make([]byte, 4) rand.Seed(time.Now().Unix()) r := rand.Perm(9) for i := range pat { pat[i] = '1' + byte(r[i]) } valid := []byte("123456789") guess: for in := bufio.NewReader(os.Stdin); ; { fmt.Print("Guess: ") guess, err := in.ReadString('\n') if err != nil { fmt.Println("\nSo, bye.") return } guess = strings.TrimSpace(guess) if len(guess) != 4 { fmt.Println("Please guess a four digit number.") continue } var cows, bulls int for ig, cg := range guess { if strings.IndexRune(guess[:ig], cg) >= 0 { fmt.Printf("Repeated digit: %c\n", cg) continue guess } switch bytes.IndexByte(pat, byte(cg)) { case -1: if bytes.IndexByte(valid, byte(cg)) == -1 { fmt.Printf("Invalid digit: %c\n", cg) continue guess } default: cows++ case ig: bulls++ } } fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls) if bulls == 4 { fmt.Println("You got it.") return } } }
Write the same code in Go as shown below in Python.
def bubble_sort(seq): changed = True while changed: changed = False for i in range(len(seq) - 1): if seq[i] > seq[i+1]: seq[i], seq[i+1] = seq[i+1], seq[i] changed = True return seq if __name__ == "__main__": from random import shuffle testset = [_ for _ in range(100)] testcase = testset.copy() shuffle(testcase) assert testcase != testset bubble_sort(testcase) assert testcase == testset
package main import "fmt" func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list) bubblesort(list) fmt.Println("sorted! ", list) } func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for n in range(1,51)])
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } return prod } func main() { fmt.Println("The products of positive divisors for the first 50 positive integers are:") for i := 1; i <= 50; i++ { fmt.Printf("%9d ", prodDivisors(i)) if i%5 == 0 { fmt.Println() } } }
Write the same code in Go as shown below in Python.
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for n in range(1,51)])
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } return prod } func main() { fmt.Println("The products of positive divisors for the first 50 positive integers are:") for i := 1; i <= 50; i++ { fmt.Printf("%9d ", prodDivisors(i)) if i%5 == 0 { fmt.Println() } } }
Convert the following code from Python to Go, ensuring the logic remains intact.
import shutil shutil.copyfile('input.txt', 'output.txt')
package main import ( "fmt" "io/ioutil" ) func main() { b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) } }
Rewrite the snippet below in Go so it works the same as the original Python code.
x = int(raw_input("Number 1: ")) y = int(raw_input("Number 2: ")) print "Sum: %d" % (x + y) print "Difference: %d" % (x - y) print "Product: %d" % (x * y) print "Quotient: %d" % (x / y) print "Remainder: %d" % (x % y) print "Quotient: %d with Remainder: %d" % divmod(x, y) print "Power: %d" % x**y raw_input( )
package main import "fmt" func main() { var a, b int fmt.Print("enter two integers: ") fmt.Scanln(&a, &b) fmt.Printf("%d + %d = %d\n", a, b, a+b) fmt.Printf("%d - %d = %d\n", a, b, a-b) fmt.Printf("%d * %d = %d\n", a, b, a*b) fmt.Printf("%d / %d = %d\n", a, b, a/b) fmt.Printf("%d %% %d = %d\n", a, b, a%b) }
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
m=((1, 1, 1, 1), (2, 4, 8, 16), (3, 9, 27, 81), (4, 16, 64, 256), (5, 25,125, 625)) print(zip(*m))
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { m := mat.NewDense(2, 3, []float64{ 1, 2, 3, 4, 5, 6, }) fmt.Println(mat.Formatted(m)) fmt.Println() fmt.Println(mat.Formatted(m.T())) }
Convert the following code from Python to Go, ensuring the logic remains intact.
import sys sys.setrecursionlimit(1025) def a(in_k, x1, x2, x3, x4, x5): k = [in_k] def b(): k[0] -= 1 return a(k[0], b, x1, x2, x3, x4) return x4() + x5() if k[0] <= 0 else b() x = lambda i: lambda: i print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
package main import "fmt" func a(k int, x1, x2, x3, x4, x5 func() int) int { var b func() int b = func() int { k-- return a(k, b, x1, x2, x3, x4) } if k <= 0 { return x4() + x5() } return b() } func main() { x := func(i int) func() int { return func() int { return i } } fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0))) }
Write the same code in Go as shown below in Python.
>>> def a(answer): print(" return answer >>> def b(answer): print(" return answer >>> for i in (False, True): for j in (False, True): print ("\nCalculating: x = a(i) and b(j)") x = a(i) and b(j) print ("Calculating: y = a(i) or b(j)") y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j)
package main import "fmt" func a(v bool) bool { fmt.Print("a") return v } func b(v bool) bool { fmt.Print("b") return v } func test(i, j bool) { fmt.Printf("Testing a(%t) && b(%t)\n", i, j) fmt.Print("Trace: ") fmt.Println("\nResult:", a(i) && b(j)) fmt.Printf("Testing a(%t) || b(%t)\n", i, j) fmt.Print("Trace: ") fmt.Println("\nResult:", a(i) || b(j)) fmt.Println("") } func main() { test(false, false) test(false, true) test(true, false) test(true, true) }
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
import sys print(sys.getrecursionlimit())
package main import ( "flag" "fmt" "runtime/debug" ) func main() { stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default") flag.Parse() if *stack > 0 { debug.SetMaxStack(*stack) } r(1) } func r(l int) { if l%1000 == 0 { fmt.Println(l) } r(l + 1) }
Generate a C++ translation of this VB snippet without changing its computational steps.
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)
#include <iostream> void bitwise(int a, int b) { std::cout << "a and b: " << (a & b) << '\n'; std::cout << "a or b: " << (a | b) << '\n'; std::cout << "a xor b: " << (a ^ b) << '\n'; std::cout << "not a: " << ~a << '\n'; std::cout << "a shl b: " << (a << b) << '\n'; std::cout << "a shr b: " << (a >> b) << '\n'; unsigned int ua = a; std::cout << "a lsr b: " << (ua >> b) << '\n'; std::cout << "a rol b: " << std::rotl(ua, b) << '\n'; std::cout << "a ror b: " << std::rotr(ua, b) << '\n'; }
Convert the following code from VB to C++, ensuring the logic remains intact.
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
#include <windows.h> #include <iostream> using namespace std; const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class dragonC { public: dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; } void draw( int iterations ) { generate( iterations ); draw(); } private: void generate( int it ) { generator.push_back( 1 ); string temp; for( int y = 0; y < it - 1; y++ ) { temp = generator; temp.push_back( 1 ); for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ ) temp.push_back( !( *x ) ); generator = temp; } } void draw() { HDC dc = bmp.getDC(); unsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff }; int mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0; for( int t = 0; t < 4; t++ ) { int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++]; MoveToEx( dc, a, b, NULL ); bmp.setPenColor( clr[t] ); for( string::iterator x = generator.begin(); x < generator.end(); x++ ) { switch( dir ) { case NORTH: if( *x ) { a += LEN; dir = EAST; } else { a -= LEN; dir = WEST; } break; case EAST: if( *x ) { b += LEN; dir = SOUTH; } else { b -= LEN; dir = NORTH; } break; case SOUTH: if( *x ) { a -= LEN; dir = WEST; } else { a += LEN; dir = EAST; } break; case WEST: if( *x ) { b -= LEN; dir = NORTH; } else { b += LEN; dir = SOUTH; } } LineTo( dc, a, b ); } } bmp.saveBitmap( "f:/rc/dragonCpp.bmp" ); } int dir; myBitmap bmp; string generator; }; int main( int argc, char* argv[] ) { dragonC d; d.draw( 17 ); return system( "pause" ); }
Please provide an equivalent version of this VB code in C++.
$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$
#include <fstream> #include <string> #include <iostream> int main( int argc , char** argv ) { int linecount = 0 ; std::string line ; std::ifstream infile( argv[ 1 ] ) ; if ( infile ) { while ( getline( infile , line ) ) { std::cout << linecount << ": " << line << '\n' ; linecount++ ; } } infile.close( ) ; return 0 ; }
Rewrite this program in C++ while keeping its functionality equivalent to the VB version.
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
template <typename T> void insert_after(Node<T>* N, T&& data) { auto node = new Node<T>{N, N->next, std::forward(data)}; if(N->next != nullptr) N->next->prev = node; N->next = node; }
Write the same algorithm in C++ as shown in this VB implementation.
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
#include <algorithm> #include <iostream> int main() { for (int i = 0; i < 10; i++) { int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a)); std::cout << a[i]; if (i < 9) std::cout << ", "; } std::cout << std::endl; return 0; }
Translate the given VB code snippet into C++ without altering its behavior.
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
#include <string> #include <cstdlib> #include <algorithm> #include <cassert> std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz"; std::string to_base(unsigned long num, int base) { if (num == 0) return "0"; std::string result; while (num > 0) { std::ldiv_t temp = std::div(num, (long)base); result += digits[temp.rem]; num = temp.quot; } std::reverse(result.begin(), result.end()); return result; } unsigned long from_base(std::string const& num_str, int base) { unsigned long result = 0; for (std::string::size_type pos = 0; pos < num_str.length(); ++pos) result = result * base + digits.find(num_str[pos]); return result; }
Generate a C++ translation of this VB snippet without changing its computational steps.
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
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
Port the provided VB code into C++ while preserving the original functionality.
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"))
#include <algorithm> #include <array> #include <cstdint> #include <numeric> #include <iomanip> #include <iostream> #include <string> std::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept { auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL}; struct byte_checksum { std::uint_fast32_t operator()() noexcept { auto checksum = static_cast<std::uint_fast32_t>(n++); for (auto i = 0; i < 8; ++i) checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0); return checksum; } unsigned n = 0; }; auto table = std::array<std::uint_fast32_t, 256>{}; std::generate(table.begin(), table.end(), byte_checksum{}); return table; } template <typename InputIterator> std::uint_fast32_t crc(InputIterator first, InputIterator last) { static auto const table = generate_crc_lookup_table(); return std::uint_fast32_t{0xFFFFFFFFuL} & ~std::accumulate(first, last, ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL}, [](std::uint_fast32_t checksum, std::uint_fast8_t value) { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); }); } int main() { auto const s = std::string{"The quick brown fox jumps over the lazy dog"}; std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\n'; }
Produce a language-to-language conversion: from VB to C++, same semantics.
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
#include <string> #include <boost/regex.hpp> #include <iostream> std::string csvToHTML( const std::string & ) ; int main( ) { std::string text = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!\n" ; std::cout << csvToHTML( text ) ; return 0 ; } std::string csvToHTML( const std::string & csvtext ) { std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ; const char* replacements [ 5 ] = { "&lt;" , "&gt;" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ; boost::regex e1( regexes[ 0 ] ) ; std::string tabletext = boost::regex_replace( csvtext , e1 , replacements[ 0 ] , boost::match_default | boost::format_all ) ; for ( int i = 1 ; i < 5 ; i++ ) { e1.assign( regexes[ i ] ) ; tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ; } tabletext = std::string( "<TABLE>\n" ) + tabletext ; tabletext.append( "</TABLE>\n" ) ; return tabletext ; }
Convert this VB block to C++, preserving its control flow and logic.
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
#include <string> #include <boost/regex.hpp> #include <iostream> std::string csvToHTML( const std::string & ) ; int main( ) { std::string text = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!\n" ; std::cout << csvToHTML( text ) ; return 0 ; } std::string csvToHTML( const std::string & csvtext ) { std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ; const char* replacements [ 5 ] = { "&lt;" , "&gt;" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ; boost::regex e1( regexes[ 0 ] ) ; std::string tabletext = boost::regex_replace( csvtext , e1 , replacements[ 0 ] , boost::match_default | boost::format_all ) ; for ( int i = 1 ; i < 5 ; i++ ) { e1.assign( regexes[ i ] ) ; tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ; } tabletext = std::string( "<TABLE>\n" ) + tabletext ; tabletext.append( "</TABLE>\n" ) ; return tabletext ; }
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
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
#include <string> #include <boost/regex.hpp> #include <iostream> std::string csvToHTML( const std::string & ) ; int main( ) { std::string text = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you?\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!\n" ; std::cout << csvToHTML( text ) ; return 0 ; } std::string csvToHTML( const std::string & csvtext ) { std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ; const char* replacements [ 5 ] = { "&lt;" , "&gt;" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ; boost::regex e1( regexes[ 0 ] ) ; std::string tabletext = boost::regex_replace( csvtext , e1 , replacements[ 0 ] , boost::match_default | boost::format_all ) ; for ( int i = 1 ; i < 5 ; i++ ) { e1.assign( regexes[ i ] ) ; tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ; } tabletext = std::string( "<TABLE>\n" ) + tabletext ; tabletext.append( "</TABLE>\n" ) ; return tabletext ; }
Port the provided VB code into C++ while preserving the original functionality.
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
PRAGMA COMPILER g++ PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive OPTION PARSE FALSE '---The class does the declaring for you CLASS Books public: const char* title; const char* author; const char* subject; int book_id; END CLASS '---pointer to an object declaration (we use a class called Books) DECLARE Book1 TYPE Books '--- the correct syntax for class Book1 = Books() '--- initialize the strings const char* in c++ Book1.title = "C++ Programming to bacon " Book1.author = "anyone" Book1.subject ="RECORD Tutorial" Book1.book_id = 1234567 PRINT "Book title  : " ,Book1.title FORMAT "%s%s\n" PRINT "Book author  : ", Book1.author FORMAT "%s%s\n" PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n" PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"
Preserve the algorithm and functionality while converting the code from VB to C++.
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
#include <vector> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <utility> long string2long( const std::string & s ) { long result ; std::istringstream( s ) >> result ; return result ; } bool isKaprekar( long number ) { long long squarenumber = ((long long)number) * number ; std::ostringstream numberbuf ; numberbuf << squarenumber ; std::string numberstring = numberbuf.str( ) ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) { std::string firstpart = numberstring.substr( 0 , i ) , secondpart = numberstring.substr( i ) ; if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) { return false ; } if ( string2long( firstpart ) + string2long( secondpart ) == number ) { return true ; } } return false ; } int main( ) { std::vector<long> kaprekarnumbers ; kaprekarnumbers.push_back( 1 ) ; for ( int i = 2 ; i < 1000001 ; i++ ) { if ( isKaprekar( i ) ) kaprekarnumbers.push_back( i ) ; } std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ; std::cout << "Kaprekar numbers up to 10000: \n" ; while ( *svi < 10000 ) { std::cout << *svi << " " ; svi++ ; } std::cout << '\n' ; std::cout << "All the Kaprekar numbers up to 1000000 :\n" ; std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) , std::ostream_iterator<long>( std::cout , "\n" ) ) ; std::cout << "There are " << kaprekarnumbers.size( ) << " Kaprekar numbers less than one million!\n" ; return 0 ; }
Please provide an equivalent version of this VB code in C++.
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
#include <vector> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <utility> long string2long( const std::string & s ) { long result ; std::istringstream( s ) >> result ; return result ; } bool isKaprekar( long number ) { long long squarenumber = ((long long)number) * number ; std::ostringstream numberbuf ; numberbuf << squarenumber ; std::string numberstring = numberbuf.str( ) ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) { std::string firstpart = numberstring.substr( 0 , i ) , secondpart = numberstring.substr( i ) ; if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) { return false ; } if ( string2long( firstpart ) + string2long( secondpart ) == number ) { return true ; } } return false ; } int main( ) { std::vector<long> kaprekarnumbers ; kaprekarnumbers.push_back( 1 ) ; for ( int i = 2 ; i < 1000001 ; i++ ) { if ( isKaprekar( i ) ) kaprekarnumbers.push_back( i ) ; } std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ; std::cout << "Kaprekar numbers up to 10000: \n" ; while ( *svi < 10000 ) { std::cout << *svi << " " ; svi++ ; } std::cout << '\n' ; std::cout << "All the Kaprekar numbers up to 1000000 :\n" ; std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) , std::ostream_iterator<long>( std::cout , "\n" ) ) ; std::cout << "There are " << kaprekarnumbers.size( ) << " Kaprekar numbers less than one million!\n" ; return 0 ; }
Generate an equivalent C++ version of this VB code.
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
#include <string> #include <map> template <typename Iterator> Iterator compress(const std::string &uncompressed, Iterator result) { int dictSize = 256; std::map<std::string,int> dictionary; for (int i = 0; i < 256; i++) dictionary[std::string(1, i)] = i; std::string w; for (std::string::const_iterator it = uncompressed.begin(); it != uncompressed.end(); ++it) { char c = *it; std::string wc = w + c; if (dictionary.count(wc)) w = wc; else { *result++ = dictionary[w]; dictionary[wc] = dictSize++; w = std::string(1, c); } } if (!w.empty()) *result++ = dictionary[w]; return result; } template <typename Iterator> std::string decompress(Iterator begin, Iterator end) { int dictSize = 256; std::map<int,std::string> dictionary; for (int i = 0; i < 256; i++) dictionary[i] = std::string(1, i); std::string w(1, *begin++); std::string result = w; std::string entry; for ( ; begin != end; begin++) { int k = *begin; if (dictionary.count(k)) entry = dictionary[k]; else if (k == dictSize) entry = w + w[0]; else throw "Bad compressed k"; result += entry; dictionary[dictSize++] = w + entry[0]; w = entry; } return result; } #include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> compressed; compress("TOBEORNOTTOBEORTOBEORNOT", std::back_inserter(compressed)); copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; std::string decompressed = decompress(compressed.begin(), compressed.end()); std::cout << decompressed << std::endl; return 0; }
Transform the following VB implementation into C++, maintaining the same output and logic.
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
#include <iomanip> #include <iostream> #include <set> #include <vector> using namespace std; unsigned hofstadter(unsigned rlistSize, unsigned slistSize) { auto n = rlistSize > slistSize ? rlistSize : slistSize; auto rlist = new vector<unsigned> { 1, 3, 7 }; auto slist = new vector<unsigned> { 2, 4, 5, 6 }; auto list = rlistSize > 0 ? rlist : slist; auto target_size = rlistSize > 0 ? rlistSize : slistSize; while (list->size() > target_size) list->pop_back(); while (list->size() < target_size) { auto lastIndex = rlist->size() - 1; auto lastr = (*rlist)[lastIndex]; auto r = lastr + (*slist)[lastIndex]; rlist->push_back(r); for (auto s = lastr + 1; s < r && list->size() < target_size;) slist->push_back(s++); } auto v = (*list)[n - 1]; delete rlist; delete slist; return v; } ostream& operator<<(ostream& os, const set<unsigned>& s) { cout << '(' << s.size() << "):"; auto i = 0; for (auto c = s.begin(); c != s.end();) { if (i++ % 20 == 0) os << endl; os << setw(5) << *c++; } return os; } int main(int argc, const char* argv[]) { const auto v1 = atoi(argv[1]); const auto v2 = atoi(argv[2]); set<unsigned> r, s; for (auto n = 1; n <= v2; n++) { if (n <= v1) r.insert(hofstadter(n, 0)); s.insert(hofstadter(0, n)); } cout << "R" << r << endl; cout << "S" << s << endl; int m = max(*r.rbegin(), *s.rbegin()); for (auto n = 1; n <= m; n++) if (r.count(n) == s.count(n)) clog << "integer " << n << " either in both or neither set" << endl; return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the VB version.
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
#include <iomanip> #include <iostream> #include <set> #include <vector> using namespace std; unsigned hofstadter(unsigned rlistSize, unsigned slistSize) { auto n = rlistSize > slistSize ? rlistSize : slistSize; auto rlist = new vector<unsigned> { 1, 3, 7 }; auto slist = new vector<unsigned> { 2, 4, 5, 6 }; auto list = rlistSize > 0 ? rlist : slist; auto target_size = rlistSize > 0 ? rlistSize : slistSize; while (list->size() > target_size) list->pop_back(); while (list->size() < target_size) { auto lastIndex = rlist->size() - 1; auto lastr = (*rlist)[lastIndex]; auto r = lastr + (*slist)[lastIndex]; rlist->push_back(r); for (auto s = lastr + 1; s < r && list->size() < target_size;) slist->push_back(s++); } auto v = (*list)[n - 1]; delete rlist; delete slist; return v; } ostream& operator<<(ostream& os, const set<unsigned>& s) { cout << '(' << s.size() << "):"; auto i = 0; for (auto c = s.begin(); c != s.end();) { if (i++ % 20 == 0) os << endl; os << setw(5) << *c++; } return os; } int main(int argc, const char* argv[]) { const auto v1 = atoi(argv[1]); const auto v2 = atoi(argv[2]); set<unsigned> r, s; for (auto n = 1; n <= v2; n++) { if (n <= v1) r.insert(hofstadter(n, 0)); s.insert(hofstadter(0, n)); } cout << "R" << r << endl; cout << "S" << s << endl; int m = max(*r.rbegin(), *s.rbegin()); for (auto n = 1; n <= m; n++) if (r.count(n) == s.count(n)) clog << "integer " << n << " either in both or neither set" << endl; return 0; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
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
#include <iostream> #include <sstream> #include <iomanip> #include <cassert> #include <vector> using namespace std; class MagicSquare { public: MagicSquare(int d) : sqr(d*d,0), sz(d) { assert(d&1); fillSqr(); } void display() { cout << "Odd Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) cout << setw( l + 2 ) << sqr[yy + x]; cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { int sx = sz / 2, sy = 0, c = 0; while( c < sz * sz ) { if( !sqr[sx + sy * sz] ) { sqr[sx + sy * sz]= c + 1; inc( sx ); dec( sy ); c++; } else { dec( sx ); inc( sy ); inc( sy ); } } } int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } vector<int> sqr; int sz; }; int main() { MagicSquare s(7); s.display(); return 0; }
Change the following VB code into C++ 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
#include <iostream> #include <sstream> #include <iomanip> #include <cassert> #include <vector> using namespace std; class MagicSquare { public: MagicSquare(int d) : sqr(d*d,0), sz(d) { assert(d&1); fillSqr(); } void display() { cout << "Odd Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) cout << setw( l + 2 ) << sqr[yy + x]; cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { int sx = sz / 2, sy = 0, c = 0; while( c < sz * sz ) { if( !sqr[sx + sy * sz] ) { sqr[sx + sy * sz]= c + 1; inc( sx ); dec( sy ); c++; } else { dec( sx ); inc( sy ); inc( sy ); } } } int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } vector<int> sqr; int sz; }; int main() { MagicSquare s(7); s.display(); return 0; }