Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Ensure the translated Go code behaves exactly like the original Python snippet.
import cmath def dft( x ): N = len( x ) result = [] for k in range( N ): r = 0 for n in range( N ): t = -2j * cmath.pi * k * n / N r += x[n] * cmath.exp( t ...
package main import ( "fmt" "math" "math/cmplx" ) func dft(x []complex128) []complex128 { N := len(x) y := make([]complex128, N) for k := 0; k < N; k++ { for n := 0; n < N; n++ { t := -1i * 2 * complex(math.Pi*float64(k)*float64(n)/float64(N), 0) y[k] += x[n] * ...
Change the programming language of this snippet from Python to Go without modifying what it does.
from itertools import count def firstGap(xs): return next(x for x in count(1) if x not in xs) def main(): print('\n'.join([ f'{repr(xs)} -> {firstGap(xs)}' for xs in [ [1, 2, 0], [3, 4, -1, 1], [7, 8, 9, 11, 12] ] ])) if __name__ == '...
package main import ( "fmt" "sort" ) func firstMissingPositive(a []int) int { var b []int for _, e := range a { if e > 0 { b = append(b, e) } } sort.Ints(b) le := len(b) if le == 0 || b[0] > 1 { return 1 } for i := 1; i < le; i++ { if...
Write the same code in Go as shown below in Python.
from spell_integer import spell_integer, SMALL, TENS, HUGE def int_from_words(num): words = num.replace(',','').replace(' and ', ' ').replace('-', ' ').split() if words[0] == 'minus': negmult = -1 words.pop(0) else: negmult = 1 small, total = 0, 0 for word in words: ...
package main import ( "fmt" "math" "regexp" "strings" ) var names = map[string]int64{ "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": ...
Transform the following Python implementation into Go, maintaining the same output and logic.
def a(n): n += 2 return n*(n**2 + 1)/2 def inv_a(x): k = 0 while k*(k**2+1)/2+2 < x: k+=1 return k if __name__ == '__main__': print("The first 20 magic constants are:"); for n in range(1, 20): print(int(a(n)), end = " "); print("\nThe 1,000th magic constant is:",in...
package main import ( "fmt" "math" "rcu" ) func magicConstant(n int) int { return (n*n + 1) * n / 2 } var ss = []string{ "\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079", } func superscript(n int) string { if n < 10 { return ss[n]...
Write the same code in Go as shown below in Python.
def makechange(denominations = [1,2,5,10,20,50,100,200], total = 988): print(f"Available denominations: {denominations}. Total is to be: {total}.") coins, remaining = sorted(denominations, reverse=True), total for n in range(len(coins)): coinsused, remaining = divmod(remaining, coins[n]) if ...
package main import "fmt" func main() { denoms := []int{200, 100, 50, 20, 10, 5, 2, 1} coins := 0 amount := 988 remaining := 988 fmt.Println("The minimum number of coins needed to make a value of", amount, "is as follows:") for _, denom := range denoms { n := remaining / denom ...
Convert this Python block to Go, preserving its control flow and logic.
def prime(limite, mostrar): global columna columna = 0 for n in range(limite): strn = str(n) if isPrime(n) and ('123' in str(n)): columna += 1 if mostrar == True: print(n, end=" "); if columna % 8 == 0: ...
package main import ( "fmt" "rcu" "strings" ) func main() { limit := 100_000 primes := rcu.Primes(limit * 10) var results []int for _, p := range primes { if p < 1000 || p > 99999 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "1...
Change the following Python code into Go without altering its purpose.
def prime(limite, mostrar): global columna columna = 0 for n in range(limite): strn = str(n) if isPrime(n) and ('123' in str(n)): columna += 1 if mostrar == True: print(n, end=" "); if columna % 8 == 0: ...
package main import ( "fmt" "rcu" "strings" ) func main() { limit := 100_000 primes := rcu.Primes(limit * 10) var results []int for _, p := range primes { if p < 1000 || p > 99999 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "1...
Preserve the algorithm and functionality while converting the code from Python to Go.
import ast class CallCountingVisitor(ast.NodeVisitor): def __init__(self): self.calls = {} def visit_Call(self, node): if isinstance(node.func, ast.Name): fun_name = node.func.id call_count = self.calls.get(fun_name, 0) self.calls[fun_name] = call_count + 1...
package main import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "sort" ) func main() { if len(os.Args) != 2 { fmt.Println("usage ff <go source filename>") return } src, err := ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err) ...
Write the same code in Go as shown below in Python.
import random price_list_size = random.choice(range(99_000, 101_000)) price_list = random.choices(range(100_000), k=price_list_size) delta_price = 1 def get_prange_count(startp, endp): return len([r for r in price_list if startp <= r <= endp]) def get_max_price(): return max(price_list) def get_5k(...
package main import ( "fmt" "log" "math" "math/rand" "time" ) var minDelta = 1.0 func getMaxPrice(prices []float64) float64 { max := prices[0] for i := 1; i < len(prices); i++ { if prices[i] > max { max = prices[i] } } return max } func getPRangeCount(...
Translate the given Python code snippet into Go without altering its behavior.
print("working...") print("First 20 Cullen numbers:") for n in range(1,21): num = n*pow(2,n)+1 print(str(num),end= " ") print() print("First 20 Woodall numbers:") for n in range(1,21): num = n*pow(2,n)-1 print(str(num),end=" ") print() print("done...")
package main import ( "fmt" big "github.com/ncw/gmp" ) func cullen(n uint) *big.Int { one := big.NewInt(1) bn := big.NewInt(int64(n)) res := new(big.Int).Lsh(one, n) res.Mul(res, bn) return res.Add(res, one) } func woodall(n uint) *big.Int { res := cullen(n) return res.Sub(res, bi...
Convert this Python block to Go, preserving its control flow and logic.
from sympy import isprime def print50(a, width=8): for i, n in enumerate(a): print(f'{n: {width},}', end='\n' if (i + 1) % 10 == 0 else '') def generate_cyclops(maxdig=9): yield 0 for d in range((maxdig + 1) // 2): arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))] ...
package main import ( "fmt" "rcu" "strconv" "strings" ) func findFirst(list []int) (int, int) { for i, n := range list { if n > 1e7 { return n, i } } return -1, -1 } func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; ...
Produce a functionally identical Go code for the snippet given in Python.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 5499, 2): if not isPrime(p+6): continue if not isPrime(p+2): continue if not isPrime(p): ...
package main import ( "fmt" "rcu" ) func main() { c := rcu.PrimeSieve(5505, false) var triples [][3]int fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:") for i := 3; i < 5500; i += 2 { if !c[i] && !c[i+2] && !c[i+6] { triples = append(triples, [3]int{i, i + 2,...
Convert this Python block to Go, preserving its control flow and logic.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 5499, 2): if not isPrime(p+6): continue if not isPrime(p+2): continue if not isPrime(p): ...
package main import ( "fmt" "rcu" ) func main() { c := rcu.PrimeSieve(5505, false) var triples [][3]int fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:") for i := 3; i < 5500; i += 2 { if !c[i] && !c[i+2] && !c[i+6] { triples = append(triples, [3]int{i, i + 2,...
Generate a Go translation of this Python snippet without changing its computational steps.
def validate_position(candidate: str): assert ( len(candidate) == 8 ), f"candidate position has invalide len = {len(candidate)}" valid_pieces = {"R": 2, "N": 2, "B": 2, "Q": 1, "K": 1} assert { piece for piece in candidate } == valid_pieces.keys(), f"candidate position contains inv...
package main import ( "fmt" "log" "strings" ) var glyphs = []rune("♜♞♝♛♚♖♘♗♕♔") var names = map[rune]string{'R': "rook", 'N': "knight", 'B': "bishop", 'Q': "queen", 'K': "king"} var g2lMap = map[rune]string{ '♜': "R", '♞': "N", '♝': "B", '♛': "Q", '♚': "K", '♖': "R", '♘': "N", '♗': "B", '♕': "Q", ...
Port the provided Python code into Go while preserving the original functionality.
def conjugate(infinitive): if not infinitive[-3:] == "are": print("'", infinitive, "' non prima coniugatio verbi.\n", sep='') return False stem = infinitive[0:-3] if len(stem) == 0: print("\'", infinitive, "\' non satis diu conjugatus\n", sep='') return False p...
package main import ( "fmt" "log" ) var endings = [][]string{ {"o", "as", "at", "amus", "atis", "ant"}, {"eo", "es", "et", "emus", "etis", "ent"}, {"o", "is", "it", "imus", "itis", "unt"}, {"io", "is", "it", "imus", "itis", "iunt"}, } var infinEndings = []string{"are", "ēre", "ere", "ire"} v...
Produce a language-to-language conversion: from Python to Go, same semantics.
def conjugate(infinitive): if not infinitive[-3:] == "are": print("'", infinitive, "' non prima coniugatio verbi.\n", sep='') return False stem = infinitive[0:-3] if len(stem) == 0: print("\'", infinitive, "\' non satis diu conjugatus\n", sep='') return False p...
package main import ( "fmt" "log" ) var endings = [][]string{ {"o", "as", "at", "amus", "atis", "ant"}, {"eo", "es", "et", "emus", "etis", "ent"}, {"o", "is", "it", "imus", "itis", "unt"}, {"io", "is", "it", "imus", "itis", "iunt"}, } var infinEndings = []string{"are", "ēre", "ere", "ire"} v...
Convert this Python block to Go, preserving its control flow and logic.
from sympy.ntheory.generate import primorial from sympy.ntheory import isprime def fortunate_number(n): i = 3 primorial_ = primorial(n) while True: if isprime(primorial_ + i): return i i += 2 fortunate_numbers = set() for i in range(1, 76): fortunate_numbers....
package main import ( "fmt" "math/big" "rcu" "sort" ) func main() { primes := rcu.Primes(379) primorial := big.NewInt(1) var fortunates []int bPrime := new(big.Int) for _, prime := range primes { bPrime.SetUint64(uint64(prime)) primorial.Mul(primorial, bPrime) ...
Convert this Python block to Go, preserving its control flow and logic.
from itertools import chain, product, takewhile, tee from functools import cmp_to_key, reduce def sortedOutline(cmp): def go(outlineText): indentTuples = indentTextPairs( outlineText.splitlines() ) return bindLR( minimumIndent(enumerate(indentTuples)) ...
package main import ( "fmt" "math" "sort" "strings" ) func sortedOutline(originalOutline []string, ascending bool) { outline := make([]string, len(originalOutline)) copy(outline, originalOutline) indent := "" del := "\x7f" sep := "\x00" var messages []string if strings.Tri...
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
from math import gcd from functools import reduce def lcm(a, b): return 0 if 0 == a or 0 == b else ( abs(a * b) // gcd(a, b) ) for i in [10, 20, 200, 2000]: print(str(i) + ':', reduce(lcm, range(1, i + 1)))
package main import ( "fmt" "math/big" "rcu" ) func lcm(n int) *big.Int { lcm := big.NewInt(1) t := new(big.Int) for _, p := range rcu.Primes(n) { f := p for f*p <= n { f *= p } lcm.Mul(lcm, t.SetUint64(uint64(f))) } return lcm } func main()...
Transform the following Python implementation into Go, maintaining the same output and logic.
from math import log def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': Euler = 0.57721566490153286 m = 0 for x in range(2, 10_000_000): if isPrime(x): m += log(1-(1/x)) + (1/x) ...
package main import ( "fmt" "math" "rcu" ) func contains(a []int, f int) bool { for _, e := range a { if e == f { return true } } return false } func main() { const euler = 0.57721566490153286 primes := rcu.Primes(1 << 31) pc := len(primes) sum := 0...
Translate the given Python code snippet into Go without altering its behavior.
u = 'abcdé' print(ord(u[-1]))
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
Produce a functionally identical Go code for the snippet given in Python.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 j = 1 print(2, end = " "); while True: while True: if isPrime(p + j*j): break j += 1 ...
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] =...
Rewrite the snippet below in Go so it works the same as the original Python code.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 j = 1 print(2, end = " "); while True: while True: if isPrime(p + j*j): break j += 1 ...
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] =...
Translate this program into Go but keep the logic exactly as in Python.
import os from collections import Counter from functools import reduce from itertools import permutations BASES = ("A", "C", "G", "T") def deduplicate(sequences): sequences = set(sequences) duplicates = set() for s, t in permutations(sequences, 2): if s != t and s in t: duplica...
package main import ( "fmt" "strings" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func getPerms(input []string) [][]string { perms := [][]string{input} le := len(input) a := make([]string, le) copy(a, input) n := le...
Write the same algorithm in Go as shown in this Python implementation.
from __future__ import annotations from itertools import chain from typing import List from typing import NamedTuple from typing import Optional class Shape(NamedTuple): rows: int cols: int class Matrix(List): @classmethod def block(cls, blocks) -> Matrix: m = Matrix() ...
package main import ( "fmt" "log" "math" ) type Matrix [][]float64 func (m Matrix) rows() int { return len(m) } func (m Matrix) cols() int { return len(m[0]) } func (m Matrix) add(m2 Matrix) Matrix { if m.rows() != m2.rows() || m.cols() != m2.cols() { log.Fatal("Matrices must have the same d...
Convert this Python snippet to Go and keep its semantics consistent.
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
package main import ( "math" "os" "strconv" "text/template" ) func sqr(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(f*f, 'f', -1, 64) } func sqrt(x string) string { f, err := strconv.ParseFloat(x, 64) i...
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
package main import ( "math" "os" "strconv" "text/template" ) func sqr(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(f*f, 'f', -1, 64) } func sqrt(x string) string { f, err := strconv.ParseFloat(x, 64) i...
Rewrite the snippet below in Go so it works the same as the original Python code.
class empty(object): pass e = empty()
package main import ( "bufio" "fmt" "log" "os" ) type SomeStruct struct { runtimeFields map[string]string } func check(err error) { if err != nil { log.Fatal(err) } } func main() { ss := SomeStruct{make(map[string]string)} scanner := bufio.NewScanner(os.Stdin) fmt.Pri...
Please provide an equivalent version of this Python code in Go.
def perim_equal(p1, p2): if len(p1) != len(p2) or set(p1) != set(p2): return False if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))): return True p2 = p2[::-1] return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))) def edge_to_periphery(e): edges = sorted(e) p =...
package main import ( "fmt" "sort" ) func contains(s []int, f int) bool { for _, e := range s { if e == f { return true } } return false } func sliceEqual(s1, s2 []int) bool { for i := 0; i < len(s1); i++ { if s1[i] != s2[i] { return false ...
Write the same code in Go as shown below in Python.
from fractions import Fraction def gauss(m): n, p = len(m), len(m[0]) for i in range(n): k = max(range(i, n), key = lambda x: abs(m[x][i])) m[i], m[k] = m[k], m[i] t = 1 / m[i][i] for j in range(i + 1, p): m[i][j] *= t for j in range(i + 1, n): t = m[j][i] for k in range(i + 1, p): m[j][k] -= t * m[i...
package main import ( "fmt" "math" "strconv" "strings" ) func argmax(m [][]float64, i int) int { col := make([]float64, len(m)) max, maxx := -1.0, -1 for x := 0; x < len(m); x++ { col[x] = math.Abs(m[x][i]) if col[x] > max { max = col[x] maxx = x ...
Produce a language-to-language conversion: from Python to Go, same semantics.
from random import choice import regex as re import time def generate_sequence(n: int ) -> str: return "".join([ choice(['A','C','G','T']) for _ in range(n) ]) def dna_findall(needle: str, haystack: str) -> None: if sum(1 for _ in re.finditer(needle, haystack, overlapped=True)) == 0: print("No mat...
package main import ( "fmt" "math/rand" "regexp" "time" ) const base = "ACGT" func findDnaSubsequence(dnaSize, chunkSize int) { dnaSeq := make([]byte, dnaSize) for i := 0; i < dnaSize; i++ { dnaSeq[i] = base[rand.Intn(4)] } dnaStr := string(dnaSeq) dnaSubseq := make([]byte...
Write the same code in Go as shown below in Python.
from pprint import pprint as pp class Template(): def __init__(self, structure): self.structure = structure self.used_payloads, self.missed_payloads = [], [] def inject_payload(self, id2data): def _inject_payload(substruct, i2d, used, missed): used.extend(i2d[x...
package main import ( "fmt" "os" "sort" "strings" "text/template" ) func main() { const t = `[[[{{index .P 1}}, {{index .P 2}}], [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], {{index .P 5}}]] ` type S struct { P map[int]string } var s S s.P = map[int]string{ ...
Produce a language-to-language conversion: from Python to Go, same semantics.
from PIL import Image im = Image.open("boxes_1.jpg") im.save("boxes_1v2.ppm")
package main import ( "log" "os/exec" "raster" ) func main() { c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-") pipe, err := c.StdoutPipe() if err != nil { log.Fatal(err) } if err = c.Start(); err != nil { log.Fatal(err) } b, err := ...
Convert this Python block to Go, preserving its control flow and logic.
from PIL import Image im = Image.open("boxes_1.jpg") im.save("boxes_1v2.ppm")
package main import ( "log" "os/exec" "raster" ) func main() { c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-") pipe, err := c.StdoutPipe() if err != nil { log.Fatal(err) } if err = c.Start(); err != nil { log.Fatal(err) } b, err := ...
Produce a functionally identical Go code for the snippet given in Python.
from ctypes import Structure, c_int rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split() rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg" "_11 SCD SCS STD TC SRD RC" "_18 SRS DTR SQD RI DRS XTC" ).split() class RS232_9pin(Structure): _fields_ = [(__, c_int, 1) fo...
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota RD9 TD9 DTR9 SG9 DSR9 RTS9 CTS9 RI9 ) func main() { ...
Port the following code from Python to Go with equivalent syntax and logic.
from ctypes import Structure, c_int rs232_9pin = "_0 CD RD TD DTR SG DSR RTS CTS RI".split() rs232_25pin = ( "_0 PG TD RD RTS CTS DSR SG CD pos neg" "_11 SCD SCS STD TC SRD RC" "_18 SRS DTR SQD RI DRS XTC" ).split() class RS232_9pin(Structure): _fields_ = [(__, c_int, 1) fo...
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota RD9 TD9 DTR9 SG9 DSR9 RTS9 CTS9 RI9 ) func main() { ...
Rewrite the snippet below in Go so it works the same as the original Python code.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == "__main__": n = 0 num = 0 print('The first 20 pairs of numbers whose sum is prime:') while True: n += 1 suma = 2*n+1 if isPrime(suma...
package main import ( "fmt" "math" "rcu" ) func main() { limit := int(math.Log(1e7) * 1e7 * 1.2) primes := rcu.Primes(limit) fmt.Println("The first 20 pairs of natural numbers whose sum is prime are:") for i := 1; i <= 20; i++ { p := primes[i] hp := p / 2 fmt.Print...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
import random def encode(correct, guess): output_arr = [''] * len(correct) for i, (correct_char, guess_char) in enumerate(zip(correct, guess)): output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-' return ''.join(output_arr) def safe_int_input(prompt, min...
package main import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" ) func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number of ...
Keep all operations the same but rewrite the snippet in Go.
import random def encode(correct, guess): output_arr = [''] * len(correct) for i, (correct_char, guess_char) in enumerate(zip(correct, guess)): output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-' return ''.join(output_arr) def safe_int_input(prompt, min...
package main import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" ) func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number of ...
Change the programming language of this snippet from Python to Go without modifying what it does.
def maxDeltas(ns): pairs = [ (abs(a - b), (a, b)) for a, b in zip(ns, ns[1:]) ] delta = max(pairs, key=lambda ab: ab[0])[0] return [ ab for ab in pairs if delta == ab[0] ] def main(): maxPairs = maxDeltas([ 1, 8, 2, -3, 0, 1, 1, -2.3, 0...
package main import ( "fmt" "math" ) func main() { list := []float64{1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3} maxDiff := -1.0 var maxPairs [][2]float64 for i := 1; i < len(list); i++ { diff := math.Abs(list[i-1] - list[i]) if diff > maxDiff { maxDi...
Keep all operations the same but rewrite the snippet in Go.
from sympy import isprime, factorint def contains_its_prime_factors_all_over_7(n): if n < 10 or isprime(n): return False strn = str(n) pfacs = factorint(n).keys() return all(f > 9 and str(f) in strn for f in pfacs) found = 0 for n in range(1_000_000_000): if contains_its_prime_factors_all_...
package main import ( "fmt" "rcu" "strconv" "strings" ) func main() { count := 0 k := 11 * 11 var res []int for count < 20 { if k%3 == 0 || k%5 == 0 || k%7 == 0 { k += 2 continue } factors := rcu.PrimeFactors(k) if len(factors) > ...
Rewrite this program in Go while keeping its functionality equivalent to the Python version.
from sympy import isprime, factorint def contains_its_prime_factors_all_over_7(n): if n < 10 or isprime(n): return False strn = str(n) pfacs = factorint(n).keys() return all(f > 9 and str(f) in strn for f in pfacs) found = 0 for n in range(1_000_000_000): if contains_its_prime_factors_all_...
package main import ( "fmt" "rcu" "strconv" "strings" ) func main() { count := 0 k := 11 * 11 var res []int for count < 20 { if k%3 == 0 || k%5 == 0 || k%7 == 0 { k += 2 continue } factors := rcu.PrimeFactors(k) if len(factors) > ...
Maintain the same structure and functionality when rewriting this code in Go.
from itertools import zip_longest fc2 = NAME, WT, COV = 0, 1, 2 def right_type(txt): try: return float(txt) except ValueError: return txt def commas_to_list(the_list, lines, start_indent=0): for n, line in lines: indent = 0 while line.startswith(' ' * (4 * indent))...
package main import "fmt" type FCNode struct { name string weight int coverage float64 children []*FCNode parent *FCNode } func newFCN(name string, weight int, coverage float64) *FCNode { return &FCNode{name, weight, coverage, nil, nil} } func (n *FCNode) addChildren(nodes []*FCNode)...
Write the same code in Go as shown below in Python.
import numpy as np class ProjectorStack: def __init__(self, vec): self.vs = np.array(vec) def push(self, v): if len(self.vs) == 0: self.vs = np.array([v]) else: self.vs = np.append(self.vs, [v], axis=0) return self def pop(self): ...
package main import ( "fmt" "log" "math" "math/rand" "time" ) type Point struct{ x, y float64 } type Circle struct { c Point r float64 } func (p Point) String() string { return fmt.Sprintf("(%f, %f)", p.x, p.y) } func distSq(a, b Point) float64 { return (a.x-b.x)*(a.x-b.x) + (a.y-...
Change the following Python code into Go without altering its purpose.
from __future__ import annotations import itertools import re from abc import ABC from abc import abstractmethod from typing import Iterable from typing import Optional RE_SPEC = [ ( "INT_RANGE", r"\{(?P<int_start>[0-9]+)..(?P<int_stop>[0-9]+)(?:(?:..)?(?P<int_step>-?[0-9]+))?}", ), (...
package main import ( "fmt" "strconv" "strings" "unicode/utf8" ) func sign(n int) int { switch { case n < 0: return -1 case n > 0: return 1 } return 0 } func abs(n int) int { if n < 0 { return -n } return n } func parseRange(r string) []string ...
Translate this program into Go but keep the logic exactly as in Python.
from turtle import * from PIL import Image import time import subprocess colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"] screen = getscreen() inch_width = 11.0 inch_height = 8.5 pixels_per_inch = 100 pix_width = int(inch_width*pixels_per_inch) pix_height = int(inch_height*pixe...
package main import ( "github.com/fogleman/gg" "log" "os/exec" "runtime" ) var palette = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func pinstripe(dc *gg.Context) { w := dc.Width() h := dc.Height() / 7...
Preserve the algorithm and functionality while converting the code from Python to Go.
import re txt = def haspunctotype(s): return 'S' if '.' in s else 'E' if '!' in s else 'Q' if '?' in s else 'N' txt = re.sub('\n', '', txt) pars = [s.strip() for s in re.split("(?:(?:(?<=[\?\!\.])(?:))|(?:(?:)(?=[\?\!\.])))", txt)] if len(pars) % 2: pars.append('') for i in range(0, len(pars)-1, 2): p...
package main import ( "fmt" "strings" ) func sentenceType(s string) string { if len(s) == 0 { return "" } var types []string for _, c := range s { if c == '?' { types = append(types, "Q") } else if c == '!' { types = append(types, "E") } ...
Ensure the translated Go code behaves exactly like the original Python snippet.
revision = "October 13th 2020" elements = ( "hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine " "neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon " "potassium calcium scandium titanium vanadium chromium manganese iron " "cobalt nickel copper zinc gall...
package main import ( "fmt" "regexp" "strings" ) var elements = ` hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon ...
Convert the following code from Python to Go, ensuring the logic remains intact.
from operator import or_ from functools import reduce def set_right_adjacent_bits(n: int, b: int) -> int: return reduce(or_, (b >> x for x in range(n+1)), 0) if __name__ == "__main__": print("SAME n & Width.\n") n = 2 bits = "1000 0100 0010 0000" first = True for b_str in bits.split(): ...
package main import ( "fmt" "strings" ) type test struct { bs string n int } func setRightBits(bits []byte, e, n int) []byte { if e == 0 || n <= 0 { return bits } bits2 := make([]byte, len(bits)) copy(bits2, bits) for i := 0; i < e-1; i++ { c := bits[i] if...
Preserve the algorithm and functionality while converting the code from Python to Go.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 n = 1 print("2",end = " ") while True: if isPrime(p + n**3): p += n**3 n = 1 print(p,end = " ")...
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] =...
Write the same algorithm in Go as shown in this Python implementation.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 n = 1 print("2",end = " ") while True: if isPrime(p + n**3): p += n**3 n = 1 print(p,end = " ")...
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] =...
Can you help me rewrite this code in Go instead of Python, keeping it the same logically?
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 n = 1 print("2",end = " ") while True: if isPrime(p + n**3): p += n**3 n = 1 print(p,end = " ")...
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] =...
Generate a Go translation of this Python snippet without changing its computational steps.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': p = 2 n = 1 print("2",end = " ") while True: if isPrime(p + n**3): p += n**3 n = 1 print(p,end = " ")...
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] =...
Produce a language-to-language conversion: from Python to Go, same semantics.
ch32 = "0123456789bcdefghjkmnpqrstuvwxyz" bool2ch = {f"{i:05b}": ch for i, ch in enumerate(ch32)} ch2bool = {v : k for k, v in bool2ch.items()} def bisect(val, mn, mx, bits): mid = (mn + mx) / 2 if val < mid: bits <<= 1 mx = mid else: ...
package main import ( "fmt" "strings" ) type Location struct{ lat, lng float64 } func (loc Location) String() string { return fmt.Sprintf("[%f, %f]", loc.lat, loc.lng) } type Range struct{ lower, upper float64 } var gBase32 = "0123456789bcdefghjkmnpqrstuvwxyz" func encodeGeohash(loc Location, prec int) st...
Translate this program into Go but keep the logic exactly as in Python.
ch32 = "0123456789bcdefghjkmnpqrstuvwxyz" bool2ch = {f"{i:05b}": ch for i, ch in enumerate(ch32)} ch2bool = {v : k for k, v in bool2ch.items()} def bisect(val, mn, mx, bits): mid = (mn + mx) / 2 if val < mid: bits <<= 1 mx = mid else: ...
package main import ( "fmt" "strings" ) type Location struct{ lat, lng float64 } func (loc Location) String() string { return fmt.Sprintf("[%f, %f]", loc.lat, loc.lng) } type Range struct{ lower, upper float64 } var gBase32 = "0123456789bcdefghjkmnpqrstuvwxyz" func encodeGeohash(loc Location, prec int) st...
Maintain the same structure and functionality when rewriting this code in Go.
from itertools import groupby from unicodedata import decomposition, name from pprint import pprint as pp commonleaders = ['the'] replacements = {u'ß': 'ss', u'ſ': 's', u'ʒ': 's', } hexdigits = set('0123456789abcdef') decdigits = set('0123456789') def splitch...
package main import ( "fmt" "regexp" "sort" "strconv" "strings" ) var tests = []struct { descr string list []string }{ {"Ignoring leading spaces", []string{ "ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ...
Change the following Python code into Go without altering its purpose.
from itertools import groupby from unicodedata import decomposition, name from pprint import pprint as pp commonleaders = ['the'] replacements = {u'ß': 'ss', u'ſ': 's', u'ʒ': 's', } hexdigits = set('0123456789abcdef') decdigits = set('0123456789') def splitch...
package main import ( "fmt" "regexp" "sort" "strconv" "strings" ) var tests = []struct { descr string list []string }{ {"Ignoring leading spaces", []string{ "ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ...
Produce a language-to-language conversion: from Python to Go, same semantics.
from itertools import permutations for i in range(0,10): if i!=1: baseList = [1,1] baseList.append(i) [print(int(''.join(map(str,j)))) for j in sorted(set(permutations(baseList)))]
package main import ( "fmt" "rcu" ) func main() { fmt.Println("Decimal numbers under 1,000 whose digits include two 1's:") var results []int for i := 11; i <= 911; i++ { digits := rcu.Digits(i, 10) count := 0 for _, d := range digits { if d == 1 { ...
Convert the following code from Python to Go, ensuring the logic remains intact.
from itertools import permutations for i in range(0,10): if i!=1: baseList = [1,1] baseList.append(i) [print(int(''.join(map(str,j)))) for j in sorted(set(permutations(baseList)))]
package main import ( "fmt" "rcu" ) func main() { fmt.Println("Decimal numbers under 1,000 whose digits include two 1's:") var results []int for i := 11; i <= 911; i++ { digits := rcu.Digits(i, 10) count := 0 for _, d := range digits { if d == 1 { ...
Ensure the translated Go code behaves exactly like the original Python snippet.
import math szamok=[] limit = 1000 for i in range(1,int(math.ceil(math.sqrt(limit))),2): num = i*i if (num < 1000 and num > 99): szamok.append(num) print(szamok)
package main import ( "fmt" "math" ) func main() { pow := 1 for p := 0; p < 5; p++ { low := int(math.Ceil(math.Sqrt(float64(pow)))) if low%2 == 0 { low++ } pow *= 10 high := int(math.Sqrt(float64(pow))) var oddSq []int for i := low; i...
Rewrite the snippet below in Go so it works the same as the original Python code.
import math szamok=[] limit = 1000 for i in range(1,int(math.ceil(math.sqrt(limit))),2): num = i*i if (num < 1000 and num > 99): szamok.append(num) print(szamok)
package main import ( "fmt" "math" ) func main() { pow := 1 for p := 0; p < 5; p++ { low := int(math.Ceil(math.Sqrt(float64(pow)))) if low%2 == 0 { low++ } pow *= 10 high := int(math.Sqrt(float64(pow))) var oddSq []int for i := low; i...
Keep all operations the same but rewrite the snippet in C++.
Private Sub Iterate(ByVal list As LinkedList(Of Integer)) Dim node = list.First Do Until node Is Nothing node = node.Next Loop End Sub
#include <iostream> #include <forward_list> int main() { std::forward_list<int> list{1, 2, 3, 4, 5}; for (int e : list) std::cout << e << std::endl; }
Convert this VB snippet to C++ and keep its semantics consistent.
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) ...
#include <fstream> #include <cstdio> int main() { constexpr auto dimx = 800u, dimy = 800u; using namespace std; ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl; for (auto j = 0u; j < dimy; ++j) for (auto i = ...
Produce a language-to-language conversion: from VB to C++, same semantics.
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) ...
#include <fstream> #include <cstdio> int main() { constexpr auto dimx = 800u, dimy = 800u; using namespace std; ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl; for (auto j = 0u; j < dimy; ++j) for (auto i = ...
Translate the given VB code snippet into C++ without altering its behavior.
Option Explicit Sub DeleteFileOrDirectory() Dim myPath As String myPath = "C:\Users\surname.name\Desktop\Docs" Kill myPath & "\input.txt" RmDir myPath End Sub
#include <cstdio> #include <direct.h> int main() { remove( "input.txt" ); remove( "/input.txt" ); _rmdir( "docs" ); _rmdir( "/docs" ); return 0; }
Transform the following VB implementation into C++, maintaining the same output and logic.
Const MAX = 20 Const ITER = 1000000 Function expected(n As Long) As Double Dim sum As Double For i = 1 To n sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i) Next i expected = sum End Function Function test(n As Long) As Double Dim count As Long Dim x As L...
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<...
Translate the given VB code snippet into C++ without altering its behavior.
Const MAX = 20 Const ITER = 1000000 Function expected(n As Long) As Double Dim sum As Double For i = 1 To n sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i) Next i expected = sum End Function Function test(n As Long) As Double Dim count As Long Dim x As L...
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<...
Write the same code in C++ as shown below in VB.
Dim name as String = "J. Doe" Dim balance as Double = 123.45 Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance) Console.WriteLine(prompt)
#include <string> #include <iostream> int main( ) { std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , replacement ( "little" ) ; std::string newString = original.replace( original.find( "X" ) , toBeReplaced.length( ) , replacement ) ; std::cout << "String after replacement: " << new...
Rewrite this program in C++ while keeping its functionality equivalent to the VB version.
Module Module1 Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,) Dim length = a.GetLength(0) - 1 Dim result(length - 1, length - 1) As Double For i = 1 To length For j = 1 To length If i < x AndAlso j < y Then result(i - ...
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *i...
Translate this program into C++ but keep the logic exactly as in VB.
Module Module1 Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,) Dim length = a.GetLength(0) - 1 Dim result(length - 1, length - 1) As Double For i = 1 To length For j = 1 To length If i < x AndAlso j < y Then result(i - ...
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *i...
Write the same code in C++ as shown below in VB.
Imports System.Math Module RayCasting Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}} Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, ...
#include <algorithm> #include <cstdlib> #include <iomanip> #include <iostream> #include <limits> using namespace std; const double epsilon = numeric_limits<float>().epsilon(); const numeric_limits<double> DOUBLE; const double MIN = DOUBLE.min(); const double MAX = DOUBLE.max(); struct Point { const double x, y; }; ...
Write a version of this VB function in C++ with identical behavior.
Imports System.Math Module RayCasting Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}} Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, ...
#include <algorithm> #include <cstdlib> #include <iomanip> #include <iostream> #include <limits> using namespace std; const double epsilon = numeric_limits<float>().epsilon(); const numeric_limits<double> DOUBLE; const double MIN = DOUBLE.min(); const double MAX = DOUBLE.max(); struct Point { const double x, y; }; ...
Write the same algorithm in C++ as shown in this VB implementation.
Function CountSubstring(str,substr) CountSubstring = 0 For i = 1 To Len(str) If Len(str) >= Len(substr) Then If InStr(i,str,substr) Then CountSubstring = CountSubstring + 1 i = InStr(i,str,substr) + Len(substr) - 1 End If Else Exit For End If Next End Function WScript.StdOut.Write CountSubstr...
#include <iostream> #include <string> int countSubstring(const std::string& str, const std::string& sub) { if (sub.length() == 0) return 0; int count = 0; for (size_t offset = str.find(sub); offset != std::string::npos; offset = str.find(sub, offset + sub.length())) { ++count; } retu...
Write a version of this VB function in C++ with identical behavior.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ...
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) ...
Ensure the translated C++ code behaves exactly like the original VB snippet.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ...
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) ...
Rewrite the snippet below in C++ so it works the same as the original VB code.
Imports System.IO Module Notes Function Main(ByVal cmdArgs() As String) As Integer Try If cmdArgs.Length = 0 Then Using sr As New StreamReader("NOTES.TXT") Console.WriteLine(sr.ReadToEnd) End Using Else Using sw As ...
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<arg...
Generate a C++ translation of this VB snippet without changing its computational steps.
Imports System.IO Module Notes Function Main(ByVal cmdArgs() As String) As Integer Try If cmdArgs.Length = 0 Then Using sr As New StreamReader("NOTES.TXT") Console.WriteLine(sr.ReadToEnd) End Using Else Using sw As ...
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<arg...
Translate this program into C++ but keep the logic exactly as in VB.
Public Function CommonDirectoryPath(ParamArray Paths()) As String Dim v As Variant Dim Path() As String, s As String Dim i As Long, j As Long, k As Long Const PATH_SEPARATOR As String = "/" For Each v In Paths ReDim Preserve Path(0 To i) Path(i) = v i = i + 1 Next v k = 1 Do For i = 0 T...
#include <algorithm> #include <iostream> #include <string> #include <vector> std::string longestPath( const std::vector<std::string> & , char ) ; int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std:...
Translate this program into C++ but keep the logic exactly as in VB.
Option Explicit sub verifydistribution(calledfunction, samples, delta) Dim i, n, maxdiff Dim d : Set d = CreateObject("Scripting.Dictionary") wscript.echo "Running """ & calledfunction & """ " & samples & " times..." for i = 1 to samples Execute "n = " & calledfunction d(n) = d(n) + 1 next n = d.Count max...
#include <map> #include <iostream> #include <cmath> template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist; for (int i = 0; i < calls; ++i) ++dist[f()]; double mean = 1.0/dist.size(); bool good = true; for (distmap::iterator i =...
Change the following VB code into C++ without altering its purpose.
Imports System.Numerics Module Module1 Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger) Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function Private Shared Fun...
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; ...
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
Imports System.Numerics Module Module1 Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger) Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function Private Shared Fun...
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; ...
Convert the following code from VB to C++, ensuring the logic remains intact.
Imports System.Numerics Module Module1 Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger) Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function Private Shared Fun...
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; ...
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
Imports System.Numerics Module Module1 Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger) Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function Private Shared Fun...
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; ...
Translate the given VB code snippet into C++ without altering its behavior.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&"....
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { ...
Translate the given VB code snippet into C++ without altering its behavior.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&"....
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { ...
Write a version of this VB function in C++ with identical behavior.
Option Explicit Private Lines(1 To 3, 1 To 3) As String Private Nb As Byte, player As Byte Private GameWin As Boolean, GameOver As Boolean Sub Main_TicTacToe() Dim p As String InitLines printLines Nb Do p = WhoPlay Debug.Print p & " play" If p = "Human" Then Call Human...
#include <windows.h> #include <iostream> #include <string> using namespace std; enum players { Computer, Human, Draw, None }; const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } }; class ttt { public: ttt() { _p = rand() % 2; reset();...
Can you help me rewrite this code in C++ instead of VB, keeping it the same logically?
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
Write the same code in C++ as shown below in VB.
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
Ensure the translated C++ code behaves exactly like the original VB snippet.
Function dns_query(url,ver) Set r = New RegExp r.Pattern = "Pinging.+?\[(.+?)\].+" Set objshell = CreateObject("WScript.Shell") Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) WScript.StdOut.WriteLine "URL: " & url Do Until objexec.StdOut.AtEndOfStream line = objexec.StdOut.ReadLine ...
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; me...
Produce a functionally identical C++ code for the snippet given in VB.
Function dns_query(url,ver) Set r = New RegExp r.Pattern = "Pinging.+?\[(.+?)\].+" Set objshell = CreateObject("WScript.Shell") Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) WScript.StdOut.WriteLine "URL: " & url Do Until objexec.StdOut.AtEndOfStream line = objexec.StdOut.ReadLine ...
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; me...
Translate this program into C++ but keep the logic exactly as in VB.
Const WIDTH = 243 Dim n As Long Dim points() As Single Dim flag As Boolean Private Sub lineto(x As Integer, y As Integer) If flag Then points(n, 1) = x points(n, 2) = y End If n = n + 1 End Sub Private Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _ ...
#include <cmath> #include <fstream> #include <iostream> #include <string> class peano_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::strin...
Write the same algorithm in C++ as shown in this VB implementation.
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double Debug.Print "[1] ""Data set:"" "; For i = LBound(Observation...
template<typename F> class fivetoseven { public: fivetoseven(F f): d5(f), rem(0), max(1) {} int operator()(); private: F d5; int rem, max; }; template<typename F> int fivetoseven<F>::operator()() { while (rem/7 == max/7) { while (max < 7) { int rand5 = d5()-1; max *= 5; rem = 5*r...
Write the same code in C++ as shown below in VB.
Imports System, System.Console Module Module1 Dim np As Boolean() Sub ms(ByVal lmt As Long) np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True Dim n As Integer = 2, j As Integer = 1 : While n < lmt If Not np(n) Then Dim k As Long = CLng(n) * n ...
#include <iomanip> #include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; ...
Write the same algorithm in C++ as shown in this VB implementation.
Option Explicit Sub Main() Dim Primes() As Long, n As Long, temp$ Dim t As Single t = Timer n = 133218295 Primes = ListPrimes(n) Debug.Print "For N = " & Format(n, "#,##0") & ", execution time : " & _ Format(Timer - t, "0.000 s") & ", " & _ Format(UBound(Primes) + 1, "#,##0") & " ...
#include <iostream> #include <cstdint> #include <queue> #include <utility> #include <vector> #include <limits> template<typename integer> class prime_generator { public: integer next_prime(); integer count() const { return count_; } private: struct queue_item { queue_item(integer prime,...
Write the same code in C++ as shown below in VB.
Module Program Sub Main() Console.WriteLine("Enter two space-delimited integers:") Dim input = Console.ReadLine().Split() Dim rows = Integer.Parse(input(0)) Dim cols = Integer.Parse(input(1)) Dim arr(rows - 1, cols - 1) As Integer arr(0, 0) = 2 Cons...
#include <iostream> int main() { int dim1, dim2; std::cin >> dim1 >> dim2; double* array_data = new double[dim1*dim2]; double** array = new double*[dim1]; for (int i = 0; i < dim1; ++i) array[i] = array_data + dim2*i; array[0][0] = 3.5; std::cout << array[0][0] << std::endl; dele...
Ensure the translated C++ code behaves exactly like the original VB snippet.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If Wo...
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xq...
Please provide an equivalent version of this VB code in C++.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If Wo...
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xq...
Translate this program into C++ but keep the logic exactly as in VB.
Option Explicit Sub Main() Const VECSIZE As Long = 3350 Const BUFSIZE As Long = 201 Dim buffer(1 To BUFSIZE) As Long Dim vect(1 To VECSIZE) As Long Dim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long For n = 1 To VECSIZE vect(n) = 2 Next n For n = 1 To BUFSIZE karray = 0 F...
#include <iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; class Gospers { cpp_int q, r, t, i, n; public: Gospers() : q{1}, r{0}, t{1}, i{1} { ++*this; } Gospers& operator++() { n = (q*(27*i-12)+5*r) / (5*t); ...
Generate a C++ translation of this VB snippet without changing its computational steps.
Public Q(100000) As Long Public Sub HofstadterQ() Dim n As Long, smaller As Long Q(1) = 1 Q(2) = 1 For n = 3 To 100000 Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2)) If Q(n) < Q(n - 1) Then smaller = smaller + 1 Next n Debug.Print "First ten terms:" For i = 1 To 10 Debug.Pr...
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first ...
Transform the following VB implementation into C++, maintaining the same output and logic.
Public Q(100000) As Long Public Sub HofstadterQ() Dim n As Long, smaller As Long Q(1) = 1 Q(2) = 1 For n = 3 To 100000 Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2)) If Q(n) < Q(n - 1) Then smaller = smaller + 1 Next n Debug.Print "First ten terms:" For i = 1 To 10 Debug.Pr...
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first ...