Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite the snippet below in D so it works the same as the original Go code.
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...
import std.algorithm; import std.bigint; import std.exception; import std.range; import std.stdio; BigInt[] primes; int[] smallPrimes; bool isPrime(BigInt value) { if (value < 2) return false; if (value % 2 == 0) return value == 2; if (value % 3 == 0) return value == 3; if (value % 5 == 0) return va...
Maintain the same structure and functionality when rewriting this code in D.
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...
import std.array : array; import std.range : take; import std.stdio; bool isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n % d == 0) return false; d += 2; if (n % d == 0) return false...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" "strings" ) var ( dig = [3]string{"00", "01", "10"} dig1 = [3]string{"", "1", "10"} ) type Zeckendorf struct{ dVal, dLen int } func NewZeck(x string) *Zeckendorf { z := new(Zeckendorf) if x == "" { x = "0" } q := 1 i := len(x) - 1 z.dLen =...
import std.stdio; int inv(int a) { return a ^ -1; } class Zeckendorf { private int dVal; private int dLen; private void a(int n) { auto i = n; while (true) { if (dLen < i) dLen = i; auto j = (dVal >> (i * 2)) & 3; switch(j) { case 0:...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } ...
import std.bigint; import std.functional; import std.stdio; alias sterling1 = memoize!sterling1Impl; BigInt sterling1Impl(int n, int k) { if (n == 0 && k == 0) { return BigInt(1); } if (n > 0 && k == 0) { return BigInt(0); } if (k > n) { return BigInt(0); } return st...
Keep all operations the same but rewrite the snippet in D.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } ...
import std.bigint; import std.functional; import std.stdio; alias sterling1 = memoize!sterling1Impl; BigInt sterling1Impl(int n, int k) { if (n == 0 && k == 0) { return BigInt(1); } if (n > 0 && k == 0) { return BigInt(0); } if (k > n) { return BigInt(0); } return st...
Convert this Go block to D, preserving its control flow and logic.
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 -...
import std.algorithm; import std.exception : enforce; import std.math; import std.stdio; void main() { creal[] pointList = [ 0.0 + 0.0i, 1.0 + 0.1i, 2.0 + -0.1i, 3.0 + 5.0i, 4.0 + 6.0i, 5.0 + 7.0i, 6.0 + 8.1i, 7.0 + 9.0i, 8.0 + 9.0i, ...
Please provide an equivalent version of this Go code in D.
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 -...
import std.algorithm; import std.exception : enforce; import std.math; import std.stdio; void main() { creal[] pointList = [ 0.0 + 0.0i, 1.0 + 0.1i, 2.0 + -0.1i, 3.0 + 5.0i, 4.0 + 6.0i, 5.0 + 7.0i, 6.0 + 8.1i, 7.0 + 9.0i, 8.0 + 9.0i, ...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "image" "image/color" "image/jpeg" "log" "math" "os" "golang.org/x/image/draw" ) func scale(dst draw.Image, src image.Image) { sr := src.Bounds() dr := dst.Bounds() mx := float64(sr.Dx()-1) / float64(dr.Dx()) my := float64(sr.Dy()-1) / float64(dr.Dy()) for x := dr.Min.X; x < dr.Max....
import grayscale_image; Image!Gray rescaleGray(in Image!Gray src, in float scaleX, in float scaleY) pure nothrow @safe in { assert(src !is null, "Input Image is null."); assert(src.nx > 1 && src.ny > 1, "Minimal input image size is 2x2."); assert(cast(uint)(src.nx * scaleX) > 0, "Output image width must b...
Change the programming language of this snippet from Go to D without modifying what it does.
package main import ( "image" "image/color" "image/jpeg" "log" "math" "os" "golang.org/x/image/draw" ) func scale(dst draw.Image, src image.Image) { sr := src.Bounds() dr := dst.Bounds() mx := float64(sr.Dx()-1) / float64(dr.Dx()) my := float64(sr.Dy()-1) / float64(dr.Dy()) for x := dr.Min.X; x < dr.Max....
import grayscale_image; Image!Gray rescaleGray(in Image!Gray src, in float scaleX, in float scaleY) pure nothrow @safe in { assert(src !is null, "Input Image is null."); assert(src.nx > 1 && src.ny > 1, "Minimal input image size is 2x2."); assert(cast(uint)(src.nx * scaleX) > 0, "Output image width must b...
Generate a D translation of this Go snippet without changing its computational steps.
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...
import std.stdio; void main() { writeln(VectorReal(5, 7) + VectorReal(2, 3)); writeln(VectorReal(5, 7) - VectorReal(2, 3)); writeln(VectorReal(5, 7) * 11); writeln(VectorReal(5, 7) / 2); } alias VectorReal = Vector!real; struct Vector(T) { private T x, y; this(T x, T y) { this.x = x; ...
Write the same code in D as shown below in Go.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { r...
import std.stdio, std.math, std.string; enum bCoeff = 7; struct Pt { double x, y; @property static Pt zero() pure nothrow @nogc @safe { return Pt(double.infinity, double.infinity); } @property bool isZero() const pure nothrow @nogc @safe { return x > 1e20 || x < -1e20; } @pr...
Port the following code from Go to D with equivalent syntax and logic.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { r...
import std.stdio, std.math, std.string; enum bCoeff = 7; struct Pt { double x, y; @property static Pt zero() pure nothrow @nogc @safe { return Pt(double.infinity, double.infinity); } @property bool isZero() const pure nothrow @nogc @safe { return x > 1e20 || x < -1e20; } @pr...
Convert this Go snippet to D and keep its semantics consistent.
package main import ( "fmt" "math" ) type cheb struct { c []float64 min, max float64 } func main() { fn := math.Cos c := newCheb(0, 1, 10, 10, fn) fmt.Println("coefficients:") for _, c := range c.c { fmt.Printf("% .15f\n", c) } fmt.Println("\nx computed a...
import std.math: PI, cos; real map(in real x, in real min_x, in real max_x, in real min_to, in real max_to) pure nothrow @safe @nogc { return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to; } void chebyshevCoef(size_t N)(in real function(in real) pure nothrow @safe @nogc func, ...
Produce a language-to-language conversion: from Go to D, same semantics.
package main import ( "fmt" "math" ) type cheb struct { c []float64 min, max float64 } func main() { fn := math.Cos c := newCheb(0, 1, 10, 10, fn) fmt.Println("coefficients:") for _, c := range c.c { fmt.Printf("% .15f\n", c) } fmt.Println("\nx computed a...
import std.math: PI, cos; real map(in real x, in real min_x, in real max_x, in real min_to, in real max_to) pure nothrow @safe @nogc { return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to; } void chebyshevCoef(size_t N)(in real function(in real) pure nothrow @safe @nogc func, ...
Change the programming language of this snippet from Go to D without modifying what it does.
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...
import std.algorithm.iteration; import std.algorithm.mutation; import std.algorithm.searching; import std.algorithm.sorting; import std.array; import std.stdio; import std.string; immutable STX = 0x02; immutable ETX = 0x03; string bwt(string s) { if (s.any!"a==0x02 || a==0x03") { throw new Exception("Inpu...
Generate an equivalent D version of this Go code.
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...
import std.algorithm.iteration; import std.algorithm.mutation; import std.algorithm.searching; import std.algorithm.sorting; import std.array; import std.stdio; import std.string; immutable STX = 0x02; immutable ETX = 0x03; string bwt(string s) { if (s.any!"a==0x02 || a==0x03") { throw new Exception("Inpu...
Translate the given Go code snippet into D without altering its behavior.
package main import "fmt" type vList struct { base *vSeg offset int } type vSeg struct { next *vSeg ele []vEle } type vEle string func (v vList) index(i int) (r vEle) { if i >= 0 { i += v.offset for sg := v.base; sg != nil; sg = sg.next { if i < len(sg.ele...
import core.stdc.stdio: fprintf, stderr; import core.stdc.stdlib: malloc, free, abort; struct VList(T) { static struct Sublist { Sublist* next; T[0] dataArr0; @property data() inout pure nothrow { return dataArr0.ptr; } static typeof(this)* alloc(in size_t le...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import "fmt" type vList struct { base *vSeg offset int } type vSeg struct { next *vSeg ele []vEle } type vEle string func (v vList) index(i int) (r vEle) { if i >= 0 { i += v.offset for sg := v.base; sg != nil; sg = sg.next { if i < len(sg.ele...
import core.stdc.stdio: fprintf, stderr; import core.stdc.stdlib: malloc, free, abort; struct VList(T) { static struct Sublist { Sublist* next; T[0] dataArr0; @property data() inout pure nothrow { return dataArr0.ptr; } static typeof(this)* alloc(in size_t le...
Translate the given Go code snippet into D without altering its behavior.
package main import ( "fmt" "math/rand" "time" ) 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 riffle(deck []int, iterations int) []int { le := len(deck) pile := make([]int, le) copy(pile, deck) for i := 0; i < i...
import std.container.array; import std.random; import std.range; import std.stdio; auto riffleShuffle(T)(T[] list, int flips) { auto newList = Array!T(list); for (int n=0; n<flips; n++) { int cutPoint = newList.length / 2 + choice([-1, 1]) * uniform!"[]"(0, newList.length...
Write the same code in D as shown below in Go.
package main import ( "fmt" "math/rand" "time" ) 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 riffle(deck []int, iterations int) []int { le := len(deck) pile := make([]int, le) copy(pile, deck) for i := 0; i < i...
import std.container.array; import std.random; import std.range; import std.stdio; auto riffleShuffle(T)(T[] list, int flips) { auto newList = Array!T(list); for (int n=0; n<flips; n++) { int cutPoint = newList.length / 2 + choice([-1, 1]) * uniform!"[]"(0, newList.length...
Write the same algorithm in D as shown in this Go implementation.
package main import ( "fmt" "math/big" ) func bernoulli(n uint) *big.Rat { a := make([]big.Rat, n+1) z := new(big.Rat) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) ...
import std.algorithm : fold; import std.conv : to; import std.exception : enforce; import std.format : formattedWrite; import std.numeric : cmp, gcd; import std.range : iota; import std.stdio; import std.traits; auto abs(T)(T val) if (isNumeric!T) { if (val < 0) { return -val; } return val; } stru...
Change the programming language of this snippet from Go to D without modifying what it does.
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
import std.stdio, std.bigint; enum uint nMax = 250; enum uint nBranches = 4; __gshared BigInt[nMax + 1] rooted = [1.BigInt, 1.BigInt ], unrooted = [1.BigInt, 1.BigInt ]; void tree(in uint br, in uint n, in uint l, in uint inSum, in BigInt cnt) nothrow { __gshared static BigIn...
Write the same code in D as shown below in Go.
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
import std.stdio, std.bigint; enum uint nMax = 250; enum uint nBranches = 4; __gshared BigInt[nMax + 1] rooted = [1.BigInt, 1.BigInt ], unrooted = [1.BigInt, 1.BigInt ]; void tree(in uint br, in uint n, in uint l, in uint inSum, in BigInt cnt) nothrow { __gshared static BigIn...
Port the following code from Go to D with equivalent syntax and logic.
package main import ( "fmt" "strings" ) type pair struct{ first, second string } var ( fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}} lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND"...
import std.stdio, std.regex, std.algorithm, std.range, std.string; string replaceAt(in string text, in uint pos, in string[] fromList, in string[] toList) pure @safe { foreach (const f, const t; zip(fromList, toList)) if (text[pos .. $].startsWith(f)) return [text[0 .. pos], t...
Port the provided Go code into D while preserving the original functionality.
package main import ( "fmt" "strings" ) type pair struct{ first, second string } var ( fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}} lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND"...
import std.stdio, std.regex, std.algorithm, std.range, std.string; string replaceAt(in string text, in uint pos, in string[] fromList, in string[] toList) pure @safe { foreach (const f, const t; zip(fromList, toList)) if (text[pos .. $].startsWith(f)) return [text[0 .. pos], t...
Convert this Go snippet to D and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func bernoulli(z *big.Rat, n int64) *big.Rat { if z == nil { z = new(big.Rat) } a := make([]big.Rat, n+1) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) } } return z.Set...
import std.algorithm : fold; import std.exception : enforce; import std.format : formattedWrite; import std.numeric : cmp, gcd; import std.range : iota; import std.stdio; import std.traits; auto abs(T)(T val) if (isNumeric!T) { if (val < 0) { return -val; } return val; } struct Frac { long num...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client.Co...
import openldap; import std.stdio; void main() { auto ldap = LDAP("ldap: auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test")); writeln("Found dn: %s", r[0].dn); foreach(k, v; r[0].entry) writeln("%s = %s", k, v); int b = ldap.bind_s(r[0].dn, "password"...
Generate an equivalent D version of this Go code.
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 } } ...
import std.algorithm; import std.range; import std.stdio; import std.typecons; alias Transition = Tuple!(int, int); bool isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; int d = 5; while (d*d <= n) { if (n%d == 0) return false; ...
Port the provided Go code into D while preserving the original functionality.
package main import ( "fmt" "log" "os" "strconv" ) type tree uint64 var ( list []tree offset = [32]uint{1: 1} ) func add(t tree) { list = append(list, 1|t<<1) } func show(t tree, l uint) { for ; l > 0; t >>= 1 { l-- var paren byte if (t & 1) != 0 { ...
import std.stdio, std.conv; alias Tree = ulong, TreeList = Tree[], Offset = uint[32]; void listTees(in uint n, in ref Offset offset, in TreeList list) nothrow @nogc @safe { static void show(in Tree t, in uint len) nothrow @nogc @safe { foreach (immutable i; 0 .. len) putchar(t & (2...
Rewrite the snippet below in D so it works the same as the original Go code.
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...
import std.stdio, std.range, std.typecons; struct CellularRNG { private uint current; private immutable uint rule; private ulong state; this(in ulong state_, in uint rule_) pure nothrow @safe @nogc { this.state = state_; this.rule = rule_; popFront; } public enum bool ...
Convert this Go snippet to D and keep its semantics consistent.
package main import ( "fmt" "log" "os" "strconv" "strings" ) const luckySize = 60000 var luckyOdd = make([]int, luckySize) var luckyEven = make([]int, luckySize) func init() { for i := 0; i < luckySize; i++ { luckyOdd[i] = i*2 + 1 luckyEven[i] = i*2 + 2 } } func filterLu...
import std.algorithm; import std.concurrency; import std.conv; import std.getopt; import std.range; import std.stdio; auto lucky(bool even, int nmax=200_000) { import std.container.array; int start = even ? 2 : 1; return new Generator!int({ auto ln = make!(Array!int)(iota(start,nmax,2)); ...
Generate a D translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" "strconv" "strings" ) const ( twoI = 2.0i invTwoI = 1.0 / twoI ) type quaterImaginary struct { b2i string } func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i...
import std.algorithm; import std.array; import std.complex; import std.conv; import std.format; import std.math; import std.stdio; import std.string; Complex!double inv(Complex!double v) { auto denom = v.re*v.re + v.im*v.im; return v.conj / denom; } QuaterImaginary toQuaterImaginary(Complex!double v) { if...
Generate an equivalent D version of this Go code.
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 =...
import std.stdio, std.random, std.math, std.range, std.algorithm, statistics_basic; struct Normals { double mu, sigma; double[2] state; size_t index = state.length; enum empty = false; void popFront() pure nothrow { index++; } @property double front() { if (index >= state.lengt...
Preserve the algorithm and functionality while converting the code from Go to D.
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 5 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 461, 277, 356, 488, 393 }; int demand[N_COLS] = { 278, 60, 461, 116, 1060 }; int costs[N_ROWS][N_COLS] = { { 46, 74, 9, 28, 99 }, { 12, 75, 6, 36, 48 }, ...
void main() { import std.stdio, std.string, std.algorithm, std.range; enum K { A, B, C, D, E, X, Y, Z, W } immutable int[K][K] costs = cast() [K.W: [K.A: 16, K.B: 16, K.C: 13, K.D: 22, K.E: 17], K.X: [K.A: 14, K.B: 14, K.C: 13, K.D: 19, K.E: 15], K.Y: [K.A: 19, K.B: 19, K.C: 20,...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import ( "fmt" "github.com/shabbyrobe/go-num" "strings" "time" ) func b10(n int64) { if n == 1 { fmt.Printf("%4d: %28s  %-24d\n", 1, "1", 1) return } n1 := n + 1 pow := make([]int64, n1) val := make([]int64, n1) var count, ten, x int64 = 0, 1, 1 ...
import std.algorithm; import std.array; import std.bigint; import std.range; import std.stdio; void main() { foreach (n; chain(iota(1, 11), iota(95, 106), only(297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878))) { auto result = getA004290(n); writefln("A004290(%d) = %s = %s * ...
Rewrite the snippet below in D so it works the same as the original Go code.
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] =...
import std.exception; import std.stdio; void main() { int n = 6; foreach (row; magicSquareSinglyEven(n)) { foreach (x; row) { writef("%2s ", x); } writeln(); } writeln("\nMagic constant: ", (n * n + 1) * n / 2); } int[][] magicSquareOdd(const int n) { enforce(n ...
Produce a functionally identical D code for the snippet given in Go.
package main import "fmt" func divisors(n int) []int { divs := []int{1} divs2 := []int{} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs2 = append(divs2, j) } } } for i := l...
import std.algorithm; import std.array; import std.stdio; int[] divisors(int n) { int[] divs = [1]; int[] divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs ~= i; if (i != j) { divs2 ~= j; } } }...
Write a version of this Go function in D with identical behavior.
package main import ( "fmt" "log" "math/big" "strings" ) type result struct { name string size int start int end int } func (r result) String() string { return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end) } func validate(diagram string) []string { ...
string makeStructFromDiagram(in string rawDiagram) pure @safe { import std.conv: text; import std.format: format; import std.string: strip, splitLines, indexOf; import std.array: empty, popFront; static void commitCurrent(ref uint anonCount, ref uint totalBits, ...
Please provide an equivalent version of this Go code in D.
package main import "fmt" const ( empty = iota black white ) const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' ) type position struct{ i, j int } func iabs(i int) int { if i < 0 { return -i } return i } func place(m, n int, pBlackQueens, pWhiteQueens *...
import std.array; import std.math; import std.stdio; import std.typecons; enum Piece { empty, black, white, } alias position = Tuple!(int, "i", int, "j"); bool place(int m, int n, ref position[] pBlackQueens, ref position[] pWhiteQueens) { if (m == 0) { return true; } bool placingBlac...
Translate this program into D but keep the logic exactly as in Go.
package main import ( "fmt" "math" "math/big" ) var bi = new(big.Int) func isPrime(n int) bool { bi.SetUint64(uint64(n)) return bi.ProbablyPrime(0) } func generateSmallPrimes(n int) []int { primes := make([]int, n) primes[0] = 2 for i, count := 3, 1; count < n; i += 2 { if is...
import std.bigint; import std.math; import std.stdio; bool isPrime(long test) { if (test == 2) { return true; } if (test % 2 == 0) { return false; } for (long d = 3 ; d * d <= test; d += 2) { if (test % d == 0) { return false; } } return true; } ...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" "os" ) type vector struct{ x, y, z float64 } func (v vector) add(w vector) vector { return vector{v.x + w.x, v.y + w.y, v.z + w.z} } func (v vector) sub(w vector) vector { return vector{v.x - w.x, v.y - w.y, v.z - w.z} } func (v vector) scale(m float64) vector...
import std.algorithm; import std.array; import std.conv; import std.file; import std.math : sqrt; import std.stdio; import std.string; void unpack(T)(T t) { } void unpack(T, U ...)(T t, ref U u) in { assert(t.length == u.length); } body { if (t.length > 0) { u[0] = t[0]; unpack(t[1..$], u[1...
Preserve the algorithm and functionality while converting the code from Go to D.
package main import ( "bufio" "fmt" "log" "os" "strings" ) type vf = func() var history []string func hello() { fmt.Println("Hello World!") history = append(history, "hello") } func hist() { if len(history) == 0 { fmt.Println("No history") } else { for _, cmd := ...
module readline_interface; import std.stdio; import std.string; alias VOIDF = void function(); void hello() { writeln("Hello World!"); histArr ~= __FUNCTION__; } string[] histArr; void hist() { if (histArr.length == 0) { writeln("No history"); } else { foreach(cmd; histArr) { ...
Generate an equivalent D version of this Go code.
package main import "fmt" type Ctrl int const ( nul Ctrl = iota soh stx etx eot enq ack bel bs ht lf vt ff cr so si dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us space ...
import std.ascii.ControlChar;
Produce a language-to-language conversion: from Go to D, same semantics.
package main import "fmt" var example []int 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 checkSeq(pos, n, minLen int, seq []int) (int, int) { switch { case pos > minLen || seq[0] > n: return minLen, 0 case seq[0] == n:...
import std.stdio; import std.typecons; alias Pair = Tuple!(int, int); auto check_seq(int pos, int[] seq, int n, int min_len) { if (pos>min_len || seq[0]>n) return Pair(min_len, 0); else if (seq[0] == n) return Pair( pos, 1); else if (pos<min_len) return try_perm(0, pos, seq, n, min_len); ...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import ( "fmt" "html" "io/ioutil" "net/http" "regexp" "strings" "time" ) func main() { ex := `<li><a href="/wiki/(.*?)"` re := regexp.MustCompile(ex) page := "http: resp, _ := http.Get(page) body, _ := ioutil.ReadAll(resp.Body) matches := re.FindAll...
import std.algorithm; import std.net.curl; import std.range; import std.regex; import std.stdio; import std.string; void process(string base, string task) { auto re2 = ctRegex!`</?[^>]*>`; auto page = base ~ task; auto content = get(page); string prefix = `using any language you may know.</div>`; ...
Transform the following Go implementation into D, maintaining the same output and logic.
package main import ( "fmt" "io/ioutil" "log" "strconv" "strings" ) type userInput struct{ formFeed, lineFeed, tab, space int } func getUserInput() []userInput { h := "0 18 0 0 0 68 0 1 0 100 0 32 0 114 0 45 0 38 0 26 0 16 0 21 0 17 0 59 0 11 " + "0 29 0 102 0 0 0 10 0 50 0 39 0 42 0 ...
import std.algorithm; import std.array; import std.conv; import std.file; import std.range; import std.stdio; struct UserInput { char formFeed; char lineFeed; char tab; char space; this(string ff, string lf, string tb, string sp) { formFeed = cast(char) ff.to!int; lineFeed = cast(c...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" "math/big" "math/rand" "time" ) type mont struct { n uint m *big.Int r2 *big.Int } func newMont(m *big.Int) *mont { if m.Bit(0) != 1 { return nil } n := uint(m.BitLen()) x := big.NewInt(1) x.Sub(x.Lsh(x, n), m) return ...
import std.bigint; import std.stdio; int bitLength(BigInt v) { if (v < 0) { v *= -1; } int result = 0; while (v > 0) { v >>= 1; result++; } return result; } BigInt modPow(BigInt b, BigInt e, BigInt n) { if (n == 1) return BigInt(0); BigInt result = 1; b =...
Produce a functionally identical D code for the snippet given in Go.
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...
import std.conv; import std.range; import std.stdio; import std.string; enum State { READY, WAITING, EXIT, DISPENSE, REFUNDING, } void fsm() { writeln("PLease enter your option when prompted"); writeln("(any characters after the first will be ignored)"); auto state = State.READY; s...
Transform the following Go implementation into D, maintaining the same output and logic.
package main import ( "fmt" "strings" ) func main() { level := ` ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######` fmt.Printf("level:%s\n", level) fmt.Printf("solution:\n%s\n", solve(level)) } func solve(board string) string { buffer = make([]byte, len(board)) width ...
import std.string, std.typecons, std.exception, std.algorithm; import queue_usage2; const struct Board { private enum El { floor = ' ', wall = '#', goal = '.', box = '$', player = '@', boxOnGoal='*' } private alias CTable = string; private immutable size_t ncols; private immutabl...
Translate this program into D but keep the logic exactly as in Go.
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...
import std.algorithm; import std.stdio; int[] getDivisors(int n) { auto divs = [1, n]; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { divs ~= i; int j = n / i; if (i != j) { divs ~= j; } } } return divs; } bool isPa...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import ( "fmt" "regexp" "strings" ) var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func commatiz...
import std.stdio, std.regex, std.range; auto commatize(in char[] txt, in uint start=0, in uint step=3, in string ins=",") @safe in { assert(step > 0); } body { if (start > txt.length || step > txt.length) return txt; enum decFloField = ctRegex!("[0-9]*\\.[0-9]+|[0-9]+"); auto mat...
Write the same algorithm in D as shown in this Go implementation.
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree {...
import std.stdio; struct Node { string sub = ""; int[] ch; this(string sub, int[] children ...) { this.sub = sub; ch = children; } } struct SuffixTree { Node[] nodes; this(string str) { nodes ~= Node(); for (int i=0; i<str.length; ++i) { a...
Write the same algorithm in D as shown in this Go implementation.
package main import "fmt" func main() { vis(buildTree("banana$")) } type tree []node type node struct { sub string ch []int } func buildTree(s string) tree { t := tree{node{}} for i := range s { t = t.addSuffix(s[i:]) } return t } func (t tree) addSuffix(suf string) tree {...
import std.stdio; struct Node { string sub = ""; int[] ch; this(string sub, int[] children ...) { this.sub = sub; ch = children; } } struct SuffixTree { Node[] nodes; this(string str) { nodes ~= Node(); for (int i=0; i<str.length; ++i) { a...
Rewrite the snippet below in D so it works the same as the original Go code.
package main import ( "fmt" "image" "reflect" ) type t struct { X int next *t } func main() { report(t{}) report(image.Point{}) } func report(x interface{}) { t := reflect.TypeOf(x) n := t.NumField() fmt.Printf("Type %v has %d fields:\n", t, n) fmt.Println("Name Type Exported") for i := 0; i...
import std.stdio; struct S { bool b; void foo() {} private void bar() {} } class C { bool b; void foo() {} private void bar() {} } void printProperties(T)() if (is(T == class) || is(T == struct)) { import std.stdio; import std.traits; writeln("Properties of ", T.stringof, ':');...
Convert the following code from Go to D, ensuring the logic remains intact.
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {le...
import std.array; import std.stdio; void main() { auto tree = eertree("eertree"); writeln(subPalindromes(tree)); } struct Node { int length; int[char] edges; int suffix; } const evenRoot = 0; const oddRoot = 1; Node[] eertree(string s) { Node[] tree = [ Node(0, null, oddRoot), ...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import "fmt" func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) } type edges map[byte]int type node struct { length int edges suffix int } const evenRoot = 0 const oddRoot = 1 func eertree(s []byte) []node { tree := []node{ evenRoot: {le...
import std.array; import std.stdio; void main() { auto tree = eertree("eertree"); writeln(subPalindromes(tree)); } struct Node { int length; int[char] edges; int suffix; } const evenRoot = 0; const oddRoot = 1; Node[] eertree(string s) { Node[] tree = [ Node(0, null, oddRoot), ...
Produce a language-to-language conversion: from Go to D, same semantics.
package main import ( "fmt" "log" "math/big" "strings" ) const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" var big0 = new(big.Int) var big58 = big.NewInt(58) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { ...
import std.bigint; import std.stdio; void main() { report("25420294593250030202636073700053352635053786165627414518"); report(0x61); report(0x626262); report(0x636363); report("0x73696d706c792061206c6f6e6720737472696e67"); report(0x516b6fcd0f); report("0xbf4f89001e670274dd"); report(0x5...
Convert the following code from Go to D, ensuring the logic remains intact.
package main import ( "fmt" "log" "math/big" "strings" ) const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" var big0 = new(big.Int) var big58 = big.NewInt(58) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { ...
import std.bigint; import std.stdio; void main() { report("25420294593250030202636073700053352635053786165627414518"); report(0x61); report(0x626262); report(0x636363); report("0x73696d706c792061206c6f6e6720737472696e67"); report(0x516b6fcd0f); report("0xbf4f89001e670274dd"); report(0x5...
Write a version of this Go function in D with identical behavior.
package main import ( "fmt" "sort" ) type matrix [][]int func dList(n, start int) (r matrix) { start-- a := make([]int, n) for i := range a { a[i] = i } a[0], a[start] = start, a[0] sort.Ints(a[1:]) first := a[1] var recurse func(last int) recurse = func(las...
import std.algorithm; import std.array; import std.range; import std.stdio; alias matrix = int[][]; auto dList(int n, int start) { start--; auto a = iota(0, n).array; a[start] = a[0]; a[0] = start; sort(a[1..$]); auto first = a[1]; matrix r; void recurse(int last) { if...
Keep all operations the same but rewrite the snippet in D.
package main import "fmt" var g = [][]int{ 0: {1}, 1: {2}, 2: {0}, 3: {1, 2, 4}, 4: {3, 5}, 5: {2, 6}, 6: {5}, 7: {4, 6, 7}, } func main() { fmt.Println(kosaraju(g)) } func kosaraju(g [][]int) []int { vis := make([]bool, len(g)) L := make([]int, len(g)) x := len(...
import std.container.array; import std.stdio; auto g = [ [1], [2], [0], [1, 2, 4], [3, 5], [2, 6], [5], [4, 6, 7], ]; int[] kosaraju(int[][] g) { auto size = g.length; Array!bool vis; vis.length = size; int[] l; l.length = size; auto x = siz...
Write the same algorithm in D as shown in this Go implementation.
package main import ( "bufio" "fmt" "log" "math/rand" "os" "regexp" "strings" "time" ) var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}} const ( nRows = 10 nCols = nRows gridSize = nRows * nCols minWords = 25 ) var ( re...
import std.random : Random, uniform, randomShuffle; import std.stdio; immutable int[][] dirs = [ [1, 0], [ 0, 1], [ 1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1] ]; enum nRows = 10; enum nCols = 10; enum gridSize = nRows * nCols; enum minWords = 25; auto rnd = Random(); class Grid { ...
Change the following Go code into D without altering its purpose.
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...
import std.file; import std.random; import std.range; import std.stdio; import std.string; string markov(string filePath, int keySize, int outputSize) { if (keySize < 1) throw new Exception("Key size can't be less than 1"); auto words = filePath.readText().chomp.split; if (outputSize < keySize || words.len...
Translate this program into D but keep the logic exactly as in Go.
package main import ( "fmt" "math/big" ) func cumulative_freq(freq map[byte]int64) map[byte]int64 { total := int64(0) cf := make(map[byte]int64) for i := 0; i < 256; i++ { b := byte(i) if v, ok := freq[b]; ok { cf[b] = total total += v } } re...
import std.array; import std.bigint; import std.stdio; import std.typecons; BigInt bigPow(BigInt b, BigInt e) { if (e == 0) { return BigInt(1); } BigInt result = 1; while (e > 1) { if (e % 2 == 0) { b *= b; e /= 2; } else { result *= b; ...
Please provide an equivalent version of this Go code in D.
package main import ( "fmt" "math/rand" "time" ) type vector []float64 func e(n uint) vector { if n > 4 { panic("n must be less than 5") } result := make(vector, 32) result[1<<n] = 1.0 return result } func cdot(a, b vector) vector { return mul(vector{0.5}, add(mul(a, b), ...
import std.exception; import std.random; import std.stdio; auto doubleArray(size_t size) { double[] result; result.length = size; result[] = 0.0; return result; } int bitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F...
Generate an equivalent D version of this Go code.
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ...
import std.stdio, std.array, std.algorithm, std.range, std.ascii, std.conv, std.string, std.regex, std.typecons; string unique(in string s) pure nothrow @safe { string result; foreach (immutable char c; s) if (!result.representation.canFind(c)) result ~= c; return result; } str...
Write the same algorithm in D as shown in this Go implementation.
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ...
import std.stdio, std.array, std.algorithm, std.range, std.ascii, std.conv, std.string, std.regex, std.typecons; string unique(in string s) pure nothrow @safe { string result; foreach (immutable char c; s) if (!result.representation.canFind(c)) result ~= c; return result; } str...
Produce a language-to-language conversion: from Go to D, same semantics.
package main import ( "fmt" "strings" ) func btoi(b bool) int { if b { return 1 } return 0 } func evolve(l, rule int) { fmt.Printf(" Rule #%d:\n", rule) cells := "O" for x := 0; x < l; x++ { cells = addNoCells(cells) width := 40 + (len(cells) >> 1) fmt....
import std.stdio, std.array, std.range, std.typecons, std.string, std.conv, std.algorithm; alias R = replicate; void main() { enum nLines = 25; enum notCell = (in char c) pure => (c == '1') ? "0" : "1"; foreach (immutable rule; [90, 30]) { writeln("\nRule: ", rule); immutable ruleBi...
Convert the following code from Go to D, ensuring the logic remains intact.
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...
import std.algorithm; import std.range; import std.stdio; void main() { string[] dict = ["a", "aa", "b", "ab", "aab"]; process(dict, ["aab", "aa b"]); dict = ["abc", "a", "ac", "b", "c", "cb", "d"]; process(dict, ["abcd", "abbc", "abcbcd", "acdbc", "abcdd"]); } void process(string[] dict, string[] te...
Write the same code in D as shown below in Go.
package romap type Romap struct{ imap map[byte]int } func New(m map[byte]int) *Romap { if m == nil { return nil } return &Romap{m} } func (rom *Romap) Get(key byte) (int, bool) { i, ok := rom.imap[key] return i, ok } func (rom *Romap) Reset(key byte) { _, ok := rom.imap[key] i...
struct DefaultAA(TK, TV) { TV[TK] standard, current; this(TV[TK] default_) pure @safe { this.standard = default_; this.current = default_.dup; } alias current this; void remove(in TK key) pure nothrow { current[key] = standard[key]; } void clear() pure @safe { ...
Translate this program into D but keep the logic exactly as in Go.
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" ...
import std.stdio, std.conv, std.array, std.string, std.range, std.algorithm, std.typecons; immutable string[string] hex2bin, bin2hex; static this() pure @safe { hex2bin = 16.iota.map!(x => tuple("%x".format(x), "%04b".format(x))).assocArray; bin2hex = 16.iota.map!(x => tuple("%b".format(x), "%x".format(x))).a...
Produce a language-to-language conversion: from Go to D, same semantics.
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" ...
import std.stdio, std.conv, std.array, std.string, std.range, std.algorithm, std.typecons; immutable string[string] hex2bin, bin2hex; static this() pure @safe { hex2bin = 16.iota.map!(x => tuple("%x".format(x), "%04b".format(x))).assocArray; bin2hex = 16.iota.map!(x => tuple("%b".format(x), "%x".format(x))).a...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "sort" ) type point struct{ x, y int } type polyomino []point type pointset map[point]bool func (p point) rotate90() point { return point{p.y, -p.x} } func (p point) rotate180() point { return point{-p.x, -p.y} } func (p point) rotate270() point { return point{-p.y, p.x} } func (...
import std.stdio, std.range, std.algorithm, std.typecons, std.conv; alias Coord = byte; alias Point = Tuple!(Coord,"x", Coord,"y"); alias Polyomino = Point[]; enum minima = (in Polyomino poly) pure @safe => Point(poly.map!q{ a.x }.reduce!min, poly.map!q{ a.y }.reduce!min); Polyomino translateToOrigin(in Polyomi...
Generate an equivalent D version of this Go code.
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", " ...
import std.stdio, std.string, std.algorithm, std.array, std.conv, std.ascii, std.range; string[] naturalSort(string[] arr) { static struct Part { string s; int opCmp(in ref Part other) const pure { return (s[0].isDigit && other.s[0].isDigit) ? cmp([s.to!ulong], [ot...
Produce a language-to-language conversion: from Go to D, same semantics.
package main import ( ed "github.com/Ernyoke/Imger/edgedetection" "github.com/Ernyoke/Imger/imgio" "log" ) func main() { img, err := imgio.ImreadRGBA("Valve_original_(1).png") if err != nil { log.Fatal("Could not read image", err) } cny, err := ed.CannyRGBA(img, 15, 45, 5) if ...
import core.stdc.stdio, std.math, std.typecons, std.string, std.conv, std.algorithm, std.ascii, std.array, bitmap, grayscale_image; enum maxBrightness = 255; alias Pixel = short; alias IntT = typeof(size_t.init.signed); void convolution(bool normalize)(in Pixel[] inp, Pixel[] outp, ...
Generate an equivalent D version of this Go code.
package main import ( "fmt" "strconv" ) func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd ...
import std.stdio, std.string, std.conv, std.ascii, std.algorithm; ulong ownCalcPass(in ulong password, in string nonce) pure nothrow @safe @nogc in { assert(nonce.representation.all!isDigit); } body { enum ulong m_1 = 0x_FFFF_FFFF_UL; enum ulong m_8 = 0x_FFFF_FFF8_UL; enum ulong m_16 ...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" "math" "math/rand" "time" ) type ff = func([]float64) float64 type parameters struct{ omega, phip, phig float64 } type state struct { iter int gbpos []float64 gbval float64 min []float64 max []float64 params parame...
import std.math; import std.random; import std.stdio; alias Func = double function(double[]); struct Parameters { double omega, phip, phig; } struct State { int iter; double[] gbpos; double gbval; double[] min; double[] max; Parameters parameters; double[][] pos; double[][] vel; ...
Preserve the algorithm and functionality while converting the code from Go to D.
package main import "fmt" type solution struct{ peg, over, land int } type move struct{ from, to int } var emptyStart = 1 var board [16]bool var jumpMoves = [16][]move{ {}, {{2, 4}, {3, 6}}, {{4, 7}, {5, 9}}, {{5, 8}, {6, 10}}, {{2, 1}, {5, 6}, {7, 11}, {8, 13}}, {{8, 12}, {9, 14}}, {{...
import std.stdio, std.array, std.string, std.range, std.algorithm; immutable N = [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1]; immutable G = [[0,1,3],[0,2,5],[1,3,6],[1,4,8],[2,4,7],[2,5,9], [3,4,5],[3,6,10],[3,7,12],[4,7,11],[4,8,13],[5,8,12], [5,9,14],[6,7,8],[7,8,9],[10,11,12],[11,12,13],[12,13,14]]; string b2s(in int[...
Maintain the same structure and functionality when rewriting this code in Fortran.
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; ...
program game_24 implicit none real :: vector(4), reals(11), result, a, b, c, d integer :: numbers(4), ascii(11), i character(len=11) :: expression character :: syntax(11) character, parameter :: one(11) = (/ '(','(','1','x','1',')','x','1',')','x','1' /) character, ...
Produce a functionally identical Fortran code for the snippet given in C++.
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; ...
program game_24 implicit none real :: vector(4), reals(11), result, a, b, c, d integer :: numbers(4), ascii(11), i character(len=11) :: expression character :: syntax(11) character, parameter :: one(11) = (/ '(','(','1','x','1',')','x','1',')','x','1' /) character, ...
Please provide an equivalent version of this C++ code in Fortran.
#include <iostream> class MyOtherClass { public: const int m_x; MyOtherClass(const int initX = 0) : m_x(initX) { } }; int main() { MyOtherClass mocA, mocB(7); std::cout << mocA.m_x << std::endl; std::cout << mocB.m_x << std::endl; return 0; }
real, parameter :: pi = 3.141593
Change the following C++ code into Fortran without altering its purpose.
#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 ...
Calculate the Hofstadter Q-sequence, using a big array rather than recursion. INTEGER ENUFF PARAMETER (ENUFF = 100000) INTEGER Q(ENUFF) Q(1) = 1 Q(2) = 1 Q(3:) = -123456789 DO I = 3,ENUFF Q(I) = Q(I - Q(I - 1)) + Q(I - Q(I - 2)) END DO Cast forth results as ...
Generate an equivalent Fortran version of this C++ code.
#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 ...
Calculate the Hofstadter Q-sequence, using a big array rather than recursion. INTEGER ENUFF PARAMETER (ENUFF = 100000) INTEGER Q(ENUFF) Q(1) = 1 Q(2) = 1 Q(3:) = -123456789 DO I = 3,ENUFF Q(I) = Q(I - Q(I - 1)) + Q(I - Q(I - 2)) END DO Cast forth results as ...
Translate this program into Fortran but keep the logic exactly as in C++.
#include <iostream> #include <string> int countSubstring(const std::string& str, const std::string& sub) { if (sub.length() == 0) return 0; int count = 0; for (size_t offset = str.find(sub); offset != std::string::npos; offset = str.find(sub, offset + sub.length())) { ++count; } retu...
program Example implicit none integer :: n n = countsubstring("the three truths", "th") write(*,*) n n = countsubstring("ababababab", "abab") write(*,*) n n = countsubstring("abaabba*bbaba*bbab", "a*b") write(*,*) n contains function countsubstring(s1, s2) result(c) character(*), intent(in) :: s...
Change the following C++ code into Fortran without altering its purpose.
#include <iomanip> #include <iostream> int mod(int n, int d) { return (d + n % d) % d; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) r...
LOGICAL FUNCTION ISPRIME(N) INTEGER N INTEGER F ISPRIME = .FALSE. DO F = 2,SQRT(DFLOAT(N)) IF (MOD(N,F).EQ.0) RETURN END DO ISPRIME = .TRUE. END FUNCTION ISPRIME PROGRAM CHASE INTEGER P1,P2,P3 INTEGER H3,D ...
Port the provided C++ code into Fortran while preserving the original functionality.
#include <windows.h> #include <iostream> #include <string> using namespace std; enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C }; enum indexes { PLAYER, COMPUTER, DRAW }; class stats { public: stats() : _draw( 0 ) { ZeroMemory( _moves, sizeof( _moves ) ); ZeroMemory( _win, sizeof( _win...
program rpsgame integer, parameter :: COMPUTER=1, HAPLESSUSER=2 integer, dimension(3) :: rps = (/1,1,1/) real, dimension(3) :: p character :: answer, cc integer :: exhaustion, i real, dimension(2) :: score = (/0, 0/) character(len=8), dimension(3) :: choices = (/'rock ','paper ',...
Translate this program into Fortran but keep the logic exactly as in C++.
#include <cln/integer.h> #include <cln/integer_io.h> #include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <sstream> #include <string> #include <cstdlib> #include <cmath> #include <map> using namespace cln ; class NextNum { public : NextNum ( cl_I & a , cl_I & b ) : first( a ) , s...
-*- mode: compilation; default-directory: "/tmp/" -*- Compilation started at Sat May 18 01:13:00 a=./f && make $a && $a f95 -Wall -ffree-form f.F -o f 0.301030010 0.176091254 0.124938756 9.69100147E-02 7.91812614E-02 6.69467747E-02 5.79919666E-02 5.11525236E-02 4.57575098E-02 THE LAW 0.30...
Port the provided C++ code into Fortran while preserving the original functionality.
#include <cln/integer.h> #include <cln/integer_io.h> #include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <sstream> #include <string> #include <cstdlib> #include <cmath> #include <map> using namespace cln ; class NextNum { public : NextNum ( cl_I & a , cl_I & b ) : first( a ) , s...
-*- mode: compilation; default-directory: "/tmp/" -*- Compilation started at Sat May 18 01:13:00 a=./f && make $a && $a f95 -Wall -ffree-form f.F -o f 0.301030010 0.176091254 0.124938756 9.69100147E-02 7.91812614E-02 6.69467747E-02 5.79919666E-02 5.11525236E-02 4.57575098E-02 THE LAW 0.30...
Ensure the translated Fortran code behaves exactly like the original C++ snippet.
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator =...
program hickerson implicit none integer, parameter :: q = selected_real_kind(30) integer, parameter :: l = selected_int_kind(15) real(q) :: s, l2 integer :: i, n, k l2 = log(2.0_q) do n = 1, 17 s = 0.5_q / l2 do i = 1, n s = (s * i) / l2 end do k...
Generate a Fortran translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator =...
program hickerson implicit none integer, parameter :: q = selected_real_kind(30) integer, parameter :: l = selected_int_kind(15) real(q) :: s, l2 integer :: i, n, k l2 = log(2.0_q) do n = 1, 17 s = 0.5_q / l2 do i = 1, n s = (s * i) / l2 end do k...
Convert this C++ block to Fortran, preserving its control flow and logic.
#include "stdafx.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string/case_conv.hpp> using namespace std; using namespace boost; typedef boost::tokenizer<boost::char_separator<char> > Tokenizer; static const char_separator<char> s...
program readconfig implicit none integer, parameter :: strlen = 100 logical :: needspeeling = .false., seedsremoved =.false. character(len=strlen) :: favouritefruit = "", fullname = "", fst, snd character(len=strlen), allocatable :: otherfamily(:), tmp(:) character(len=1000) :: line int...
Can you help me rewrite this code in Fortran instead of C++, keeping it the same logically?
#include <cassert> #include <vector> #include <QImage> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list...
program Kron_frac implicit none interface function matkronpow(M, n) result(Mpowern) integer, dimension(:,:), intent(in) :: M integer, intent(in) :: n integer, dimension(size(M, 1)**n, size(M,2)**n) :: Mpowern end function matkronpow function kron(A, B) result(M) integer, dimens...
Write a version of this C++ function in Fortran with identical behavior.
#include <iostream> #include <string> using namespace std; int main() { string dog = "Benjamin", Dog = "Samba", DOG = "Bernie"; cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl; }
program Example implicit none character(8) :: dog, Dog, DOG dog = "Benjamin" Dog = "Samba" DOG = "Bernie" if (dog == DOG) then write(*,*) "There is just one dog named ", dog else write(*,*) "The three dogs are named ", dog, Dog, " and ", DOG end if end program Example
Port the following code from C++ to Fortran with equivalent syntax and logic.
#include <iostream> #include <time.h> using namespace std; class stooge { public: void sort( int* arr, int start, int end ) { if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] ); int n = end - start; if( n > 2 ) { n /= 3; sort( arr, start, end - n ); sort( arr, start + n, en...
program Stooge implicit none integer :: i integer :: array(50) = (/ (i, i = 50, 1, -1) /) call Stoogesort(array) write(*,"(10i5)") array contains recursive subroutine Stoogesort(a) integer, intent(in out) :: a(:) integer :: j, t, temp j = size(a) if(a(j) < a(1)) then temp = a(j) a...
Convert this C++ block to Fortran, preserving its control flow and logic.
#include <time.h> #include <iostream> using namespace std; const int MAX = 126; class shell { public: shell() { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; } void sort( int* a, int count ) { _cnt = count; for( i...
MODULE sort CONTAINS SUBROUTINE Shell_Sort(a) IMPLICIT NONE INTEGER :: i, j, increment REAL :: temp REAL, INTENT(in out) :: a(:) increment = SIZE(a) / 2 DO WHILE (increment > 0) DO i = increment+1, SIZE(a) j = i temp = a(i) DO WHILE (j >= increment+1 .AND. a(j-increment...
Change the programming language of this snippet from C++ to Fortran without modifying what it does.
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look at ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you...
MODULE SAMPLER CONTAINS SAM00200 CHARACTER*20 FUNCTION GETREC(N,F,IS) Careful. Some compilers get confused over the function name's usage. SAM00400 INTEGER N INTEGER F CHARACTER...
Write the same code in Fortran as shown below in C++.
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look at ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you...
MODULE SAMPLER CONTAINS SAM00200 CHARACTER*20 FUNCTION GETREC(N,F,IS) Careful. Some compilers get confused over the function name's usage. SAM00400 INTEGER N INTEGER F CHARACTER...
Please provide an equivalent version of this C++ code in Fortran.
class invertedAssign { int data; public: invertedAssign(int data):data(data){} int getData(){return data;} void operator=(invertedAssign& other) const { other.data = this->data; } }; #include <iostream> int main(){ invertedAssign a = 0; invertedAssign b = 42; std::cout << a.getData() << ' ' << b....
INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT)
Rewrite this program in Fortran while keeping its functionality equivalent to the C++ version.
class invertedAssign { int data; public: invertedAssign(int data):data(data){} int getData(){return data;} void operator=(invertedAssign& other) const { other.data = this->data; } }; #include <iostream> int main(){ invertedAssign a = 0; invertedAssign b = 42; std::cout << a.getData() << ' ' << b....
INQUIRE(FILE = FILENAME(1:L), EXIST = MAYBE, ERR = 666, IOSTAT = RESULT)
Translate this program into Fortran but keep the logic exactly as in C++.
#include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <limits> #include <numeric> #include <sstream> #include <vector> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} ...
program lu1 implicit none call check( reshape([real(8)::1,2,1,3,4,1,5,7,0 ],[3,3]) ) call check( reshape([real(8)::11,1,3,2,9,5,17,5,24,2,18,7,2,6,1,1],[4,4]) ) contains subroutine check(a) real(8), intent(in) :: a(:,:) integer :: i,j,n real(8), allocatable :: a...
Rewrite this program in Fortran while keeping its functionality equivalent to the C++ version.
#include <vector> #include <algorithm> #include <string> template <class T> struct sort_table_functor { typedef bool (*CompFun)(const T &, const T &); const CompFun ordering; const int column; const bool reverse; sort_table_functor(CompFun o, int c, bool r) : ordering(o), column(c), reverse(r) { } boo...
module ExampleOptionalParameter implicit none contains subroutine sort_table(table, ordering, column, reverse) type(table_type), intent(inout) :: table integer, optional :: column logical, optional :: reverse optional :: ordering interface integer function ordering(a, b) t...