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 ) result.append( r ) return result def idft( y ): N = len( y ) result = [] for n in range( N ): r = 0 for k in range( N ): t = 2j * cmath.pi * k * n / N r += y[k] * cmath.exp( t ) r /= N+0j result.append( r ) return result if __name__ == "__main__": x = [ 2, 3, 5, 7, 11 ] print( "vals: " + ' '.join( f"{f:11.2f}" for f in x )) y = dft( x ) print( "DFT: " + ' '.join( f"{f:11.2f}" for f in y )) z = idft( y ) print( "inverse:" + ' '.join( f"{f:11.2f}" for f in z )) print( " - real:" + ' '.join( f"{f.real:11.2f}" for f in z )) N = 8 print( f"Complex signals, 1-4 cycles in {N} samples; energy into successive DFT bins" ) for rot in (0, 1, 2, 3, -4, -3, -2, -1): if rot > N/2: print( "Signal change frequency exceeds sample rate and will result in artifacts") sig = [ cmath.rect( 1, cmath.pi*2*rot/N*i ) for i in range( N ) ] print( f"{rot:2} cycle" + ' '.join( f"{f:11.2f}" for f in sig )) dft_sig = dft( sig ) print( f" DFT: " + ' '.join( f"{f:11.2f}" for f in dft_sig )) print( f" ABS: " + ' '.join( f"{abs(f):11.2f}" for f in dft_sig ))
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] * cmplx.Exp(t) } } return y } func idft(y []complex128) []float64 { N := len(y) x := make([]complex128, N) for n := 0; n < N; n++ { for k := 0; k < N; k++ { t := 1i * 2 * complex(math.Pi*float64(k)*float64(n)/float64(N), 0) x[n] += y[k] * cmplx.Exp(t) } x[n] /= complex(float64(N), 0) if math.Abs(imag(x[n])) < 1e-14 { x[n] = complex(real(x[n]), 0) } } z := make([]float64, N) for i, c := range x { z[i] = float64(real(c)) } return z } func main() { z := []float64{2, 3, 5, 7, 11} x := make([]complex128, len(z)) fmt.Println("Original sequence:", z) for i, n := range z { x[i] = complex(n, 0) } y := dft(x) fmt.Println("\nAfter applying the Discrete Fourier Transform:") fmt.Printf("%0.14g", y) fmt.Println("\n\nAfter applying the Inverse Discrete Fourier Transform to the above transform:") z = idft(y) fmt.Printf("%0.14g", z) fmt.Println() }
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__ == '__main__': main()
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 b[i]-b[i-1] > 1 { return b[i-1] + 1 } } return b[le-1] + 1 } func main() { fmt.Println("The first missing positive integers for the following arrays are:\n") aa := [][]int{ {1, 2, 0}, {3, 4, -1, 1}, {7, 8, 9, 11, 12}, {1, 2, 3, 4, 5}, {-6, -5, -2, -1}, {5, -5}, {-2}, {1}, {}} for _, a := range aa { fmt.Println(a, "->", firstMissingPositive(a)) } }
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: if word in SMALL: small += SMALL.index(word) elif word in TENS: small += TENS.index(word) * 10 elif word == 'hundred': small *= 100 elif word == 'thousand': total += small * 1000 small = 0 elif word in HUGE: total += small * 1000 ** HUGE.index(word) small = 0 else: raise ValueError("Don't understand %r part of %r" % (word, num)) return negmult * (total + small) if __name__ == '__main__': for n in range(-10000, 10000, 17): assert n == int_from_words(spell_integer(n)) for n in range(20): assert 13**n == int_from_words(spell_integer(13**n)) print('\n for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): txt = spell_integer(n) num = int_from_words(txt) print('%+4i <%s> %s' % (n, '==' if n == num else '??', txt)) print('') n = 201021002001 while n: txt = spell_integer(n) num = int_from_words(txt) print('%12i <%s> %s' % (n, '==' if n == num else '??', txt)) n //= -10 txt = spell_integer(n) num = int_from_words(txt) print('%12i <%s> %s' % (n, '==' if n == num else '??', txt)) print('')
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": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17, "eighteen": 18, "nineteen": 19, "twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90, "hundred": 100, "thousand": 1000, "million": 1000000, "billion": 1000000000, "trillion": 1000000000000, "quadrillion": 1000000000000000, "quintillion": 1000000000000000000, } var seps = regexp.MustCompile(`,|-| and | `) var zeros = regexp.MustCompile(`^(zero|nought|nil|none|nothing)$`) func nameToNum(name string) (int64, error) { text := strings.ToLower(strings.TrimSpace(name)) isNegative := strings.HasPrefix(text, "minus ") if isNegative { text = text[6:] } if strings.HasPrefix(text, "a ") { text = "one" + text[1:] } words := seps.Split(text, -1) for i := len(words) - 1; i >= 0; i-- { if words[i] == "" { if i < len(words)-1 { copy(words[i:], words[i+1:]) } words = words[:len(words)-1] } } size := len(words) if size == 1 && zeros.MatchString(words[0]) { return 0, nil } var multiplier, lastNum, sum int64 = 1, 0, 0 for i := size - 1; i >= 0; i-- { num, ok := names[words[i]] if !ok { return 0, fmt.Errorf("'%s' is not a valid number", words[i]) } else { switch { case num == lastNum, num >= 1000 && lastNum >= 100: return 0, fmt.Errorf("'%s' is not a well formed numeric string", name) case num >= 1000: multiplier = num if i == 0 { sum += multiplier } case num >= 100: multiplier *= 100 if i == 0 { sum += multiplier } case num >= 20 && lastNum >= 10 && lastNum <= 90: return 0, fmt.Errorf("'%s' is not a well formed numeric string", name) case num >= 20: sum += num * multiplier case lastNum >= 1 && lastNum <= 90: return 0, fmt.Errorf("'%s' is not a well formed numeric string", name) default: sum += num * multiplier } } lastNum = num } if isNegative && sum == -sum { return math.MinInt64, nil } if sum < 0 { return 0, fmt.Errorf("'%s' is outside the range of an int64", name) } if isNegative { return -sum, nil } else { return sum, nil } } func main() { names := [...]string{ "none", "one", "twenty-five", "minus one hundred and seventeen", "hundred and fifty-six", "minus two thousand two", "nine thousand, seven hundred, one", "minus six hundred and twenty six thousand, eight hundred and fourteen", "four million, seven hundred thousand, three hundred and eighty-six", "fifty-one billion, two hundred and fifty-two million, seventeen thousand, one hundred eighty-four", "two hundred and one billion, twenty-one million, two thousand and one", "minus three hundred trillion, nine million, four hundred and one thousand and thirty-one", "seventeen quadrillion, one hundred thirty-seven", "a quintillion, eight trillion and five", "minus nine quintillion, two hundred and twenty-three quadrillion, three hundred and seventy-two trillion, thirty-six billion, eight hundred and fifty-four million, seven hundred and seventy-five thousand, eight hundred and eight", } for _, name := range names { num, err := nameToNum(name) if err != nil { fmt.Println(err) } else { fmt.Printf("%20d = %s\n", num, name) } } }
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:",int(a(1000))); for e in range(1, 20): print(f'10^{e}: {inv_a(10**e)}');
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] } if n < 20 { return ss[1] + ss[n-10] } return ss[2] + ss[0] } func main() { fmt.Println("First 20 magic constants:") for n := 3; n <= 22; n++ { fmt.Printf("%5d ", magicConstant(n)) if (n-2)%10 == 0 { fmt.Println() } } fmt.Println("\n1,000th magic constant:", rcu.Commatize(magicConstant(1002))) fmt.Println("\nSmallest order magic square with a constant greater than:") for i := 1; i <= 20; i++ { goal := math.Pow(10, float64(i)) order := int(math.Cbrt(goal*2)) + 1 fmt.Printf("10%-2s : %9s\n", superscript(i), rcu.Commatize(order)) } }
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 coinsused > 0: print(" ", coinsused, "*", coins[n]) makechange()
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 if n > 0 { coins += n fmt.Printf(" %3d x %d\n", denom, n) remaining %= denom if remaining == 0 { break } } } fmt.Println("\nA total of", coins, "coins in all.") }
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: print('') return columna if __name__ == "__main__": print("Números primos que contienen 123:") limite = 100000 prime(limite, True) print("\n\nEncontrados ", columna, " números primos por debajo de", limite) limite = 1000000 prime(limite, False) print("\n\nEncontrados ", columna, " números primos por debajo de", limite)
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, "123") { results = append(results, p) } } climit := rcu.Commatize(limit) fmt.Printf("Primes under %s which contain '123' when expressed in decimal:\n", climit) for i, p := range results { fmt.Printf("%7s ", rcu.Commatize(p)) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\n\nFound", len(results), "such primes under", climit, "\b.") limit = 1_000_000 climit = rcu.Commatize(limit) count := len(results) for _, p := range primes { if p < 100_000 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "123") { count++ } } fmt.Println("\nFound", count, "such primes under", climit, "\b.") }
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: print('') return columna if __name__ == "__main__": print("Números primos que contienen 123:") limite = 100000 prime(limite, True) print("\n\nEncontrados ", columna, " números primos por debajo de", limite) limite = 1000000 prime(limite, False) print("\n\nEncontrados ", columna, " números primos por debajo de", limite)
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, "123") { results = append(results, p) } } climit := rcu.Commatize(limit) fmt.Printf("Primes under %s which contain '123' when expressed in decimal:\n", climit) for i, p := range results { fmt.Printf("%7s ", rcu.Commatize(p)) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\n\nFound", len(results), "such primes under", climit, "\b.") limit = 1_000_000 climit = rcu.Commatize(limit) count := len(results) for _, p := range primes { if p < 100_000 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "123") { count++ } } fmt.Println("\nFound", count, "such primes under", climit, "\b.") }
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 self.generic_visit(node) filename = input('Enter a filename to parse: ') with open(filename, encoding='utf-8') as f: contents = f.read() root = ast.parse(contents, filename=filename) visitor = CallCountingVisitor() visitor.visit(root) top10 = sorted(visitor.calls.items(), key=lambda x: x[1], reverse=True)[:10] for name, count in top10: print(name,'called',count,'times')
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) return } fs := token.NewFileSet() a, err := parser.ParseFile(fs, os.Args[1], src, 0) if err != nil { fmt.Println(err) return } f := fs.File(a.Pos()) m := make(map[string]int) ast.Inspect(a, func(n ast.Node) bool { if ce, ok := n.(*ast.CallExpr); ok { start := f.Offset(ce.Pos()) end := f.Offset(ce.Lparen) m[string(src[start:end])]++ } return true }) cs := make(calls, 0, len(m)) for k, v := range m { cs = append(cs, &call{k, v}) } sort.Sort(cs) for i, c := range cs { fmt.Printf("%-20s %4d\n", c.expr, c.count) if i == 9 { break } } } type call struct { expr string count int } type calls []*call func (c calls) Len() int { return len(c) } func (c calls) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c calls) Less(i, j int) bool { return c[i].count > c[j].count }
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(mn=0, mx=get_max_price(), num=5_000): "Binary search for num items between mn and mx, adjusting mx" count = get_prange_count(mn, mx) delta_mx = (mx - mn) / 2 while count != num and delta_mx >= delta_price / 2: mx += -delta_mx if count > num else +delta_mx mx = mx // 1 count, delta_mx = get_prange_count(mn, mx), delta_mx / 2 return mx, count def get_all_5k(mn=0, mx=get_max_price(), num=5_000): "Get all non-overlapping ranges" partmax, partcount = get_5k(mn, mx, num) result = [(mn, partmax, partcount)] while partmax < mx: partmin = partmax + delta_price partmax, partcount = get_5k(partmin, mx, num) assert partcount > 0, \ f"price_list from {partmin} with too many of the same price" result.append((partmin, partmax, partcount)) return result if __name__ == '__main__': print(f"Using {price_list_size} random prices from 0 to {get_max_price()}") result = get_all_5k() print(f"Splits into {len(result)} bins of approx 5000 elements") for mn, mx, count in result: print(f" From {mn:8.1f} ... {mx:8.1f} with {count} items.") if len(price_list) != sum(count for mn, mx, count in result): print("\nWhoops! Some items missing:")
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(prices []float64, min, max float64) int { count := 0 for _, price := range prices { if price >= min && price <= max { count++ } } return count } func get5000(prices []float64, min, max float64, n int) (float64, int) { count := getPRangeCount(prices, min, max) delta := (max - min) / 2 for count != n && delta >= minDelta/2 { if count > n { max -= delta } else { max += delta } max = math.Floor(max) count = getPRangeCount(prices, min, max) delta /= 2 } return max, count } func getAll5000(prices []float64, min, max float64, n int) [][3]float64 { pmax, pcount := get5000(prices, min, max, n) res := [][3]float64{{min, pmax, float64(pcount)}} for pmax < max { pmin := pmax + 1 pmax, pcount = get5000(prices, pmin, max, n) if pcount == 0 { log.Fatal("Price list from", pmin, "has too many with same price.") } res = append(res, [3]float64{pmin, pmax, float64(pcount)}) } return res } func main() { rand.Seed(time.Now().UnixNano()) numPrices := 99000 + rand.Intn(2001) maxPrice := 1e5 prices := make([]float64, numPrices) for i := 0; i < numPrices; i++ { prices[i] = float64(rand.Intn(int(maxPrice) + 1)) } actualMax := getMaxPrice(prices) fmt.Println("Using", numPrices, "items with prices from 0 to", actualMax, "\b:") res := getAll5000(prices, 0, actualMax, 5000) fmt.Println("Split into", len(res), "bins of approx 5000 elements:") total := 0 for _, r := range res { min := int(r[0]) tmx := r[1] if tmx > actualMax { tmx = actualMax } max := int(tmx) cnt := int(r[2]) total += cnt fmt.Printf(" From %6d to %6d with %4d items\n", min, max, cnt) } if total != numPrices { fmt.Println("Something went wrong - grand total of", total, "doesn't equal", numPrices, "\b!") } }
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, big.NewInt(2)) } func main() { fmt.Println("First 20 Cullen numbers (n * 2^n + 1):") for n := uint(1); n <= 20; n++ { fmt.Printf("%d ", cullen(n)) } fmt.Println("\n\nFirst 20 Woodall numbers (n * 2^n - 1):") for n := uint(1); n <= 20; n++ { fmt.Printf("%d ", woodall(n)) } fmt.Println("\n\nFirst 5 Cullen primes (in terms of n):") count := 0 for n := uint(1); count < 5; n++ { cn := cullen(n) if cn.ProbablyPrime(15) { fmt.Printf("%d ", n) count++ } } fmt.Println("\n\nFirst 12 Woodall primes (in terms of n):") count = 0 for n := uint(1); count < 12; n++ { cn := woodall(n) if cn.ProbablyPrime(15) { fmt.Printf("%d ", n) count++ } } fmt.Println() }
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))] for left in arr: for right in arr: yield int(left + '0' + right) def generate_prime_cyclops(): for c in generate_cyclops(): if isprime(c): yield c def generate_blind_prime_cyclops(): for c in generate_prime_cyclops(): cstr = str(c) mid = len(cstr) // 2 if isprime(int(cstr[:mid] + cstr[mid+1:])): yield c def generate_palindromic_cyclops(maxdig=9): 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))] for s in arr: yield int(s + '0' + s[::-1]) def generate_palindromic_prime_cyclops(): for c in generate_palindromic_cyclops(): if isprime(c): yield c print('The first 50 cyclops numbers are:') gen = generate_cyclops() print50([next(gen) for _ in range(50)]) for i, c in enumerate(generate_cyclops()): if c > 10000000: print( f'\nThe next cyclops number after 10,000,000 is {c} at position {i:,}.') break print('\nThe first 50 prime cyclops numbers are:') gen = generate_prime_cyclops() print50([next(gen) for _ in range(50)]) for i, c in enumerate(generate_prime_cyclops()): if c > 10000000: print( f'\nThe next prime cyclops number after 10,000,000 is {c} at position {i:,}.') break print('\nThe first 50 blind prime cyclops numbers are:') gen = generate_blind_prime_cyclops() print50([next(gen) for _ in range(50)]) for i, c in enumerate(generate_blind_prime_cyclops()): if c > 10000000: print( f'\nThe next blind prime cyclops number after 10,000,000 is {c} at position {i:,}.') break print('\nThe first 50 palindromic prime cyclops numbers are:') gen = generate_palindromic_prime_cyclops() print50([next(gen) for _ in range(50)], 11) for i, c in enumerate(generate_palindromic_prime_cyclops()): if c > 10000000: print( f'\nThe next palindromic prime cyclops number after 10,000,000 is {c} at position {i}.') break
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; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } func main() { ranges := [][2]int{ {0, 0}, {101, 909}, {11011, 99099}, {1110111, 9990999}, {111101111, 119101111}, } var cyclops []int for _, r := range ranges { numDigits := len(fmt.Sprint(r[0])) center := numDigits / 2 for i := r[0]; i <= r[1]; i++ { digits := rcu.Digits(i, 10) if digits[center] == 0 { count := 0 for _, d := range digits { if d == 0 { count++ } } if count == 1 { cyclops = append(cyclops, i) } } } } fmt.Println("The first 50 cyclops numbers are:") for i, n := range cyclops[0:50] { fmt.Printf("%6s ", rcu.Commatize(n)) if (i+1)%10 == 0 { fmt.Println() } } n, i := findFirst(cyclops) ns, is := rcu.Commatize(n), rcu.Commatize(i) fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is) var primes []int for _, n := range cyclops { if rcu.IsPrime(n) { primes = append(primes, n) } } fmt.Println("\n\nThe first 50 prime cyclops numbers are:") for i, n := range primes[0:50] { fmt.Printf("%6s ", rcu.Commatize(n)) if (i+1)%10 == 0 { fmt.Println() } } n, i = findFirst(primes) ns, is = rcu.Commatize(n), rcu.Commatize(i) fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is) var bpcyclops []int var ppcyclops []int for _, p := range primes { ps := fmt.Sprint(p) split := strings.Split(ps, "0") noMiddle, _ := strconv.Atoi(split[0] + split[1]) if rcu.IsPrime(noMiddle) { bpcyclops = append(bpcyclops, p) } if ps == reverse(ps) { ppcyclops = append(ppcyclops, p) } } fmt.Println("\n\nThe first 50 blind prime cyclops numbers are:") for i, n := range bpcyclops[0:50] { fmt.Printf("%6s ", rcu.Commatize(n)) if (i+1)%10 == 0 { fmt.Println() } } n, i = findFirst(bpcyclops) ns, is = rcu.Commatize(n), rcu.Commatize(i) fmt.Printf("\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is) fmt.Println("\n\nThe first 50 palindromic prime cyclops numbers are:\n") for i, n := range ppcyclops[0:50] { fmt.Printf("%9s ", rcu.Commatize(n)) if (i+1)%8 == 0 { fmt.Println() } } n, i = findFirst(ppcyclops) ns, is = rcu.Commatize(n), rcu.Commatize(i) fmt.Printf("\n\nFirst such number > 10 million is %s at zero-based index %s\n", ns, is) }
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): continue print(f'[{p} {p+2} {p+6}]')
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, i + 6}) } } for _, triple := range triples { var t [3]string for i := 0; i < 3; i++ { t[i] = rcu.Commatize(triple[i]) } fmt.Printf("%5s %5s %5s\n", t[0], t[1], t[2]) } fmt.Println("\nFound", len(triples), "such prime triplets.") }
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): continue print(f'[{p} {p+2} {p+6}]')
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, i + 6}) } } for _, triple := range triples { var t [3]string for i := 0; i < 3; i++ { t[i] = rcu.Commatize(triple[i]) } fmt.Printf("%5s %5s %5s\n", t[0], t[1], t[2]) } fmt.Println("\nFound", len(triples), "such prime triplets.") }
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 invalid pieces" for piece_type in valid_pieces.keys(): assert ( candidate.count(piece_type) == valid_pieces[piece_type] ), f"piece type '{piece_type}' has invalid count" bishops_pos = [index for index, value in enumerate(candidate) if value == "B"] assert ( bishops_pos[0] % 2 != bishops_pos[1] % 2 ), f"candidate position has both bishops in the same color" assert [piece for piece in candidate if piece in "RK"] == [ "R", "K", "R", ], "candidate position has K outside of RR" def calc_position(start_pos: str): try: validate_position(start_pos) except AssertionError: raise AssertionError subset_step1 = [piece for piece in start_pos if piece not in "QB"] nights_positions = [ index for index, value in enumerate(subset_step1) if value == "N" ] nights_table = { (0, 1): 0, (0, 2): 1, (0, 3): 2, (0, 4): 3, (1, 2): 4, (1, 3): 5, (1, 4): 6, (2, 3): 7, (2, 4): 8, (3, 4): 9, } N = nights_table.get(tuple(nights_positions)) subset_step2 = [piece for piece in start_pos if piece != "B"] Q = subset_step2.index("Q") dark_squares = [ piece for index, piece in enumerate(start_pos) if index in range(0, 9, 2) ] light_squares = [ piece for index, piece in enumerate(start_pos) if index in range(1, 9, 2) ] D = dark_squares.index("B") L = light_squares.index("B") return 4 * (4 * (6*N + Q) + D) + L if __name__ == '__main__': for example in ["QNRBBNKR", "RNBQKBNR", "RQNBBKRN", "RNQBBKRN"]: print(f'Position: {example}; Chess960 PID= {calc_position(example)}')
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", '♔': "K", } var ntable = map[string]int{"01": 0, "02": 1, "03": 2, "04": 3, "12": 4, "13": 5, "14": 6, "23": 7, "24": 8, "34": 9} func g2l(pieces string) string { lets := "" for _, p := range pieces { lets += g2lMap[p] } return lets } func spid(pieces string) int { pieces = g2l(pieces) if len(pieces) != 8 { log.Fatal("There must be exactly 8 pieces.") } for _, one := range "KQ" { count := 0 for _, p := range pieces { if p == one { count++ } } if count != 1 { log.Fatalf("There must be one %s.", names[one]) } } for _, two := range "RNB" { count := 0 for _, p := range pieces { if p == two { count++ } } if count != 2 { log.Fatalf("There must be two %s.", names[two]) } } r1 := strings.Index(pieces, "R") r2 := strings.Index(pieces[r1+1:], "R") + r1 + 1 k := strings.Index(pieces, "K") if k < r1 || k > r2 { log.Fatal("The king must be between the rooks.") } b1 := strings.Index(pieces, "B") b2 := strings.Index(pieces[b1+1:], "B") + b1 + 1 if (b2-b1)%2 == 0 { log.Fatal("The bishops must be on opposite color squares.") } piecesN := strings.ReplaceAll(pieces, "Q", "") piecesN = strings.ReplaceAll(piecesN, "B", "") n1 := strings.Index(piecesN, "N") n2 := strings.Index(piecesN[n1+1:], "N") + n1 + 1 np := fmt.Sprintf("%d%d", n1, n2) N := ntable[np] piecesQ := strings.ReplaceAll(pieces, "B", "") Q := strings.Index(piecesQ, "Q") D := strings.Index("0246", fmt.Sprintf("%d", b1)) L := strings.Index("1357", fmt.Sprintf("%d", b2)) if D == -1 { D = strings.Index("0246", fmt.Sprintf("%d", b2)) L = strings.Index("1357", fmt.Sprintf("%d", b1)) } return 96*N + 16*Q + 4*D + L } func main() { for _, pieces := range []string{"♕♘♖♗♗♘♔♖", "♖♘♗♕♔♗♘♖", "♖♕♘♗♗♔♖♘", "♖♘♕♗♗♔♖♘"} { fmt.Printf("%s or %s has SP-ID of %d\n", pieces, g2l(pieces), spid(pieces)) } }
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 print("Praesens indicativi temporis of '", infinitive, "':", sep='') for ending in ("o", "as", "at", "amus", "atis", "ant"): print(" ", stem, ending, sep='') print() if __name__ == '__main__': for infinitive in ("amare", "dare", "qwerty", "are"): conjugate(infinitive)
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"} var pronouns = []string{"I", "you (singular)", "he, she or it", "we", "you (plural)", "they"} var englishEndings = []string{"", "", "s", "", "", ""} func conjugate(infinitive, english string) { letters := []rune(infinitive) le := len(letters) if le < 4 { log.Fatal("Infinitive is too short for a regular verb.") } infinEnding := string(letters[le-3:]) conj := -1 for i, s := range infinEndings { if s == infinEnding { conj = i break } } if conj == -1 { log.Fatalf("Infinitive ending -%s not recognized.", infinEnding) } stem := string(letters[:le-3]) fmt.Printf("Present indicative tense, active voice, of '%s' to '%s':\n", infinitive, english) for i, ending := range endings[conj] { fmt.Printf(" %s%-4s %s %s%s\n", stem, ending, pronouns[i], english, englishEndings[i]) } fmt.Println() } func main() { pairs := [][2]string{{"amare", "love"}, {"vidēre", "see"}, {"ducere", "lead"}, {"audire", "hear"}} for _, pair := range pairs { conjugate(pair[0], pair[1]) } }
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 print("Praesens indicativi temporis of '", infinitive, "':", sep='') for ending in ("o", "as", "at", "amus", "atis", "ant"): print(" ", stem, ending, sep='') print() if __name__ == '__main__': for infinitive in ("amare", "dare", "qwerty", "are"): conjugate(infinitive)
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"} var pronouns = []string{"I", "you (singular)", "he, she or it", "we", "you (plural)", "they"} var englishEndings = []string{"", "", "s", "", "", ""} func conjugate(infinitive, english string) { letters := []rune(infinitive) le := len(letters) if le < 4 { log.Fatal("Infinitive is too short for a regular verb.") } infinEnding := string(letters[le-3:]) conj := -1 for i, s := range infinEndings { if s == infinEnding { conj = i break } } if conj == -1 { log.Fatalf("Infinitive ending -%s not recognized.", infinEnding) } stem := string(letters[:le-3]) fmt.Printf("Present indicative tense, active voice, of '%s' to '%s':\n", infinitive, english) for i, ending := range endings[conj] { fmt.Printf(" %s%-4s %s %s%s\n", stem, ending, pronouns[i], english, englishEndings[i]) } fmt.Println() } func main() { pairs := [][2]string{{"amare", "love"}, {"vidēre", "see"}, {"ducere", "lead"}, {"audire", "hear"}} for _, pair := range pairs { conjugate(pair[0], pair[1]) } }
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.add(fortunate_number(i)) first50 = sorted(list(fortunate_numbers))[:50] print('The first 50 fortunate numbers:') print(('{:<3} ' * 10).format(*(first50[:10]))) print(('{:<3} ' * 10).format(*(first50[10:20]))) print(('{:<3} ' * 10).format(*(first50[20:30]))) print(('{:<3} ' * 10).format(*(first50[30:40]))) print(('{:<3} ' * 10).format(*(first50[40:])))
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) for j := 3; ; j += 2 { jj := big.NewInt(int64(j)) bPrime.Add(primorial, jj) if bPrime.ProbablyPrime(5) { fortunates = append(fortunates, j) break } } } m := make(map[int]bool) for _, f := range fortunates { m[f] = true } fortunates = fortunates[:0] for k := range m { fortunates = append(fortunates, k) } sort.Ints(fortunates) fmt.Println("After sorting, the first 50 distinct fortunate numbers are:") for i, f := range fortunates[0:50] { fmt.Printf("%3d ", f) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println() }
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)) )(lambda unitIndent: Right( outlineFromForest( unitIndent, nest(foldTree( lambda x: lambda xs: Node(x)( sorted(xs, key=cmp_to_key(cmp)) ) )(Node('')( forestFromIndentLevels( indentLevelsFromLines( unitIndent )(indentTuples) ) ))) ) )) return go def main(): ascending = comparing(root) descending = flip(ascending) spacedOutline = tabbedOutline = confusedOutline = raggedOutline = def displaySort(kcmp): k, cmp = kcmp return [ tested(cmp, k, label)( outline ) for (label, outline) in [ ('4-space indented', spacedOutline), ('tab indented', tabbedOutline), ('Unknown 1', confusedOutline), ('Unknown 2', raggedOutline) ] ] def tested(cmp, cmpName, outlineName): def go(outline): print('\n' + outlineName, cmpName + ':') either(print)(print)( sortedOutline(cmp)(outline) ) return go ap([ displaySort ])([ ("(A -> Z)", ascending), ("(Z -> A)", descending) ]) def forestFromIndentLevels(tuples): def go(xs): if xs: intIndent, v = xs[0] firstTreeLines, rest = span( lambda x: intIndent < x[0] )(xs[1:]) return [Node(v)(go(firstTreeLines))] + go(rest) else: return [] return go(tuples) def indentLevelsFromLines(indentUnit): def go(xs): w = len(indentUnit) return [ (len(x[0]) // w, x[1]) for x in xs ] return go def indentTextPairs(xs): def indentAndText(s): pfx = list(takewhile(lambda c: c.isspace(), s)) return (pfx, s[len(pfx):]) return [indentAndText(x) for x in xs] def outlineFromForest(tabString, forest): def go(indent): def serial(node): return [indent + root(node)] + list( concatMap( go(tabString + indent) )(nest(node)) ) return serial return '\n'.join( concatMap(go(''))(forest) ) def minimumIndent(indexedPrefixes): (xs, ts) = tee(indexedPrefixes) (ys, zs) = tee(ts) def mindentLR(charSet): if list(charSet): def w(x): return len(x[1][0]) unit = min(filter(w, ys), key=w)[1][0] unitWidth = len(unit) def widthCheck(a, ix): wx = len(ix[1][0]) return a if (a or 0 == wx) else ( ix[0] if 0 != wx % unitWidth else a ) oddLine = reduce(widthCheck, zs, None) return Left( 'Inconsistent indentation width at line ' + ( str(1 + oddLine) ) ) if oddLine else Right(''.join(unit)) else: return Right('') def tabSpaceCheck(a, ics): charSet = a[0].union(set(ics[1][0])) return a if a[1] else ( charSet, ics[0] if 1 < len(charSet) else None ) indentCharSet, mbAnomalyLine = reduce( tabSpaceCheck, xs, (set([]), None) ) return bindLR( Left( 'Mixed indent characters found in line ' + str( 1 + mbAnomalyLine ) ) if mbAnomalyLine else Right(list(indentCharSet)) )(mindentLR) def Left(x): return {'type': 'Either', 'Right': None, 'Left': x} def Right(x): return {'type': 'Either', 'Left': None, 'Right': x} def Node(v): return lambda xs: {'type': 'Tree', 'root': v, 'nest': xs} def ap(fs): def go(xs): return [ f(x) for (f, x) in product(fs, xs) ] return go def bindLR(m): def go(mf): return ( mf(m.get('Right')) if None is m.get('Left') else m ) return go def comparing(f): def go(x, y): fx = f(x) fy = f(y) return -1 if fx < fy else (1 if fx > fy else 0) return go def concatMap(f): def go(xs): return chain.from_iterable(map(f, xs)) return go def either(fl): return lambda fr: lambda e: fl(e['Left']) if ( None is e['Right'] ) else fr(e['Right']) def flip(f): return lambda a, b: f(b, a) def foldTree(f): def go(node): return f(root(node))([ go(x) for x in nest(node) ]) return go def nest(t): return t.get('nest') def root(t): return t.get('root') def span(p): def match(ab): b = ab[1] return not b or not p(b[0]) def f(ab): a, b = ab return a + [b[0]], b[1:] def go(xs): return until(match)(f)(([], xs)) return go def until(p): def go(f): def g(x): v = x while not p(v): v = f(v) return v return g return go if __name__ == '__main__': main()
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.TrimLeft(outline[0], " \t") != outline[0] { fmt.Println(" outline structure is unclear") return } for i := 1; i < len(outline); i++ { line := outline[i] lc := len(line) if strings.HasPrefix(line, " ") || strings.HasPrefix(line, " \t") || line[0] == '\t' { lc2 := len(strings.TrimLeft(line, " \t")) currIndent := line[0 : lc-lc2] if indent == "" { indent = currIndent } else { correctionNeeded := false if (strings.ContainsRune(currIndent, '\t') && !strings.ContainsRune(indent, '\t')) || (!strings.ContainsRune(currIndent, '\t') && strings.ContainsRune(indent, '\t')) { m := fmt.Sprintf("corrected inconsistent whitespace use at line %q", line) messages = append(messages, indent+m) correctionNeeded = true } else if len(currIndent)%len(indent) != 0 { m := fmt.Sprintf("corrected inconsistent indent width at line %q", line) messages = append(messages, indent+m) correctionNeeded = true } if correctionNeeded { mult := int(math.Round(float64(len(currIndent)) / float64(len(indent)))) outline[i] = strings.Repeat(indent, mult) + line[lc-lc2:] } } } } levels := make([]int, len(outline)) levels[0] = 1 margin := "" for level := 1; ; level++ { allPos := true for i := 1; i < len(levels); i++ { if levels[i] == 0 { allPos = false break } } if allPos { break } mc := len(margin) for i := 1; i < len(outline); i++ { if levels[i] == 0 { line := outline[i] if strings.HasPrefix(line, margin) && line[mc] != ' ' && line[mc] != '\t' { levels[i] = level } } } margin += indent } lines := make([]string, len(outline)) lines[0] = outline[0] var nodes []string for i := 1; i < len(outline); i++ { if levels[i] > levels[i-1] { if len(nodes) == 0 { nodes = append(nodes, outline[i-1]) } else { nodes = append(nodes, sep+outline[i-1]) } } else if levels[i] < levels[i-1] { j := levels[i-1] - levels[i] nodes = nodes[0 : len(nodes)-j] } if len(nodes) > 0 { lines[i] = strings.Join(nodes, "") + sep + outline[i] } else { lines[i] = outline[i] } } if ascending { sort.Strings(lines) } else { maxLen := len(lines[0]) for i := 1; i < len(lines); i++ { if len(lines[i]) > maxLen { maxLen = len(lines[i]) } } for i := 0; i < len(lines); i++ { lines[i] = lines[i] + strings.Repeat(del, maxLen-len(lines[i])) } sort.Sort(sort.Reverse(sort.StringSlice(lines))) } for i := 0; i < len(lines); i++ { s := strings.Split(lines[i], sep) lines[i] = s[len(s)-1] if !ascending { lines[i] = strings.TrimRight(lines[i], del) } } if len(messages) > 0 { fmt.Println(strings.Join(messages, "\n")) fmt.Println() } fmt.Println(strings.Join(lines, "\n")) } func main() { outline := []string{ "zeta", " beta", " gamma", " lambda", " kappa", " mu", " delta", "alpha", " theta", " iota", " epsilon", } outline2 := make([]string, len(outline)) for i := 0; i < len(outline); i++ { outline2[i] = strings.ReplaceAll(outline[i], " ", "\t") } outline3 := []string{ "alpha", " epsilon", " iota", " theta", "zeta", " beta", " delta", " gamma", " \t kappa", " lambda", " mu", } outline4 := []string{ "zeta", " beta", " gamma", " lambda", " kappa", " mu", " delta", "alpha", " theta", " iota", " epsilon", } fmt.Println("Four space indented outline, ascending sort:") sortedOutline(outline, true) fmt.Println("\nFour space indented outline, descending sort:") sortedOutline(outline, false) fmt.Println("\nTab indented outline, ascending sort:") sortedOutline(outline2, true) fmt.Println("\nTab indented outline, descending sort:") sortedOutline(outline2, false) fmt.Println("\nFirst unspecified outline, ascending sort:") sortedOutline(outline3, true) fmt.Println("\nFirst unspecified outline, descending sort:") sortedOutline(outline3, false) fmt.Println("\nSecond unspecified outline, ascending sort:") sortedOutline(outline4, true) fmt.Println("\nSecond unspecified outline, descending sort:") sortedOutline(outline4, false) }
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() { fmt.Println("The LCMs of the numbers 1 to N inclusive is:") for _, i := range []int{10, 20, 200, 2000} { fmt.Printf("%4d: %s\n", i, lcm(i)) } }
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) print("MM =", Euler + m)
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.0 fmt.Println("Primes added M") fmt.Println("------------ --------------") for i, p := range primes { rp := 1.0 / float64(p) sum += math.Log(1.0-rp) + rp c := i + 1 if (c%1e7) == 0 || c == pc { fmt.Printf("%11s %0.12f\n", rcu.Commatize(c), sum+euler) } } }
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 p += j*j if p > 16000: break print(p, end = " "); 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] = true } for { p += 2 if !c[p] { break } } } return c } func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func commas(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(15999) fmt.Println("Quadrat special primes under 16,000:") fmt.Println(" Prime1 Prime2 Gap Sqrt") lastQuadSpecial := 3 gap := 1 count := 1 fmt.Printf("%7d %7d %6d %4d\n", 2, 3, 1, 1) for i := 5; i < 16000; i += 2 { if c[i] { continue } gap = i - lastQuadSpecial if isSquare(gap) { sqrt := int(math.Sqrt(float64(gap))) fmt.Printf("%7s %7s %6s %4d\n", commas(lastQuadSpecial), commas(i), commas(gap), sqrt) lastQuadSpecial = i count++ } } fmt.Println("\n", count+1, "such primes found.") }
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 p += j*j if p > 16000: break print(p, end = " "); 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] = true } for { p += 2 if !c[p] { break } } } return c } func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func commas(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(15999) fmt.Println("Quadrat special primes under 16,000:") fmt.Println(" Prime1 Prime2 Gap Sqrt") lastQuadSpecial := 3 gap := 1 count := 1 fmt.Printf("%7d %7d %6d %4d\n", 2, 3, 1, 1) for i := 5; i < 16000; i += 2 { if c[i] { continue } gap = i - lastQuadSpecial if isSquare(gap) { sqrt := int(math.Sqrt(float64(gap))) fmt.Printf("%7s %7s %6s %4d\n", commas(lastQuadSpecial), commas(i), commas(gap), sqrt) lastQuadSpecial = i count++ } } fmt.Println("\n", count+1, "such primes found.") }
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: duplicates.add(s) return sequences - duplicates def smash(s, t): for i in range(len(s)): if t.startswith(s[i:]): return s[:i] + t return s + t def shortest_superstring(sequences): sequences = deduplicate(sequences) shortest = "".join(sequences) for perm in permutations(sequences): superstring = reduce(smash, perm) if len(superstring) < len(shortest): shortest = superstring return shortest def shortest_superstrings(sequences): sequences = deduplicate(sequences) shortest = set(["".join(sequences)]) shortest_length = sum(len(s) for s in sequences) for perm in permutations(sequences): superstring = reduce(smash, perm) superstring_length = len(superstring) if superstring_length < shortest_length: shortest.clear() shortest.add(superstring) shortest_length = superstring_length elif superstring_length == shortest_length: shortest.add(superstring) return shortest def print_report(sequence): buf = [f"Nucleotide counts for {sequence}:\n"] counts = Counter(sequence) for base in BASES: buf.append(f"{base:>10}{counts.get(base, 0):>12}") other = sum(v for k, v in counts.items() if k not in BASES) buf.append(f"{'Other':>10}{other:>12}") buf.append(" " * 5 + "_" * 17) buf.append(f"{'Total length':>17}{sum(counts.values()):>5}") print(os.linesep.join(buf), "\n") if __name__ == "__main__": test_cases = [ ("TA", "AAG", "TA", "GAA", "TA"), ("CATTAGGG", "ATTAG", "GGG", "TA"), ("AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA"), ( "ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT", "GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT", "GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC", "CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC", "GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT", "TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA", ), ] for case in test_cases: for superstring in shortest_superstrings(case): print_report(superstring)
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 - 1 fact := factorial(n + 1) for c := 1; c < fact; c++ { i := n - 1 j := n for i >= 0 && a[i] > a[i+1] { i-- } if i == -1 { i = n } for a[j] < a[i] { j-- } a[i], a[j] = a[j], a[i] j = n i++ if i == n+1 { i = 0 } for i < j { a[i], a[j] = a[j], a[i] i++ j-- } b := make([]string, le) copy(b, a) perms = append(perms, b) } return perms } func distinct(slist []string) []string { distinctSet := make(map[string]int, len(slist)) i := 0 for _, s := range slist { if _, ok := distinctSet[s]; !ok { distinctSet[s] = i i++ } } result := make([]string, len(distinctSet)) for s, i := range distinctSet { result[i] = s } return result } func printCounts(seq string) { bases := [][]rune{{'A', 0}, {'C', 0}, {'G', 0}, {'T', 0}} for _, c := range seq { for _, base := range bases { if c == base[0] { base[1]++ } } } sum := 0 fmt.Println("\nNucleotide counts for", seq, "\b:\n") for _, base := range bases { fmt.Printf("%10c%12d\n", base[0], base[1]) sum += int(base[1]) } le := len(seq) fmt.Printf("%10s%12d\n", "Other", le-sum) fmt.Printf(" ____________________\n%14s%8d\n", "Total length", le) } func headTailOverlap(s1, s2 string) int { for start := 0; ; start++ { ix := strings.IndexByte(s1[start:], s2[0]) if ix == -1 { return 0 } else { start += ix } if strings.HasPrefix(s2, s1[start:]) { return len(s1) - start } } } func deduplicate(slist []string) []string { var filtered []string arr := distinct(slist) for i, s1 := range arr { withinLarger := false for j, s2 := range arr { if j != i && strings.Contains(s2, s1) { withinLarger = true break } } if !withinLarger { filtered = append(filtered, s1) } } return filtered } func shortestCommonSuperstring(slist []string) string { ss := deduplicate(slist) shortestSuper := strings.Join(ss, "") for _, perm := range getPerms(ss) { sup := perm[0] for i := 0; i < len(ss)-1; i++ { overlapPos := headTailOverlap(perm[i], perm[i+1]) sup += perm[i+1][overlapPos:] } if len(sup) < len(shortestSuper) { shortestSuper = sup } } return shortestSuper } func main() { testSequences := [][]string{ {"TA", "AAG", "TA", "GAA", "TA"}, {"CATTAGGG", "ATTAG", "GGG", "TA"}, {"AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA"}, { "ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT", "GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT", "GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC", "CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC", "GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT", "TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA", }, } for _, test := range testSequences { scs := shortestCommonSuperstring(test) printCounts(scs) } }
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() for hblock in blocks: for row in zip(*hblock): m.append(list(chain.from_iterable(row))) return m def dot(self, b: Matrix) -> Matrix: assert self.shape.cols == b.shape.rows m = Matrix() for row in self: new_row = [] for c in range(len(b[0])): col = [b[r][c] for r in range(len(b))] new_row.append(sum(x * y for x, y in zip(row, col))) m.append(new_row) return m def __matmul__(self, b: Matrix) -> Matrix: return self.dot(b) def __add__(self, b: Matrix) -> Matrix: assert self.shape == b.shape rows, cols = self.shape return Matrix( [[self[i][j] + b[i][j] for j in range(cols)] for i in range(rows)] ) def __sub__(self, b: Matrix) -> Matrix: assert self.shape == b.shape rows, cols = self.shape return Matrix( [[self[i][j] - b[i][j] for j in range(cols)] for i in range(rows)] ) def strassen(self, b: Matrix) -> Matrix: rows, cols = self.shape assert rows == cols, "matrices must be square" assert self.shape == b.shape, "matrices must be the same shape" assert rows and (rows & rows - 1) == 0, "shape must be a power of 2" if rows == 1: return self.dot(b) p = rows // 2 a11 = Matrix([n[:p] for n in self[:p]]) a12 = Matrix([n[p:] for n in self[:p]]) a21 = Matrix([n[:p] for n in self[p:]]) a22 = Matrix([n[p:] for n in self[p:]]) b11 = Matrix([n[:p] for n in b[:p]]) b12 = Matrix([n[p:] for n in b[:p]]) b21 = Matrix([n[:p] for n in b[p:]]) b22 = Matrix([n[p:] for n in b[p:]]) m1 = (a11 + a22).strassen(b11 + b22) m2 = (a21 + a22).strassen(b11) m3 = a11.strassen(b12 - b22) m4 = a22.strassen(b21 - b11) m5 = (a11 + a12).strassen(b22) m6 = (a21 - a11).strassen(b11 + b12) m7 = (a12 - a22).strassen(b21 + b22) c11 = m1 + m4 - m5 + m7 c12 = m3 + m5 c21 = m2 + m4 c22 = m1 - m2 + m3 + m6 return Matrix.block([[c11, c12], [c21, c22]]) def round(self, ndigits: Optional[int] = None) -> Matrix: return Matrix([[round(i, ndigits) for i in row] for row in self]) @property def shape(self) -> Shape: cols = len(self[0]) if self else 0 return Shape(len(self), cols) def examples(): a = Matrix( [ [1, 2], [3, 4], ] ) b = Matrix( [ [5, 6], [7, 8], ] ) c = Matrix( [ [1, 1, 1, 1], [2, 4, 8, 16], [3, 9, 27, 81], [4, 16, 64, 256], ] ) d = Matrix( [ [4, -3, 4 / 3, -1 / 4], [-13 / 3, 19 / 4, -7 / 3, 11 / 24], [3 / 2, -2, 7 / 6, -1 / 4], [-1 / 6, 1 / 4, -1 / 6, 1 / 24], ] ) e = Matrix( [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ] ) f = Matrix( [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) print("Naive matrix multiplication:") print(f" a * b = {a @ b}") print(f" c * d = {(c @ d).round()}") print(f" e * f = {e @ f}") print("Strassen's matrix multiplication:") print(f" a * b = {a.strassen(b)}") print(f" c * d = {c.strassen(d).round()}") print(f" e * f = {e.strassen(f)}") if __name__ == "__main__": examples()
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 dimensions.") } c := make(Matrix, m.rows()) for i := 0; i < m.rows(); i++ { c[i] = make([]float64, m.cols()) for j := 0; j < m.cols(); j++ { c[i][j] = m[i][j] + m2[i][j] } } return c } func (m Matrix) sub(m2 Matrix) Matrix { if m.rows() != m2.rows() || m.cols() != m2.cols() { log.Fatal("Matrices must have the same dimensions.") } c := make(Matrix, m.rows()) for i := 0; i < m.rows(); i++ { c[i] = make([]float64, m.cols()) for j := 0; j < m.cols(); j++ { c[i][j] = m[i][j] - m2[i][j] } } return c } func (m Matrix) mul(m2 Matrix) Matrix { if m.cols() != m2.rows() { log.Fatal("Cannot multiply these matrices.") } c := make(Matrix, m.rows()) for i := 0; i < m.rows(); i++ { c[i] = make([]float64, m2.cols()) for j := 0; j < m2.cols(); j++ { for k := 0; k < m2.rows(); k++ { c[i][j] += m[i][k] * m2[k][j] } } } return c } func (m Matrix) toString(p int) string { s := make([]string, m.rows()) pow := math.Pow(10, float64(p)) for i := 0; i < m.rows(); i++ { t := make([]string, m.cols()) for j := 0; j < m.cols(); j++ { r := math.Round(m[i][j]*pow) / pow t[j] = fmt.Sprintf("%g", r) if t[j] == "-0" { t[j] = "0" } } s[i] = fmt.Sprintf("%v", t) } return fmt.Sprintf("%v", s) } func params(r, c int) [4][6]int { return [4][6]int{ {0, r, 0, c, 0, 0}, {0, r, c, 2 * c, 0, c}, {r, 2 * r, 0, c, r, 0}, {r, 2 * r, c, 2 * c, r, c}, } } func toQuarters(m Matrix) [4]Matrix { r := m.rows() / 2 c := m.cols() / 2 p := params(r, c) var quarters [4]Matrix for k := 0; k < 4; k++ { q := make(Matrix, r) for i := p[k][0]; i < p[k][1]; i++ { q[i-p[k][4]] = make([]float64, c) for j := p[k][2]; j < p[k][3]; j++ { q[i-p[k][4]][j-p[k][5]] = m[i][j] } } quarters[k] = q } return quarters } func fromQuarters(q [4]Matrix) Matrix { r := q[0].rows() c := q[0].cols() p := params(r, c) r *= 2 c *= 2 m := make(Matrix, r) for i := 0; i < c; i++ { m[i] = make([]float64, c) } for k := 0; k < 4; k++ { for i := p[k][0]; i < p[k][1]; i++ { for j := p[k][2]; j < p[k][3]; j++ { m[i][j] = q[k][i-p[k][4]][j-p[k][5]] } } } return m } func strassen(a, b Matrix) Matrix { if a.rows() != a.cols() || b.rows() != b.cols() || a.rows() != b.rows() { log.Fatal("Matrices must be square and of equal size.") } if a.rows() == 0 || (a.rows()&(a.rows()-1)) != 0 { log.Fatal("Size of matrices must be a power of two.") } if a.rows() == 1 { return a.mul(b) } qa := toQuarters(a) qb := toQuarters(b) p1 := strassen(qa[1].sub(qa[3]), qb[2].add(qb[3])) p2 := strassen(qa[0].add(qa[3]), qb[0].add(qb[3])) p3 := strassen(qa[0].sub(qa[2]), qb[0].add(qb[1])) p4 := strassen(qa[0].add(qa[1]), qb[3]) p5 := strassen(qa[0], qb[1].sub(qb[3])) p6 := strassen(qa[3], qb[2].sub(qb[0])) p7 := strassen(qa[2].add(qa[3]), qb[0]) var q [4]Matrix q[0] = p1.add(p2).sub(p4).add(p6) q[1] = p4.add(p5) q[2] = p6.add(p7) q[3] = p2.sub(p3).add(p5).sub(p7) return fromQuarters(q) } func main() { a := Matrix{{1, 2}, {3, 4}} b := Matrix{{5, 6}, {7, 8}} c := Matrix{{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}} d := Matrix{{4, -3, 4.0 / 3, -1.0 / 4}, {-13.0 / 3, 19.0 / 4, -7.0 / 3, 11.0 / 24}, {3.0 / 2, -2, 7.0 / 6, -1.0 / 4}, {-1.0 / 6, 1.0 / 4, -1.0 / 6, 1.0 / 24}} e := Matrix{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} f := Matrix{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}} fmt.Println("Using 'normal' matrix multiplication:") fmt.Printf(" a * b = %v\n", a.mul(b)) fmt.Printf(" c * d = %v\n", c.mul(d).toString(6)) fmt.Printf(" e * f = %v\n", e.mul(f)) fmt.Println("\nUsing 'Strassen' matrix multiplication:") fmt.Printf(" a * b = %v\n", strassen(a, b)) fmt.Printf(" c * d = %v\n", strassen(c, d).toString(6)) fmt.Printf(" e * f = %v\n", strassen(e, f)) }
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) if err != nil { return "NA" } return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64) } func main() { f := template.FuncMap{"sqr": sqr, "sqrt": sqrt} t := template.Must(template.New("").Funcs(f).Parse(`. = {{.}} square: {{sqr .}} square root: {{sqrt .}} `)) t.Execute(os.Stdout, "3") }
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) if err != nil { return "NA" } return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64) } func main() { f := template.FuncMap{"sqr": sqr, "sqrt": sqrt} t := template.Must(template.New("").Funcs(f).Parse(`. = {{.}} square: {{sqr .}} square root: {{sqrt .}} `)) t.Execute(os.Stdout, "3") }
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.Println("Create two fields at runtime: ") for i := 1; i <= 2; i++ { fmt.Printf(" Field #%d:\n", i) fmt.Print(" Enter name  : ") scanner.Scan() name := scanner.Text() fmt.Print(" Enter value : ") scanner.Scan() value := scanner.Text() check(scanner.Err()) ss.runtimeFields[name] = value fmt.Println() } for { fmt.Print("Which field do you want to inspect ? ") scanner.Scan() name := scanner.Text() check(scanner.Err()) value, ok := ss.runtimeFields[name] if !ok { fmt.Println("There is no field of that name, try again") } else { fmt.Printf("Its value is '%s'\n", value) return } } }
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 = list(edges.pop(0)) if edges else [] last = p[-1] if p else None while edges: for n, (i, j) in enumerate(edges): if i == last: p.append(j) last = j edges.pop(n) break elif j == last: p.append(i) last = i edges.pop(n) break else: return ">>>Error! Invalid edge format<<<" return p[:-1] if __name__ == '__main__': print('Perimeter format equality checks:') for eq_check in [ { 'Q': (8, 1, 3), 'R': (1, 3, 8)}, { 'U': (18, 8, 14, 10, 12, 17, 19), 'V': (8, 14, 10, 12, 17, 19, 18)} ]: (n1, p1), (n2, p2) = eq_check.items() eq = '==' if perim_equal(p1, p2) else '!=' print(' ', n1, eq, n2) print('\nEdge to perimeter format translations:') edge_d = { 'E': {(1, 11), (7, 11), (1, 7)}, 'F': {(11, 23), (1, 17), (17, 23), (1, 11)}, 'G': {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}, 'H': {(1, 3), (9, 11), (3, 11), (1, 11)} } for name, edges in edge_d.items(): print(f" {name}: {edges}\n -> {edge_to_periphery(edges)}")
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 } } return true } func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func perimEqual(p1, p2 []int) bool { le := len(p1) if le != len(p2) { return false } for _, p := range p1 { if !contains(p2, p) { return false } } c := make([]int, le) copy(c, p1) for r := 0; r < 2; r++ { for i := 0; i < le; i++ { if sliceEqual(c, p2) { return true } t := c[le-1] copy(c[1:], c[0:le-1]) c[0] = t } reverse(c) } return false } type edge [2]int func faceToPerim(face []edge) []int { le := len(face) if le == 0 { return nil } edges := make([]edge, le) for i := 0; i < le; i++ { if face[i][1] <= face[i][0] { return nil } edges[i] = face[i] } sort.Slice(edges, func(i, j int) bool { if edges[i][0] != edges[j][0] { return edges[i][0] < edges[j][0] } return edges[i][1] < edges[j][1] }) var perim []int first, last := edges[0][0], edges[0][1] perim = append(perim, first, last) copy(edges, edges[1:]) edges = edges[0 : le-1] le-- outer: for le > 0 { for i, e := range edges { found := false if e[0] == last { perim = append(perim, e[1]) last, found = e[1], true } else if e[1] == last { perim = append(perim, e[0]) last, found = e[0], true } if found { copy(edges[i:], edges[i+1:]) edges = edges[0 : le-1] le-- if last == first { if le == 0 { break outer } else { return nil } } continue outer } } } return perim[0 : len(perim)-1] } func main() { fmt.Println("Perimeter format equality checks:") areEqual := perimEqual([]int{8, 1, 3}, []int{1, 3, 8}) fmt.Printf(" Q == R is %t\n", areEqual) areEqual = perimEqual([]int{18, 8, 14, 10, 12, 17, 19}, []int{8, 14, 10, 12, 17, 19, 18}) fmt.Printf(" U == V is %t\n", areEqual) e := []edge{{7, 11}, {1, 11}, {1, 7}} f := []edge{{11, 23}, {1, 17}, {17, 23}, {1, 11}} g := []edge{{8, 14}, {17, 19}, {10, 12}, {10, 14}, {12, 17}, {8, 18}, {18, 19}} h := []edge{{1, 3}, {9, 11}, {3, 11}, {1, 11}} fmt.Println("\nEdge to perimeter format translations:") for i, face := range [][]edge{e, f, g, h} { perim := faceToPerim(face) if perim == nil { fmt.Printf(" %c => Invalid edge format\n", i + 'E') } else { fmt.Printf(" %c => %v\n", i + 'E', perim) } } }
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][k] for i in range(n - 1, -1, -1): for j in range(i): m[j][-1] -= m[j][i] * m[i][-1] return [row[-1] for row in m] def network(n,k0,k1,s): m = [[0] * (n+1) for i in range(n)] resistors = s.split('|') for resistor in resistors: a,b,r = resistor.split(' ') a,b,r = int(a), int(b), Fraction(1,int(r)) m[a][a] += r m[b][b] += r if a > 0: m[a][b] -= r if b > 0: m[b][a] -= r m[k0][k0] = Fraction(1, 1) m[k1][-1] = Fraction(1, 1) return gauss(m)[k1] assert 10 == network(7,0,1,"0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8") assert 3/2 == network(3*3,0,3*3-1,"0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1") assert Fraction(13,7) == network(4*4,0,4*4-1,"0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1") assert 180 == network(4,0,3,"0 1 150|0 2 50|1 3 300|2 3 250")
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 } } return maxx } func gauss(m [][]float64) []float64 { n, p := len(m), len(m[0]) for i := 0; i < n; i++ { k := i + argmax(m[i:n], i) m[i], m[k] = m[k], m[i] t := 1 / m[i][i] for j := i + 1; j < p; j++ { m[i][j] *= t } for j := i + 1; j < n; j++ { t = m[j][i] for l := i + 1; l < p; l++ { m[j][l] -= t * m[i][l] } } } for i := n - 1; i >= 0; i-- { for j := 0; j < i; j++ { m[j][p-1] -= m[j][i] * m[i][p-1] } } col := make([]float64, len(m)) for x := 0; x < len(m); x++ { col[x] = m[x][p-1] } return col } func network(n, k0, k1 int, s string) float64 { m := make([][]float64, n) for i := 0; i < n; i++ { m[i] = make([]float64, n+1) } for _, resistor := range strings.Split(s, "|") { rarr := strings.Fields(resistor) a, _ := strconv.Atoi(rarr[0]) b, _ := strconv.Atoi(rarr[1]) ri, _ := strconv.Atoi(rarr[2]) r := 1.0 / float64(ri) m[a][a] += r m[b][b] += r if a > 0 { m[a][b] -= r } if b > 0 { m[b][a] -= r } } m[k0][k0] = 1 m[k1][n] = 1 return gauss(m)[k1] } func main() { var fa [4]float64 fa[0] = network(7, 0, 1, "0 2 6|2 3 4|3 4 10|4 5 2|5 6 8|6 1 4|3 5 6|3 6 6|3 1 8|2 1 8") fa[1] = network(9, 0, 8, "0 1 1|1 2 1|3 4 1|4 5 1|6 7 1|7 8 1|0 3 1|3 6 1|1 4 1|4 7 1|2 5 1|5 8 1") fa[2] = network(16, 0, 15, "0 1 1|1 2 1|2 3 1|4 5 1|5 6 1|6 7 1|8 9 1|9 10 1|10 11 1|12 13 1|13 14 1|14 15 1|0 4 1|4 8 1|8 12 1|1 5 1|5 9 1|9 13 1|2 6 1|6 10 1|10 14 1|3 7 1|7 11 1|11 15 1") fa[3] = network(4, 0, 3, "0 1 150|0 2 50|1 3 300|2 3 250") for _, f := range fa { fmt.Printf("%.6g\n", f) } }
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 matches found") else: print(f"Found {needle} at the following indices: ") for match in re.finditer(needle, haystack, overlapped=True): print(f"{match.start()}:{match.end()} ") dna_seq = generate_sequence(200) sample_seq = generate_sequence(4) c = 1 for i in dna_seq: print(i, end="") if c % 20 != 0 else print(f"{i}") c += 1 print(f"\nSearch Sample: {sample_seq}") dna_findall(sample_seq, dna_seq)
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, 4) for i := 0; i < 4; i++ { dnaSubseq[i] = base[rand.Intn(4)] } dnaSubstr := string(dnaSubseq) fmt.Println("DNA sequnence:") for i := chunkSize; i <= len(dnaStr); i += chunkSize { start := i - chunkSize fmt.Printf("%3d..%3d: %s\n", start+1, i, dnaStr[start:i]) } fmt.Println("\nSubsequence to locate:", dnaSubstr) var r = regexp.MustCompile(dnaSubstr) var matches = r.FindAllStringIndex(dnaStr, -1) if len(matches) == 0 { fmt.Println("No matches found.") } else { fmt.Println("Matches found at the following indices:") for _, m := range matches { fmt.Printf("%3d..%-3d\n", m[0]+1, m[1]) } } } func main() { rand.Seed(time.Now().UnixNano()) findDnaSubsequence(200, 20) fmt.Println() findDnaSubsequence(600, 40) }
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] for x in substruct if type(x) is not tuple and x in i2d) missed.extend(f'?? for x in substruct if type(x) is not tuple and x not in i2d) return tuple(_inject_payload(x, i2d, used, missed) if type(x) is tuple else i2d.get(x, f'?? for x in substruct) ans = _inject_payload(self.structure, id2data, self.used_payloads, self.missed_payloads) self.unused_payloads = sorted(set(id2data.values()) - set(self.used_payloads)) self.missed_payloads = sorted(set(self.missed_payloads)) return ans if __name__ == '__main__': index2data = {p: f'Payload print(" print('\n '.join(list(index2data.values()))) for structure in [ (((1, 2), (3, 4, 1), 5),), (((1, 2), (10, 4, 1), 5),)]: print("\n\n pp(structure, width=13) print("\n TEMPLATE WITH PAYLOADS:") t = Template(structure) out = t.inject_payload(index2data) pp(out) print("\n UNUSED PAYLOADS:\n ", end='') unused = t.unused_payloads print('\n '.join(unused) if unused else '-') print(" MISSING PAYLOADS:\n ", end='') missed = t.missed_payloads print('\n '.join(missed) if missed else '-')
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{ 0: "'Payload#0'", 1: "'Payload#1'", 2: "'Payload#2'", 3: "'Payload#3'", 4: "'Payload#4'", 5: "'Payload#5'", 6: "'Payload#6'", } tmpl := template.Must(template.New("").Parse(t)) tmpl.Execute(os.Stdout, s) var unused []int for k, _ := range s.P { if !strings.Contains(t, fmt.Sprintf("{{index .P %d}}", k)) { unused = append(unused, k) } } sort.Ints(unused) fmt.Println("\nThe unused payloads have indices of :", unused) }
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 := raster.ReadPpmFrom(pipe) if err != nil { log.Fatal(err) } if err = b.WritePpmFile("Unfilledcirc.ppm"); err != nil { log.Fatal(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 := raster.ReadPpmFrom(pipe) if err != nil { log.Fatal(err) } if err = b.WritePpmFile("Unfilledcirc.ppm"); err != nil { log.Fatal(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) for __ in rs232_9pin] class RS232_25pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_25pin]
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota RD9 TD9 DTR9 SG9 DSR9 RTS9 CTS9 RI9 ) func main() { p := RI9 | TD9 | CD9 fmt.Printf("Type=%T value=%#04x\n", p, p) }
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) for __ in rs232_9pin] class RS232_25pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_25pin]
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota RD9 TD9 DTR9 SG9 DSR9 RTS9 CTS9 RI9 ) func main() { p := RI9 | TD9 | CD9 fmt.Printf("Type=%T value=%#04x\n", p, p) }
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): num += 1 if num < 21: print('{:2}'.format(n), "+", '{:2}'.format(n+1), "=", '{:2}'.format(suma)) else: break
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.Printf("%2d + %2d = %2d\n", hp, hp+1, p) } fmt.Println("\nThe 10 millionth such pair is:") p := primes[1e7] hp := p / 2 fmt.Printf("%2d + %2d = %2d\n", hp, hp+1, p) }
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_val, max_val): while True: user_input = input(prompt) try: user_input = int(user_input) except ValueError: continue if min_val <= user_input <= max_val: return user_input def play_game(): print("Welcome to Mastermind.") print("You will need to guess a random code.") print("For each guess, you will receive a hint.") print("In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.") print() number_of_letters = safe_int_input("Select a number of possible letters for the code (2-20): ", 2, 20) code_length = safe_int_input("Select a length for the code (4-10): ", 4, 10) letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters] code = ''.join(random.choices(letters, k=code_length)) guesses = [] while True: print() guess = input(f"Enter a guess of length {code_length} ({letters}): ").upper().strip() if len(guess) != code_length or any([char not in letters for char in guess]): continue elif guess == code: print(f"\nYour guess {guess} was correct!") break else: guesses.append(f"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}") for i_guess in guesses: print("------------------------------------") print(i_guess) print("------------------------------------") if __name__ == '__main__': play_game()
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 holes (the code length, 4-10)") guesses := flag.Int("guesses", 12, "number of guesses allowed (7-20)") unique := flag.Bool("unique", false, "disallow duplicate colours in the code") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMastermind(*colours, *holes, *guesses, *unique) if err != nil { log.Fatal(err) } err = m.Play() if err != nil { log.Fatal(err) } } type mastermind struct { colours int holes int guesses int unique bool code string past []string scores []string } func NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) { if colours < 2 || colours > 20 { return nil, errors.New("colours must be between 2 and 20 inclusive") } if holes < 4 || holes > 10 { return nil, errors.New("holes must be between 4 and 10 inclusive") } if guesses < 7 || guesses > 20 { return nil, errors.New("guesses must be between 7 and 20 inclusive") } if unique && holes > colours { return nil, errors.New("holes must be > colours when using unique") } return &mastermind{ colours: colours, holes: holes, guesses: guesses, unique: unique, past: make([]string, 0, guesses), scores: make([]string, 0, guesses), }, nil } func (m *mastermind) Play() error { m.generateCode() fmt.Printf("A set of %s has been selected as the code.\n", m.describeCode(m.unique)) fmt.Printf("You have %d guesses.\n", m.guesses) for len(m.past) < m.guesses { guess, err := m.inputGuess() if err != nil { return err } fmt.Println() m.past = append(m.past, guess) str, won := m.scoreString(m.score(guess)) if won { plural := "es" if len(m.past) == 1 { plural = "" } fmt.Printf("You found the code in %d guess%s.\n", len(m.past), plural) return nil } m.scores = append(m.scores, str) m.printHistory() fmt.Println() } fmt.Printf("You are out of guesses. The code was %s.\n", m.code) return nil } const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" const blacks = "XXXXXXXXXX" const whites = "OOOOOOOOOO" const nones = "----------" func (m *mastermind) describeCode(unique bool) string { ustr := "" if unique { ustr = " unique" } return fmt.Sprintf("%d%s letters (from 'A' to %q)", m.holes, ustr, charset[m.colours-1], ) } func (m *mastermind) printHistory() { for i, g := range m.past { fmt.Printf("-----%s---%[1]s--\n", nones[:m.holes]) fmt.Printf("%2d: %s : %s\n", i+1, g, m.scores[i]) } } func (m *mastermind) generateCode() { code := make([]byte, m.holes) if m.unique { p := rand.Perm(m.colours) for i := range code { code[i] = charset[p[i]] } } else { for i := range code { code[i] = charset[rand.Intn(m.colours)] } } m.code = string(code) } func (m *mastermind) inputGuess() (string, error) { var input string for { fmt.Printf("Enter guess #%d: ", len(m.past)+1) if _, err := fmt.Scanln(&input); err != nil { return "", err } input = strings.ToUpper(strings.TrimSpace(input)) if m.validGuess(input) { return input, nil } fmt.Printf("A guess must consist of %s.\n", m.describeCode(false)) } } func (m *mastermind) validGuess(input string) bool { if len(input) != m.holes { return false } for i := 0; i < len(input); i++ { c := input[i] if c < 'A' || c > charset[m.colours-1] { return false } } return true } func (m *mastermind) score(guess string) (black, white int) { scored := make([]bool, m.holes) for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { black++ scored[i] = true } } for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { continue } for j := 0; j < len(m.code); j++ { if i != j && !scored[j] && guess[i] == m.code[j] { white++ scored[j] = true } } } return } func (m *mastermind) scoreString(black, white int) (string, bool) { none := m.holes - black - white return blacks[:black] + whites[:white] + nones[:none], black == m.holes }
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_val, max_val): while True: user_input = input(prompt) try: user_input = int(user_input) except ValueError: continue if min_val <= user_input <= max_val: return user_input def play_game(): print("Welcome to Mastermind.") print("You will need to guess a random code.") print("For each guess, you will receive a hint.") print("In this hint, X denotes a correct letter, and O a letter in the original string but in a different position.") print() number_of_letters = safe_int_input("Select a number of possible letters for the code (2-20): ", 2, 20) code_length = safe_int_input("Select a length for the code (4-10): ", 4, 10) letters = 'ABCDEFGHIJKLMNOPQRST'[:number_of_letters] code = ''.join(random.choices(letters, k=code_length)) guesses = [] while True: print() guess = input(f"Enter a guess of length {code_length} ({letters}): ").upper().strip() if len(guess) != code_length or any([char not in letters for char in guess]): continue elif guess == code: print(f"\nYour guess {guess} was correct!") break else: guesses.append(f"{len(guesses)+1}: {' '.join(guess)} => {' '.join(encode(code, guess))}") for i_guess in guesses: print("------------------------------------") print(i_guess) print("------------------------------------") if __name__ == '__main__': play_game()
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 holes (the code length, 4-10)") guesses := flag.Int("guesses", 12, "number of guesses allowed (7-20)") unique := flag.Bool("unique", false, "disallow duplicate colours in the code") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMastermind(*colours, *holes, *guesses, *unique) if err != nil { log.Fatal(err) } err = m.Play() if err != nil { log.Fatal(err) } } type mastermind struct { colours int holes int guesses int unique bool code string past []string scores []string } func NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) { if colours < 2 || colours > 20 { return nil, errors.New("colours must be between 2 and 20 inclusive") } if holes < 4 || holes > 10 { return nil, errors.New("holes must be between 4 and 10 inclusive") } if guesses < 7 || guesses > 20 { return nil, errors.New("guesses must be between 7 and 20 inclusive") } if unique && holes > colours { return nil, errors.New("holes must be > colours when using unique") } return &mastermind{ colours: colours, holes: holes, guesses: guesses, unique: unique, past: make([]string, 0, guesses), scores: make([]string, 0, guesses), }, nil } func (m *mastermind) Play() error { m.generateCode() fmt.Printf("A set of %s has been selected as the code.\n", m.describeCode(m.unique)) fmt.Printf("You have %d guesses.\n", m.guesses) for len(m.past) < m.guesses { guess, err := m.inputGuess() if err != nil { return err } fmt.Println() m.past = append(m.past, guess) str, won := m.scoreString(m.score(guess)) if won { plural := "es" if len(m.past) == 1 { plural = "" } fmt.Printf("You found the code in %d guess%s.\n", len(m.past), plural) return nil } m.scores = append(m.scores, str) m.printHistory() fmt.Println() } fmt.Printf("You are out of guesses. The code was %s.\n", m.code) return nil } const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" const blacks = "XXXXXXXXXX" const whites = "OOOOOOOOOO" const nones = "----------" func (m *mastermind) describeCode(unique bool) string { ustr := "" if unique { ustr = " unique" } return fmt.Sprintf("%d%s letters (from 'A' to %q)", m.holes, ustr, charset[m.colours-1], ) } func (m *mastermind) printHistory() { for i, g := range m.past { fmt.Printf("-----%s---%[1]s--\n", nones[:m.holes]) fmt.Printf("%2d: %s : %s\n", i+1, g, m.scores[i]) } } func (m *mastermind) generateCode() { code := make([]byte, m.holes) if m.unique { p := rand.Perm(m.colours) for i := range code { code[i] = charset[p[i]] } } else { for i := range code { code[i] = charset[rand.Intn(m.colours)] } } m.code = string(code) } func (m *mastermind) inputGuess() (string, error) { var input string for { fmt.Printf("Enter guess #%d: ", len(m.past)+1) if _, err := fmt.Scanln(&input); err != nil { return "", err } input = strings.ToUpper(strings.TrimSpace(input)) if m.validGuess(input) { return input, nil } fmt.Printf("A guess must consist of %s.\n", m.describeCode(false)) } } func (m *mastermind) validGuess(input string) bool { if len(input) != m.holes { return false } for i := 0; i < len(input); i++ { c := input[i] if c < 'A' || c > charset[m.colours-1] { return false } } return true } func (m *mastermind) score(guess string) (black, white int) { scored := make([]bool, m.holes) for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { black++ scored[i] = true } } for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { continue } for j := 0; j < len(m.code); j++ { if i != j && !scored[j] && guess[i] == m.code[j] { white++ scored[j] = true } } } return } func (m *mastermind) scoreString(black, white int) (string, bool) { none := m.holes - black - white return blacks[:black] + whites[:white] + nones[:none], black == m.holes }
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, 5.5, 8, 6, 2, 9, 11, 10, 3 ]) for ab in maxPairs: print(ab) if __name__ == '__main__': main()
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 { maxDiff = diff maxPairs = [][2]float64{{list[i-1], list[i]}} } else if diff == maxDiff { maxPairs = append(maxPairs, [2]float64{list[i-1], list[i]}) } } fmt.Println("The maximum difference between adjacent pairs of the list is:", maxDiff) fmt.Println("The pairs with this difference are:", maxPairs) }
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_over_7(n): found += 1 print(f'{n: 12,}', end = '\n' if found % 10 == 0 else '') if found == 20: break
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) > 1 { s := strconv.Itoa(k) includesAll := true prev := -1 for _, f := range factors { if f == prev { continue } fs := strconv.Itoa(f) if strings.Index(s, fs) == -1 { includesAll = false break } } if includesAll { res = append(res, k) count++ } } k += 2 } for _, e := range res[0:10] { fmt.Printf("%10s ", rcu.Commatize(e)) } fmt.Println() for _, e := range res[10:20] { fmt.Printf("%10s ", rcu.Commatize(e)) } fmt.Println() }
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_over_7(n): found += 1 print(f'{n: 12,}', end = '\n' if found % 10 == 0 else '') if found == 20: break
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) > 1 { s := strconv.Itoa(k) includesAll := true prev := -1 for _, f := range factors { if f == prev { continue } fs := strconv.Itoa(f) if strings.Index(s, fs) == -1 { includesAll = false break } } if includesAll { res = append(res, k) count++ } } k += 2 } for _, e := range res[0:10] { fmt.Printf("%10s ", rcu.Commatize(e)) } fmt.Println() for _, e := range res[10:20] { fmt.Printf("%10s ", rcu.Commatize(e)) } fmt.Println() }
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)): indent += 1 indent -= 1 fields = [right_type(f) for f in line.strip().split(',')] if indent == start_indent: the_list.append(fields) elif indent > start_indent: lst = [fields] sub = commas_to_list(lst, lines, indent) the_list[-1] = (the_list[-1], lst) if sub not in (None, ['']) : the_list.append(sub) else: return fields if fields else None return None def pptreefields(lst, indent=0, widths=['%-32s', '%-8g', '%-10g']): lhs = ' ' * (4 * indent) for item in lst: if type(item) != tuple: name, *rest = item print(widths[0] % (lhs + name), end='|') for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]): if type(item) == str: width = width[:-1] + 's' print(width % item, end='|') print() else: item, children = item name, *rest = item print(widths[0] % (lhs + name), end='|') for width, item in zip_longest(widths[1:len(rest)], rest, fillvalue=widths[-1]): if type(item) == str: width = width[:-1] + 's' print(width % item, end='|') print() pptreefields(children, indent+1) def default_field(node_list): node_list[WT] = node_list[WT] if node_list[WT] else 1.0 node_list[COV] = node_list[COV] if node_list[COV] else 0.0 def depth_first(tree, visitor=default_field): for item in tree: if type(item) == tuple: item, children = item depth_first(children, visitor) visitor(item) def covercalc(tree): sum_covwt, sum_wt = 0, 0 for item in tree: if type(item) == tuple: item, children = item item[COV] = covercalc(children) sum_wt += item[WT] sum_covwt += item[COV] * item[WT] cov = sum_covwt / sum_wt return cov if __name__ == '__main__': lstc = [] commas_to_list(lstc, ((n, ln) for n, ln in enumerate(fc2.split('\n')))) depth_first(lstc) print('\n\nTOP COVERAGE = %f\n' % covercalc(lstc)) depth_first(lstc) pptreefields(['NAME_HIERARCHY WEIGHT COVERAGE'.split()] + lstc)
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) { for _, node := range nodes { node.parent = n n.children = append(n.children, node) } n.updateCoverage() } func (n *FCNode) setCoverage(value float64) { if n.coverage != value { n.coverage = value if n.parent != nil { n.parent.updateCoverage() } } } func (n *FCNode) updateCoverage() { v1 := 0.0 v2 := 0 for _, node := range n.children { v1 += float64(node.weight) * node.coverage v2 += node.weight } n.setCoverage(v1 / float64(v2)) } func (n *FCNode) show(level int) { indent := level * 4 nl := len(n.name) + indent fmt.Printf("%*s%*s %3d | %8.6f |\n", nl, n.name, 32-nl, "|", n.weight, n.coverage) if len(n.children) == 0 { return } for _, child := range n.children { child.show(level + 1) } } var houses = []*FCNode{ newFCN("house1", 40, 0), newFCN("house2", 60, 0), } var house1 = []*FCNode{ newFCN("bedrooms", 1, 0.25), newFCN("bathrooms", 1, 0), newFCN("attic", 1, 0.75), newFCN("kitchen", 1, 0.1), newFCN("living_rooms", 1, 0), newFCN("basement", 1, 0), newFCN("garage", 1, 0), newFCN("garden", 1, 0.8), } var house2 = []*FCNode{ newFCN("upstairs", 1, 0), newFCN("groundfloor", 1, 0), newFCN("basement", 1, 0), } var h1Bathrooms = []*FCNode{ newFCN("bathroom1", 1, 0.5), newFCN("bathroom2", 1, 0), newFCN("outside_lavatory", 1, 1), } var h1LivingRooms = []*FCNode{ newFCN("lounge", 1, 0), newFCN("dining_room", 1, 0), newFCN("conservatory", 1, 0), newFCN("playroom", 1, 1), } var h2Upstairs = []*FCNode{ newFCN("bedrooms", 1, 0), newFCN("bathroom", 1, 0), newFCN("toilet", 1, 0), newFCN("attics", 1, 0.6), } var h2Groundfloor = []*FCNode{ newFCN("kitchen", 1, 0), newFCN("living_rooms", 1, 0), newFCN("wet_room_&_toilet", 1, 0), newFCN("garage", 1, 0), newFCN("garden", 1, 0.9), newFCN("hot_tub_suite", 1, 1), } var h2Basement = []*FCNode{ newFCN("cellars", 1, 1), newFCN("wine_cellar", 1, 1), newFCN("cinema", 1, 0.75), } var h2UpstairsBedrooms = []*FCNode{ newFCN("suite_1", 1, 0), newFCN("suite_2", 1, 0), newFCN("bedroom_3", 1, 0), newFCN("bedroom_4", 1, 0), } var h2GroundfloorLivingRooms = []*FCNode{ newFCN("lounge", 1, 0), newFCN("dining_room", 1, 0), newFCN("conservatory", 1, 0), newFCN("playroom", 1, 0), } func main() { cleaning := newFCN("cleaning", 1, 0) house1[1].addChildren(h1Bathrooms) house1[4].addChildren(h1LivingRooms) houses[0].addChildren(house1) h2Upstairs[0].addChildren(h2UpstairsBedrooms) house2[0].addChildren(h2Upstairs) h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms) house2[1].addChildren(h2Groundfloor) house2[2].addChildren(h2Basement) houses[1].addChildren(house2) cleaning.addChildren(houses) topCoverage := cleaning.coverage fmt.Printf("TOP COVERAGE = %8.6f\n\n", topCoverage) fmt.Println("NAME HIERARCHY | WEIGHT | COVERAGE |") cleaning.show(0) h2Basement[2].setCoverage(1) diff := cleaning.coverage - topCoverage fmt.Println("\nIf the coverage of the Cinema node were increased from 0.75 to 1") fmt.Print("the top level coverage would increase by ") fmt.Printf("%8.6f to %8.6f\n", diff, topCoverage+diff) h2Basement[2].setCoverage(0.75) }
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): if len(self.vs) > 0: ret, self.vs = self.vs[-1], self.vs[:-1] return ret def __mul__(self, v): s = np.zeros(len(v)) for vi in self.vs: s = s + vi * np.dot(vi, v) return s class GaertnerBoundary: def __init__(self, pts): self.projector = ProjectorStack([]) self.centers, self.square_radii = np.array([]), np.array([]) self.empty_center = np.array([np.NaN for _ in pts[0]]) def push_if_stable(bound, pt): if len(bound.centers) == 0: bound.square_radii = np.append(bound.square_radii, 0.0) bound.centers = np.array([pt]) return True q0, center = bound.centers[0], bound.centers[-1] C, r2 = center - q0, bound.square_radii[-1] Qm, M = pt - q0, bound.projector Qm_bar = M * Qm residue, e = Qm - Qm_bar, sqdist(Qm, C) - r2 z, tol = 2 * sqnorm(residue), np.finfo(float).eps * max(r2, 1.0) isstable = np.abs(z) > tol if isstable: center_new = center + (e / z) * residue r2new = r2 + (e * e) / (2 * z) bound.projector.push(residue / np.linalg.norm(residue)) bound.centers = np.append(bound.centers, np.array([center_new]), axis=0) bound.square_radii = np.append(bound.square_radii, r2new) return isstable def pop(bound): n = len(bound.centers) bound.centers = bound.centers[:-1] bound.square_radii = bound.square_radii[:-1] if n >= 2: bound.projector.pop() return bound class NSphere: def __init__(self, c, sqr): self.center = np.array(c) self.sqradius = sqr def isinside(pt, nsphere, atol=1e-6, rtol=0.0): r2, R2 = sqdist(pt, nsphere.center), nsphere.sqradius return r2 <= R2 or np.isclose(r2, R2, atol=atol**2,rtol=rtol**2) def allinside(pts, nsphere, atol=1e-6, rtol=0.0): for p in pts: if not isinside(p, nsphere, atol, rtol): return False return True def move_to_front(pts, i): pt = pts[i] for j in range(len(pts)): pts[j], pt = pt, np.array(pts[j]) if j == i: break return pts def dist(p1, p2): return np.linalg.norm(p1 - p2) def sqdist(p1, p2): return sqnorm(p1 - p2) def sqnorm(p): return np.sum(np.array([x * x for x in p])) def ismaxlength(bound): len(bound.centers) == len(bound.empty_center) + 1 def makeNSphere(bound): if len(bound.centers) == 0: return NSphere(bound.empty_center, 0.0) return NSphere(bound.centers[-1], bound.square_radii[-1]) def _welzl(pts, pos, bdry): support_count, nsphere = 0, makeNSphere(bdry) if ismaxlength(bdry): return nsphere, 0 for i in range(pos): if not isinside(pts[i], nsphere): isstable = push_if_stable(bdry, pts[i]) if isstable: nsphere, s = _welzl(pts, i, bdry) pop(bdry) move_to_front(pts, i) support_count = s + 1 return nsphere, support_count def find_max_excess(nsphere, pts, k1): err_max, k_max = -np.Inf, k1 - 1 for (k, pt) in enumerate(pts[k_max:]): err = sqdist(pt, nsphere.center) - nsphere.sqradius if err > err_max: err_max, k_max = err, k + k1 return err_max, k_max - 1 def welzl(points, maxiterations=2000): pts, eps = np.array(points, copy=True), np.finfo(float).eps bdry, t = GaertnerBoundary(pts), 1 nsphere, s = _welzl(pts, t, bdry) for i in range(maxiterations): e, k = find_max_excess(nsphere, pts, t + 1) if e <= eps: break pt = pts[k] push_if_stable(bdry, pt) nsphere_new, s_new = _welzl(pts, s, bdry) pop(bdry) move_to_front(pts, k) nsphere = nsphere_new t, s = s + 1, s_new + 1 return nsphere if __name__ == '__main__': TESTDATA =[ np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0]]), np.array([[5.0, -2.0], [-3.0, -2.0], [-2.0, 5.0], [1.0, 6.0], [0.0, 2.0]]), np.array([[2.0, 4.0, -1.0], [1.0, 5.0, -3.0], [8.0, -4.0, 1.0], [3.0, 9.0, -5.0]]), np.random.normal(size=(8, 5)) ] for test in TESTDATA: nsphere = welzl(test) print("For points: ", test) print(" Center is at: ", nsphere.center) print(" Radius is: ", np.sqrt(nsphere.sqradius), "\n")
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-b.y)*(a.y-b.y) } func getCircleCenter(bx, by, cx, cy float64) Point { b := bx*bx + by*by c := cx*cx + cy*cy d := bx*cy - by*cx return Point{(cy*b - by*c) / (2 * d), (bx*c - cx*b) / (2 * d)} } func (ci Circle) contains(p Point) bool { return distSq(ci.c, p) <= ci.r*ci.r } func (ci Circle) encloses(ps []Point) bool { for _, p := range ps { if !ci.contains(p) { return false } } return true } func (ci Circle) String() string { return fmt.Sprintf("{%v, %f}", ci.c, ci.r) } func circleFrom3(a, b, c Point) Circle { i := getCircleCenter(b.x-a.x, b.y-a.y, c.x-a.x, c.y-a.y) i.x += a.x i.y += a.y return Circle{i, math.Sqrt(distSq(i, a))} } func circleFrom2(a, b Point) Circle { c := Point{(a.x + b.x) / 2, (a.y + b.y) / 2} return Circle{c, math.Sqrt(distSq(a, b)) / 2} } func secTrivial(rs []Point) Circle { size := len(rs) if size > 3 { log.Fatal("There shouldn't be more than 3 points.") } if size == 0 { return Circle{Point{0, 0}, 0} } if size == 1 { return Circle{rs[0], 0} } if size == 2 { return circleFrom2(rs[0], rs[1]) } for i := 0; i < 2; i++ { for j := i + 1; j < 3; j++ { c := circleFrom2(rs[i], rs[j]) if c.encloses(rs) { return c } } } return circleFrom3(rs[0], rs[1], rs[2]) } func welzlHelper(ps, rs []Point, n int) Circle { rc := make([]Point, len(rs)) copy(rc, rs) if n == 0 || len(rc) == 3 { return secTrivial(rc) } idx := rand.Intn(n) p := ps[idx] ps[idx], ps[n-1] = ps[n-1], p d := welzlHelper(ps, rc, n-1) if d.contains(p) { return d } rc = append(rc, p) return welzlHelper(ps, rc, n-1) } func welzl(ps []Point) Circle { var pc = make([]Point, len(ps)) copy(pc, ps) rand.Shuffle(len(pc), func(i, j int) { pc[i], pc[j] = pc[j], pc[i] }) return welzlHelper(pc, []Point{}, len(pc)) } func main() { rand.Seed(time.Now().UnixNano()) tests := [][]Point{ {Point{0, 0}, Point{0, 1}, Point{1, 0}}, {Point{5, -2}, Point{-3, -2}, Point{-2, 5}, Point{1, 6}, Point{0, 2}}, } for _, test := range tests { fmt.Println(welzl(test)) } }
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]+))?}", ), ( "ORD_RANGE", r"\{(?P<ord_start>[^0-9])..(?P<ord_stop>[^0-9])(?:(?:..)?(?P<ord_step>-?[0-9]+))?}", ), ( "LITERAL", r".+?(?=\{|$)", ), ] RE_EXPRESSION = re.compile( "|".join(rf"(?P<{name}>{pattern})" for name, pattern in RE_SPEC) ) class Expression(ABC): @abstractmethod def expand(self, prefix: str) -> Iterable[str]: pass class Literal(Expression): def __init__(self, value: str): self.value = value def expand(self, prefix: str) -> Iterable[str]: return [f"{prefix}{self.value}"] class IntRange(Expression): def __init__( self, start: int, stop: int, step: Optional[int] = None, zfill: int = 0 ): self.start, self.stop, self.step = fix_range(start, stop, step) self.zfill = zfill def expand(self, prefix: str) -> Iterable[str]: return ( f"{prefix}{str(i).zfill(self.zfill)}" for i in range(self.start, self.stop, self.step) ) class OrdRange(Expression): def __init__(self, start: str, stop: str, step: Optional[int] = None): self.start, self.stop, self.step = fix_range(ord(start), ord(stop), step) def expand(self, prefix: str) -> Iterable[str]: return (f"{prefix}{chr(i)}" for i in range(self.start, self.stop, self.step)) def expand(expressions: Iterable[Expression]) -> Iterable[str]: expanded = [""] for expression in expressions: expanded = itertools.chain.from_iterable( [expression.expand(prefix) for prefix in expanded] ) return expanded def zero_fill(start, stop) -> int: def _zfill(s): if len(s) <= 1 or not s.startswith("0"): return 0 return len(s) return max(_zfill(start), _zfill(stop)) def fix_range(start, stop, step): if not step: if start <= stop: step = 1 else: step = -1 elif step < 0: start, stop = stop, start if start < stop: step = abs(step) else: start -= 1 stop -= 1 elif start > stop: step = -step if (start - stop) % step == 0: stop += step return start, stop, step def parse(expression: str) -> Iterable[Expression]: for match in RE_EXPRESSION.finditer(expression): kind = match.lastgroup if kind == "INT_RANGE": start = match.group("int_start") stop = match.group("int_stop") step = match.group("int_step") zfill = zero_fill(start, stop) if step is not None: step = int(step) yield IntRange(int(start), int(stop), step, zfill=zfill) elif kind == "ORD_RANGE": start = match.group("ord_start") stop = match.group("ord_stop") step = match.group("ord_step") if step is not None: step = int(step) yield OrdRange(start, stop, step) elif kind == "LITERAL": yield Literal(match.group()) def examples(): cases = [ r"simpleNumberRising{1..3}.txt", r"simpleAlphaDescending-{Z..X}.txt", r"steppedDownAndPadded-{10..00..5}.txt", r"minusSignFlipsSequence {030..20..-5}.txt", r"reverseSteppedNumberRising{1..6..-2}.txt", r"combined-{Q..P}{2..1}.txt", r"emoji{🌵..🌶}{🌽..🌾}etc", r"li{teral", r"rangeless{}empty", r"rangeless{random}string", r"steppedNumberRising{1..6..2}.txt", r"steppedNumberDescending{20..9..2}.txt", r"steppedAlphaDescending-{Z..M..2}.txt", r"reverseSteppedAlphaRising{A..F..-2}.txt", r"reversedSteppedAlphaDescending-{Z..M..-2}.txt", ] for case in cases: print(f"{case} ->") expressions = parse(case) for itm in expand(expressions): print(f"{' '*4}{itm}") print("") if __name__ == "__main__": examples()
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 { if r == "" { return []string{"{}"} } sp := strings.Split(r, "..") if len(sp) == 1 { return []string{"{" + r + "}"} } sta := sp[0] end := sp[1] inc := "1" if len(sp) > 2 { inc = sp[2] } n1, ok1 := strconv.Atoi(sta) n2, ok2 := strconv.Atoi(end) n3, ok3 := strconv.Atoi(inc) if ok3 != nil { return []string{"{" + r + "}"} } numeric := (ok1 == nil) && (ok2 == nil) if !numeric { if (ok1 == nil && ok2 != nil) || (ok1 != nil && ok2 == nil) { return []string{"{" + r + "}"} } if utf8.RuneCountInString(sta) != 1 || utf8.RuneCountInString(end) != 1 { return []string{"{" + r + "}"} } n1 = int(([]rune(sta))[0]) n2 = int(([]rune(end))[0]) } width := 1 if numeric { if len(sta) < len(end) { width = len(end) } else { width = len(sta) } } if n3 == 0 { if numeric { return []string{fmt.Sprintf("%0*d", width, n1)} } else { return []string{sta} } } var res []string asc := n1 < n2 if n3 < 0 { asc = !asc t := n1 d := abs(n1-n2) % (-n3) n1 = n2 - d*sign(n2-n1) n2 = t n3 = -n3 } i := n1 if asc { for ; i <= n2; i += n3 { if numeric { res = append(res, fmt.Sprintf("%0*d", width, i)) } else { res = append(res, string(rune(i))) } } } else { for ; i >= n2; i -= n3 { if numeric { res = append(res, fmt.Sprintf("%0*d", width, i)) } else { res = append(res, string(rune(i))) } } } return res } func rangeExpand(s string) []string { res := []string{""} rng := "" inRng := false for _, c := range s { if c == '{' && !inRng { inRng = true rng = "" } else if c == '}' && inRng { rngRes := parseRange(rng) rngLen := len(rngRes) var res2 []string for i := 0; i < len(res); i++ { for j := 0; j < rngLen; j++ { res2 = append(res2, res[i]+rngRes[j]) } } res = res2 inRng = false } else if inRng { rng += string(c) } else { for i := 0; i < len(res); i++ { res[i] += string(c) } } } if inRng { for i := 0; i < len(res); i++ { res[i] += "{" + rng } } return res } func main() { examples := []string{ "simpleNumberRising{1..3}.txt", "simpleAlphaDescending-{Z..X}.txt", "steppedDownAndPadded-{10..00..5}.txt", "minusSignFlipsSequence {030..20..-5}.txt", "reverseSteppedNumberRising{1..6..-2}.txt", "combined-{Q..P}{2..1}.txt", "emoji{🌵..🌶}{🌽..🌾}etc", "li{teral", "rangeless{}empty", "rangeless{random}string", "mixedNumberAlpha{5..k}", "steppedAlphaRising{P..Z..2}.txt", "stops after endpoint-{02..10..3}.txt", "steppedNumberRising{1..6..2}.txt", "steppedNumberDescending{20..9..2}", "steppedAlphaDescending-{Z..M..2}.txt", "reversedSteppedAlphaDescending-{Z..M..-2}.txt", } for _, s := range examples { fmt.Print(s, "->\n ") res := rangeExpand(s) fmt.Println(strings.Join(res, "\n ")) fmt.Println() } }
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*pixels_per_inch) screen.setup (width=pix_width, height=pix_height, startx=0, starty=0) screen.screensize(pix_width,pix_height) left_edge = -screen.window_width()//2 right_edge = screen.window_width()//2 bottom_edge = -screen.window_height()//2 top_edge = screen.window_height()//2 screen.delay(0) screen.tracer(5) for inch in range(int(inch_width)-1): line_width = inch + 1 pensize(line_width) colornum = 0 min_x = left_edge + (inch * pixels_per_inch) max_x = left_edge + ((inch+1) * pixels_per_inch) for y in range(bottom_edge,top_edge,line_width): penup() pencolor(colors[colornum]) colornum = (colornum + 1) % len(colors) setposition(min_x,y) pendown() setposition(max_x,y) screen.getcanvas().postscript(file="striped.eps") im = Image.open("striped.eps") im.save("striped.jpg") subprocess.run(["mspaint", "/pt", "striped.jpg"])
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 for b := 1; b <= 11; b++ { for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 { dc.SetHexColor(palette[ci%8]) y := h * (b - 1) dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h)) dc.Fill() } } } func main() { dc := gg.NewContext(842, 595) pinstripe(dc) fileName := "color_pinstripe.png" dc.SavePNG(fileName) var cmd *exec.Cmd if runtime.GOOS == "windows" { cmd = exec.Command("mspaint", "/pt", fileName) } else { cmd = exec.Command("lp", fileName) } if err := cmd.Run(); err != nil { log.Fatal(err) } }
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): print((pars[i] + pars[i + 1]).ljust(54), "==>", haspunctotype(pars[i + 1]))
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") } else if c == '.' { types = append(types, "S") } } if strings.IndexByte("?!.", s[len(s)-1]) == -1 { types = append(types, "N") } return strings.Join(types, "|") } func main() { s := "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" fmt.Println(sentenceType(s)) }
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 gallium germanium arsenic selenium bromine " "krypton rubidium strontium yttrium zirconium niobium molybdenum " "technetium ruthenium rhodium palladium silver cadmium indium tin " "antimony tellurium iodine xenon cesium barium lanthanum cerium " "praseodymium neodymium promethium samarium europium gadolinium terbium " "dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum " "tungsten rhenium osmium iridium platinum gold mercury thallium lead " "bismuth polonium astatine radon francium radium actinium thorium " "protactinium uranium neptunium plutonium americium curium berkelium " "californium einsteinium fermium mendelevium nobelium lawrencium " "rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium " "roentgenium copernicium nihonium flerovium moscovium livermorium " "tennessine oganesson" ) def report(): items = elements.split() print(f"Last revision date: {revision}") print(f"Number of elements: {len(items)}") print(f"Last element  : {items[-1]}") if __name__ == "__main__": report()
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 potassium calcium scandium titanium vanadium chromium manganese iron cobalt nickel copper zinc gallium germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium niobium molybdenum technetium ruthenium rhodium palladium silver cadmium indium tin antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium neodymium promethium samarium europium gadolinium terbium dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum gold mercury thallium lead bismuth polonium astatine radon francium radium actinium thorium protactinium uranium neptunium plutonium americium curium berkelium californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium flerovium moscovium livermorium tennessine oganesson ` func main() { lastRevDate := "March 24th, 2020" re := regexp.MustCompile(`\s+`) els := re.Split(strings.TrimSpace(elements), -1) numEls := len(els) elements2 := strings.Join(els, " ") fmt.Println("Last revision Date: ", lastRevDate) fmt.Println("Number of elements: ", numEls) lix := strings.LastIndex(elements2, " ") fmt.Println("Last element  : ", elements2[lix+1:]) }
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(): b = int(b_str, 2) e = len(b_str) if first: first = False print(f"n = {n}; Width e = {e}:\n") result = set_right_adjacent_bits(n, b) print(f" Input b: {b:0{e}b}") print(f" Result: {result:0{e}b}\n") print("SAME Input & Width.\n") bits = '01' + '1'.join('0'*x for x in range(10, 0, -1)) for n in range(4): first = True for b_str in bits.split(): b = int(b_str, 2) e = len(b_str) if first: first = False print(f"n = {n}; Width e = {e}:\n") result = set_right_adjacent_bits(n, b) print(f" Input b: {b:0{e}b}") print(f" Result: {result:0{e}b}\n")
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 c == 1 { j := i + 1 for j <= i+n && j < e { bits2[j] = 1 j++ } } } return bits2 } func main() { b := "010000000000100000000010000000010000000100000010000010000100010010" tests := []test{ test{"1000", 2}, test{"0100", 2}, test{"0010", 2}, test{"0000", 2}, test{b, 0}, test{b, 1}, test{b, 2}, test{b, 3}, } for _, test := range tests { bs := test.bs e := len(bs) n := test.n fmt.Println("n =", n, "\b; Width e =", e, "\b:") fmt.Println(" Input b:", bs) bits := []byte(bs) for i := 0; i < len(bits); i++ { bits[i] = bits[i] - '0' } bits = setRightBits(bits, e, n) var sb strings.Builder for i := 0; i < len(bits); i++ { sb.WriteByte(bits[i] + '0') } fmt.Println(" Result :", sb.String()) } }
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 = " ") else: n += 1 if p + n**3 >= 15000: break
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] = true } for { p += 2 if !c[p] { break } } } return c } func isCube(n int) bool { s := int(math.Cbrt(float64(n))) return s*s*s == n } func commas(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(14999) fmt.Println("Cubic special primes under 15,000:") fmt.Println(" Prime1 Prime2 Gap Cbrt") lastCubicSpecial := 3 gap := 1 count := 1 fmt.Printf("%7d %7d %6d %4d\n", 2, 3, 1, 1) for i := 5; i < 15000; i += 2 { if c[i] { continue } gap = i - lastCubicSpecial if isCube(gap) { cbrt := int(math.Cbrt(float64(gap))) fmt.Printf("%7s %7s %6s %4d\n", commas(lastCubicSpecial), commas(i), commas(gap), cbrt) lastCubicSpecial = i count++ } } fmt.Println("\n", count+1, "such primes found.") }
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 = " ") else: n += 1 if p + n**3 >= 15000: break
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] = true } for { p += 2 if !c[p] { break } } } return c } func isCube(n int) bool { s := int(math.Cbrt(float64(n))) return s*s*s == n } func commas(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(14999) fmt.Println("Cubic special primes under 15,000:") fmt.Println(" Prime1 Prime2 Gap Cbrt") lastCubicSpecial := 3 gap := 1 count := 1 fmt.Printf("%7d %7d %6d %4d\n", 2, 3, 1, 1) for i := 5; i < 15000; i += 2 { if c[i] { continue } gap = i - lastCubicSpecial if isCube(gap) { cbrt := int(math.Cbrt(float64(gap))) fmt.Printf("%7s %7s %6s %4d\n", commas(lastCubicSpecial), commas(i), commas(gap), cbrt) lastCubicSpecial = i count++ } } fmt.Println("\n", count+1, "such primes found.") }
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 = " ") else: n += 1 if p + n**3 >= 15000: break
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] = true } for { p += 2 if !c[p] { break } } } return c } func isCube(n int) bool { s := int(math.Cbrt(float64(n))) return s*s*s == n } func commas(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(14999) fmt.Println("Cubic special primes under 15,000:") fmt.Println(" Prime1 Prime2 Gap Cbrt") lastCubicSpecial := 3 gap := 1 count := 1 fmt.Printf("%7d %7d %6d %4d\n", 2, 3, 1, 1) for i := 5; i < 15000; i += 2 { if c[i] { continue } gap = i - lastCubicSpecial if isCube(gap) { cbrt := int(math.Cbrt(float64(gap))) fmt.Printf("%7s %7s %6s %4d\n", commas(lastCubicSpecial), commas(i), commas(gap), cbrt) lastCubicSpecial = i count++ } } fmt.Println("\n", count+1, "such primes found.") }
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 = " ") else: n += 1 if p + n**3 >= 15000: break
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] = true } for { p += 2 if !c[p] { break } } } return c } func isCube(n int) bool { s := int(math.Cbrt(float64(n))) return s*s*s == n } func commas(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(14999) fmt.Println("Cubic special primes under 15,000:") fmt.Println(" Prime1 Prime2 Gap Cbrt") lastCubicSpecial := 3 gap := 1 count := 1 fmt.Printf("%7d %7d %6d %4d\n", 2, 3, 1, 1) for i := 5; i < 15000; i += 2 { if c[i] { continue } gap = i - lastCubicSpecial if isCube(gap) { cbrt := int(math.Cbrt(float64(gap))) fmt.Printf("%7s %7s %6s %4d\n", commas(lastCubicSpecial), commas(i), commas(gap), cbrt) lastCubicSpecial = i count++ } } fmt.Println("\n", count+1, "such primes found.") }
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: bits = bits << 1 | 1 mn = mid return mn, mx, bits def encoder(lat, lng, pre): latmin, latmax = -90, 90 lngmin, lngmax = -180, 180 bits = 0 for i in range(pre * 5): if i % 2: latmin, latmax, bits = bisect(lat, latmin, latmax, bits) else: lngmin, lngmax, bits = bisect(lng, lngmin, lngmax, bits) b = f"{bits:0{pre * 5}b}" geo = (bool2ch[b[i*5: (i+1)*5]] for i in range(pre)) return ''.join(geo) def decoder(geo): minmaxes, latlong = [[-90.0, 90.0], [-180.0, 180.0]], True for c in geo: for bit in ch2bool[c]: minmaxes[latlong][bit != '1'] = sum(minmaxes[latlong]) / 2 latlong = not latlong return minmaxes if __name__ == '__main__': for (lat, lng), pre in [([51.433718, -0.214126], 2), ([51.433718, -0.214126], 9), ([57.64911, 10.40744] , 11), ([57.64911, 10.40744] , 22)]: print("encoder(lat=%f, lng=%f, pre=%i) = %r" % (lat, lng, pre, encoder(lat, lng, pre)))
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) string { latRange := Range{-90, 90} lngRange := Range{-180, 180} var hash strings.Builder hashVal := 0 bits := 0 even := true for hash.Len() < prec { val := loc.lat rng := latRange if even { val = loc.lng rng = lngRange } mid := (rng.lower + rng.upper) / 2 if val > mid { hashVal = (hashVal << 1) + 1 rng = Range{mid, rng.upper} if even { lngRange = Range{mid, lngRange.upper} } else { latRange = Range{mid, latRange.upper} } } else { hashVal <<= 1 if even { lngRange = Range{lngRange.lower, mid} } else { latRange = Range{latRange.lower, mid} } } even = !even if bits < 4 { bits++ } else { bits = 0 hash.WriteByte(gBase32[hashVal]) hashVal = 0 } } return hash.String() } func main() { locs := []Location{ {51.433718, -0.214126}, {51.433718, -0.214126}, {57.64911, 10.40744}, } precs := []int{2, 9, 11} for i, loc := range locs { geohash := encodeGeohash(loc, precs[i]) fmt.Printf("geohash for %v, precision %-2d = %s\n", loc, precs[i], geohash) } }
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: bits = bits << 1 | 1 mn = mid return mn, mx, bits def encoder(lat, lng, pre): latmin, latmax = -90, 90 lngmin, lngmax = -180, 180 bits = 0 for i in range(pre * 5): if i % 2: latmin, latmax, bits = bisect(lat, latmin, latmax, bits) else: lngmin, lngmax, bits = bisect(lng, lngmin, lngmax, bits) b = f"{bits:0{pre * 5}b}" geo = (bool2ch[b[i*5: (i+1)*5]] for i in range(pre)) return ''.join(geo) def decoder(geo): minmaxes, latlong = [[-90.0, 90.0], [-180.0, 180.0]], True for c in geo: for bit in ch2bool[c]: minmaxes[latlong][bit != '1'] = sum(minmaxes[latlong]) / 2 latlong = not latlong return minmaxes if __name__ == '__main__': for (lat, lng), pre in [([51.433718, -0.214126], 2), ([51.433718, -0.214126], 9), ([57.64911, 10.40744] , 11), ([57.64911, 10.40744] , 22)]: print("encoder(lat=%f, lng=%f, pre=%i) = %r" % (lat, lng, pre, encoder(lat, lng, pre)))
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) string { latRange := Range{-90, 90} lngRange := Range{-180, 180} var hash strings.Builder hashVal := 0 bits := 0 even := true for hash.Len() < prec { val := loc.lat rng := latRange if even { val = loc.lng rng = lngRange } mid := (rng.lower + rng.upper) / 2 if val > mid { hashVal = (hashVal << 1) + 1 rng = Range{mid, rng.upper} if even { lngRange = Range{mid, lngRange.upper} } else { latRange = Range{mid, latRange.upper} } } else { hashVal <<= 1 if even { lngRange = Range{lngRange.lower, mid} } else { latRange = Range{latRange.lower, mid} } } even = !even if bits < 4 { bits++ } else { bits = 0 hash.WriteByte(gBase32[hashVal]) hashVal = 0 } } return hash.String() } func main() { locs := []Location{ {51.433718, -0.214126}, {51.433718, -0.214126}, {57.64911, 10.40744}, } precs := []int{2, 9, 11} for i, loc := range locs { geohash := encodeGeohash(loc, precs[i]) fmt.Printf("geohash for %v, precision %-2d = %s\n", loc, precs[i], geohash) } }
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 splitchar(c): ' De-ligature. De-accent a char' de = decomposition(c) if de: de = [d for d in de.split() if all(c.lower() in hexdigits for c in d)] n = name(c, c).upper() if len(de)> 1 and 'PRECEDE' in n: de[1], de[0] = de[0], de[1] tmp = [ unichr(int(k, 16)) for k in de] base, others = tmp[0], tmp[1:] if 'LIGATURE' in n: base += others.pop(0) else: base = c return base def sortkeygen(s): s = unicode(s).strip() s = ' '.join(s.split()) s = s.lower() words = s.split() if len(words) > 1 and words[0] in commonleaders: s = ' '.join( words[1:]) s = ''.join(splitchar(c) for c in s) s = ''.join( replacements.get(ch, ch) for ch in s ) s = [ int("".join(g)) if isinteger else "".join(g) for isinteger,g in groupby(s, lambda x: x in decdigits)] return s def naturalsort(items): return sorted(items, key=sortkeygen) if __name__ == '__main__': import string ns = naturalsort print '\n txt = ['%signore leading spaces: 2%+i' % (' '*i, i-2) for i in range(4)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['ignore m.a.s%s spaces: 2%+i' % (' '*i, i-2) for i in range(4)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['Equiv.%sspaces: 3%+i' % (ch, i-3) for i,ch in enumerate(reversed(string.whitespace))] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n s = 'CASE INDEPENENT' txt = [s[:i].lower() + s[i:] + ': 3%+i' % (i-3) for i in range(1,5)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['The Wind in the Willows','The 40th step more', 'The 39 steps', 'Wanda'] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['Equiv. %s accents: 2%+i' % (ch, i-2) for i,ch in enumerate(u'\xfd\xddyY')] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = [u'\462 ligatured ij', 'no ligature',] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n s = u'ʒſßs' txt = ['Start with an %s: 2%+i' % (ch, i-2) for i,ch in enumerate(s)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; print '\n'.join(sorted(txt)) print 'Naturally sorted:'; print '\n'.join(ns(txt))
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", " ignore leading spaces: 2+1", }}, {"Ignoring multiple adjacent spaces", []string{ "ignore m.a.s spaces: 2-2", "ignore m.a.s spaces: 2-1", "ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1", }}, {"Equivalent whitespace characters", []string{ "Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\fspaces: 3-1", "Equiv.\bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2", }}, {"Case Indepenent sort", []string{ "cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1", }}, {"Numeric fields as numerics", []string{ "foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt", }}, } func main() { for _, test := range tests { fmt.Println(test.descr) fmt.Println("Input order:") for _, s := range test.list { fmt.Printf(" %q\n", s) } fmt.Println("Natural order:") l := make(list, len(test.list)) for i, s := range test.list { l[i] = newNatStr(s) } sort.Sort(l) for _, s := range l { fmt.Printf(" %q\n", s.s) } fmt.Println() } } type natStr struct { s string t []tok } func newNatStr(s string) (t natStr) { t.s = s s = strings.ToLower(strings.Join(strings.Fields(s), " ")) x := dx.FindAllString(s, -1) t.t = make([]tok, len(x)) for i, s := range x { if n, err := strconv.Atoi(s); err == nil { t.t[i].n = n } else { t.t[i].s = s } } return t } var dx = regexp.MustCompile(`\d+|\D+`) type tok struct { s string n int } func (f1 tok) Cmp(f2 tok) int { switch { case f1.s == "": switch { case f2.s > "" || f1.n < f2.n: return -1 case f1.n > f2.n: return 1 } case f2.s == "" || f1.s > f2.s: return 1 case f1.s < f2.s: return -1 } return 0 } type list []natStr func (l list) Len() int { return len(l) } func (l list) Swap(i, j int) { l[i], l[j] = l[j], l[i] } func (l list) Less(i, j int) bool { ti := l[i].t for k, t := range l[j].t { if k == len(ti) { return true } switch ti[k].Cmp(t) { case -1: return true case 1: return false } } return false }
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 splitchar(c): ' De-ligature. De-accent a char' de = decomposition(c) if de: de = [d for d in de.split() if all(c.lower() in hexdigits for c in d)] n = name(c, c).upper() if len(de)> 1 and 'PRECEDE' in n: de[1], de[0] = de[0], de[1] tmp = [ unichr(int(k, 16)) for k in de] base, others = tmp[0], tmp[1:] if 'LIGATURE' in n: base += others.pop(0) else: base = c return base def sortkeygen(s): s = unicode(s).strip() s = ' '.join(s.split()) s = s.lower() words = s.split() if len(words) > 1 and words[0] in commonleaders: s = ' '.join( words[1:]) s = ''.join(splitchar(c) for c in s) s = ''.join( replacements.get(ch, ch) for ch in s ) s = [ int("".join(g)) if isinteger else "".join(g) for isinteger,g in groupby(s, lambda x: x in decdigits)] return s def naturalsort(items): return sorted(items, key=sortkeygen) if __name__ == '__main__': import string ns = naturalsort print '\n txt = ['%signore leading spaces: 2%+i' % (' '*i, i-2) for i in range(4)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['ignore m.a.s%s spaces: 2%+i' % (' '*i, i-2) for i in range(4)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['Equiv.%sspaces: 3%+i' % (ch, i-3) for i,ch in enumerate(reversed(string.whitespace))] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n s = 'CASE INDEPENENT' txt = [s[:i].lower() + s[i:] + ': 3%+i' % (i-3) for i in range(1,5)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['The Wind in the Willows','The 40th step more', 'The 39 steps', 'Wanda'] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = ['Equiv. %s accents: 2%+i' % (ch, i-2) for i,ch in enumerate(u'\xfd\xddyY')] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n txt = [u'\462 ligatured ij', 'no ligature',] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n s = u'ʒſßs' txt = ['Start with an %s: 2%+i' % (ch, i-2) for i,ch in enumerate(s)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; print '\n'.join(sorted(txt)) print 'Naturally sorted:'; print '\n'.join(ns(txt))
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", " ignore leading spaces: 2+1", }}, {"Ignoring multiple adjacent spaces", []string{ "ignore m.a.s spaces: 2-2", "ignore m.a.s spaces: 2-1", "ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1", }}, {"Equivalent whitespace characters", []string{ "Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\fspaces: 3-1", "Equiv.\bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2", }}, {"Case Indepenent sort", []string{ "cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1", }}, {"Numeric fields as numerics", []string{ "foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt", }}, } func main() { for _, test := range tests { fmt.Println(test.descr) fmt.Println("Input order:") for _, s := range test.list { fmt.Printf(" %q\n", s) } fmt.Println("Natural order:") l := make(list, len(test.list)) for i, s := range test.list { l[i] = newNatStr(s) } sort.Sort(l) for _, s := range l { fmt.Printf(" %q\n", s.s) } fmt.Println() } } type natStr struct { s string t []tok } func newNatStr(s string) (t natStr) { t.s = s s = strings.ToLower(strings.Join(strings.Fields(s), " ")) x := dx.FindAllString(s, -1) t.t = make([]tok, len(x)) for i, s := range x { if n, err := strconv.Atoi(s); err == nil { t.t[i].n = n } else { t.t[i].s = s } } return t } var dx = regexp.MustCompile(`\d+|\D+`) type tok struct { s string n int } func (f1 tok) Cmp(f2 tok) int { switch { case f1.s == "": switch { case f2.s > "" || f1.n < f2.n: return -1 case f1.n > f2.n: return 1 } case f2.s == "" || f1.s > f2.s: return 1 case f1.s < f2.s: return -1 } return 0 } type list []natStr func (l list) Len() int { return len(l) } func (l list) Swap(i, j int) { l[i], l[j] = l[j], l[i] } func (l list) Less(i, j int) bool { ti := l[i].t for k, t := range l[j].t { if k == len(ti) { return true } switch ti[k].Cmp(t) { case -1: return true case 1: return false } } return false }
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 { count++ } } if count == 2 { results = append(results, i) } } for i, n := range results { fmt.Printf("%5d", n) if (i+1)%7 == 0 { fmt.Println() } } fmt.Println("\n\nFound", len(results), "such numbers.") }
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 { count++ } } if count == 2 { results = append(results, i) } } for i, n := range results { fmt.Printf("%5d", n) if (i+1)%7 == 0 { fmt.Println() } } fmt.Println("\n\nFound", len(results), "such numbers.") }
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 <= high; i += 2 { oddSq = append(oddSq, i*i) } fmt.Println(len(oddSq), "odd squares from", pow/10, "to", pow, "\b:") for i := 0; i < len(oddSq); i++ { fmt.Printf("%d ", oddSq[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\n") } }
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 <= high; i += 2 { oddSq = append(oddSq, i*i) } fmt.Println(len(oddSq), "odd squares from", pow/10, "to", pow, "\b:") for i := 0; i < len(oddSq); i++ { fmt.Printf("%d ", oddSq[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\n") } }
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) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
#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 = 0u; i < dimx; ++i) ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256); ofs.close(); return EXIT_SUCCESS; }
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) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
#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 = 0u; i < dimx; ++i) ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256); ofs.close(); return EXIT_SUCCESS; }
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 Long, bits As Long For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 bits = bits Or x x = 2 ^ (Int(n * Rnd())) Loop Next i test = count / ITER End Function Public Sub main() Dim n As Long Debug.Print " n avg. exp. (error%)" Debug.Print "== ====== ====== ========" For n = 1 To MAX av = test(n) ex = expected(n) Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " "; Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")" Next n End Sub
#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<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
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 Long, bits As Long For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 bits = bits Or x x = 2 ^ (Int(n * Rnd())) Loop Next i test = count / ITER End Function Public Sub main() Dim n As Long Debug.Print " n avg. exp. (error%)" Debug.Print "== ====== ====== ========" For n = 1 To MAX av = test(n) ex = expected(n) Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " "; Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")" Next n End Sub
#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<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
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: " << newString << " \n" ; return 0 ; }
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 - 1, j - 1) = a(i - 1, j - 1) ElseIf i >= x AndAlso j < y Then result(i - 1, j - 1) = a(i, j - 1) ElseIf i < x AndAlso j >= y Then result(i - 1, j - 1) = a(i - 1, j) Else result(i - 1, j - 1) = a(i, j) End If Next Next Return result End Function Function Det(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sign = 1 Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += sign * a(0, i - 1) * Det(Minor(a, 0, i)) sign *= -1 Next Return sum End If End Function Function Perm(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += a(0, i - 1) * Perm(Minor(a, 0, i)) Next Return sum End If End Function Sub WriteLine(a As Double(,)) For i = 1 To a.GetLength(0) Console.Write("[") For j = 1 To a.GetLength(1) If j > 1 Then Console.Write(", ") End If Console.Write(a(i - 1, j - 1)) Next Console.WriteLine("]") Next End Sub Sub Test(a As Double(,)) If a.GetLength(0) <> a.GetLength(1) Then Throw New ArgumentException("The dimensions must be equal") End If WriteLine(a) Console.WriteLine("Permanant  : {0}", Perm(a)) Console.WriteLine("Determinant: {0}", Det(a)) Console.WriteLine() End Sub Sub Main() Test({{1, 2}, {3, 4}}) Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}) Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}}) End Sub End Module
#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 << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
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 - 1, j - 1) = a(i - 1, j - 1) ElseIf i >= x AndAlso j < y Then result(i - 1, j - 1) = a(i, j - 1) ElseIf i < x AndAlso j >= y Then result(i - 1, j - 1) = a(i - 1, j) Else result(i - 1, j - 1) = a(i, j) End If Next Next Return result End Function Function Det(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sign = 1 Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += sign * a(0, i - 1) * Det(Minor(a, 0, i)) sign *= -1 Next Return sum End If End Function Function Perm(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += a(0, i - 1) * Perm(Minor(a, 0, i)) Next Return sum End If End Function Sub WriteLine(a As Double(,)) For i = 1 To a.GetLength(0) Console.Write("[") For j = 1 To a.GetLength(1) If j > 1 Then Console.Write(", ") End If Console.Write(a(i - 1, j - 1)) Next Console.WriteLine("]") Next End Sub Sub Test(a As Double(,)) If a.GetLength(0) <> a.GetLength(1) Then Throw New ArgumentException("The dimensions must be equal") End If WriteLine(a) Console.WriteLine("Permanant  : {0}", Perm(a)) Console.WriteLine("Determinant: {0}", Det(a)) Console.WriteLine() End Sub Sub Main() Test({{1, 2}, {3, 4}}) Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}) Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}}) End Sub End Module
#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 << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
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, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}} Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}} Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}} Private shapes As Integer()()() = {square, squareHole, strange, hexagon} Public Sub Main() Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}} For Each shape As Integer()() In shapes For Each point As Double() In testPoints Console.Write(String.Format("{0} ", Contains(shape, point).ToString.PadLeft(7))) Next Console.WriteLine() Next End Sub Private Function Contains(shape As Integer()(), point As Double()) As Boolean Dim inside As Boolean = False Dim length As Integer = shape.Length For i As Integer = 0 To length - 1 If Intersects(shape(i), shape((i + 1) Mod length), point) Then inside = Not inside End If Next Return inside End Function Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean If a(1) > b(1) Then Return Intersects(b, a, p) If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001 If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False If p(0) < Min(a(0), b(0)) Then Return True Dim red As Double = (p(1) - a(1)) / (p(0) - a(0)) Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0)) Return red >= blue End Function End Module
#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; }; struct Edge { const Point a, b; bool operator()(const Point& p) const { if (a.y > b.y) return Edge{ b, a }(p); if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon }); if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false; if (p.x < min(a.x, b.x)) return true; auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX; auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX; return blue >= red; } }; struct Figure { const string name; const initializer_list<Edge> edges; bool contains(const Point& p) const { auto c = 0; for (auto e : edges) if (e(p)) c++; return c % 2 != 0; } template<unsigned char W = 3> void check(const initializer_list<Point>& points, ostream& os) const { os << "Is point inside figure " << name << '?' << endl; for (auto p : points) os << " (" << setw(W) << p.x << ',' << setw(W) << p.y << "): " << boolalpha << contains(p) << endl; os << endl; } }; int main() { const initializer_list<Point> points = { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} }; const Figure square = { "Square", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} } }; const Figure square_hole = { "Square hole", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}}, {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}} } }; const Figure strange = { "Strange", { {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}}, {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}} } }; const Figure exagon = { "Exagon", { {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}}, {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}} } }; for(auto f : {square, square_hole, strange, exagon}) f.check(points, cout); return EXIT_SUCCESS; }
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, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}} Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}} Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}} Private shapes As Integer()()() = {square, squareHole, strange, hexagon} Public Sub Main() Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}} For Each shape As Integer()() In shapes For Each point As Double() In testPoints Console.Write(String.Format("{0} ", Contains(shape, point).ToString.PadLeft(7))) Next Console.WriteLine() Next End Sub Private Function Contains(shape As Integer()(), point As Double()) As Boolean Dim inside As Boolean = False Dim length As Integer = shape.Length For i As Integer = 0 To length - 1 If Intersects(shape(i), shape((i + 1) Mod length), point) Then inside = Not inside End If Next Return inside End Function Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean If a(1) > b(1) Then Return Intersects(b, a, p) If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001 If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False If p(0) < Min(a(0), b(0)) Then Return True Dim red As Double = (p(1) - a(1)) / (p(0) - a(0)) Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0)) Return red >= blue End Function End Module
#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; }; struct Edge { const Point a, b; bool operator()(const Point& p) const { if (a.y > b.y) return Edge{ b, a }(p); if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon }); if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false; if (p.x < min(a.x, b.x)) return true; auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX; auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX; return blue >= red; } }; struct Figure { const string name; const initializer_list<Edge> edges; bool contains(const Point& p) const { auto c = 0; for (auto e : edges) if (e(p)) c++; return c % 2 != 0; } template<unsigned char W = 3> void check(const initializer_list<Point>& points, ostream& os) const { os << "Is point inside figure " << name << '?' << endl; for (auto p : points) os << " (" << setw(W) << p.x << ',' << setw(W) << p.y << "): " << boolalpha << contains(p) << endl; os << endl; } }; int main() { const initializer_list<Point> points = { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} }; const Figure square = { "Square", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} } }; const Figure square_hole = { "Square hole", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}}, {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}} } }; const Figure strange = { "Strange", { {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}}, {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}} } }; const Figure exagon = { "Exagon", { {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}}, {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}} } }; for(auto f : {square, square_hole, strange, exagon}) f.check(points, cout); return EXIT_SUCCESS; }
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 CountSubstring("the three truths","th") & vbCrLf WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf
#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; } return count; } int main() { std::cout << countSubstring("the three truths", "th") << '\n'; std::cout << countSubstring("ababababab", "abab") << '\n'; std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n'; return 0; }
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) ElseIf lft > 0 Then For Each itm As Integer In lst res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul) Next End If Return res End Function Sub Main(ByVal args As String()) WriteLine(string.Join(" ", unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13))) End Sub End Module
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
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) ElseIf lft > 0 Then For Each itm As Integer In lst res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul) Next End If Return res End Function Sub Main(ByVal args As String()) WriteLine(string.Join(" ", unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13))) End Sub End Module
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
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 New StreamWriter("NOTES.TXT", True) sw.WriteLine(Date.Now.ToString()) sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs)) End Using End If Catch End Try End Function End Module
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
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 New StreamWriter("NOTES.TXT", True) sw.WriteLine(Date.Now.ToString()) sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs)) End Using End If Catch End Try End Function End Module
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
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 To UBound(Path) If i Then If InStr(k, Path(i), PATH_SEPARATOR) <> j Then Exit Do ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then Exit Do End If Else j = InStr(k, Path(i), PATH_SEPARATOR) If j = 0 Then Exit Do End If End If Next i s = Left$(Path(0), j + CLng(k <> 1)) k = j + 1 Loop CommonDirectoryPath = s End Function Sub Main() Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/home/user1/tmp" Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members", _ "/home/user1/abc/coven/members") = _ "/home/user1" Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/hope/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/" End Sub
#include <algorithm> #include <iostream> #include <string> #include <vector> std::string longestPath( const std::vector<std::string> & , char ) ; int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std::vector<std::string> myDirs ( dirs , dirs + 3 ) ; std::cout << "The longest common path of the given directories is " << longestPath( myDirs , '/' ) << "!\n" ; return 0 ; } std::string longestPath( const std::vector<std::string> & dirs , char separator ) { std::vector<std::string>::const_iterator vsi = dirs.begin( ) ; int maxCharactersCommon = vsi->length( ) ; std::string compareString = *vsi ; for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) { std::pair<std::string::const_iterator , std::string::const_iterator> p = std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ; if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) maxCharactersCommon = p.first - compareString.begin( ) ; } std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ; return compareString.substr( 0 , found ) ; }
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 maxdiff = 0 wscript.echo "Expected average count is " & Int(samples/n) & " across " & n & " buckets." for each i in d.Keys dim diff : diff = abs(1 - d(i) / (samples/n)) if diff > maxdiff then maxdiff = diff wscript.echo "Bucket " & i & " had " & d(i) & " occurences" _ & vbTab & " difference from expected=" & FormatPercent(diff, 2) next wscript.echo "Maximum found variation is " & FormatPercent(maxdiff, 2) _ & ", desired limit is " & FormatPercent(delta, 2) & "." if maxdiff > delta then wscript.echo "Skewed!" else wscript.echo "Smooth!" end sub
#include <map> #include <iostream> #include <cmath> template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist; for (int i = 0; i < calls; ++i) ++dist[f()]; double mean = 1.0/dist.size(); bool good = true; for (distmap::iterator i = dist.begin(); i != dist.end(); ++i) { if (std::abs((1.0 * i->second)/calls - mean) > delta) { std::cout << "Relative frequency " << i->second/(1.0*calls) << " of result " << i->first << " deviates by more than " << delta << " from the expected value " << mean << "\n"; good = false; } } return good; }
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 Function Impl(n As Integer, k As Integer) As BigInteger If n = 0 AndAlso k = 0 Then Return 1 End If If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then Return 0 End If If n = k Then Return 1 End If If k > n Then Return 0 End If Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1) End Function Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger Dim key = CacheKey(n, k) If COMPUTED.ContainsKey(key) Then Return COMPUTED(key) End If Dim result = Impl(n, k) COMPUTED.Add(key, result) Return result End Function End Class Sub Main() Console.WriteLine("Stirling numbers of the second kind:") Dim max = 12 Console.Write("n/k") For n = 0 To max Console.Write("{0,10}", n) Next Console.WriteLine() For n = 0 To max Console.Write("{0,3}", n) For k = 0 To n Console.Write("{0,10}", Sterling.Sterling2(n, k)) Next Console.WriteLine() Next Console.WriteLine("The maximum value of S2(100, k) = ") Dim previous = BigInteger.Zero For k = 1 To 100 Dim current = Sterling.Sterling2(100, k) If current > previous Then previous = current Else Console.WriteLine(previous) Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1) Exit For End If Next End Sub End Module
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
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 Function Impl(n As Integer, k As Integer) As BigInteger If n = 0 AndAlso k = 0 Then Return 1 End If If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then Return 0 End If If n = k Then Return 1 End If If k > n Then Return 0 End If Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1) End Function Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger Dim key = CacheKey(n, k) If COMPUTED.ContainsKey(key) Then Return COMPUTED(key) End If Dim result = Impl(n, k) COMPUTED.Add(key, result) Return result End Function End Class Sub Main() Console.WriteLine("Stirling numbers of the second kind:") Dim max = 12 Console.Write("n/k") For n = 0 To max Console.Write("{0,10}", n) Next Console.WriteLine() For n = 0 To max Console.Write("{0,3}", n) For k = 0 To n Console.Write("{0,10}", Sterling.Sterling2(n, k)) Next Console.WriteLine() Next Console.WriteLine("The maximum value of S2(100, k) = ") Dim previous = BigInteger.Zero For k = 1 To 100 Dim current = Sterling.Sterling2(100, k) If current > previous Then previous = current Else Console.WriteLine(previous) Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1) Exit For End If Next End Sub End Module
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
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 Function Impl(n As Integer, k As Integer) As BigInteger If n = 0 AndAlso k = 0 Then Return 1 End If If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then Return 0 End If If n = k Then Return 1 End If If k > n Then Return 0 End If Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1) End Function Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger Dim key = CacheKey(n, k) If COMPUTED.ContainsKey(key) Then Return COMPUTED(key) End If Dim result = Impl(n, k) COMPUTED.Add(key, result) Return result End Function End Class Sub Main() Console.WriteLine("Stirling numbers of the second kind:") Dim max = 12 Console.Write("n/k") For n = 0 To max Console.Write("{0,10}", n) Next Console.WriteLine() For n = 0 To max Console.Write("{0,3}", n) For k = 0 To n Console.Write("{0,10}", Sterling.Sterling2(n, k)) Next Console.WriteLine() Next Console.WriteLine("The maximum value of S2(100, k) = ") Dim previous = BigInteger.Zero For k = 1 To 100 Dim current = Sterling.Sterling2(100, k) If current > previous Then previous = current Else Console.WriteLine(previous) Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1) Exit For End If Next End Sub End Module
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
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 Function Impl(n As Integer, k As Integer) As BigInteger If n = 0 AndAlso k = 0 Then Return 1 End If If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then Return 0 End If If n = k Then Return 1 End If If k > n Then Return 0 End If Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1) End Function Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger Dim key = CacheKey(n, k) If COMPUTED.ContainsKey(key) Then Return COMPUTED(key) End If Dim result = Impl(n, k) COMPUTED.Add(key, result) Return result End Function End Class Sub Main() Console.WriteLine("Stirling numbers of the second kind:") Dim max = 12 Console.Write("n/k") For n = 0 To max Console.Write("{0,10}", n) Next Console.WriteLine() For n = 0 To max Console.Write("{0,3}", n) For k = 0 To n Console.Write("{0,10}", Sterling.Sterling2(n, k)) Next Console.WriteLine() Next Console.WriteLine("The maximum value of S2(100, k) = ") Dim previous = BigInteger.Zero For k = 1 To 100 Dim current = Sterling.Sterling2(100, k) If current > previous Then previous = current Else Console.WriteLine(previous) Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1) Exit For End If Next End Sub End Module
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
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&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
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&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
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 HumanPlay GameWin = IsWinner("X") Else Call ComputerPlay GameWin = IsWinner("O") End If If Not GameWin Then GameOver = IsEnd Loop Until GameWin Or GameOver If Not GameOver Then Debug.Print p & " Win !" Else Debug.Print "Game Over!" End If End Sub Sub InitLines(Optional S As String) Dim i As Byte, j As Byte Nb = 0: player = 0 For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) Lines(i, j) = "#" Next j Next i End Sub Sub printLines(Nb As Byte) Dim i As Byte, j As Byte, strT As String Debug.Print "Loop " & Nb For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) strT = strT & Lines(i, j) Next j Debug.Print strT strT = vbNullString Next i End Sub Function WhoPlay(Optional S As String) As String If player = 0 Then player = 1 WhoPlay = "Human" Else player = 0 WhoPlay = "Computer" End If End Function Sub HumanPlay(Optional S As String) Dim L As Byte, C As Byte, GoodPlay As Boolean Do L = Application.InputBox("Choose the row", "Numeric only", Type:=1) If L > 0 And L < 4 Then C = Application.InputBox("Choose the column", "Numeric only", Type:=1) If C > 0 And C < 4 Then If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then Lines(L, C) = "X" Nb = Nb + 1 printLines Nb GoodPlay = True End If End If End If Loop Until GoodPlay End Sub Sub ComputerPlay(Optional S As String) Dim L As Byte, C As Byte, GoodPlay As Boolean Randomize Timer Do L = Int((Rnd * 3) + 1) C = Int((Rnd * 3) + 1) If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then Lines(L, C) = "O" Nb = Nb + 1 printLines Nb GoodPlay = True End If Loop Until GoodPlay End Sub Function IsWinner(S As String) As Boolean Dim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String Ch = String(UBound(Lines, 1), S) For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) strTL = strTL & Lines(i, j) strTC = strTC & Lines(j, i) Next j If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For strTL = vbNullString: strTC = vbNullString Next i strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3) strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1) If strTL = Ch Or strTC = Ch Then IsWinner = True End Function Function IsEnd() As Boolean Dim i As Byte, j As Byte For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) If Lines(i, j) = "#" Then Exit Function Next j Next i IsEnd = True End Function
#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(); } void play() { int res = Draw; while( true ) { drawGrid(); while( true ) { if( _p ) getHumanMove(); else getComputerMove(); drawGrid(); res = checkVictory(); if( res != None ) break; ++_p %= 2; } if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!"; else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!"; else cout << "It's a draw!"; cout << endl << endl; string r; cout << "Play again( Y / N )? "; cin >> r; if( r != "Y" && r != "y" ) return; ++_p %= 2; reset(); } } private: void reset() { for( int x = 0; x < 9; x++ ) _field[x] = None; } void drawGrid() { system( "cls" ); COORD c = { 0, 2 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); cout << " 1 | 2 | 3 " << endl; cout << "---+---+---" << endl; cout << " 4 | 5 | 6 " << endl; cout << "---+---+---" << endl; cout << " 7 | 8 | 9 " << endl << endl << endl; int f = 0; for( int y = 0; y < 5; y += 2 ) for( int x = 1; x < 11; x += 4 ) { if( _field[f] != None ) { COORD c = { x, 2 + y }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); string o = _field[f] == Computer ? "X" : "O"; cout << o; } f++; } c.Y = 9; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); } int checkVictory() { for( int i = 0; i < 8; i++ ) { if( _field[iWin[i][0]] != None && _field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] ) { return _field[iWin[i][0]]; } } int i = 0; for( int f = 0; f < 9; f++ ) { if( _field[f] != None ) i++; } if( i == 9 ) return Draw; return None; } void getHumanMove() { int m; cout << "Enter your move ( 1 - 9 ) "; while( true ) { m = 0; do { cin >> m; } while( m < 1 && m > 9 ); if( _field[m - 1] != None ) cout << "Invalid move. Try again!" << endl; else break; } _field[m - 1] = Human; } void getComputerMove() { int move = 0; do{ move = rand() % 9; } while( _field[move] != None ); for( int i = 0; i < 8; i++ ) { int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2]; if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None ) { move = try3; if( _field[try1] == Computer ) break; } if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) { move = try2; if( _field[try1] == Computer ) break; } if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None ) { move = try1; if( _field[try2] == Computer ) break; } } _field[move] = Computer; } int _p; int _field[9]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); ttt tic; tic.play(); return 0; }
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 If r.Test(line) Then WScript.StdOut.WriteLine "IP Version " &_ ver & ": " & r.Replace(line,"$1") End If Loop End Function Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
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 If r.Test(line) Then WScript.StdOut.WriteLine "IP Version " &_ ver & ": " & r.Replace(line,"$1") End If Loop End Function Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
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, _ ByVal i1 As Integer, ByVal i2 As Integer) If (lg = 1) Then Call lineto(x * 3, y * 3) Exit Sub End If lg = lg / 3 Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2) Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2) Call Peano(x + lg, y + lg, lg, i1, 1 - i2) Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2) Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2) Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2) Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2) Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2) Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2) End Sub Sub main() n = 1: flag = False Call Peano(0, 0, WIDTH, 0, 0) ReDim points(1 To n - 1, 1 To 2) n = 1: flag = True Call Peano(0, 0, WIDTH, 0, 0) ActiveSheet.Shapes.AddPolyline points End Sub
#include <cmath> #include <fstream> #include <iostream> #include <string> class peano_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::string& s); double x_; double y_; int angle_; int length_; }; void peano_curve::write(std::ostream& out, int size, int length, int order) { length_ = length; x_ = length; y_ = length; angle_ = 90; out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; std::string s = "L"; for (int i = 0; i < order; ++i) s = rewrite(s); execute(out, s); out << "'/>\n</svg>\n"; } std::string peano_curve::rewrite(const std::string& s) { std::string t; for (char c : s) { switch (c) { case 'L': t += "LFRFL-F-RFLFR+F+LFRFL"; break; case 'R': t += "RFLFR+F+LFRFL-F-RFLFR"; break; default: t += c; break; } } return t; } void peano_curve::line(std::ostream& out) { double theta = (3.14159265359 * angle_)/180.0; x_ += length_ * std::cos(theta); y_ += length_ * std::sin(theta); out << " L" << x_ << ',' << y_; } void peano_curve::execute(std::ostream& out, const std::string& s) { out << 'M' << x_ << ',' << y_; for (char c : s) { switch (c) { case 'F': line(out); break; case '+': angle_ = (angle_ + 90) % 360; break; case '-': angle_ = (angle_ - 90) % 360; break; } } } int main() { std::ofstream out("peano_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return 1; } peano_curve pc; pc.write(out, 656, 8, 4); return 0; }
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(ObservationFrequencies) To UBound(ObservationFrequencies) Total = Total + ObservationFrequencies(i) Debug.Print ObservationFrequencies(i); " "; Next i DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies) Ei = Total / (DegreesOfFreedom + 1) For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei Next i p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True) Debug.Print Debug.Print "Chi-squared test for given frequencies" Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", "; Debug.Print "df ="; DegreesOfFreedom; ", "; Debug.Print "p-value = "; Format(p_value, "0.0000") Test4DiscreteUniformDistribution = p_value > Significance End Function Private Function Dice5() As Integer Dice5 = Int(5 * Rnd + 1) End Function Private Function Dice7() As Integer Dim i As Integer Do i = 5 * (Dice5 - 1) + Dice5 Loop While i > 21 Dice7 = i Mod 7 + 1 End Function Sub TestDice7() Dim i As Long, roll As Integer Dim Bins(1 To 7) As Variant For i = 1 To 1000000 roll = Dice7 Bins(roll) = Bins(roll) + 1 Next i Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """" End Sub
template<typename F> class fivetoseven { public: fivetoseven(F f): d5(f), rem(0), max(1) {} int operator()(); private: F d5; int rem, max; }; template<typename F> int fivetoseven<F>::operator()() { while (rem/7 == max/7) { while (max < 7) { int rand5 = d5()-1; max *= 5; rem = 5*rem + rand5; } int groups = max / 7; if (rem >= 7*groups) { rem -= 7*groups; max -= 7*groups; } } int result = rem % 7; rem /= 7; max /= 7; return result+1; } int d5() { return 5.0*std::rand()/(RAND_MAX + 1.0) + 1; } fivetoseven<int(*)()> d7(d5); int main() { srand(time(0)); test_distribution(d5, 1000000, 0.001); test_distribution(d7, 1000000, 0.001); }
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 While k < lmt : np(CInt(k)) = True : k += n : End While End If : n += j : j = 2 : End While End Sub Function is_Mag(ByVal n As Integer) As Boolean Dim res, rm As Integer, p As Integer = 10 While n >= p res = Math.DivRem(n, p, rm) If np(res + rm) Then Return False p = p * 10 : End While : Return True End Function Sub Main(ByVal args As String()) ms(100_009) : Dim mn As String = " magnanimous numbers:" WriteLine("First 45{0}", mn) : Dim l As Integer = 0, c As Integer = 0 While c < 400 : If is_Mag(l) Then c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, "{0,4} ", "{0,8:n0} "), l) If c < 45 AndAlso c Mod 15 = 0 Then WriteLine() If c = 240 Then WriteLine(vbLf & vbLf & "241st through 250th{0}", mn) If c = 390 Then WriteLine(vbLf & vbLf & "391st through 400th{0}", mn) End If : l += 1 : End While End Sub End Module
#include <iomanip> #include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } bool is_magnanimous(unsigned int n) { for (unsigned int p = 10; n >= p; p *= 10) { if (!is_prime(n % p + n / p)) return false; } return true; } int main() { unsigned int count = 0, n = 0; std::cout << "First 45 magnanimous numbers:\n"; for (; count < 45; ++n) { if (is_magnanimous(n)) { if (count > 0) std::cout << (count % 15 == 0 ? "\n" : ", "); std::cout << std::setw(3) << n; ++count; } } std::cout << "\n\n241st through 250th magnanimous numbers:\n"; for (unsigned int i = 0; count < 250; ++n) { if (is_magnanimous(n)) { if (count++ >= 240) { if (i++ > 0) std::cout << ", "; std::cout << n; } } } std::cout << "\n\n391st through 400th magnanimous numbers:\n"; for (unsigned int i = 0; count < 400; ++n) { if (is_magnanimous(n)) { if (count++ >= 390) { if (i++ > 0) std::cout << ", "; std::cout << n; } } } std::cout << '\n'; return 0; }
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") & " primes numbers." For n = 0 To 19 temp = temp & ", " & Primes(n) Next Debug.Print "First twenty primes : "; Mid(temp, 3) n = 0: temp = vbNullString Do While Primes(n) < 100 n = n + 1 Loop Do While Primes(n) < 150 temp = temp & ", " & Primes(n) n = n + 1 Loop Debug.Print "Primes between 100 and 150 : " & Mid(temp, 3) Dim ccount As Long n = 0 Do While Primes(n) < 7700 n = n + 1 Loop Do While Primes(n) < 8000 ccount = ccount + 1 n = n + 1 Loop Debug.Print "Number of primes between 7,700 and 8,000 : " & ccount n = 1 Do While n <= 100000 n = n * 10 Debug.Print "The " & n & "th prime: "; Format(Primes(n - 1), "#,##0") Loop Debug.Print "VBA has a limit in array Debug.Print "With my computer, the limit for an array of Long is : 133 218 295" Debug.Print "The last prime I could find is the : " & _ Format(UBound(Primes), "#,##0") & "th, Value : " & _ Format(Primes(UBound(Primes)), "#,##0") End Sub Function ListPrimes(MAX As Long) As Long() Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long ReDim t(2 To MAX) ReDim L(MAX \ 2) s = Sqr(MAX) For i = 3 To s Step 2 If t(i) = False Then For j = i * i To MAX Step i t(j) = True Next End If Next i L(0) = 2 For i = 3 To MAX Step 2 If t(i) = False Then c = c + 1 L(c) = i End If Next i ReDim Preserve L(c) ListPrimes = L End Function
#include <iostream> #include <cstdint> #include <queue> #include <utility> #include <vector> #include <limits> template<typename integer> class prime_generator { public: integer next_prime(); integer count() const { return count_; } private: struct queue_item { queue_item(integer prime, integer multiple, unsigned int wheel_index) : prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {} integer prime_; integer multiple_; unsigned int wheel_index_; }; struct cmp { bool operator()(const queue_item& a, const queue_item& b) const { return a.multiple_ > b.multiple_; } }; static integer wheel_next(unsigned int& index) { integer offset = wheel_[index]; ++index; if (index == std::size(wheel_)) index = 0; return offset; } typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue; integer next_ = 11; integer count_ = 0; queue queue_; unsigned int wheel_index_ = 0; static const unsigned int wheel_[]; static const integer primes_[]; }; template<typename integer> const unsigned int prime_generator<integer>::wheel_[] = { 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10 }; template<typename integer> const integer prime_generator<integer>::primes_[] = { 2, 3, 5, 7 }; template<typename integer> integer prime_generator<integer>::next_prime() { if (count_ < std::size(primes_)) return primes_[count_++]; integer n = next_; integer prev = 0; while (!queue_.empty()) { queue_item item = queue_.top(); if (prev != 0 && prev != item.multiple_) n += wheel_next(wheel_index_); if (item.multiple_ > n) break; else if (item.multiple_ == n) { queue_.pop(); queue_item new_item(item); new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_); queue_.push(new_item); } else throw std::overflow_error("prime_generator: overflow!"); prev = item.multiple_; } if (std::numeric_limits<integer>::max()/n > n) queue_.emplace(n, n * n, wheel_index_); next_ = n + wheel_next(wheel_index_); ++count_; return n; } int main() { typedef uint32_t integer; prime_generator<integer> pgen; std::cout << "First 20 primes:\n"; for (int i = 0; i < 20; ++i) { integer p = pgen.next_prime(); if (i != 0) std::cout << ", "; std::cout << p; } std::cout << "\nPrimes between 100 and 150:\n"; for (int n = 0; ; ) { integer p = pgen.next_prime(); if (p > 150) break; if (p >= 100) { if (n != 0) std::cout << ", "; std::cout << p; ++n; } } int count = 0; for (;;) { integer p = pgen.next_prime(); if (p > 8000) break; if (p >= 7700) ++count; } std::cout << "\nNumber of primes between 7700 and 8000: " << count << '\n'; for (integer n = 10000; n <= 10000000; n *= 10) { integer prime; while (pgen.count() != n) prime = pgen.next_prime(); std::cout << n << "th prime: " << prime << '\n'; } return 0; }
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 Console.WriteLine(arr(0, 0)) End Sub End Module
#include <iostream> int main() { int dim1, dim2; std::cin >> dim1 >> dim2; double* array_data = new double[dim1*dim2]; double** array = new double*[dim1]; for (int i = 0; i < dim1; ++i) array[i] = array_data + dim2*i; array[0][0] = 3.5; std::cout << array[0][0] << std::endl; delete[] array; delete[] array_data; return 0; }
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 WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
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 WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
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 For l = VECSIZE To 1 Step -1 num = 100000 * vect(l) + karray * l karray = num \ (2 * l - 1) vect(l) = num - karray * (2 * l - 1) Next l k = karray \ 100000 buffer(n) = more + k more = karray - k * 100000 Next n Debug.Print CStr(buffer(1)); Debug.Print "." l = 0 For n = 2 To BUFSIZE Debug.Print Format$(buffer(n), "00000"); l = l + 1 If l = 10 Then l = 0 Debug.Print End If Next n End Sub
#include <iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; class Gospers { cpp_int q, r, t, i, n; public: Gospers() : q{1}, r{0}, t{1}, i{1} { ++*this; } Gospers& operator++() { n = (q*(27*i-12)+5*r) / (5*t); while(n != (q*(675*i-216)+125*r)/(125*t)) { r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r); q = i*(2*i-1)*q; t = 3*(3*i+1)*(3*i+2)*t; i++; n = (q*(27*i-12)+5*r) / (5*t); } q = 10*q; r = 10*r-10*n*t; return *this; } int operator*() { return (int)n; } }; int main() { Gospers g; std::cout << *g << "."; for(;;) { std::cout << *++g; } }
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.Print Q(i); Next i Debug.print Debug.Print "The 1000th term is:"; Q(1000) Debug.Print "Number of times smaller:"; smaller End Sub
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }
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.Print Q(i); Next i Debug.print Debug.Print "The 1000th term is:"; Q(1000) Debug.Print "Number of times smaller:"; smaller End Sub
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }