Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from Rust to Go with equivalent syntax and logic.
#[derive(Clone, Copy, Debug)] enum Operator { Sub, Plus, Mul, Div, } #[derive(Clone, Debug)] struct Factor { content: String, value: i32, } fn apply(op: Operator, left: &[Factor], right: &[Factor]) -> Vec<Factor> { let mut ret = Vec::new(); for l in left.iter() { for r in right...
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op...
Can you help me rewrite this code in Go instead of Rust, keeping it the same logically?
#[derive(Clone, Copy, Debug)] enum Operator { Sub, Plus, Mul, Div, } #[derive(Clone, Debug)] struct Factor { content: String, value: i32, } fn apply(op: Operator, left: &[Factor], right: &[Factor]) -> Vec<Factor> { let mut ret = Vec::new(); for l in left.iter() { for r in right...
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op...
Convert the following code from Rust to Go, ensuring the logic remains intact.
use std::convert::TryInto; use std::env; use std::num::Wrapping; const REPLACEMENT_TABLE: [[u8; 16]; 8] = [ [4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3], [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9], [5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11], [7, 13, 10, 1, 0, 8, 9, 15,...
package main import "fmt" type sBox [8][16]byte type gost struct { k87, k65, k43, k21 [256]byte enc []byte } func newGost(s *sBox) *gost { var g gost for i := range g.k87 { g.k87[i] = s[7][i>>4]<<4 | s[6][i&15] g.k65[i] = s[5][i>>4]<<4 | s[4][i&15] g.k43[i] = s...
Maintain the same structure and functionality when rewriting this code in Go.
use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Read, Write}; use std::iter::repeat; struct ImageGray8 { width: usize, height: usize, data: Vec<u8>, } fn load_pgm(filename: &str) -> io::Result<ImageGray8> { let mut file = BufReader::new(File::open(filename)?); ...
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" ) func hough(im image.Image, ntx, mry int) draw.Image { nimx := im.Bounds().Max.X mimy := im.Bounds().Max.Y him := image.NewGray(image.Rect(0, 0, ntx, mry)) draw.Draw(him, him.Bounds(), ...
Port the provided Rust code into Go while preserving the original functionality.
#[derive(Debug)] enum SetOperation { Union, Intersection, Difference, } #[derive(Debug, PartialEq)] enum RangeType { Inclusive, Exclusive, } #[derive(Debug)] struct CompositeSet<'a> { operation: SetOperation, a: &'a RealSet<'a>, b: &'a RealSet<'a>, } #[derive(Debug)] struct RangeSet {...
package main import "fmt" type Set func(float64) bool func Union(a, b Set) Set { return func(x float64) bool { return a(x) || b(x) } } func Inter(a, b Set) Set { return func(x float64) bool { return a(x) && b(x) } } func Diff(a, b Set) Set { return func(x float64) bool { return a(x) && !b(x) } } func...
Write the same code in Go as shown below in Rust.
#[derive(Debug)] enum SetOperation { Union, Intersection, Difference, } #[derive(Debug, PartialEq)] enum RangeType { Inclusive, Exclusive, } #[derive(Debug)] struct CompositeSet<'a> { operation: SetOperation, a: &'a RealSet<'a>, b: &'a RealSet<'a>, } #[derive(Debug)] struct RangeSet {...
package main import "fmt" type Set func(float64) bool func Union(a, b Set) Set { return func(x float64) bool { return a(x) || b(x) } } func Inter(a, b Set) Set { return func(x float64) bool { return a(x) && b(x) } } func Diff(a, b Set) Set { return func(x float64) bool { return a(x) && !b(x) } } func...
Port the provided Rust code into Go while preserving the original functionality.
fn print_super_d_numbers(d: u32, limit: u32) { use rug::Assign; use rug::Integer; println!("First {} super-{} numbers:", limit, d); let digits = d.to_string().repeat(d as usize); let mut count = 0; let mut n = 1; let mut s = Integer::new(); while count < limit { s.assign(Inte...
package main import ( "fmt" "math/big" "strings" "time" ) func main() { start := time.Now() rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"} one := big.NewInt(1) nine := big.NewInt(9) for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) ...
Generate a Go translation of this Rust snippet without changing its computational steps.
fn print_super_d_numbers(d: u32, limit: u32) { use rug::Assign; use rug::Integer; println!("First {} super-{} numbers:", limit, d); let digits = d.to_string().repeat(d as usize); let mut count = 0; let mut n = 1; let mut s = Integer::new(); while count < limit { s.assign(Inte...
package main import ( "fmt" "math/big" "strings" "time" ) func main() { start := time.Now() rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"} one := big.NewInt(1) nine := big.NewInt(9) for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) ...
Rewrite this program in Go while keeping its functionality equivalent to the Rust version.
fn padovan_recur() -> impl std::iter::Iterator<Item = usize> { let mut p = vec![1, 1, 1]; let mut n = 0; std::iter::from_fn(move || { let pn = if n < 3 { p[n] } else { p[0] + p[1] }; p[0] = p[1]; p[1] = p[2]; p[2] = pn; n += 1; Some(pn) }) } fn padovan_fl...
package main import ( "fmt" "math" "math/big" "strings" ) func padovanRecur(n int) []int { p := make([]int, n) p[0], p[1], p[2] = 1, 1, 1 for i := 3; i < n; i++ { p[i] = p[i-2] + p[i-3] } return p } func padovanFloor(n int) []int { var p, s, t, u = new(big.Rat), new(bi...
Rewrite this program in Go while keeping its functionality equivalent to the Rust version.
use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead}; fn text_char(ch: char) -> Option<char> { match ch { 'a' | 'b' | 'c' => Some('2'), 'd' | 'e' | 'f' => Some('3'), 'g' | 'h' | 'i' => Some('4'), 'j' | 'k' | 'l' => Some('5'), 'm' | 'n' | 'o' => Some...
package main import ( "bufio" "flag" "fmt" "io" "log" "os" "strings" "unicode" ) func main() { log.SetFlags(0) log.SetPrefix("textonyms: ") wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } t ...
Preserve the algorithm and functionality while converting the code from Rust to Go.
use std::rc::Rc; use std::ops::{Add, Mul}; #[derive(Clone)] struct Church<'a, T: 'a> { runner: Rc<dyn Fn(Rc<dyn Fn(T) -> T + 'a>) -> Rc<dyn Fn(T) -> T + 'a> + 'a>, } impl<'a, T> Church<'a, T> { fn zero() -> Self { Church { runner: Rc::new(|_f| { Rc::new(|x| x) }...
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } fun...
Convert this Rust snippet to Go and keep its semantics consistent.
use std::rc::Rc; use std::ops::{Add, Mul}; #[derive(Clone)] struct Church<'a, T: 'a> { runner: Rc<dyn Fn(Rc<dyn Fn(T) -> T + 'a>) -> Rc<dyn Fn(T) -> T + 'a> + 'a>, } impl<'a, T> Church<'a, T> { fn zero() -> Self { Church { runner: Rc::new(|_f| { Rc::new(|x| x) }...
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } fun...
Translate this program into Go but keep the logic exactly as in Rust.
use ring::digest::{digest, SHA256}; use ripemd160::{Digest, Ripemd160}; use hex::FromHex; static X: &str = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352"; static Y: &str = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"; static ALPHABET: [char; 58] = [ '1', '2', '3', '4', '5...
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _,...
Rewrite this program in Go while keeping its functionality equivalent to the Rust version.
use ring::digest::{digest, SHA256}; use ripemd160::{Digest, Ripemd160}; use hex::FromHex; static X: &str = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352"; static Y: &str = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"; static ALPHABET: [char; 58] = [ '1', '2', '3', '4', '5...
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _,...
Generate a Go translation of this Rust snippet without changing its computational steps.
use std::net::Ipv4Addr; fn canonical_cidr(cidr: &str) -> Result<String, &str> { let mut split = cidr.splitn(2, '/'); if let (Some(addr), Some(mask)) = (split.next(), split.next()) { let addr = addr.parse::<Ipv4Addr>().map(u32::from).map_err(|_| cidr)?; let mask = mask.parse::<u8>().map_err(|_| ...
package main import ( "fmt" "log" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func canonicalize(cidr string) string { split := strings.Split(cidr, "/") dotted := split[0] size, err := strconv.Atoi(split[1]) check(err) ...
Write a version of this Rust function in Go with identical behavior.
use std::net::Ipv4Addr; fn canonical_cidr(cidr: &str) -> Result<String, &str> { let mut split = cidr.splitn(2, '/'); if let (Some(addr), Some(mask)) = (split.next(), split.next()) { let addr = addr.parse::<Ipv4Addr>().map(u32::from).map_err(|_| cidr)?; let mask = mask.parse::<u8>().map_err(|_| ...
package main import ( "fmt" "log" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func canonicalize(cidr string) string { split := strings.Split(cidr, "/") dotted := split[0] size, err := strconv.Atoi(split[1]) check(err) ...
Convert this Rust block to Go, preserving its control flow and logic.
pub fn pi(n: usize) -> f64 { let mut a : f64 = 1.0; let two : f64= 2.0; let mut g = 1.0 / two.sqrt(); let mut s = 0.0; let mut k = 1; while k<=n { let a1 = (a+g)/two; let g1 = (a*g).sqrt(); a = a1; g = g1; s += (a.powi(2)-g.powi(2)) * two.powi((k...
package main import ( "fmt" "math/big" ) func main() { one := big.NewFloat(1) two := big.NewFloat(2) four := big.NewFloat(4) prec := uint(768) a := big.NewFloat(1).SetPrec(prec) g := new(big.Float).SetPrec(prec) t := new(big.Float).SetPrec(prec) u := new(big.Float).SetP...
Port the following code from Rust to Go with equivalent syntax and logic.
pub fn pi(n: usize) -> f64 { let mut a : f64 = 1.0; let two : f64= 2.0; let mut g = 1.0 / two.sqrt(); let mut s = 0.0; let mut k = 1; while k<=n { let a1 = (a+g)/two; let g1 = (a*g).sqrt(); a = a1; g = g1; s += (a.powi(2)-g.powi(2)) * two.powi((k...
package main import ( "fmt" "math/big" ) func main() { one := big.NewFloat(1) two := big.NewFloat(2) four := big.NewFloat(4) prec := uint(768) a := big.NewFloat(1).SetPrec(prec) g := new(big.Float).SetPrec(prec) t := new(big.Float).SetPrec(prec) u := new(big.Float).SetP...
Please provide an equivalent version of this Rust code in Go.
mod bit_array; mod prime_sieve; use prime_sieve::PrimeSieve; fn modpow(mut base: usize, mut exp: usize, n: usize) -> usize { if n == 1 { return 0; } let mut result = 1; base %= n; while exp > 0 { if (exp & 1) == 1 { result = (result * base) % n; } b...
package main import "fmt" func sieve(limit int) []int { var primes []int c := make([]bool, limit + 1) p := 3 p2 := p * p for p2 <= limit { for i := p2; i <= limit; i += 2 * p { c[i] = true } for ok := true; ok; ok = c[p] { p += 2 } ...
Generate a Go translation of this Rust snippet without changing its computational steps.
extern crate primal; extern crate rayon; extern crate rug; use rayon::prelude::*; use rug::Integer; fn partial(p1 : usize, p2 : usize) -> String { let mut aux = Integer::from(1); let (_, hi) = primal::estimate_nth_prime(p2 as u64); let sieve = primal::Sieve::new(hi as usize); let prime1 = sieve.nth_pr...
package main import ( "fmt" "math/big" "time" "github.com/jbarham/primegen.go" ) func main() { start := time.Now() pg := primegen.New() var i uint64 p := big.NewInt(1) tmp := new(big.Int) for i <= 9 { fmt.Printf("primorial(%v) = %v\n", i, p) i++ p = p.Mul(p, tmp.SetUint64(pg.Next())) } for _, j := ...
Write a version of this Rust function in Go with identical behavior.
use num_bigint::BigInt; use num_integer::Integer; use num_traits::{One, Zero}; use std::fmt; #[derive(Debug, Clone, PartialEq, PartialOrd)] struct Rational { nominator: BigInt, denominator: BigInt, } impl Rational { fn new(n: &BigInt, d: &BigInt) -> Rational { assert!(!d.is_zero(), "denominator ca...
package main import ( "fmt" "math/big" "strings" ) var zero = new(big.Int) var one = big.NewInt(1) func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat { if br.Num().Cmp(zero) == 0 { return fracs } iquo := new(big.Int) irem := new(big.Int) iquo.QuoRem(br.Denom(),...
Translate this program into Go but keep the logic exactly as in Rust.
use num_bigint::BigInt; use num_integer::Integer; use num_traits::{One, Zero}; use std::fmt; #[derive(Debug, Clone, PartialEq, PartialOrd)] struct Rational { nominator: BigInt, denominator: BigInt, } impl Rational { fn new(n: &BigInt, d: &BigInt) -> Rational { assert!(!d.is_zero(), "denominator ca...
package main import ( "fmt" "math/big" "strings" ) var zero = new(big.Int) var one = big.NewInt(1) func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat { if br.Num().Cmp(zero) == 0 { return fracs } iquo := new(big.Int) irem := new(big.Int) iquo.QuoRem(br.Denom(),...
Can you help me rewrite this code in Go instead of Rust, keeping it the same logically?
fn cwalk(mut vis: &mut Vec<Vec<bool>>, count: &mut isize, w: usize, h: usize, y: usize, x: usize, d: usize) { if x == 0 || y == 0 || x == w || y == h { *count += 1; return; } vis[y][x] = true; vis[h - y][w - x] = true; if x != 0 && ! vis[y][x - 1] { cwalk(&mut vis, count, ...
package main import "fmt" var grid []byte var w, h, last int var cnt int var next [4]int var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func walk(y, x int) { if y == 0 || y == h || x == 0 || x == w { cnt += 2 return } t := y*(w+1) + x grid[t]++ grid[last-t]++ for i, d :...
Generate a Go translation of this Rust snippet without changing its computational steps.
fn cwalk(mut vis: &mut Vec<Vec<bool>>, count: &mut isize, w: usize, h: usize, y: usize, x: usize, d: usize) { if x == 0 || y == 0 || x == w || y == h { *count += 1; return; } vis[y][x] = true; vis[h - y][w - x] = true; if x != 0 && ! vis[y][x - 1] { cwalk(&mut vis, count, ...
package main import "fmt" var grid []byte var w, h, last int var cnt int var next [4]int var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func walk(y, x int) { if y == 0 || y == h || x == 0 || x == w { cnt += 2 return } t := y*(w+1) + x grid[t]++ grid[last-t]++ for i, d :...
Port the following code from Rust to Go with equivalent syntax and logic.
use std::time::Instant; use separator::Separatable; const NUMBER_OF_CUBAN_PRIMES: usize = 200; const COLUMNS: usize = 10; const LAST_CUBAN_PRIME: usize = 100_000; fn main() { println!("Calculating the first {} cuban primes and the {}th cuban prime...", NUMBER_OF_CUBAN_PRIMES, LAST_CUBAN_PRIME); let start = In...
package main import ( "fmt" "math/big" ) func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { var z big.Int var cube1, cube2, cube100k, diff uint64 cubans := make(...
Convert this Rust snippet to Go and keep its semantics consistent.
extern crate image; extern crate rand; use rand::prelude::*; use std::f32; fn main() { let max_iterations = 50_000; let img_side = 800; let tri_size = 400.0; let mut imgbuf = image::ImageBuffer::new(img_side, img_side); let mut vertices: [[f32; 2]; 3] = [[0.0, 0.0]; 3]; for i in 0....
package main import ( "fmt" "image" "image/color" "image/draw" "image/gif" "log" "math" "math/rand" "os" "time" ) var bwPalette = color.Palette{ color.Transparent, color.White, color.RGBA{R: 0xff, A: 0xff}, color.RGBA{G: 0xff, A: 0xff}, color.RGBA{B: 0xff, A: 0xff}, } func main() { const ( width ...
Convert this Rust block to Go, preserving its control flow and logic.
extern crate image; extern crate rand; use rand::prelude::*; use std::f32; fn main() { let max_iterations = 50_000; let img_side = 800; let tri_size = 400.0; let mut imgbuf = image::ImageBuffer::new(img_side, img_side); let mut vertices: [[f32; 2]; 3] = [[0.0, 0.0]; 3]; for i in 0....
package main import ( "fmt" "image" "image/color" "image/draw" "image/gif" "log" "math" "math/rand" "os" "time" ) var bwPalette = color.Palette{ color.Transparent, color.White, color.RGBA{R: 0xff, A: 0xff}, color.RGBA{G: 0xff, A: 0xff}, color.RGBA{B: 0xff, A: 0xff}, } func main() { const ( width ...
Maintain the same structure and functionality when rewriting this code in Go.
type Number = f64; #[derive(Debug, Copy, Clone, PartialEq)] struct Operator { token: char, operation: fn(Number, Number) -> Number, precedence: u8, is_left_associative: bool, } #[derive(Debug, Clone, PartialEq)] enum Token { Digit(Number), Operator(Operator), LeftParen, RightParen, } ...
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) f...
Translate the given Rust code snippet into Go without altering its behavior.
fn main() { println!("{}", noise(3.14, 42.0, 7.0)); } fn noise(x: f64, y: f64, z: f64) -> f64 { let x0 = x.floor() as usize & 255; let y0 = y.floor() as usize & 255; let z0 = z.floor() as usize & 255; let x = x - x.floor(); let y = y - y.floor(); let z = z - z.floor(); let u = fade(x); let v = fade(y); l...
package main import ( "fmt" "math" ) func main() { fmt.Println(noise(3.14, 42, 7)) } func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(z) u := fa...
Write the same algorithm in Go as shown in this Rust implementation.
extern crate num; use num::FromPrimitive; use num::bigint::BigInt; use std::collections::HashSet; fn rev_add(num: &BigInt) -> BigInt { let rev_string: String = num.to_string().chars().rev().collect(); let rev_val: BigInt = rev_string.parse().unwrap(); num + rev_val } fn is_palindrome(num: &BigInt)...
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
Rewrite this program in Go while keeping its functionality equivalent to the Rust version.
extern crate num; use num::FromPrimitive; use num::bigint::BigInt; use std::collections::HashSet; fn rev_add(num: &BigInt) -> BigInt { let rev_string: String = num.to_string().chars().rev().collect(); let rev_val: BigInt = rev_string.parse().unwrap(); num + rev_val } fn is_palindrome(num: &BigInt)...
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
Keep all operations the same but rewrite the snippet in Go.
use std::num::Wrapping as w; const MSG: &str = "a Top Secret secret"; const KEY: &str = "this is my secret key"; fn main() { let mut isaac = Isaac::new(); isaac.seed(KEY, true); let encr = isaac.vernam(MSG.as_bytes()); println!("msg: {}", MSG); println!("key: {}", KEY); print!("XOR: "); ...
package main import "fmt" const ( msg = "a Top Secret secret" key = "this is my secret key" ) func main() { var z state z.seed(key) fmt.Println("Message: ", msg) fmt.Println("Key  : ", key) fmt.Println("XOR  : ", z.vernam(msg)) } type state struct { aa, bb, cc uint32 mm ...
Generate an equivalent Go version of this Rust code.
use std::num::Wrapping as w; const MSG: &str = "a Top Secret secret"; const KEY: &str = "this is my secret key"; fn main() { let mut isaac = Isaac::new(); isaac.seed(KEY, true); let encr = isaac.vernam(MSG.as_bytes()); println!("msg: {}", MSG); println!("key: {}", KEY); print!("XOR: "); ...
package main import "fmt" const ( msg = "a Top Secret secret" key = "this is my secret key" ) func main() { var z state z.seed(key) fmt.Println("Message: ", msg) fmt.Println("Key  : ", key) fmt.Println("XOR  : ", z.vernam(msg)) } type state struct { aa, bb, cc uint32 mm ...
Please provide an equivalent version of this Rust code in Go.
fn power_of_two(l: isize, n: isize) -> isize { let mut test: isize = 0; let log: f64 = 2.0_f64.ln() / 10.0_f64.ln(); let mut factor: isize = 1; let mut looop = l; let mut nn = n; while looop > 10 { factor *= 10; looop /= 10; } while nn > 0 { test = test + 1; ...
package main import ( "fmt" "math" "time" ) const ld10 = math.Ln2 / math.Ln10 func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func p(L, n uint64) uint64 { i := L digits :=...
Change the following Rust code into Go without altering its purpose.
fn power_of_two(l: isize, n: isize) -> isize { let mut test: isize = 0; let log: f64 = 2.0_f64.ln() / 10.0_f64.ln(); let mut factor: isize = 1; let mut looop = l; let mut nn = n; while looop > 10 { factor *= 10; looop /= 10; } while nn > 0 { test = test + 1; ...
package main import ( "fmt" "math" "time" ) const ld10 = math.Ln2 / math.Ln10 func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func p(L, n uint64) uint64 { i := L digits :=...
Convert the following code from Rust to Go, ensuring the logic remains intact.
fn is_prime(n: u32) -> bool { if n < 2 { return false; } if n % 2 == 0 { return n == 2; } if n % 3 == 0 { return n == 3; } let mut p = 5; while p * p <= n { if n % p == 0 { return false; } p += 2; if n % p == 0 { ...
package main import ( "fmt" "log" "math/big" ) var ( primes []*big.Int smallPrimes []int ) func init() { two := big.NewInt(2) three := big.NewInt(3) p521 := big.NewInt(521) p29 := big.NewInt(29) primes = append(primes, two) smallPrimes = append(smallPrimes, 2) fo...
Ensure the translated Go code behaves exactly like the original Rust snippet.
mod bit_array; mod prime_sieve; use prime_sieve::PrimeSieve; fn find_prime_partition( sieve: &PrimeSieve, number: usize, count: usize, min_prime: usize, primes: &mut Vec<usize>, index: usize, ) -> bool { if count == 1 { if number >= min_prime && sieve.is_prime(number) { ...
package main import ( "fmt" "log" ) var ( primes = sieve(100000) foundCombo = false ) func sieve(limit uint) []uint { primes := []uint{2} c := make([]bool, limit+1) p := uint(3) for { p2 := p * p if p2 > limit { break } for i := p2...
Translate the given Rust code snippet into Go without altering its behavior.
#[derive(Copy, Clone)] struct Point { x: f64, y: f64, } use std::fmt; impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } fn perpendicular_distance(p: &Point, p1: &Point, p2: &Point) -> f64 { let dx = p2.x - p...
package main import ( "fmt" "math" ) type point struct{ x, y float64 } func RDP(l []point, ε float64) []point { x := 0 dMax := -1. last := len(l) - 1 p1 := l[0] p2 := l[last] x21 := p2.x - p1.x y21 := p2.y - p1.y for i, p := range l[1:last] { if d := math.Abs(y21*p.x -...
Translate this program into Go but keep the logic exactly as in Rust.
#[derive(Copy, Clone)] struct Point { x: f64, y: f64, } use std::fmt; impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } fn perpendicular_distance(p: &Point, p1: &Point, p2: &Point) -> f64 { let dx = p2.x - p...
package main import ( "fmt" "math" ) type point struct{ x, y float64 } func RDP(l []point, ε float64) []point { x := 0 dMax := -1. last := len(l) - 1 p1 := l[0] p2 := l[last] x21 := p2.x - p1.x y21 := p2.y - p1.y for i, p := range l[1:last] { if d := math.Abs(y21*p.x -...
Please provide an equivalent version of this Rust code in Go.
use std::fmt; use std::ops::{Add, Div, Mul, Sub}; #[derive(Copy, Clone, Debug)] pub struct Vector<T> { pub x: T, pub y: T, } impl<T> fmt::Display for Vector<T> where T: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(prec) = f.precision() { write!...
package main import "fmt" type vector []float64 func (v vector) add(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi + v2[i] } return r } func (v vector) sub(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi - v...
Change the programming language of this snippet from Rust to Go without modifying what it does.
use core::cmp::Ordering; const STX: char = '\u{0002}'; const ETX: char = '\u{0003}'; pub fn special_cmp(lhs: &str, rhs: &str) -> Ordering { let mut iter1 = lhs.chars(); let mut iter2 = rhs.chars(); loop { match (iter1.next(), iter2.next()) { (Some(lhs), Some(rhs)) => { ...
package main import ( "fmt" "sort" "strings" ) const stx = "\002" const etx = "\003" func bwt(s string) (string, error) { if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 { return "", fmt.Errorf("String can't contain STX or ETX") } s = stx + s + etx le := len(s) tab...
Can you help me rewrite this code in Go instead of Rust, keeping it the same logically?
use core::cmp::Ordering; const STX: char = '\u{0002}'; const ETX: char = '\u{0003}'; pub fn special_cmp(lhs: &str, rhs: &str) -> Ordering { let mut iter1 = lhs.chars(); let mut iter2 = rhs.chars(); loop { match (iter1.next(), iter2.next()) { (Some(lhs), Some(rhs)) => { ...
package main import ( "fmt" "sort" "strings" ) const stx = "\002" const etx = "\003" func bwt(s string) (string, error) { if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 { return "", fmt.Errorf("String can't contain STX or ETX") } s = stx + s + etx le := len(s) tab...
Generate a Go translation of this Rust snippet without changing its computational steps.
mod bit_array; mod prime_sieve; use prime_sieve::PrimeSieve; fn upper_bound_for_nth_prime(n: usize) -> usize { let x = n as f64; (x * (x.ln() + x.ln().ln())) as usize } fn compute_transitions(limit: usize) { use std::collections::BTreeMap; let mut transitions = BTreeMap::new(); let mut prev = 2...
package main import ( "fmt" "sort" ) func sieve(limit uint64) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := uint64(3) for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } ...
Port the provided Rust code into Go while preserving the original functionality.
fn main() { struct WolfGen(ElementaryCA); impl WolfGen { fn new() -> WolfGen { let (_, ca) = ElementaryCA::new(30); WolfGen(ca) } fn next(&mut self) -> u8 { let mut out = 0; for i in 0..8 { out |= ((1 & self.0.next())<<i)as...
package main import "fmt" const n = 64 func pow2(x uint) uint64 { return uint64(1) << x } func evolve(state uint64, rule int) { for p := 0; p < 10; p++ { b := uint64(0) for q := 7; q >= 0; q-- { st := state b |= (st & 1) << uint(q) state = 0 fo...
Keep all operations the same but rewrite the snippet in Go.
use math::{histogram::Histogram, traits::ToIterator}; use rand; use rand_distr::{Distribution, Normal}; fn mean(data: &[f32]) -> Option<f32> { let sum: f32 = data.iter().sum(); Some(sum / data.len() as f32) } fn standard_deviation(data: &[f32]) -> Option<f32> { let mean = mean(data).expect("inval...
package main import ( "fmt" "math" "math/rand" "strings" ) func norm2() (s, c float64) { r := math.Sqrt(-2 * math.Log(rand.Float64())) s, c = math.Sincos(2 * math.Pi * rand.Float64()) return s * r, c * r } func main() { const ( n = 10000 bins = 12 sig =...
Generate a Go translation of this Rust snippet without changing its computational steps.
use std::env; fn main() { let n: usize = match env::args().nth(1).and_then(|arg| arg.parse().ok()).ok_or( "Please specify the size of the magic square, as a positive multiple of 4 plus 2.", ) { Ok(arg) if arg % 2 == 1 || arg >= 6 && (arg - 2) % 4 == 0 => arg, Err...
package main import ( "fmt" "log" ) func magicSquareOdd(n int) ([][]int, error) { if n < 3 || n%2 == 0 { return nil, fmt.Errorf("base must be odd and > 2") } value := 1 gridSize := n * n c, r := n/2, 0 result := make([][]int, n) for i := 0; i < n; i++ { result[i] =...
Change the following Rust code into Go without altering its purpose.
enum State { Ready, Waiting, Dispense, Refunding, Exit, } #[methods_enum::gen(Act: run)] impl State { pub fn set(&mut self); pub fn input_char(&mut self, ch: char); fn run(&mut self, act: Act) { match self { State::Ready => match act { Act::set() => ...
package main import ( "bufio" "fmt" "log" "os" "strings" ) type state int const ( ready state = iota waiting exit dispense refunding ) func check(err error) { if err != nil { log.Fatal(err) } } func fsm() { fmt.Println("Please enter your option when promp...
Write a version of this Rust function in Go with identical behavior.
use std::convert::TryInto; fn get_divisors(n: u32) -> Vec<u32> { let mut results = Vec::new(); for i in 1..(n / 2 + 1) { if n % i == 0 { results.push(i); } } results.push(n); results } fn is_summable(x: i32, divisors: &[u32]) -> bool { if !divisors.is_empty() { ...
package main import "fmt" func getDivisors(n int) []int { divs := []int{1, n} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs = append(divs, j) } } } return divs } func sum(div...
Write the same code in Go as shown below in Rust.
use itertools::Itertools; use std::collections::HashMap; fn isqrt(n: u64) -> u64 { let mut s = (n as f64).sqrt() as u64; s = (s + n / s) >> 1; if s * s > n { s - 1 } else { s } } fn is_square(n: u64) -> bool { match n & 0xf { 0 | 1 | 4 | 9 => { let t = isqrt...
package main import ( "fmt" "math" "sort" "time" ) type term struct { coeff uint64 ix1, ix2 int8 } const maxDigits = 19 func toUint64(digits []int8, reverse bool) uint64 { sum := uint64(0) if !reverse { for i := 0; i < len(digits); i++ { sum = sum*10 + uint64(d...
Change the following Rust code into Go without altering its purpose.
use std::env; use std::fs; use std::collections::HashMap; extern crate rand; use rand::{seq::index::sample, thread_rng}; fn read_data(filename: &str) -> String { fs::read_to_string(filename).expect("Something went wrong reading the file") } fn main() { let args: Vec<String> = env::args().collect(); let ...
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int...
Maintain the same structure and functionality when rewriting this code in Go.
use std::collections::HashSet; fn create_string(s: &str, v: Vec<Option<usize>>) -> String { let mut idx = s.len(); let mut slice_vec = vec![]; while let Some(prev) = v[idx] { slice_vec.push(&s[prev..idx]); idx = prev; } slice_vec.reverse(); slice_vec.join(" ") } fn word_break...
package main import ( "fmt" "strings" ) type dict map[string]bool func newDict(words ...string) dict { d := dict{} for _, w := range words { d[w] = true } return d } func (d dict) wordBreak(s string) (broken []string, ok bool) { if s == "" { return nil, true } typ...
Write the same code in Go as shown below in Rust.
extern crate crypto; use crypto::digest::Digest; use crypto::sha2::Sha256; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; fn sha256_merkle_tree(filename: &str, block_size: usize) -> std::io::Result<Option<Vec<u8>>> { let mut md = Sha256::new(); let mut input = BufReader::new(File::open(fi...
package main import ( "crypto/sha256" "fmt" "io" "log" "os" ) func main() { const blockSize = 1024 f, err := os.Open("title.png") if err != nil { log.Fatal(err) } defer f.Close() var hashes [][]byte buffer := make([]byte, blockSize) h := sha256.New() fo...
Transform the following Rust implementation into Go, maintaining the same output and logic.
use rug::Integer; fn partitions(n: usize) -> Integer { let mut p = Vec::with_capacity(n + 1); p.push(Integer::from(1)); for i in 1..=n { let mut num = Integer::from(0); let mut k = 1; loop { let mut j = (k * (3 * k - 1)) / 2; if j > i { bre...
package main import ( "fmt" "math/big" "time" ) var p []*big.Int var pd []int func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 } func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] } ...
Rewrite this program in Go while keeping its functionality equivalent to the Rust version.
fn hpo2(n: u32) -> u32 { n & (0xFFFFFFFF - n + 1) } fn lhpo2(n: u32) -> u32 { let mut q: u32 = 0; let mut m: u32 = hpo2(n); while m % 2 == 0 { m >>= 1; q += 1; } q } fn nimsum(x: u32, y: u32) -> u32 { x ^ y } fn nimprod(x: u32, y: u32) -> u32 { if x < 2 || y < 2 { ...
package main import ( "fmt" "strings" ) func hpo2(n uint) uint { return n & (-n) } func lhpo2(n uint) uint { q := uint(0) m := hpo2(n) for m%2 == 0 { m = m >> 1 q++ } return q } func nimsum(x, y uint) uint { return x ^ y } func nimprod(x, y uint) uint { if x < 2 ...
Keep all operations the same but rewrite the snippet in Go.
use image::error::ImageResult; use image::{Rgb, RgbImage}; fn hsv_to_rgb(h: f64, s: f64, v: f64) -> Rgb<u8> { let hp = h / 60.0; let c = s * v; let x = c * (1.0 - (hp % 2.0 - 1.0).abs()); let m = v - c; let mut r = 0.0; let mut g = 0.0; let mut b = 0.0; if hp <= 1.0 { r = c; ...
package main import ( "github.com/fogleman/gg" "math" ) const tau = 2 * math.Pi func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri...
Write the same code in Go as shown below in Rust.
use std::{ collections::BTreeMap, fs::{read_dir, File}, hash::Hasher, io::Read, path::{Path, PathBuf}, }; type Duplicates = BTreeMap<(u64, u64), Vec<PathBuf>>; struct DuplicateFinder { found: Duplicates, min_size: u64, } impl DuplicateFinder { fn search(path: impl AsRef<Path>, min_siz...
package main import ( "fmt" "crypto/md5" "io/ioutil" "log" "os" "path/filepath" "sort" "time" ) type fileData struct { filePath string info os.FileInfo } type hash [16]byte func check(err error) { if err != nil { log.Fatal(err) } } func checksum(filePath ...
Port the following code from Rust to Go with equivalent syntax and logic.
extern crate regex; use std::io; use std::io::prelude::*; use regex::Regex; fn find_bare_lang_tags(input: &str) -> Vec<(Option<String>, i32)> { let mut language_pairs = vec![]; let mut language = None; let mut counter = 0_i32; let header_re = Regex::new(r"==\{\{header\|(?P<lang>[[:alpha:]]+)\}\}==")...
package main import ( "fmt" "io/ioutil" "log" "os" "regexp" "strings" ) type header struct { start, end int lang string } type data struct { count int names *[]string } func newData(count int, name string) *data { return &data{count, &[]string{name}} } var bmap = m...
Convert this Rust snippet to Go and keep its semantics consistent.
fn palindromicgapfuls(digit: u64, count: u64, keep: usize) -> Vec<u64> { let mut palcnt = 0u64; let to_skip = count - keep as u64; let mut gapfuls: Vec<u64> = vec![]; let nn = digit * 11; let (mut power, mut base) = (1, 1u64); loop { power += 1; if power & 1 == 0 { b...
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } ...
Translate this program into Go but keep the logic exactly as in Rust.
fn palindromicgapfuls(digit: u64, count: u64, keep: usize) -> Vec<u64> { let mut palcnt = 0u64; let to_skip = count - keep as u64; let mut gapfuls: Vec<u64> = vec![]; let nn = digit * 11; let (mut power, mut base) = (1, 1u64); loop { power += 1; if power & 1 == 0 { b...
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } ...
Produce a functionally identical Go code for the snippet given in Rust.
fn print_diffs(vec: &[usize]) { for i in 0..vec.len() { if i > 0 { print!(" ({}) ", vec[i] - vec[i - 1]); } print!("{}", vec[i]); } println!(); } fn main() { let limit = 1000000; let mut asc = Vec::new(); let mut desc = Vec::new(); let mut max_asc = Ve...
package main import ( "fmt" "rcu" ) const LIMIT = 999999 var primes = rcu.Primes(LIMIT) func longestSeq(dir string) { pd := 0 longSeqs := [][]int{{2}} currSeq := []int{2} for i := 1; i < len(primes); i++ { d := primes[i] - primes[i-1] if (dir == "ascending" && d <= pd) || (di...
Convert the following code from Rust to Go, ensuring the logic remains intact.
use rug::Integer; fn generate_primes(limit: usize) -> Vec<usize> { let mut sieve = vec![true; limit >> 1]; let mut p = 3; let mut sq = p * p; while sq < limit { if sieve[p >> 1] { let mut q = sq; while q < limit { sieve[q >> 1] = false; ...
package main import ( "fmt" "math/big" "rcu" ) func main() { const LIMIT = 11000 primes := rcu.Primes(LIMIT) facts := make([]*big.Int, LIMIT) facts[0] = big.NewInt(1) for i := int64(1); i < LIMIT; i++ { facts[i] = new(big.Int) facts[i].Mul(facts[i-1], big.NewInt(i)) ...
Please provide an equivalent version of this Rust code in Go.
fn padovan(n: u64, x: u64) -> u64 { if n < 2 { return 0; } match n { 2 if x <= n + 1 => 1, 2 => padovan(n, x - 2) + padovan(n, x - 3), _ if x <= n + 1 => padovan(n - 1, x), _ => ((x - n - 1)..(x - 1)).fold(0, |acc, value| acc + padovan(n, value)), } } fn main() {...
package main import "fmt" func padovanN(n, t int) []int { if n < 2 || t < 3 { ones := make([]int, t) for i := 0; i < t; i++ { ones[i] = 1 } return ones } p := padovanN(n-1, t) for i := n + 1; i < t; i++ { p[i] = 0 for j := i - 2; j >= i-n-1; ...
Convert the following code from Rust to Go, ensuring the logic remains intact.
fn is_prime(n: u32) -> bool { assert!(n < 64); ((1u64 << n) & 0x28208a20a08a28ac) != 0 } fn prime_triangle_row(a: &mut [u32]) -> bool { if a.len() == 2 { return is_prime(a[0] + a[1]); } for i in (1..a.len() - 1).step_by(2) { if is_prime(a[0] + a[i]) { a.swap(i, 1); ...
package main import "fmt" var canFollow [][]bool var arrang []int var bFirst = true var pmap = make(map[int]bool) func init() { for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} { pmap[i] = true } } func ptrs(res, n, done int) int { ad := arrang[done-1] if n-done <= 1 { ...
Produce a language-to-language conversion: from Rust to Go, same semantics.
fn get_digits(mut n: usize) -> [usize; 10] { let mut digits = [0; 10]; while n > 0 { digits[n % 10] += 1; n /= 10; } digits } fn ormiston_pairs() -> impl std::iter::Iterator<Item = (usize, usize)> { let mut digits = [0; 10]; let mut prime = 0; let mut primes = primal::Pri...
package main import ( "fmt" "rcu" ) func main() { const limit = 1e9 primes := rcu.Primes(limit) var orm30 [][2]int j := int(1e5) count := 0 var counts []int for i := 0; i < len(primes)-1; i++ { p1 := primes[i] p2 := primes[i+1] if (p2-p1)%18 != 0 { ...
Maintain the same structure and functionality when rewriting this code in Go.
fn digits(mut n: u32, dig: &mut [u32]) { for i in 0..dig.len() { dig[i] = n % 10; n /= 10; } } fn evalpoly(x: u64, p: &[u32]) -> u64 { let mut result = 0; for y in p.iter().rev() { result *= x; result += *y as u64; } result } fn max_prime_bases(ndig: u32, max...
package main import ( "fmt" "math" "rcu" ) var maxDepth = 6 var maxBase = 36 var c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true) var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var maxStrings [][][]int var mostBases = -1 func maxSlice(a []int) in...
Generate an equivalent Go version of this Rust code.
use std::collections::BTreeMap; struct ErdosSelfridge { primes: Vec<usize>, category: Vec<u32>, } impl ErdosSelfridge { fn new(limit: usize) -> ErdosSelfridge { let mut es = ErdosSelfridge { primes: primal::Primes::all().take(limit).collect(), category: Vec::new(), ...
package main import ( "fmt" "math" "rcu" ) var limit = int(math.Log(1e6) * 1e6 * 1.2) var primes = rcu.Primes(limit) var prevCats = make(map[int]int) func cat(p int) int { if v, ok := prevCats[p]; ok { return v } pf := rcu.PrimeFactors(p + 1) all := true for _, f := range pf...
Preserve the algorithm and functionality while converting the code from Rust to Go.
fn main() { use std::collections::HashMap; let mut primes = primal::Primes::all(); let mut last_prime = primes.next().unwrap(); let mut gap_starts = HashMap::new(); let mut find_gap_start = move |gap: usize| -> usize { if let Some(start) = gap_starts.get(&gap) { return *star...
package main import ( "fmt" "rcu" ) func main() { limit := int(1e9) gapStarts := make(map[int]int) primes := rcu.Primes(limit * 5) for i := 1; i < len(primes); i++ { gap := primes[i] - primes[i-1] if _, ok := gapStarts[gap]; !ok { gapStarts[gap] = primes[i-1] ...
Produce a functionally identical Go code for the snippet given in Rust.
fn day_of_week(year: u32, month: u32, day: u32) -> u32 { const LEAPYEAR_FIRSTDOOMSDAYS: [u32; 12] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]; const NONLEAPYEAR_FIRSTDOOMSDAYS: [u32; 12] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]; assert!(year > 1581 && year < 10000); assert!(month >= 1 && month <= 12); asse...
package main import ( "fmt" "strconv" ) var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} func anchorDay(y int) int { return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7 } func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) } var firs...
Port the following code from Rust to Go with equivalent syntax and logic.
fn day_of_week(year: u32, month: u32, day: u32) -> u32 { const LEAPYEAR_FIRSTDOOMSDAYS: [u32; 12] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]; const NONLEAPYEAR_FIRSTDOOMSDAYS: [u32; 12] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]; assert!(year > 1581 && year < 10000); assert!(month >= 1 && month <= 12); asse...
package main import ( "fmt" "strconv" ) var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} func anchorDay(y int) int { return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7 } func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) } var firs...
Produce a functionally identical Go code for the snippet given in Rust.
fn main() { let mut a: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0], vec![4.0, 1.0, 6.0], vec![7.0, 8.0, 9.0] ]; let mut b: Vec<Vec<f64>> = vec![vec![2.0, -1.0, 0.0], vec![-1.0, 2.0, -1.0]...
package main import "fmt" type vector = []float64 type matrix []vector func (m matrix) inverse() matrix { le := len(m) for _, v := range m { if len(v) != le { panic("Not a square matrix") } } aug := make(matrix, le) for i := 0; i < le; i++ { aug[i] = make(vecto...
Write a version of this Rust function in Go with identical behavior.
fn main() { let mut a: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0], vec![4.0, 1.0, 6.0], vec![7.0, 8.0, 9.0] ]; let mut b: Vec<Vec<f64>> = vec![vec![2.0, -1.0, 0.0], vec![-1.0, 2.0, -1.0]...
package main import "fmt" type vector = []float64 type matrix []vector func (m matrix) inverse() matrix { le := len(m) for _, v := range m { if len(v) != le { panic("Not a square matrix") } } aug := make(matrix, le) for i := 0; i < le; i++ { aug[i] = make(vecto...
Generate a Go translation of this Rust snippet without changing its computational steps.
use std::fmt::Write; use rand::{Rng, distributions::{Distribution, Standard}}; const EMPTY: u8 = b'.'; #[derive(Clone, Debug)] struct Board { grid: [[u8; 8]; 8], } impl Distribution<Board> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Board { let mut board = Board::empty(); ...
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) var grid [8][8]byte func abs(i int) int { if i >= 0 { return i } else { return -i } } func createFen() string { placeKings() placePieces("PPPPPPPP", true) placePieces("pppppppp", true) ...
Produce a functionally identical Go code for the snippet given in Rust.
use svg::node::element::path::Data; use svg::node::element::Path; struct SierpinskiSquareCurve { current_x: f64, current_y: f64, current_angle: i32, line_length: f64, } impl SierpinskiSquareCurve { fn new(x: f64, y: f64, length: f64, angle: i32) -> SierpinskiSquareCurve { SierpinskiSqua...
package main import ( "github.com/fogleman/gg" "github.com/trubitsyn/go-lindenmayer" "log" "math" ) const twoPi = 2 * math.Pi var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h, theta float64 func main() { dc.SetRGB(0, 0, 1) dc.C...
Maintain the same structure and functionality when rewriting this code in Go.
fn perfect_powers(n: u128) -> Vec<u128> { let mut powers = Vec::<u128>::new(); let sqrt = (n as f64).sqrt() as u128; for i in 2..=sqrt { let mut p = i * i; while p < n { powers.push(p); p *= i; } } powers.sort(); powers.dedup(); powers } fn bs...
package main import ( "fmt" "math" "sort" ) func totient(n int) int { tot := n i := 2 for i*i <= n { if n%i == 0 { for n%i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } ...
Generate a Go translation of this Rust snippet without changing its computational steps.
fn perfect_powers(n: u128) -> Vec<u128> { let mut powers = Vec::<u128>::new(); let sqrt = (n as f64).sqrt() as u128; for i in 2..=sqrt { let mut p = i * i; while p < n { powers.push(p); p *= i; } } powers.sort(); powers.dedup(); powers } fn bs...
package main import ( "fmt" "math" "sort" ) func totient(n int) int { tot := n i := 2 for i*i <= n { if n%i == 0 { for n%i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } ...
Write the same algorithm in Go as shown in this Rust implementation.
fn digit_product(base: u32, mut n: u32) -> u32 { let mut product = 1; while n != 0 { product *= n % base; n /= base; } product } fn prime_factor_sum(mut n: u32) -> u32 { let mut sum = 0; while (n & 1) == 0 { sum += 2; n >>= 1; } let mut p = 3; whil...
package main import ( "fmt" "rcu" "strconv" ) func contains(a []int, n int) bool { for _, e := range a { if e == n { return true } } return false } func main() { for b := 2; b <= 36; b++ { if rcu.IsPrime(b) { continue } count...
Translate this program into Go but keep the logic exactly as in Rust.
struct NumberNames { cardinal: &'static str, ordinal: &'static str, } impl NumberNames { fn get_name(&self, ordinal: bool) -> &'static str { if ordinal { return self.ordinal; } self.cardinal } } const SMALL_NAMES: [NumberNames; 20] = [ NumberNames { card...
package main import ( "fmt" "strings" "unicode" ) func main() { f := NewFourIsSeq() fmt.Print("The lengths of the first 201 words are:") for i := 1; i <= 201; i++ { if i%25 == 1 { fmt.Printf("\n%3d: ", i) } _, n := f.WordLen(i) fmt.Printf(" %2d", n) } fmt.Println() fmt.Println("Length of sentence ...
Generate an equivalent Go version of this Rust code.
fn read_numbers<T>() -> Vec<T> where T: std::str::FromStr { use std::io::Write; std::io::stdout().flush().unwrap(); let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.split(" ").map(|word| word.trim().parse::<T>().ok().unwrap()).collect() } fn main() { print!("E...
package bank import ( "bytes" "errors" "fmt" "log" "sort" "sync" ) type PID string type RID string type RMap map[RID]int func (m RMap) String() string { rs := make([]string, len(m)) i := 0 for r := range m { rs[i] = string(r) i++ } sort.Strings(rs) var...
Rewrite this program in Go while keeping its functionality equivalent to the Rust version.
fn sum_of_any_subset(n: isize, f: &[isize]) -> bool { let len = f.len(); if len == 0 { return false; } if f.contains(&n) { return true; } let mut total = 0; for i in 0..len { total += f[i]; } if n == total { return true; } if n > total { ...
package main import ( "fmt" "rcu" ) func powerset(set []int) [][]int { if len(set) == 0 { return [][]int{{}} } head := set[0] tail := set[1:] p1 := powerset(tail) var p2 [][]int for _, s := range powerset(tail) { h := []int{head} h = append(h, s...) ...
Rewrite this program in Go while keeping its functionality equivalent to the Rust version.
use std::fs::File; use std::io::Read; use reqwest::blocking::Client; use reqwest::Identity; fn main() -> std::io::Result<()> { let identity = { let mut buf = Vec::new(); File::open("badssl.com-client.p12")?.read_to_end(&mut buf)?; Identity::from_pkcs12_der(&buf, "badssl...
package main import ( "crypto/tls" "io/ioutil" "log" "net/http" ) func main() { cert, err := tls.LoadX509KeyPair( "./client.local.tld/client.local.tld.crt", "./client.local.tld/client.local.tld.key", ) if err != nil { log.Fatal("Error while loading x509 key pair", err) } tlsConfig := &tls.Config...
Write the same code in Go as shown below in Rust.
use std::collections::{BTreeMap, BTreeSet}; #[derive(Clone, Debug)] pub struct Graph { neighbors: BTreeMap<usize, BTreeSet<usize>>, } impl Graph { pub fn new(size: usize) -> Self { Self { neighbors: (0..size).fold(BTreeMap::new(), |mut acc, x| { acc.insert(x, BTreeSet::new...
package main import ( "fmt" "math/big" ) var g = [][]int{ 0: {1}, 2: {0}, 5: {2, 6}, 6: {5}, 1: {2}, 3: {1, 2, 4}, 4: {5, 3}, 7: {4, 7, 6}, } func main() { tarjan(g, func(c []int) { fmt.Println(c) }) } func tarjan(g [][]int, emit func([]int)) { var indexed, stacked...
Convert this Rust block to Go, preserving its control flow and logic.
fn init_zc() -> Vec<usize> { let mut zc = vec![0; 1000]; zc[0] = 3; for x in 1..=9 { zc[x] = 2; zc[10 * x] = 2; zc[100 * x] = 2; let mut y = 10; while y <= 90 { zc[y + x] = 1; zc[10 * y + x] = 1; zc[10 * (y + x)] = 1; y ...
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" ) func main() { fact := big.NewInt(1) sum := 0.0 first := int64(0) firstRatio := 0.0 fmt.Println("The mean proportion of zero digits in factorials up to the following are:") for n := int64(1); n <= 50000; n++ { ...
Convert this Rust snippet to Go and keep its semantics consistent.
use std::{thread, time}; fn print_rocket(above: u32) { print!( " oo oooo oooo oooo "); for _num in 1..above+1 { println!(" ||"); } } fn main() { for number in (1..6).rev() { print!("\x1B[2J"); println!("{} =>", number); print_rocket(0); let dur = time::Duration::from_millis(10...
package main import ( "fmt" "time" ) const rocket = ` /\ ( ) ( ) /|/\|\ /_||||_\ ` func printRocket(above int) { fmt.Print(rocket) for i := 1; i <= above; i++ { fmt.Println(" ||") } } func cls() { fmt.Print("\x1B[2J") } func main() { for n := 5; n >= 1; n-...
Rewrite the snippet below in D so it works the same as the original PHP code.
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
void main(in string[] args) { import std.stdio, std.algorithm, std.math, std.file; auto data = sort(cast(ubyte[])args[0].read); return data .group .map!(g => g[1] / double(data.length)) .map!(p => -p * p.log2) .sum .writeln; }
Produce a functionally identical D code for the snippet given in PHP.
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
void main(in string[] args) { import std.stdio, std.algorithm, std.math, std.file; auto data = sort(cast(ubyte[])args[0].read); return data .group .map!(g => g[1] / double(data.length)) .map!(p => -p * p.log2) .sum .writeln; }
Change the programming language of this snippet from PHP to D without modifying what it does.
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return...
import std.stdio, std.math, std.algorithm; immutable struct Point { double x, y; } immutable struct Edge { Point a, b; } immutable struct Figure { string name; Edge[] edges; } bool contains(in Figure poly, in Point p) pure nothrow @safe @nogc { static bool raySegI(in Point p, in Edge edge) pure nothro...
Convert this PHP snippet to D and keep its semantics consistent.
class MyException extends Exception { }
import std.stdio; void test1() { throw new Exception("Sample Exception"); } void test2() { try { test1(); } catch (Exception ex) { writeln(ex); throw ex; } } void test3() { try test2(); finally writeln("test3 finally"); } void test4() { scope(exit) writeln("Te...
Convert this PHP block to D, preserving its control flow and logic.
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwi...
import std.stdio, std.random, std.math, std.algorithm, std.range, std.typetuple; void main() { void op(char c)() { if (stack.length < 2) throw new Exception("Wrong expression."); stack[$ - 2] = mixin("stack[$ - 2]" ~ c ~ "stack[$ - 1]"); stack.popBack(); } const ...
Convert the following code from PHP to D, ensuring the logic remains intact.
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwi...
import std.stdio, std.random, std.math, std.algorithm, std.range, std.typetuple; void main() { void op(char c)() { if (stack.length < 2) throw new Exception("Wrong expression."); stack[$ - 2] = mixin("stack[$ - 2]" ~ c ~ "stack[$ - 1]"); stack.popBack(); } const ...
Generate an equivalent D version of this PHP code.
define("PI", 3.14159265358); define("MSG", "Hello World");
import std.random; int sqr(int x) { return x ^^ 2; } enum int x = 5; enum y = sqr(5); enum MyEnum { A, B, C } immutable double pi = 3.1415; immutable int z; static this() { z = uniform(0, 100); } class Test1 { immutable int w; this() { w = uniform(0, 100); } } void foo(con...
Port the following code from PHP to D with equivalent syntax and logic.
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
void main() { import std.stdio, std.algorithm; "the three truths".count("th").writeln; "ababababab".count("abab").writeln; }
Convert the following code from PHP to D, ensuring the logic remains intact.
<?php header("Content-type: image/png"); $width = 512; $height = 512; $img = imagecreatetruecolor($width,$height); $bg = imagecolorallocate($img,255,255,255); imagefilledrectangle($img, 0, 0, $width, $width, $bg); $depth = 8; function drawTree($x1, $y1, $angle, $depth){ global $img; if ($depth != 0)...
import std.stdio, std.math; enum width = 1000, height = 1000; enum length = 400; enum scale = 6.0 / 10; void tree(in double x, in double y, in double length, in double angle) { if (length < 1) return; immutable x2 = x + length * angle.cos; immutable y2 = y + length * a...
Keep all operations the same but rewrite the snippet in D.
<?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo ""; $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $player ....
import std.stdio, std.random, std.string, std.conv, std.array, std.typecons; enum Choice { rock, paper, scissors } bool beats(in Choice c1, in Choice c2) pure nothrow @safe @nogc { with (Choice) return (c1 == paper && c2 == rock) || (c1 == scissors && c2 == paper) || ...
Change the programming language of this snippet from PHP to D without modifying what it does.
<?php $conf = file_get_contents('parse-conf-file.txt'); $conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf); $conf = preg_replace_callback( '/^([a-z]+)\s*=((?=.*\,.*).*)$/mi', function ($matches) { $r = ''; foreach (explode(',', $matches[2]) AS $val) { $r .= $matches[1] . '[]...
import std.stdio, std.string, std.conv, std.regex, std.getopt; enum VarName(alias var) = var.stringof; void setOpt(alias Var)(in string line) { auto m = match(line, regex(`^(?i)` ~ VarName!Var ~ `(?-i)(\s*=?\s+(.*))?`)); if (!m.empty) { static if (is(typeof(Var) == string[])) Var = m.capt...
Write the same code in D as shown below in PHP.
<?php $dog = 'Benjamin'; $Dog = 'Samba'; $DOG = 'Bernie'; echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n"; function DOG() { return 'Bernie'; } echo 'There is only 1 dog named ' . dog() . "\n";
import std.stdio; void main() { string dog = "Benjamin"; string Dog = "Samba"; string DOG = "Bernie"; writefln("There are three dogs named ", dog, ", ", Dog, ", and ", DOG, "'"); }
Ensure the translated D code behaves exactly like the original PHP snippet.
function stoogeSort(&$arr, $i, $j) { if($arr[$j] < $arr[$i]) { list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); } if(($j - $i) > 1) { $t = ($j - $i + 1) / 3; stoogesort($arr, $i, $j - $t); stoogesort($arr, $i + $t, $j); stoogesort($arr, $i, $j - $t); } }
import std.stdio, std.algorithm, std.array; void stoogeSort(T)(T[] seq) pure nothrow { if (seq.back < seq.front) swap(seq.front, seq.back); if (seq.length > 2) { immutable m = seq.length / 3; seq[0 .. $ - m].stoogeSort(); seq[m .. $].stoogeSort(); seq[0 .. $ - m].stooge...
Convert this PHP block to D, preserving its control flow and logic.
function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $ar...
import std.stdio: writeln; void shellSort(T)(T[] seq) pure nothrow { int inc = seq.length / 2; while (inc) { foreach (ref i, el; seq) { while (i >= inc && seq[i - inc] > el) { seq[i] = seq[i - inc]; i -= inc; } seq[i] = el; } ...
Port the provided PHP code into D while preserving the original functionality.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOC...
void main() { import std.stdio, std.file, std.string; auto file_lines = readText("input.txt").splitLines(); writeln((file_lines.length > 6) ? file_lines[6] : "line not found"); }
Change the following PHP code into D without altering its purpose.
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOC...
void main() { import std.stdio, std.file, std.string; auto file_lines = readText("input.txt").splitLines(); writeln((file_lines.length > 6) ? file_lines[6] : "line not found"); }
Translate this program into D but keep the logic exactly as in PHP.
<?php $s = 'http://foo/bar/'; $s = rawurlencode($s); ?>
import std.stdio, std.uri; void main() { writeln(encodeComponent("http: }