Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert this Go snippet to D and keep its semantics consistent.
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" ) func main() { f, err := os.Open("unixdict.txt") if err != nil { log.Fatalln(err) } defer f.Close() s := bufio.NewScanner(f) rie := regexp.MustCompile("^ie|[^c]ie") rei := regexp.MustCompile("^ei|[^c]ei") var cie, ie int var cei, ei ...
import std.file; import std.stdio; int main(string[] args) { if (args.length < 2) { stderr.writeln(args[0], " filename"); return 1; } int cei, cie, ie, ei; auto file = File(args[1]); foreach(line; file.byLine) { auto res = eval(cast(string) line); cei += res.cei; ...
Ensure the translated D code behaves exactly like the original Go snippet.
package raster import "math" func ipart(x float64) float64 { return math.Floor(x) } func round(x float64) float64 { return ipart(x + .5) } func fpart(x float64) float64 { return x - ipart(x) } func rfpart(x float64) float64 { return 1 - fpart(x) } func (g *Grmap) AaLine(x1, y1, x2, y2 float64) { ...
import std.math, std.algorithm, grayscale_image; void aaLine(Color)(ref Image!Color img, double x1, double y1, double x2, double y2, in Color color) pure nothrow @safe @nogc { static double round(in double x) pure nothrow @safe @nogc { re...
Generate a D translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "sort" ) func permute(s string) []string { var res []string if len(s) == 0 { return res } b := []byte(s) var rc func(int) rc = func(np int) { if np == 1 { res = append(res, string(b)) return } np1 := n...
import std.algorithm; import std.array; import std.conv; import std.stdio; string next(string s) { auto sb = appender!string; auto index = s.length - 1; while (index > 0 && s[index - 1] >= s[index]) { index--; } if (index == 0) { return "0"; } auto index2 = ...
Write a version of this Go function in D with identical behavior.
package main import ( "fmt" "sort" ) func permute(s string) []string { var res []string if len(s) == 0 { return res } b := []byte(s) var rc func(int) rc = func(np int) { if np == 1 { res = append(res, string(b)) return } np1 := n...
import std.algorithm; import std.array; import std.conv; import std.stdio; string next(string s) { auto sb = appender!string; auto index = s.length - 1; while (index > 0 && s[index - 1] >= s[index]) { index--; } if (index == 0) { return "0"; } auto index2 = ...
Transform the following Go implementation into D, maintaining the same output and logic.
package main import ( "github.com/fogleman/gg" "image/color" "math" ) var ( red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} magenta = color.RGBA{255, 0, 255, 255} cyan = color.RGBA{0, 255, 255, 255} ) var ( w, h ...
import std.math; import std.stdio; real degrees(real deg) { immutable tau = 2.0 * PI; return deg * tau / 360.0; } immutable part_ratio = 2.0 * cos(72.degrees); immutable side_ratio = 1.0 / (part_ratio + 2.0); void pentagon(Turtle turtle, real size) { turtle.right(36.degrees); turtle.begin_fill(); ...
Change the following Go code into D without altering its purpose.
package main import ( "bytes" "fmt" "strings" ) var in = ` 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 0111001111001110...
import std.stdio, std.algorithm, std.string, std.functional, std.typecons, std.typetuple, bitmap; struct BlackWhite { ubyte c; alias c this; static immutable black = typeof(this)(0), white = typeof(this)(1); } alias Neighbours = BlackWhite[9]; alias Img = Image!BlackWhite; Im...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/rand" ) type symbols struct{ k, q, r, b, n rune } var A = symbols{'K', 'Q', 'R', 'B', 'N'} var W = symbols{'♔', '♕', '♖', '♗', '♘'} var B = symbols{'♚', '♛', '♜', '♝', '♞'} var krn = []string{ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr...
void main() { import std.stdio, std.range, std.algorithm, std.string, permutations2; const pieces = "KQRrBbNN"; alias I = indexOf; auto starts = pieces.dup.permutations.filter!(p => I(p, 'B') % 2 != I(p, 'b') % 2 && ((I(p, 'r') < I(p, 'K') && I(p, 'K') < I(p, 'R'))...
Rewrite the snippet below in D so it works the same as the original Go code.
package main import ( "fmt" "regexp" ) var bits = []string{ "0 0 0 1 1 0 1 ", "0 0 1 1 0 0 1 ", "0 0 1 0 0 1 1 ", "0 1 1 1 1 0 1 ", "0 1 0 0 0 1 1 ", "0 1 1 0 0 0 1 ", "0 1 0 1 1 1 1 ", "0 1 1 1 0 1 1 ", "0 1 1 0 1 1 1 ", "0 0 0 1 0 1 1 ", } var ( lhs = make(map[st...
import std.algorithm : countUntil, each, map; import std.array : array; import std.conv : to; import std.range : empty, retro; import std.stdio : writeln; import std.string : strip; import std.typecons : tuple; immutable LEFT_DIGITS = [ " ## #", " ## #", " # ##", " #### #", " # ##", " #...
Change the following Go code into D without altering its purpose.
package main import ( "fmt" "os/exec" ) func main() { command := "EventCreate" args := []string{"/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION", "/SO", "Go", "/D", "\"Rosetta Code Example\""} cmd := exec.Command(command, args...) err := cmd.Run() if err != nil { fmt....
import std.process; import std.stdio; void main() { auto cmd = executeShell(`EventCreate /t INFORMATION /id 123 /l APPLICATION /so Dlang /d "Rosetta Code Example"`); if (cmd.status == 0) { writeln("Output: ", cmd.output); } else { writeln("Failed to execute command, status=", cmd.status); ...
Port the provided Go code into D while preserving the original functionality.
package main import "fmt" import "C" func main() { code := []byte{ 0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d, 0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75, 0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75, 0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3, } le := len(code) buf := C.mmap(nil, C.size_t(le), C.PROT...
int test(in int a, in int b) pure nothrow @nogc { immutable ubyte[9] code = [0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3]; alias F = extern(C) int function(int, int) pure nothrow @nogc; immutable f = cast(F)code.ptr; return f(a, b); } void main() { import std.stdio; test(7, 12).wri...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import ( "fmt" "math" ) const eps = 1e-14 type point struct{ x, y float64 } func (p point) String() string { if p.x == 0 { p.x = 0 } if p.y == 0 { p.y = 0 } return fmt.Sprintf("(%g, %g)", p.x, p.y) } func sq(x float64) float64 { return x * x } ...
import std.format; import std.math; import std.stdio; immutable EPS = 1e-14; struct Point { private double x; private double y; public this(double x, double y) { this.x = x; this.y = y; } public double getX() { return x; } public double getY() { return y;...
Transform the following Go implementation into D, maintaining the same output and logic.
package main import ( "fmt" "github.com/rivo/uniseg" "log" "regexp" "strings" ) func join(words, seps []string) string { lw := len(words) ls := len(seps) if lw != ls+1 { log.Fatal("mismatch between number of words and separators") } var sb strings.Builder for i := 0...
import std.stdio; import std.uni; string redact(string source, string word, bool partial = false, bool insensitive = false, bool overkill = false) { bool different(char s, char w) { if (insensitive) { return s.toUpper != w.toUpper; } else { return s != w; } } ...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c,...
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons; struct HopidoPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableC...
Change the programming language of this snippet from Go to D without modifying what it does.
package main import ( "fmt" "sort" ) var board = []string{ ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0...", } var moves = [][2]int{ {-3, 0}, {0, 3}, {3, 0}, {0, -3}, {2, 2}, {2, -2}, {-2, 2}, {-2, -2}, } var grid [][]int var totalToFill = 0 func solve(r, c,...
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons; struct HopidoPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableC...
Translate this program into D but keep the logic exactly as in Go.
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00...
import std.stdio, std.conv, std.string, std.range, std.array, std.typecons, std.algorithm; struct { alias BitSet8 = ubyte; alias Cell = uint; enum : string { unavailableInCell = "#", availableInCell = "." } enum : Cell { unavailableCell = Cell.max, availableCell = 0 } this(in string inPuzzle) pu...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "sort" "strconv" "strings" ) var example1 = []string{ "00,00,00,00,00,00,00,00,00", "00,00,46,45,00,55,74,00,00", "00,38,00,00,43,00,00,78,00", "00,35,00,00,00,00,00,71,00", "00,00,33,00,00,00,59,00,00", "00,17,00,00,00,00,00,67,00", "00,18,00,00...
import std.stdio, std.conv, std.string, std.range, std.array, std.typecons, std.algorithm; struct { alias BitSet8 = ubyte; alias Cell = uint; enum : string { unavailableInCell = "#", availableInCell = "." } enum : Cell { unavailableCell = Cell.max, availableCell = 0 } this(in string inPuzzle) pu...
Produce a functionally identical D code for the snippet given in Go.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func (e example) CallMethod(n string) int { if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() { return int(m.Call(nil)[0].Int()) } fmt.Println("Unknown method:", ...
import std.stdio; struct Catcher { void foo() { writeln("This is foo"); } void bar() { writeln("This is bar"); } void opDispatch(string name, ArgsTypes...)(ArgsTypes args) { writef("Tried to handle unknown method '%s'", name); if (ArgsTypes.length) { write(", with arguments: "...
Translate the given Go code snippet into D without altering its behavior.
package main import "fmt" import "io/ioutil" import "log" import "os" import "regexp" import "strings" func main() { err := fix() if err != nil { log.Fatalln(err) } } func fix() (err error) { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { return err } out, err := Lang(string(buf)) if err != nil { ...
import std.stdio, std.regex, std.string, std.array; immutable langs = "_div abap actionscript actionscript3 ada apache applescript apt_sources asm asp autoit avisynth bash basic4gl bf blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp cpp-qt csharp css d delphi diff dos dot eiffel email fortran freebasic...
Change the following Go code into D without altering its purpose.
package main import ( "fmt" "math/rand" "time" ) var snl = map[int]int{ 4: 14, 9: 31, 17: 7, 20: 38, 28: 84, 40: 59, 51: 67, 54: 34, 62: 19, 63: 81, 64: 60, 71: 91, 87: 24, 93: 73, 95: 75, 99: 78, } const sixThrowsAgain = true func turn(player, square int) int { for { roll := 1 + ran...
import std.stdio; auto snl() { int[int] temp; temp[4] = 14; temp[9] = 31; temp[17] = 7; temp[20] = 38; temp[28] = 84; temp[40] = 59; temp[51] = 67; temp[54] = 34; temp[62] = 19; temp[63] = 81; temp[64] = 60; temp[71] = 91; temp[87] = 24; temp[93] = 73; ...
Convert this Go snippet to D and keep its semantics consistent.
package main import ( "fmt" "math/rand" "time" ) var snl = map[int]int{ 4: 14, 9: 31, 17: 7, 20: 38, 28: 84, 40: 59, 51: 67, 54: 34, 62: 19, 63: 81, 64: 60, 71: 91, 87: 24, 93: 73, 95: 75, 99: 78, } const sixThrowsAgain = true func turn(player, square int) int { for { roll := 1 + ran...
import std.stdio; auto snl() { int[int] temp; temp[4] = 14; temp[9] = 31; temp[17] = 7; temp[20] = 38; temp[28] = 84; temp[40] = 59; temp[51] = 67; temp[54] = 34; temp[62] = 19; temp[63] = 81; temp[64] = 60; temp[71] = 91; temp[87] = 24; temp[93] = 73; ...
Preserve the algorithm and functionality while converting the code from Go to D.
package main import "fmt" type frac struct{ num, den int } func (f frac) String() string { return fmt.Sprintf("%d/%d", f.num, f.den) } func f(l, r frac, n int) { m := frac{l.num + r.num, l.den + r.den} if m.den <= n { f(l, m, n) fmt.Print(m, " ") f(m, r, n) } } func main() {...
string toString() const { if (den != 0) return num.text ~ "/" ~ den.text; if (num == 0) return "NaRat"; else return ((num < 0) ? "-" : "+") ~ "infRat"; }
Produce a language-to-language conversion: from Go to D, same semantics.
package main import "fmt" type frac struct{ num, den int } func (f frac) String() string { return fmt.Sprintf("%d/%d", f.num, f.den) } func f(l, r frac, n int) { m := frac{l.num + r.num, l.den + r.den} if m.den <= n { f(l, m, n) fmt.Print(m, " ") f(m, r, n) } } func main() {...
string toString() const { if (den != 0) return num.text ~ "/" ~ den.text; if (num == 0) return "NaRat"; else return ((num < 0) ? "-" : "+") ~ "infRat"; }
Preserve the algorithm and functionality while converting the code from Go to D.
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, sea...
import std.stdio, std.range, std.algorithm, std.typecons, std.conv; auto properDivisors(in ulong n) pure nothrow @safe { return iota(1UL, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x); } enum pDivsSum = (in ulong n) pure nothrow @safe => n.properDivisors.sum; auto aliquot(in ulong n, in ...
Translate the given Go code snippet into D without altering its behavior.
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, sea...
import std.stdio, std.range, std.algorithm, std.typecons, std.conv; auto properDivisors(in ulong n) pure nothrow @safe { return iota(1UL, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x); } enum pDivsSum = (in ulong n) pure nothrow @safe => n.properDivisors.sum; auto aliquot(in ulong n, in ...
Change the programming language of this snippet from Go to D without modifying what it does.
package main import "fmt" func main() { var i int32 = 1 fmt.Printf("i : type %-7T value %d\n", i, i) j := 2 fmt.Printf("j : type %-7T value %d\n", j, j) var k int64 = int64(i) + int64(j) fmt.Printf("k : type %-7T value %d\n", k, k) ...
void main() { import std.stdio, std.typetuple, std.variant, std.complex; enum IntEnum : int { A, B } union IntFloatUnion { int x; float y; } struct IntStruct { int x; } class ClassRef {} class DerivedClassRef : ClassRef {} alias IntDouble = Algebraic!(int, double); alias ComplexDouble =...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import "fmt" func main() { var i int32 = 1 fmt.Printf("i : type %-7T value %d\n", i, i) j := 2 fmt.Printf("j : type %-7T value %d\n", j, j) var k int64 = int64(i) + int64(j) fmt.Printf("k : type %-7T value %d\n", k, k) ...
void main() { import std.stdio, std.typetuple, std.variant, std.complex; enum IntEnum : int { A, B } union IntFloatUnion { int x; float y; } struct IntStruct { int x; } class ClassRef {} class DerivedClassRef : ClassRef {} alias IntDouble = Algebraic!(int, double); alias ComplexDouble =...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" "time" "math/big" ) func main() { start := time.Now() one := big.NewInt(1) mp := big.NewInt(0) bp := big.NewInt(0) const max = 22 for count, p := 0, uint(2); count < max; { mp.Lsh(one, p) mp.Sub(mp, one) if mp.ProbablyPrime(0) { elapsed := time.Since(start).Seconds()...
import std.bigint; import std.stdio; bool isPrime(BigInt bi) { if (bi < 2) return false; if (bi % 2 == 0) return bi == 2; if (bi % 3 == 0) return bi == 3; auto test = BigInt(5); while (test * test < bi) { if (bi % test == 0) return false; test += 2; if (bi % test == 0) ...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" "time" "math/big" ) func main() { start := time.Now() one := big.NewInt(1) mp := big.NewInt(0) bp := big.NewInt(0) const max = 22 for count, p := 0, uint(2); count < max; { mp.Lsh(one, p) mp.Sub(mp, one) if mp.ProbablyPrime(0) { elapsed := time.Since(start).Seconds()...
import std.bigint; import std.stdio; bool isPrime(BigInt bi) { if (bi < 2) return false; if (bi % 2 == 0) return bi == 2; if (bi % 3 == 0) return bi == 3; auto test = BigInt(5); while (test * test < bi) { if (bi % test == 0) return false; test += 2; if (bi % test == 0) ...
Translate this program into D but keep the logic exactly as in Go.
package main import ( "container/heap" "fmt" "strings" ) type CubeSum struct { x, y uint16 value uint64 } func (c *CubeSum) fixvalue() { c.value = cubes[c.x] + cubes[c.y] } type CubeSumHeap []*CubeSum func (h CubeSumHeap) Len() int { return len(h) } func (h CubeSumHeap) Less(i, j int) bool { retu...
void main() { import std.stdio, std.range, std.algorithm, std.typecons, std.string; auto iCubes = iota(1u, 1201u).map!(x => tuple(x, x ^^ 3)); bool[Tuple!(uint, uint)][uint] sum2cubes; foreach (i, immutable i3; iCubes) foreach (j, immutable j3; iCubes[i .. $]) sum2cubes[i3 + j3][tu...
Translate this program into D but keep the logic exactly as in Go.
package main import ( "fmt" "math/big" ) func main() { fmt.Print("!0 through !10: 0") one := big.NewInt(1) n := big.NewInt(1) f := big.NewInt(1) l := big.NewInt(1) next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) } for ; ; next() { fmt.Print(" ", l) if n.Int...
import std.stdio, std.bigint, std.range, std.algorithm, std.conv; BigInt leftFact(in uint n) pure nothrow { BigInt result = 0, factorial = 1; foreach (immutable i; 1 .. n + 1) { result += factorial; factorial *= i; } return result; } void main() { writeln("First 11 left factorials...
Please provide an equivalent version of this Go code in D.
package main import ( "fmt" "math/big" ) func main() { fmt.Print("!0 through !10: 0") one := big.NewInt(1) n := big.NewInt(1) f := big.NewInt(1) l := big.NewInt(1) next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) } for ; ; next() { fmt.Print(" ", l) if n.Int...
import std.stdio, std.bigint, std.range, std.algorithm, std.conv; BigInt leftFact(in uint n) pure nothrow { BigInt result = 0, factorial = 1; foreach (immutable i; 1 .. n + 1) { result += factorial; factorial *= i; } return result; } void main() { writeln("First 11 left factorials...
Port the provided Go code into D while preserving the original functionality.
package main import ( "fmt" "log" "strings" ) const dimensions int = 8 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 size := d * d mu...
import std.stdio; void main() { int n=8; foreach(row; magicSquareDoublyEven(n)) { foreach(col; row) { writef("%2s ", col); } writeln; } writeln("\nMagic constant: ", (n*n+1)*n/2); } int[][] magicSquareDoublyEven(int n) { import std.exception; enforce(n>=4 &&...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1) p := uint64(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true ...
import std.array; import std.math; import std.stdio; long[] sieve(long limit) { long[] primes = [2]; bool[] c = uninitializedArray!(bool[])(cast(size_t)(limit + 1)); long p = 3; while (true) { long p2 = p * p; if (p2 > limit) { break; } for (long i = p2; i <=...
Port the following code from Go to D with equivalent syntax and logic.
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { units := []string{ "tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer", } convs := []float32{ 0.025...
import std.stdio, std.string, std.algorithm, std.conv; void main(in string[] args) { auto factor = ["arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, "fut": 0.3048, "kilometer": 1_000.0, ...
Port the following code from Go to D with equivalent syntax and logic.
package main import "fmt" func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj } func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) =...
import std.stdio; import std.algorithm; import std.random; import std.range; int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = 2 * gap - 1; sum += gap; } return n + adj; } Range pancakeSort(Range)(Range r) { foreach_reverse (immutable i; 2...
Write the same code in D as shown below in Go.
package main import "fmt" const ( N = 2200 N2 = N * N * 2 ) func main() { s := 3 var s1, s2 int var r [N + 1]bool var ab [N2 + 1]bool for a := 1; a <= N; a++ { a2 := a * a for b := a; b <= N; b++ { ab[a2 + b * b] = true } } for c := 1; ...
import std.bitmanip : BitArray; import std.stdio; enum N = 2_200; enum N2 = 2*N*N; void main() { BitArray found; found.length = N+1; BitArray aabb; aabb.length = N2+1; uint s=3; for (uint a=1; a<=N; ++a) { uint aa = a*a; for (uint b=1; b<N; ++b) { aabb[aa + b*b] ...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import "fmt" type pair struct{ x, y int } func main() { const max = 1685 var all []pair for a := 2; a < max; a++ { for b := a + 1; b < max-a; b++ { all = append(all, pair{a, b}) } } fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)") products := countProducts(all...
void main() { import std.stdio, std.algorithm, std.range, std.typecons; const s1 = cartesianProduct(iota(1, 101), iota(1, 101)) .filter!(p => 1 < p[0] && p[0] < p[1] && p[0] + p[1] < 100) .array; alias P = const Tuple!(int, int); enum add = (P p) => p[0] + p[1]; enu...
Write a version of this Go function in D with identical behavior.
package main import "fmt" const max = 12 var ( super []byte pos int cnt [max]int ) func factSum(n int) int { s := 0 for x, f := 0, 1; x < n; { x++ f *= x s += f } return s } func r(n int) bool { if n == 0 { return false } c := super[pos-n...
import std.stdio, std.ascii, std.algorithm, core.memory, permutations2; string superpermutation(in uint n) nothrow in { assert(n > 0 && n < uppercase.length); } out(result) { assert(uppercase[0 .. n].dup.permutations.all!(p => result.canFind(p))); } body { string result = uppercase[0 .. n]; bool...
Convert the following code from Go to D, ensuring the logic remains intact.
package main import ( "fmt" "math" "math/big" "reflect" "strings" "unsafe" ) func Float64IsInt(f float64) bool { _, frac := math.Modf(f) return frac == 0 } func Float32IsInt(f float32) bool { return Float64IsInt(float64(f)) } func Complex128IsInt(c complex128) bool { return imag(c) == 0 && Float6...
import std.complex; import std.math; import std.meta; import std.stdio; import std.traits; void main() { print(25.000000); print(24.999999); print(24.999999, 0.00001); print(25.000100); print(-2.1e120); print(-5e-2); print(real.nan); print(real.infinity); print(5.0+0.0i); print(...
Generate a D translation of this Go snippet without changing its computational steps.
package main import "fmt" var ( a [17][17]int idx [4]int ) func findGroup(ctype, min, max, depth int) bool { if depth == 4 { cs := "" if ctype == 0 { cs = "un" } fmt.Printf("Totally %sconnected group:", cs) for i := 0; i < 4; i++ { fmt.Pri...
import std.stdio, std.string, std.algorithm, std.range; immutable(char)[][] generateMatrix() { immutable r = format("-%b", 53643); return r.length.iota.map!(i => r[$-i .. $] ~ r[0 .. $-i]).array; } string ramseyCheck(in char[][] mat) pure @safe in { foreach (immutable r, const row; mat) { assert...
Translate the given Go code snippet into D without altering its behavior.
package main import "fmt" type any = interface{} func showType(a any) { switch a.(type) { case rune: fmt.Printf("The type of '%c' is %T\n", a, a) default: fmt.Printf("The type of '%v' is %T\n", a, a) } } func main() { values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"} for ...
import std.stdio; auto typeString(T)(T _) { return T.stringof; } class C {} struct S {} void main() { writeln(typeString(1)); writeln(typeString(1L)); writeln(typeString(1.0f)); writeln(typeString(1.0)); writeln(typeString('c')); writeln(typeString("string")); writeln(typeString(new C...
Produce a language-to-language conversion: from Go to D, same semantics.
package main import "fmt" func sieve(limit uint64) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := uint64(4); i < limit; i += 2 { c[i] = true } p := uint64(3) for { p2 := p * p if p2 >= limit { break } ...
import std.stdio; immutable PRIMES = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 28...
Change the following Go code into D without altering its purpose.
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah"...
import std.stdio, std.typecons; auto hashJoin(size_t index1, size_t index2, T1, T2) (in T1[] table1, in T2[] table2) pure @safe if (is(typeof(T1.init[index1]) == typeof(T2.init[index2]))) { T1[][typeof(T1.init[index1])] h; foreach (const s; table1) h[s[index1]] ~= s; Tuple!...
Translate the given Go code snippet into D without altering its behavior.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { ...
#include <stdio.h> #include <stdlib.h> int main(){ int temp; int numbers=3; int a[numbers+1], upto = 4, temp2; for( temp2 = 1 ; temp2 <= numbers; temp2++){ a[temp2]=1; } a[numbers]=0; temp=numbers; while(1){ if(a[temp]==upto){ temp--; if(temp==0) break; } else{ a[temp]++; while(temp<nu...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { ...
#include <stdio.h> #include <stdlib.h> int main(){ int temp; int numbers=3; int a[numbers+1], upto = 4, temp2; for( temp2 = 1 ; temp2 <= numbers; temp2++){ a[temp2]=1; } a[numbers]=0; temp=numbers; while(1){ if(a[temp]==upto){ temp--; if(temp==0) break; } else{ a[temp]++; while(temp<nu...
Produce a language-to-language conversion: from Go to D, same semantics.
package main import ( "log" "math/rand" "testing" "time" "github.com/gonum/plot" "github.com/gonum/plot/plotter" "github.com/gonum/plot/plotutil" "github.com/gonum/plot/vg" ) func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false ...
import std.stdio, std.algorithm, std.container, std.datetime, std.random, std.typetuple; immutable int[] allOnes, sortedData, randomData; static this() { immutable size_t arraySize = 10_000; allOnes = new int[arraySize]; foreach (ref d; allOnes) d = 1; sortedData = new int[array...
Transform the following Go implementation into D, maintaining the same output and logic.
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...
import std.stdio, std.algorithm, std.range, std.conv, std.string, std.concurrency, permutations2, arithmetic_rational; string solve(in int target, in int[] problem) { static struct T { Rational r; string e; } Generator!T computeAllOperations(in Rational[] L) { return new typeof(return)({ ...
Keep all operations the same but rewrite the snippet in D.
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...
import std.stdio, std.algorithm, std.range, std.conv, std.string, std.concurrency, permutations2, arithmetic_rational; string solve(in int target, in int[] problem) { static struct T { Rational r; string e; } Generator!T computeAllOperations(in Rational[] L) { return new typeof(return)({ ...
Convert this Go block to D, preserving its control flow and logic.
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...
import std.stdio, std.range, std.algorithm; uint rol(in uint x, in uint nBits) @safe pure nothrow @nogc { return (x << nBits) | (x >> (32 - nBits)); } alias Nibble = ubyte; alias SBox = immutable Nibble[16][8]; private bool _validateSBox(in SBox data) @safe pure nothrow @nogc { foreach (const ref row; data...
Convert this Go block to D, preserving its control flow and logic.
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(), ...
import std.math, grayscale_image; Image!Gray houghTransform(in Image!Gray im, in size_t hx=460, in size_t hy=360) pure nothrow in { assert(im !is null); assert(hx > 0 && hy > 0); assert((hy & 1) == 0, "hy argument must be even."); } body { auto result = new Image!Gray(hx, hy);...
Port the following code from Go to D with equivalent syntax and logic.
package main import "fmt" const jobs = 12 type environment struct{ seq, cnt int } var ( env [jobs]environment seq, cnt *int ) func hail() { fmt.Printf("% 4d", *seq) if *seq == 1 { return } (*cnt)++ if *seq&1 != 0 { *seq = 3*(*seq) + 1 } else { *seq /= 2 ...
import std.stdio, std.algorithm, std.range, std.array; struct Prop { int[string] data; ref opDispatch(string s)() pure nothrow { return data[s]; } } immutable code = ` writef("% 4d", e.seq); if (e.seq != 1) { e.cnt++; e.seq = (e.seq & 1) ? 3 * e.seq + 1 : e.seq / 2; }`; void main() { ...
Translate this program into D but keep the logic exactly as in Go.
package main import "fmt" func ts(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { ...
import std.bigint; import std.stdio; import std.typecons; alias Pair = Tuple!(long, "n", long, "p"); enum BIGZERO = BigInt("0"); enum BIGONE = BigInt("1"); enum BIGTWO = BigInt("2"); enum BIGTEN = BigInt("10"); struct Solution { BigInt root1, root2; bool exists; } BigInt modPow(BigInt b, BigInt e, BigInt n...
Translate this program into D but keep the logic exactly as in Go.
package main import "fmt" func ts(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { ...
import std.bigint; import std.stdio; import std.typecons; alias Pair = Tuple!(long, "n", long, "p"); enum BIGZERO = BigInt("0"); enum BIGONE = BigInt("1"); enum BIGTWO = BigInt("2"); enum BIGTEN = BigInt("10"); struct Solution { BigInt root1, root2; bool exists; } BigInt modPow(BigInt b, BigInt e, BigInt n...
Change the programming language of this snippet from Go to D without modifying what it does.
type dlNode struct { int next, prev *dlNode } type dlList struct { members map[*dlNode]int head, tail **dlNode }
import std.stdio; class LinkedList(T) { Node!(T) head, tail; int opApply (int delegate(uint, Node!(T)) dg) { uint i = 0; auto link = head; int result = 0; while (link) { result = dg (i, link); if (result) return result; i++; link = link.next; } return result; } static LinkedList!(T) ...
Translate the given Go code snippet into D without altering its behavior.
package main import ( "bufio" "errors" "fmt" "go/ast" "go/parser" "go/token" "os" "reflect" ) func main() { in := bufio.NewScanner(os.Stdin) for { fmt.Print("Expr: ") in.Scan() if err := in.Err(); err != nil { fmt.Println(err) re...
import std.stdio, std.string, std.array, std.algorithm, std.typecons; struct Var { const char name; bool val; } const string expr; Var[] vars; bool pop(ref bool[] arr) pure nothrow { const last = arr.back; arr.popBack; return last; } enum isOperator = (in char c) pure => "&|!^".canFind(c); enum ...
Please provide an equivalent version of this Go code in D.
package main import ( "bufio" "errors" "fmt" "go/ast" "go/parser" "go/token" "os" "reflect" ) func main() { in := bufio.NewScanner(os.Stdin) for { fmt.Print("Expr: ") in.Scan() if err := in.Err(); err != nil { fmt.Println(err) re...
import std.stdio, std.string, std.array, std.algorithm, std.typecons; struct Var { const char name; bool val; } const string expr; Var[] vars; bool pop(ref bool[] arr) pure nothrow { const last = arr.back; arr.popBack; return last; } enum isOperator = (in char c) pure => "&|!^".canFind(c); enum ...
Write the same code in D as shown below in Go.
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...
struct Set(T) { const pure nothrow bool delegate(in T) contains; bool opIn_r(in T x) const pure nothrow { return contains(x); } Set opBinary(string op)(in Set set) const pure nothrow if (op == "+" || op == "-") { static if (op == "+") return Set(x => contains(x) || set....
Generate an equivalent D version of this Go code.
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...
struct Set(T) { const pure nothrow bool delegate(in T) contains; bool opIn_r(in T x) const pure nothrow { return contains(x); } Set opBinary(string op)(in Set set) const pure nothrow if (op == "+" || op == "-") { static if (op == "+") return Set(x => contains(x) || set....
Rewrite the snippet below in D so it works the same as the original Go code.
package main import ( "fmt" "unicode" ) var states = []string{"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland",...
import std.stdio, std.algorithm, std.string, std.exception; auto states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "M...
Preserve the algorithm and functionality while converting the code from Go to D.
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) ...
import std.bigint; import std.conv; import std.stdio; import std.string; void main() { auto rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"]; BigInt one = 1; BigInt nine = 9; for (int ii = 2; ii <= 9; ii++) { writefln("First 10 super-%d numbers:", ii); ...
Convert this Go block to D, preserving its control flow and logic.
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) ...
import std.bigint; import std.conv; import std.stdio; import std.string; void main() { auto rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"]; BigInt one = 1; BigInt nine = 9; for (int ii = 2; ii <= 9; ii++) { writefln("First 10 super-%d numbers:", ii); ...
Generate a D translation of this Go snippet without changing its computational steps.
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 ...
void main() { import std.stdio, std.string, std.range, std.algorithm, std.ascii; immutable src = "unixdict.txt"; const words = src.File.byLineCopy.map!strip.filter!(w => w.all!isAlpha).array; immutable table = makeTrans("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", ...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "image" "reflect" ) type t int func (r t) Twice() t { return r * 2 } func (r t) Half() t { return r / 2 } func (r t) Less(r2 t) bool { return r < r2 } func (r t) privateMethod() {} func main() { report(t(0)) report(image.Point{}) } func report(x interface{}) { v := ...
struct S { bool b; void foo() {} private void bar() {} } class C { bool b; void foo() {} private void bar() {} } void printMethods(T)() if (is(T == class) || is(T == struct)) { import std.stdio; import std.traits; writeln("Methods of ", T.stringof, ":"); foreach (m; __traits...
Produce a functionally identical D code for the snippet given in Go.
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 _,...
import std.stdio, std.algorithm, std.digest.ripemd, sha_256_2; struct PPoint { ubyte[32] x, y; } private enum bitcoinVersion = 0; private enum RIPEMD160_digest_len = typeof("".ripemd160Of).length; private alias sha = SHA256.digest; alias Address = ubyte[1 + 4 + RIPEMD160_digest_len]; char[] toBase58(ref Address a...
Produce a functionally identical D code for the snippet given in Go.
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 _,...
import std.stdio, std.algorithm, std.digest.ripemd, sha_256_2; struct PPoint { ubyte[32] x, y; } private enum bitcoinVersion = 0; private enum RIPEMD160_digest_len = typeof("".ripemd160Of).length; private alias sha = SHA256.digest; alias Address = ubyte[1 + 4 + RIPEMD160_digest_len]; char[] toBase58(ref Address a...
Generate a D translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/big" ) func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10; n ...
import std.stdio, std.mathspecial, std.range, std.algorithm, std.bigint, std.conv; enum permutation = (in uint n, in uint k) pure => reduce!q{a * b}(1.BigInt, iota(n - k + 1, n + 1)); enum combination = (in uint n, in uint k) pure => n.permutation(k) / reduce!q{a * b}(1.BigInt, iota(1, k + 1)); enum b...
Write a version of this Go function in D with identical behavior.
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...
import std.bigint; import std.conv; import std.math; import std.stdio; BigInt IntSqRoot(BigInt value, BigInt guess) { BigInt term; do { term = value / guess; auto temp = term - guess; if (temp < 0) { temp = -temp; } if (temp <= 1) { break; ...
Produce a functionally identical D code for the snippet given in Go.
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...
import std.bigint; import std.conv; import std.math; import std.stdio; BigInt IntSqRoot(BigInt value, BigInt guess) { BigInt term; do { term = value / guess; auto temp = term - guess; if (temp < 0) { temp = -temp; } if (temp <= 1) { break; ...
Write a version of this Go function in D with identical behavior.
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 := ...
import std.stdio; import std.format; import std.bigint; import std.math; import std.algorithm; int sieveLimit = 1300_000; bool[] notPrime; void main() { sieve(sieveLimit); foreach (i; 0..10) writefln("primorial(%d): %d", i, primorial(i)); foreach (i; 1..6) writefln("primorial(10^%d) has len...
Change the programming language of this snippet from Go to D without modifying what it does.
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(),...
import std.stdio, std.bigint, std.algorithm, std.range, std.conv, std.typecons, arithmetic_rational: Rat = Rational; Rat[] egyptian(Rat r) pure nothrow { typeof(return) result; if (r >= 1) { if (r.denominator == 1) return [r, Rat(0, 1)]; result = [Rat(r.numerator / r.denomin...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
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(),...
import std.stdio, std.bigint, std.algorithm, std.range, std.conv, std.typecons, arithmetic_rational: Rat = Rational; Rat[] egyptian(Rat r) pure nothrow { typeof(return) result; if (r >= 1) { if (r.denominator == 1) return [r, Rat(0, 1)]; result = [Rat(r.numerator / r.denomin...
Keep all operations the same but rewrite the snippet in D.
package main import ( "fmt" "math" ) type cFunc func(float64) float64 func main() { fmt.Println("integral:", glq(math.Exp, -3, 3, 5)) } func glq(f cFunc, a, b float64, n int) float64 { x, w := glqNodes(n, f) show := func(label string, vs []float64) { fmt.Printf("%8s: ", label) ...
import std.stdio, std.math; immutable struct GaussLegendreQuadrature(size_t N, FP=double, size_t NBITS=50) { immutable static double[N] lroots, weight; alias FP[N + 1][N + 1] CoefMat; pure nothrow @safe @nogc static this() { static FP legendreEval(in ref FP...
Generate a D translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt poi...
import std.typecons, std.math, std.algorithm, std.random, std.range, std.traits, core.memory; struct Point(size_t k, F) if (isFloatingPoint!F) { F[k] data; alias data this; enum size_t length = k; double sqd(in ref Point!(k, F) q) const pure nothrow @nogc { ...
Change the programming language of this snippet from Go to D without modifying what it does.
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt poi...
import std.typecons, std.math, std.algorithm, std.random, std.range, std.traits, core.memory; struct Point(size_t k, F) if (isFloatingPoint!F) { F[k] data; alias data this; enum size_t length = k; double sqd(in ref Point!(k, F) q) const pure nothrow @nogc { ...
Preserve the algorithm and functionality while converting the code from Go to D.
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 :...
import core.stdc.stdio, core.stdc.stdlib, core.stdc.string, std.typecons; enum int[2][4] dir = [[0, -1], [-1, 0], [0, 1], [1, 0]]; __gshared ubyte[] grid; __gshared uint w, h, len; __gshared ulong cnt; __gshared uint[4] next; void walk(in uint y, in uint x) nothrow @nogc { if (!y || y == h || !x || x == w) { ...
Translate the given Go code snippet into D without altering its behavior.
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 :...
import core.stdc.stdio, core.stdc.stdlib, core.stdc.string, std.typecons; enum int[2][4] dir = [[0, -1], [-1, 0], [0, 1], [1, 0]]; __gshared ubyte[] grid; __gshared uint w, h, len; __gshared ulong cnt; __gshared uint[4] next; void walk(in uint y, in uint x) nothrow @nogc { if (!y || y == h || !x || x == w) { ...
Generate a D translation of this Go snippet without changing its computational steps.
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(...
import std.math; import std.stdio; void main() { long[] primes = [3, 5]; immutable cutOff = 200; immutable bigUn = 100_000; immutable chunks = 50; immutable little = bigUn / chunks; immutable tn = " cuban prime"; writefln("The first %s%ss:", cutOff, tn); int c; bool showEach = true...
Transform the following Go implementation into D, maintaining the same output and logic.
package main import ( "fmt" "sort" "strconv" ) var games = [6]string{"12", "13", "14", "23", "24", "34"} var results = "000000" func nextResult() bool { if results == "222222" { return false } res, _ := strconv.ParseUint(results, 3, 32) results = fmt.Sprintf("%06s", strconv.Format...
void main() { import std.stdio, std.range, std.array, std.algorithm, combinations3; immutable scoring = [0, 1, 3]; auto r3 = [0, 1, 2]; immutable combs = 4.iota.array.combinations(2).array; uint[10][4] histo; foreach (immutable results; cartesianProduct(r3, r3, r3, r3, r3, r3)) { int[...
Maintain the same structure and functionality when rewriting this code in D.
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...
import std.container; import std.stdio; void main() { string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; writeln("infix: ", infix); writeln("postfix: ", infixToPostfix(infix)); } string infixToPostfix(string infix) { import std.array; immutable ops = ["+", "-", "/", "*", "^"]; auto sb = ...
Produce a functionally identical D code for the snippet given in Go.
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...
import std.stdio, std.math; struct PerlinNoise { private static double fade(in double t) pure nothrow @safe @nogc { return t ^^ 3 * (t * (t * 6 - 15) + 10); } private static double lerp(in double t, in double a, in double b) pure nothrow @safe @nogc { return a + t * (b - a); } ...
Produce a language-to-language conversion: from Go to D, same semantics.
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func...
import std.stdio; import std.algorithm; import std.range; import std.array; struct Point { int x; int y; Point opBinary(string op = "+")(Point o) { return Point( o.x + x, o.y + y ); } } struct Map { int w = 8; int h = 8; bool[][] m = [ [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0...
Port the provided Go code into D while preserving the original functionality.
package astar import "container/heap" type Node interface { To() []Arc Heuristic(from Node) int } type Arc struct { To Node Cost int } type rNode struct { n Node from Node l int g int f int fx int } type openHeap []*rNode func...
import std.stdio; import std.algorithm; import std.range; import std.array; struct Point { int x; int y; Point opBinary(string op = "+")(Point o) { return Point( o.x + x, o.y + y ); } } struct Map { int w = 8; int h = 8; bool[][] m = [ [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0...
Change the following Go code into D without altering its purpose.
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if ...
import std.stdio, std.range, std.file, std.algorithm, std.string; auto genRow(in int w, in int[] s) pure nothrow @safe { static int[][] genSeg(in int[][] o, in int sp) pure nothrow @safe { if (o.empty) return [[2].replicate(sp)]; typeof(return) result; foreach (immutable x; 1 ...
Write the same code in D as shown below in Go.
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if ...
import std.stdio, std.range, std.file, std.algorithm, std.string; auto genRow(in int w, in int[] s) pure nothrow @safe { static int[][] genSeg(in int[][] o, in int sp) pure nothrow @safe { if (o.empty) return [[2].replicate(sp)]; typeof(return) result; foreach (immutable x; 1 ...
Port the following code from Go to D with equivalent syntax and logic.
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(...
import std.stdio, std.conv, std.range, std.typecons, std.bigInt; auto rev(in BigInt n) { return n.text.retro.text.BigInt; } alias Res = Tuple!(bool, BigInt); Res lychrel(BigInt n) { static Res[BigInt] cache; if (n in cache) return cache[n]; auto r = n.rev; auto res = Res(true, n); i...
Convert this Go snippet to D and keep its semantics consistent.
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(...
import std.stdio, std.conv, std.range, std.typecons, std.bigInt; auto rev(in BigInt n) { return n.text.retro.text.BigInt; } alias Res = Tuple!(bool, BigInt); Res lychrel(BigInt n) { static Res[BigInt] cache; if (n in cache) return cache[n]; auto r = n.rev; auto res = Res(true, n); i...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
import std.stdio, std.regex, std.conv, std.string, std.range, arithmetic_rational; struct Pair { int x; Rational r; } Pair[][] parseEquations(in string text) { auto r = regex(r"\s*(?P<sign>[+-])?\s*(?:(?P<mul>\d+)\s*\*)?\s*" ~ r"arctan\((?P<num>\d+)/(?P<denom>\d+)\)"); Pair[][] mach...
Produce a functionally identical D code for the snippet given in Go.
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
import std.stdio, std.regex, std.conv, std.string, std.range, arithmetic_rational; struct Pair { int x; Rational r; } Pair[][] parseEquations(in string text) { auto r = regex(r"\s*(?P<sign>[+-])?\s*(?:(?P<mul>\d+)\s*\*)?\s*" ~ r"arctan\((?P<num>\d+)/(?P<denom>\d+)\)"); Pair[][] mach...
Write a version of this Go function in D with identical behavior.
package main import ( "fmt" "math" "regexp" "strings" ) var names = map[string]int64{ "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": ...
import std.stdio, std.array, std.string, std.algorithm, std.bigint, std.range, number_names; BigInt bigIntFromWords(in string num) in { assert(!num.empty); } body { auto words = num.replace(",", "").replace(" and ", " ") .replace("-", " ").split; immutable sign = (words[0] == "minu...
Write the same code in D as shown below in Go.
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 ...
import std.algorithm: min; import std.algorithm: copy; import std.typetuple: TypeTuple; import std.typecons: staticIota; struct ISAAC { private uint[mm.length] randResult; private uint randCount; private uint[256] mm; private uint aa, bb, cc; private void isaac() pure nothrow @safe @no...
Rewrite the snippet below in D so it works the same as the original Go code.
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 ...
import std.algorithm: min; import std.algorithm: copy; import std.typetuple: TypeTuple; import std.typecons: staticIota; struct ISAAC { private uint[mm.length] randResult; private uint randCount; private uint[256] mm; private uint aa, bb, cc; private void isaac() pure nothrow @safe @no...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } ...
import std.stdio, std.algorithm, std.range; alias TRank = ulong; TRank factorial(in uint n) pure nothrow { TRank result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } void computePermutation(size_t N)(ref uint[N] vec, TRank rank) pure nothrow if (N > 0 && N < 22) { N.io...
Convert this Go snippet to D and keep its semantics consistent.
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } ...
import std.stdio, std.algorithm, std.range; alias TRank = ulong; TRank factorial(in uint n) pure nothrow { TRank result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } void computePermutation(size_t N)(ref uint[N] vec, TRank rank) pure nothrow if (N > 0 && N < 22) { N.io...
Change the programming language of this snippet from Go to D without modifying what it does.
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 :=...
import std.math; import std.stdio; int p(int l, int n) { int test = 0; double logv = log(2.0) / log(10.0); int factor = 1; int loop = l; while (loop > 10) { factor *= 10; loop /= 10; } while (n > 0) { int val; test++; val = cast(int)(factor * pow(10...
Rewrite the snippet below in D so it works the same as the original Go code.
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 :=...
import std.math; import std.stdio; int p(int l, int n) { int test = 0; double logv = log(2.0) / log(10.0); int factor = 1; int loop = l; while (loop > 10) { factor *= 10; loop /= 10; } while (n > 0) { int val; test++; val = cast(int)(factor * pow(10...
Rewrite the snippet below in D so it works the same as the original Go code.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64...
import std.bigint; import std.conv; import std.functional; import std.stdio; alias sterling2 = memoize!sterling2Impl; BigInt sterling2Impl(int n, int k) { if (n == 0 && k == 0) { return BigInt(1); } if ((n > 0 && k == 0) || (n == 0 && k > 0)) { return BigInt(0); } if (n == k) { ...
Write the same algorithm in D as shown in this Go implementation.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64...
import std.bigint; import std.conv; import std.functional; import std.stdio; alias sterling2 = memoize!sterling2Impl; BigInt sterling2Impl(int n, int k) { if (n == 0 && k == 0) { return BigInt(1); } if ((n > 0 && k == 0) || (n == 0 && k > 0)) { return BigInt(0); } if (n == k) { ...
Port the following code from Go to D with equivalent syntax and logic.
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { re...
import std.bigint; import std.stdio; import std.typecons; enum BIGZERO = BigInt(0); BigInt modPow(BigInt b, BigInt e, BigInt n) { if (n == 1) return BIGZERO; BigInt result = 1; b = b % n; while (e > 0) { if (e % 2 == 1) { result = (result * b) % n; } e >>= 1; ...
Generate an equivalent D version of this Go code.
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { re...
import std.bigint; import std.stdio; import std.typecons; enum BIGZERO = BigInt(0); BigInt modPow(BigInt b, BigInt e, BigInt n) { if (n == 1) return BIGZERO; BigInt result = 1; b = b % n; while (e > 0) { if (e % 2 == 1) { result = (result * b) % n; } e >>= 1; ...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" big "github.com/ncw/gmp" "sort" ) var ( one = new(big.Int).SetUint64(1) two = new(big.Int).SetUint64(2) three = new(big.Int).SetUint64(3) ) func pierpont(ulim, vlim int, first bool) []*big.Int { p := new(big.Int) p2 := new(big.Int).Set(one) p3 := ne...
import std.algorithm; import std.bigint; import std.random; import std.stdio; immutable PRIMES = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,...