Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from Go to D with equivalent syntax and logic.
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } ...
import std.algorithm, std.range, std.traits, permutations2, permutations_by_swapping1; auto prod(Range)(Range r) nothrow @safe @nogc { return reduce!q{a * b}(ForeachType!Range(1), r); } T permanent(T)(in T[][] a) nothrow @safe in { assert(a.all!(row => row.length == a[0].length)); } body { auto r =...
Change the programming language of this snippet from Go to D without modifying what it does.
package main import ( "fmt" "rcu" "strings" ) func main() { var numbers []int for n := 0; n < 1000; n++ { ns := fmt.Sprintf("%d", n) ds := fmt.Sprintf("%d", rcu.DigitSum(n, 10)) if strings.Contains(ns, ds) { numbers = append(numbers, n) } } fmt.P...
import std.algorithm; import std.conv; import std.stdio; int digitSum(int n) { int s = 0; do { s += n % 10; } while (n /= 10); return s; } void main() { foreach (i; 0 .. 1000) { if (i.to!string.canFind(digitSum(i).to!string)) { write(i, ' '); } } writeln...
Produce a language-to-language conversion: from Go to D, same semantics.
package main import ( "math/rand" "fmt" ) func main() { list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for i := 1; i <= 10; i++ { sattoloCycle(list) fmt.Println(list) } } func sattoloCycle(list []int) { for x := len(list) -1; x > 0; x-- { j := rand.Intn(x) list[x], list[j] = list[j], list[x] } }
import std.stdio; void main() { auto items = [0,1,2,3,4,5]; sattoloCycle(items); items.writeln; } void sattoloCycle(R)(R items) { import std.algorithm : swapAt; import std.random : uniform; for (int i=items.length; i-- > 1;) { int j = uniform(0, i); items.swapAt(i, j); } ...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import ( "math/rand" "fmt" ) func main() { list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for i := 1; i <= 10; i++ { sattoloCycle(list) fmt.Println(list) } } func sattoloCycle(list []int) { for x := len(list) -1; x > 0; x-- { j := rand.Intn(x) list[x], list[j] = list[j], list[x] } }
import std.stdio; void main() { auto items = [0,1,2,3,4,5]; sattoloCycle(items); items.writeln; } void sattoloCycle(R)(R items) { import std.algorithm : swapAt; import std.random : uniform; for (int i=items.length; i-- > 1;) { int j = uniform(0, i); items.swapAt(i, j); } ...
Write the same code in D as shown below in Go.
package main import ( "fmt" "math/rand" "time" ) func cyclesort(ints []int) int { writes := 0 for cyclestart := 0; cyclestart < len(ints)-1; cyclestart++ { item := ints[cyclestart] pos := cyclestart for i := cyclestart + 1; i < len(ints); i++ { if ints[i] < item { pos++ } } if pos == cycl...
import std.stdio, std.algorithm; uint cycleSort(T)(T[] data) pure nothrow @safe @nogc { typeof(return) nWrites = 0; foreach (immutable cycleStart, item1; data) { size_t pos = cycleStart; foreach (item2; data[cycleStart + 1 .. $]) if (item2 < item1) po...
Write the same code in D as shown below in Go.
package main import ( "fmt" "math/rand" "time" ) func cyclesort(ints []int) int { writes := 0 for cyclestart := 0; cyclestart < len(ints)-1; cyclestart++ { item := ints[cyclestart] pos := cyclestart for i := cyclestart + 1; i < len(ints); i++ { if ints[i] < item { pos++ } } if pos == cycl...
import std.stdio, std.algorithm; uint cycleSort(T)(T[] data) pure nothrow @safe @nogc { typeof(return) nWrites = 0; foreach (immutable cycleStart, item1; data) { size_t pos = cycleStart; foreach (item2; data[cycleStart + 1 .. $]) if (item2 < item1) po...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import "fmt" func sameDigits(n, b int) bool { f := n % b n /= b for n > 0 { if n%b != f { return false } n /= b } return true } func isBrazilian(n int) bool { if n < 7 { return false } if n%2 == 0 && n >= 8 { return true...
import std.stdio; bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0) return true; for (int b = 2; b < n - 1; ++b) { i...
Convert this Go snippet to D and keep its semantics consistent.
package main import "fmt" func sameDigits(n, b int) bool { f := n % b n /= b for n > 0 { if n%b != f { return false } n /= b } return true } func isBrazilian(n int) bool { if n < 7 { return false } if n%2 == 0 && n >= 8 { return true...
import std.stdio; bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0) return true; for (int b = 2; b < n - 1; ++b) { i...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import ( "archive/tar" "compress/gzip" "flag" "io" "log" "os" "time" ) func main() { filename := flag.String("file", "TAPE.FILE", "filename within TAR") data := flag.String("data", "", "data for file") outfile := flag.String(...
import std.stdio; void main() { version(Windows) { File f = File("TAPE.FILE", "w"); } else { File f = File("/dev/tape", "w"); } f.writeln("Hello World!"); }
Maintain the same structure and functionality when rewriting this code in D.
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[...
import std.stdio; void main() { int[] a; bool[int] used; bool[int] used1000; bool foundDup; a ~= 0; used[0] = true; used1000[0] = true; int n = 1; while (n <= 15 || !foundDup || used1000.length < 1001) { int next = a[n - 1] - n; if (next < 1 || (next in used) !is n...
Translate the given Go code snippet into D without altering its behavior.
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[...
import std.stdio; void main() { int[] a; bool[int] used; bool[int] used1000; bool foundDup; a ~= 0; used[0] = true; used1000[0] = true; int n = 1; while (n <= 15 || !foundDup || used1000.length < 1001) { int next = a[n - 1] - n; if (next < 1 || (next in used) !is n...
Convert the following code from Go to D, ensuring the logic remains intact.
package main import "fmt" type Func func(int) int type FuncFunc func(Func) Func type RecursiveFunc func (RecursiveFunc) Func func main() { fac := Y(almost_fac) fib := Y(almost_fib) fmt.Println("fac(10) = ", fac(10)) fmt.Println("fib(10) = ", fib(10)) } func Y(f FuncFunc) Func { g := func(r RecursiveFunc) Func ...
import std.stdio, std.traits, std.algorithm, std.range; auto Y(S, T...)(S delegate(T) delegate(S delegate(T)) f) { static struct F { S delegate(T) delegate(F) f; alias f this; } return (x => x(x))(F(x => f((T v) => x(x)(v)))); } void main() { auto factorial = Y((int delegate(int) self...
Produce a functionally identical D code for the snippet given in Go.
package main import "fmt" func sumDivisors(n int) int { sum := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { sum += i j := n / i if j != i { sum += j } } i += k } return...
import std.stdio; uint divisor_sum(uint n) { uint total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (uint p = 3; p * p <= n; p += 2) { uint sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; ...
Translate the given Go code snippet into D without altering its behavior.
package main import "fmt" func sumDivisors(n int) int { sum := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { sum += i j := n / i if j != i { sum += j } } i += k } return...
import std.stdio; uint divisor_sum(uint n) { uint total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) { total += power; } for (uint p = 3; p * p <= n; p += 2) { uint sum = 1; for (power = p; n % p == 0; power *= p, n /= p) { sum += power; ...
Convert this Go snippet to D and keep its semantics consistent.
package main import ( "fmt" "sync" ) var a = []int{170, 45, 75, 90, 802, 24, 2, 66} var aMax = 1000 const bead = 'o' func main() { fmt.Println("before:", a) beadSort() fmt.Println("after: ", a) } func beadSort() { all := make([]byte, aMax*len(a)) abacus := make([][]byte, ...
import std.stdio, std.algorithm, std.range, std.array, std.functional; alias repeat0 = curry!(repeat, 0); auto columns(R)(R m) pure @safe { return m .map!walkLength .reduce!max .iota .map!(i => m.filter!(s => s.length > i).walkLength.repeat0); } auto beadSort(in uin...
Keep all operations the same but rewrite the snippet in D.
package main import ( "fmt" "log" "strconv" ) func co9Peterson(base int) (cob func(string) (byte, error), err error) { if base < 2 || base > 36 { return nil, fmt.Errorf("co9Peterson: %d invalid base", base) } addDigits := func(a, b byte) (string, error) {...
import std.stdio, std.algorithm, std.range; uint[] castOut(in uint base=10, in uint start=1, in uint end=999999) { auto ran = iota(base - 1) .filter!(x => x % (base - 1) == (x * x) % (base - 1)); auto x = start / (base - 1); immutable y = start % (base - 1); typeof(return) result; w...
Transform the following Go implementation into D, maintaining the same output and logic.
package main import ( "fmt" "log" "strconv" ) func co9Peterson(base int) (cob func(string) (byte, error), err error) { if base < 2 || base > 36 { return nil, fmt.Errorf("co9Peterson: %d invalid base", base) } addDigits := func(a, b byte) (string, error) {...
import std.stdio, std.algorithm, std.range; uint[] castOut(in uint base=10, in uint start=1, in uint end=999999) { auto ran = iota(base - 1) .filter!(x => x % (base - 1) == (x * x) % (base - 1)); auto x = start / (base - 1); immutable y = start % (base - 1); typeof(return) result; w...
Translate this program into D but keep the logic exactly as in Go.
package main import ( "encoding/json" "fmt" "io" "os" "sort" "strings" "time" "unicode" ) type Item struct { Stamp time.Time Name string Tags []string `json:",omitempty"` Notes string `json:",omitempty"` } func (i *Item) String() string { s := i.Stamp.Format...
import std.stdio, std.algorithm, std.string, std.conv, std.array, std.file, std.csv, std.datetime; private { immutable filename = "simdb.csv"; struct Item { string name, date, category; } void addItem(in string[] item) { if (item.length < 3) return printUsage(); ...
Generate a D translation of this Go snippet without changing its computational steps.
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } retu...
import std.stdio; uint divisor_count(uint n) { uint total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (uint p = 3; p * p <= n; p += 2) { uint count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > ...
Keep all operations the same but rewrite the snippet in D.
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } retu...
import std.stdio; uint divisor_count(uint n) { uint total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (uint p = 3; p * p <= n; p += 2) { uint count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > ...
Maintain the same structure and functionality when rewriting this code in D.
package main import "fmt" func möbius(to int) []int { if to < 1 { to = 1 } mobs := make([]int, to+1) primes := []int{2} for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { if p > j { break ...
import std.math; import std.stdio; immutable MU_MAX = 1_000_000; int mobiusFunction(int n) { static initialized = false; static int[MU_MAX + 1] MU; if (initialized) { return MU[n]; } MU[] = 1; int root = cast(int) sqrt(cast(real) MU_MAX); for (int i = 2; i <= root; i++) { ...
Translate the given Go code snippet into D without altering its behavior.
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } re...
import std.math; import std.stdio; uint divisorCount(uint n) { uint total = 1; for (; (n & 1) == 0; n >>= 1) { total++; } for (uint p = 3; p * p <= n; p += 2) { uint count = 1; for (; n % p == 0; n /= p) { count++; } total *= count; } ...
Change the programming language of this snippet from Go to D without modifying what it does.
package main import "fmt" func prodDivisors(n int) int { prod := 1 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { prod *= i j := n / i if j != i { prod *= j } } i += k } re...
import std.math; import std.stdio; uint divisorCount(uint n) { uint total = 1; for (; (n & 1) == 0; n >>= 1) { total++; } for (uint p = 3; p * p <= n; p += 2) { uint count = 1; for (; n % p == 0; n /= p) { count++; } total *= count; } ...
Produce a functionally identical D code for the snippet given in Go.
package cards import ( "math/rand" ) type Suit uint8 const ( Spade Suit = 3 Heart Suit = 2 Diamond Suit = 1 Club Suit = 0 ) func (s Suit) String() string { const suites = "CDHS" return suites[s : s+1] } type Rank uint8 const ( Ace Rank = 1 Two Rank = 2 Three Rank = 3 Four Rank = 4 Fiv...
import std.stdio, std.typecons, std.algorithm, std.traits, std.array, std.range, std.random; enum Pip {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace} enum Suit {Diamonds, Spades, Hearts, Clubs} alias Card = Tuple!(Pip, Suit); auto newDeck() pure nothrow @safe { retu...
Write the same algorithm in D as shown in this Go implementation.
package main import "fmt" func gcd(n, k int) int { if n < k || k < 1 { panic("Need n >= k and k >= 1") } s := 1 for n&1 == 0 && k&1 == 0 { n >>= 1 k >>= 1 s <<= 1 } t := n if n&1 != 0 { t = -k } for t != 0 { for t&1 == 0 { ...
import std.stdio; import std.numeric; int[10000] cache; bool is_perfect_totient(int num) { int tot = 0; for (int i = 1; i < num; i++) { if (gcd(num, i) == 1) { tot++; } } int sum = tot + cache[tot]; cache[num] = sum; return num == sum; } void main() { int j = 1...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import "fmt" func gcd(n, k int) int { if n < k || k < 1 { panic("Need n >= k and k >= 1") } s := 1 for n&1 == 0 && k&1 == 0 { n >>= 1 k >>= 1 s <<= 1 } t := n if n&1 != 0 { t = -k } for t != 0 { for t&1 == 0 { ...
import std.stdio; import std.numeric; int[10000] cache; bool is_perfect_totient(int num) { int tot = 0; for (int i = 1; i < num; i++) { if (gcd(num, i) == 1) { tot++; } } int sum = tot + cache[tot]; cache[num] = sum; return num == sum; } void main() { int j = 1...
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 unsigned := true l := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { l[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { l[n][k] = new(big.Int) } ...
import std.algorithm : map; import std.bigint; import std.range; import std.stdio; BigInt factorial(BigInt n) { if (n == 0) return BigInt(1); BigInt res = 1; while (n > 0) { res *= n--; } return res; } BigInt lah(BigInt n, BigInt k) { if (k == 1) return factorial(n); if (k == n) re...
Generate an equivalent D version of this Go code.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true l := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { l[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { l[n][k] = new(big.Int) } ...
import std.algorithm : map; import std.bigint; import std.range; import std.stdio; BigInt factorial(BigInt n) { if (n == 0) return BigInt(1); BigInt res = 1; while (n > 0) { res *= n--; } return res; } BigInt lah(BigInt n, BigInt k) { if (k == 1) return factorial(n); if (k == n) re...
Convert the following code from Go to D, ensuring the logic remains intact.
package main import "fmt" func twoSum(a []int, targetSum int) (int, int, bool) { len := len(a) if len < 2 { return 0, 0, false } for i := 0; i < len - 1; i++ { if a[i] <= targetSum { for j := i + 1; j < len; j++ { sum := a[i] + a[j] if sum ==...
import std.stdio; void main() { const arr = [0, 2, 11, 19, 90]; const sum = 21; writeln(arr.twoSum(21)); } int[] twoSum(const int[] arr, const int sum) in { import std.algorithm.sorting : isSorted; assert(arr.isSorted); } out(result) { assert(result.length == 0 || arr[result[0]] + arr[result...
Change the following Go code into D without altering its purpose.
package main import "fmt" func twoSum(a []int, targetSum int) (int, int, bool) { len := len(a) if len < 2 { return 0, 0, false } for i := 0; i < len - 1; i++ { if a[i] <= targetSum { for j := i + 1; j < len; j++ { sum := a[i] + a[j] if sum ==...
import std.stdio; void main() { const arr = [0, 2, 11, 19, 90]; const sum = 21; writeln(arr.twoSum(21)); } int[] twoSum(const int[] arr, const int sum) in { import std.algorithm.sorting : isSorted; assert(arr.isSorted); } out(result) { assert(result.length == 0 || arr[result[0]] + arr[result...
Maintain the same structure and functionality when rewriting this code in D.
package main import ( "fmt" "strconv" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false ...
import std.algorithm; import std.array; import std.conv; import std.range; import std.stdio; immutable MAX = 10_000_000; bool[] primes; bool[] sieve(int limit) { bool[] p = uninitializedArray!(bool[])(limit); p[0..2] = false; p[2..$] = true; foreach (i; 2..limit) { if (p[i]) { for ...
Transform the following Go implementation into D, maintaining the same output and logic.
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } retu...
import std.stdio; uint divisor_count(uint n) { uint total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (uint p = 3; p * p <= n; p += 2) { uint count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1...
Convert this Go snippet to D and keep its semantics consistent.
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i...
import std.bigint; import std.stdio; bool isPrime(BigInt n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } auto i = BigInt(5); while (i * i <= n) { if (n % i == 0){ return false; ...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i...
import std.bigint; import std.stdio; bool isPrime(BigInt n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } auto i = BigInt(5); while (i * i <= n) { if (n % i == 0){ return false; ...
Rewrite the snippet below in D so it works the same as the original Go code.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) }...
import std.stdio; bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2,3,5,7: break; default: return false; } n /= 10; sum += r; } return sum == 13; } void main() ...
Translate this program into D but keep the logic exactly as in Go.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) }...
import std.stdio; bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2,3,5,7: break; default: return false; } n /= 10; sum += r; } return sum == 13; } void main() ...
Translate the given Go code snippet into D without altering its behavior.
package main import ( "fmt" big "github.com/ncw/gmp" "strings" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { ...
import std.bigint; 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...
Convert this Go block to D, preserving its control flow and logic.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) if len(a) > 1 && !recurse(len(a) - 1) { panic("sorted permutation not found!") } fmt.Println("after: ", a) } func recurse(last int) bool { ...
import std.stdio, std.algorithm, permutations2; void permutationSort(T)(T[] items) pure nothrow @safe @nogc { foreach (const perm; items.permutations!false) if (perm.isSorted) break; } void main() { auto data = [2, 7, 4, 3, 5, 1, 0, 9, 8, 6, -1]; data.permutationSort; data.writeln;...
Convert the following code from Go to D, ensuring the logic remains intact.
package main import "fmt" func main() { fmt.Println(root(3, 8)) fmt.Println(root(3, 9)) fmt.Println(root(2, 2e18)) } func root(N, X int) int { for r := 1; ; { x := X for i := 1; i < N; i++ { x /= r } x -= r Δ...
import std.bigint; import std.stdio; auto iRoot(BigInt b, int n) in { assert(b >=0 && n > 0); } body { if (b < 2) return b; auto n1 = n - 1; auto n2 = BigInt(n); auto n3 = BigInt(n1); auto c = BigInt(1); auto d = (n3 + b) / n2; auto e = (n3 * d + b / d^^n1) / n2; while (c != d && c ...
Port the provided Go code into D while preserving the original functionality.
package main import "fmt" func main() { fmt.Println(root(3, 8)) fmt.Println(root(3, 9)) fmt.Println(root(2, 2e18)) } func root(N, X int) int { for r := 1; ; { x := X for i := 1; i < N; i++ { x /= r } x -= r Δ...
import std.bigint; import std.stdio; auto iRoot(BigInt b, int n) in { assert(b >=0 && n > 0); } body { if (b < 2) return b; auto n1 = n - 1; auto n2 = BigInt(n); auto n3 = BigInt(n1); auto c = BigInt(1); auto d = (n3 + b) / n2; auto e = (n3 * d + b / d^^n1) / n2; while (c != d && c ...
Convert the following code from Go to D, ensuring the logic remains intact.
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
#!/usr/bin/env rdmd -version=scriptedmain module scriptedmain; import std.stdio; int meaningOfLife() { return 42; } version (scriptedmain) { void main(string[] args) { writeln("Main: The meaning of life is ", meaningOfLife()); } }
Change the programming language of this snippet from Go to D without modifying what it does.
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
#!/usr/bin/env rdmd -version=scriptedmain module scriptedmain; import std.stdio; int meaningOfLife() { return 42; } version (scriptedmain) { void main(string[] args) { writeln("Main: The meaning of life is ", meaningOfLife()); } }
Write the same code in D as shown below in Go.
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d...
import std.stdio; bool isPrime(uint n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } for (uint p = 5; p * p <= n; p += 4) { if (n % p == 0) { return false; } p += 2; if...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d...
import std.stdio; bool isPrime(uint n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } for (uint p = 5; p * p <= n; p += 4) { if (n % p == 0) { return false; } p += 2; if...
Convert the following code from Go to D, ensuring the logic remains intact.
package main import ( "fmt" "time" ) func main() { var year int var t time.Time var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 } for { fmt.Print("Please select a year: ") _, err := fmt.Scanf("%d", &year) if err != nil { fmt.Println(err) continue } else { break } } fmt.Prin...
void lastSundays(in uint year) { import std.stdio, std.datetime; foreach (immutable month; 1 .. 13) { auto date = Date(year, month, 1); date.day(date.daysInMonth); date.roll!"days"(-(date.dayOfWeek + 7) % 7); date.writeln; } } void main() { lastSundays(2013); }
Please provide an equivalent version of this Go code in D.
package main import ( "fmt" "time" ) func main() { var year int var t time.Time var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 } for { fmt.Print("Please select a year: ") _, err := fmt.Scanf("%d", &year) if err != nil { fmt.Println(err) continue } else { break } } fmt.Prin...
void lastSundays(in uint year) { import std.stdio, std.datetime; foreach (immutable month; 1 .. 13) { auto date = Date(year, month, 1); date.day(date.daysInMonth); date.roll!"days"(-(date.dayOfWeek + 7) % 7); date.writeln; } } void main() { lastSundays(2013); }
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" "math/rand" "time" ) type matrix [][]int func shuffle(row []int, n int) { rand.Shuffle(n, func(i, j int) { row[i], row[j] = row[j], row[i] }) } func latinSquare(n int) { if n <= 0 { fmt.Println("[]\n") return } latin := make(matrix,...
import std.array; import std.random; import std.stdio; alias Matrix = int[][]; void latinSquare(int n) { if (n <= 0) { writeln("[]"); return; } Matrix latin = uninitializedArray!Matrix(n, n); foreach (row; latin) { for (int i = 0; i < n; i++) { row[i] = i; ...
Write the same algorithm in D as shown in this Go implementation.
package main import ( "fmt" "sort" "strconv" "strings" ) func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } retu...
import std.array; import std.stdio; int turn(int base, int n) { int sum = 0; while (n != 0) { int re = n % base; n /= base; sum += re; } return sum % base; } void fairShare(int base, int count) { writef("Base %2d:", base); foreach (i; 0..count) { auto t = turn(b...
Convert this Go snippet to D and keep its semantics consistent.
package main import ( "fmt" "strconv" ) func uabs(a, b uint64) uint64 { if a > b { return a - b } return b - a } func isEsthetic(n, b uint64) bool { if n == 0 { return false } i := n % b n /= b for n > 0 { j := n % b if uabs(i, j) != 1 { ...
import std.conv; import std.stdio; ulong uabs(ulong a, ulong b) { if (a > b) { return a - b; } return b - a; } bool isEsthetic(ulong n, ulong b) { if (n == 0) { return false; } auto i = n % b; n /= b; while (n > 0) { auto j = n % b; if (uabs(i, j) != 1) ...
Convert this Go snippet to D and keep its semantics consistent.
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
import std.stdio; import std.uni; import std.utf; void main() { int a; int δ; char c; wchar w; dchar d; writeln("some text"); writeln("some text"c); writeln("こんにちは"c); writeln("Здравствуйте"w); writeln("שלום"d); }
Produce a functionally identical D code for the snippet given in Go.
package permute func Iter(p []int) func() int { f := pf(len(p)) return func() int { return f(p) } } func pf(n int) func([]int) int { sign := 1 switch n { case 0, 1: return func([]int) (s int) { s = sign sign = 0 return } defa...
import std.algorithm, std.array, std.typecons, std.range; struct Spermutations(bool doCopy=true) { private immutable uint n; alias TResult = Tuple!(int[], int); int opApply(in int delegate(in ref TResult) nothrow dg) nothrow { int result; int sign = 1; alias Int2 = Tuple!(int, int...
Translate this program into D but keep the logic exactly as in Go.
package main import "fmt" func nextInCycle(c []int, index int) int { return c[index % len(c)] } func kolakoski(c []int, slen int) []int { s := make([]int, slen) i, k := 0, 0 for { s[i] = nextInCycle(c, k) if s[k] > 1 { for j := 1; j < s[k]; j++ { i++ ...
import std.stdio; void repeat(int count, void delegate(int) action) { for (int i=0; i<count; i++) { action(i); } } T nextInCycle(T)(T[] self, int index) { return self[index % self.length]; } T[] kolakoski(T)(T[] self, int len) { T[] s; s.length = len; int i; int k; while (i<le...
Translate the given Go code snippet into D without altering its behavior.
package main import ( "bufio" "errors" "fmt" "math" "os" "regexp" "strconv" "strings" ) func main() { fmt.Println("Numbers please separated by space/commas:") sc := bufio.NewScanner(os.Stdin) sc.Scan() s, n, min, max, err := spark(sc.Text()) if err != nil { ...
void main() { import std.stdio, std.range, std.algorithm, std.conv, std.string, std.regex; "Numbers please separated by space/commas: ".write; immutable numbers = readln .strip .splitter(r"[\s,]+".regex) .array ...
Produce a language-to-language conversion: from Go to D, same semantics.
package main import ( "fmt" "github.com/biogo/biogo/align" ab "github.com/biogo/biogo/alphabet" "github.com/biogo/biogo/feat" "github.com/biogo/biogo/seq/linear" ) func main() { lc := ab.Must(ab.NewAlphabet("-abcdefghijklmnopqrstuvwxyz", feat.Undefined, '-', 0, true)) ...
void main() { import std.stdio, std.algorithm; immutable s1 = "rosettacode"; immutable s2 = "raisethysword"; string s1b, s2b; size_t pos1, pos2; foreach (immutable c; levenshteinDistanceAndPath(s1, s2)[1]) { final switch (c) with (EditOp) { case none, substitute: ...
Convert the following code from Go to D, ensuring the logic remains intact.
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back =...
import std.stdio, std.algorithm, power_set2; T[] lis(T)(T[] items) pure nothrow { return items .powerSet .filter!isSorted .minPos!q{ a.length > b.length } .front; } void main() { [3, 2, 6, 4, 5, 1].lis.writeln; [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import "fmt" type person struct{ name string age int } func copy(p person) person { return person{p.name, p.age} } func main() { p := person{"Dave", 40} fmt.Println(p) q := copy(p) fmt.Println(q) }
enum GenStruct(string name, string fieldName) = "struct " ~ name ~ "{ int " ~ fieldName ~ "; }"; mixin(GenStruct!("Foo", "bar")); void main() { Foo f; f.bar = 10; }
Translate this program into D but keep the logic exactly as in Go.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) var ten = big.NewInt(10) var twenty = big.NewInt(20) var hundred = big.NewInt(100) func sqrt(n float64, limit int) { if n < 0 { log.Fatal("Number cannot be negative") } count := 0 for n != math.Trunc(n) { n *= 10...
import std.bigint; import std.math; import std.stdio; void main() { BigInt i = 2; BigInt j = cast(long) floor(sqrt(cast(real) 2.0)); BigInt k = j; BigInt d = j; int n = 500; int n0 = n; do { write(d); i = (i - k * d) * 100; k = 20 * j; for (d = 1; d <= 10; d+...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) var ten = big.NewInt(10) var twenty = big.NewInt(20) var hundred = big.NewInt(100) func sqrt(n float64, limit int) { if n < 0 { log.Fatal("Number cannot be negative") } count := 0 for n != math.Trunc(n) { n *= 10...
import std.bigint; import std.math; import std.stdio; void main() { BigInt i = 2; BigInt j = cast(long) floor(sqrt(cast(real) 2.0)); BigInt k = j; BigInt d = j; int n = 500; int n0 = n; do { write(d); i = (i - k * d) * 100; k = 20 * j; for (d = 1; d <= 10; d+...
Keep all operations the same but rewrite the snippet in D.
package main import ( "fmt" "sort" "strings" ) type indexSort struct { val sort.Interface ind []int } func (s indexSort) Len() int { return len(s.ind) } func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] } func (s indexSort) Swap(i, j int) { s.val.Swap(s.ind[i], s.ind[j]) s.ind[i], ...
import std.stdio, std.string, std.algorithm, std.array, std.range, std.conv; T[] orderDisjointArrayItems(T)(in T[] data, in T[] items) pure @safe { int[] itemIndices; foreach (item; items.dup.sort().uniq) { immutable int itemCount = items.count(item); assert(data.count(item) >= itemCoun...
Rewrite the snippet below in D so it works the same as the original Go code.
package main import ( "fmt" "math/big" ) func rank(l []uint) (r big.Int) { for _, n := range l { r.Lsh(&r, n+1) r.SetBit(&r, int(n), 1) } return } func unrank(n big.Int) (l []uint) { m := new(big.Int).Set(&n) for a := m.BitLen(); a > 0; { m.SetBit(m, a-1, 0) ...
import std.stdio, std.algorithm, std.array, std.conv, std.bigint; BigInt rank(T)(in T[] x) pure @safe { return BigInt("0x" ~ x.map!text.join('F')); } BigInt[] unrank(BigInt n) pure { string s; while (n) { s = "0123456789ABCDEF"[n % 16] ~ s; n /= 16; } return s.split('F').map!BigI...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import ( "fmt" "math/rand" "time" ) const boxW = 41 const boxH = 37 const pinsBaseW = 19 const nMaxBalls = 55 const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 const ( empty = ' ' ball = 'o' wall = '|' corner = '+' floor = '-' pin = '.' ) ...
import std.stdio, std.algorithm, std.random, std.array; enum int boxW = 41, boxH = 37; enum int pinsBaseW = 19; enum int nMaxBalls = 55; static assert(boxW >= 2 && boxH >= 2); static assert((boxW - 4) >= (pinsBaseW * 2 - 1)); static assert((boxH - 3) >= pinsBaseW); enum centerH = pinsBaseW + (boxW - (p...
Convert this Go snippet to D and keep its semantics consistent.
package main import ( "fmt" "math" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { var squares []int outer: for i := 1; i < 50; i++ { if isSquare(i) { squares = append(squares, i) } else { n := i ...
import std.stdio; void f(int n) { if (n < 1) { return; } int i = 1; while (true) { int sq = i * i; while (sq > n) { sq /= 10; } if (sq == n) { "%3d %9d %4d".writefln(n, i * i, i); return; } i++; } } void...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import "fmt" func circleSort(a []int, lo, hi, swaps int) int { if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- } ...
import std.stdio, std.algorithm, std.array, std.traits; void circlesort(T)(T[] items) if (isMutable!T) { uint inner(size_t lo, size_t hi, uint swaps) { if (lo == hi) return swaps; auto high = hi; auto low = lo; immutable mid = (hi - lo) / 2; while (lo < hi) { ...
Convert this Go block to D, preserving its control flow and logic.
package expand type Expander interface { Expand() []string } type Text string func (t Text) Expand() []string { return []string{string(t)} } type Alternation []Expander func (alt Alternation) Expand() []string { var out []string for _, e := range alt { out = append(out, e.Expand()...) } return out } ...
import std.stdio, std.typecons, std.array, std.range, std.algorithm, std.string; Nullable!(Tuple!(string[], string)) getGroup(string s, in uint depth) pure nothrow @safe { string[] sout; auto comma = false; while (!s.empty) { const r = getItems(s, depth); const g = r[0]; s...
Generate a D translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "sort" "strconv" ) type wheel struct { next int values []string } type wheelMap = map[string]wheel func generate(wheels wheelMap, start string, maxCount int) { count := 0 w := wheels[start] for { s := w.values[w.next] v, err := strconv.At...
import std.exception; import std.range; import std.stdio; struct Wheel { private string[] values; private uint index; invariant { enforce(index < values.length, "index out of range"); } this(string[] value...) in { enforce(value.length > 0, "Cannot create a wheel with no elements"...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import ( "fmt" "sort" "strconv" ) type wheel struct { next int values []string } type wheelMap = map[string]wheel func generate(wheels wheelMap, start string, maxCount int) { count := 0 w := wheels[start] for { s := w.values[w.next] v, err := strconv.At...
import std.exception; import std.range; import std.stdio; struct Wheel { private string[] values; private uint index; invariant { enforce(index < values.length, "index out of range"); } this(string[] value...) in { enforce(value.length > 0, "Cannot create a wheel with no elements"...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import ( "fmt" "golang.org/x/net/html" "io/ioutil" "net/http" "regexp" "strings" ) var ( expr = `<h3 class="title"><a class=.*?href="(.*?)".*?>(.*?)</a></h3>` + `.*?<div class="compText aAbs" ><p class=.*?>(.*?)</p></div>` rx = regexp.MustCompile(expr) ) type Yaho...
import std.stdio, std.exception, std.regex, std.algorithm, std.string, std.net.curl; struct YahooResult { string url, title, content; string toString() const { return "\nTitle: %s\nLink: %s\nText: %s" .format(title, url, content); } } struct YahooSearch { private strin...
Please provide an equivalent version of this Go code in D.
package main import ( "fmt" "math" ) var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe on...
import std.stdio, std.typecons, std.math; class ValueException : Exception { this(string msg_) pure { super(msg_); } } struct V2 { double x, y; } struct Circle { double x, y, r; } Tuple!(Circle, Circle) circlesFromTwoPointsAndRadius(in V2 p1, in V2 p2, in double r) pure in { assert(r >= 0, "radius can't be ...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" "math" ) var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe on...
import std.stdio, std.typecons, std.math; class ValueException : Exception { this(string msg_) pure { super(msg_); } } struct V2 { double x, y; } struct Circle { double x, y, r; } Tuple!(Circle, Circle) circlesFromTwoPointsAndRadius(in V2 p1, in V2 p2, in double r) pure in { assert(r >= 0, "radius can't be ...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import ( "fmt" "math" ) func max(a, b uint64) uint64 { if a > b { return a } return b } func min(a, b uint64) uint64 { if a < b { return a } return b } func ndigits(x uint64) (n int) { for ; x > 0; x /= 10 { n++ } return } fu...
import std.stdio, std.range, std.algorithm, std.typecons, std.conv; auto fangs(in long n) pure nothrow @safe { auto pairs = iota(2, cast(int)(n ^^ 0.5)) .filter!(x => !(n % x)).map!(x => [x, n / x]); enum dLen = (in long x) => x.text.length; immutable half = dLen(n) / 2; enum halvesQ ...
Transform the following Go implementation into D, maintaining the same output and logic.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" ...
import std.stdio; class Cistercian { private immutable SIZE = 15; private char[SIZE][SIZE] canvas; public this(int n) { initN(); draw(n); } private void initN() { foreach (ref row; canvas) { row[] = ' '; row[5] = 'x'; } } private vo...
Write the same code in D as shown below in Go.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" ...
import std.stdio; class Cistercian { private immutable SIZE = 15; private char[SIZE][SIZE] canvas; public this(int n) { initN(); draw(n); } private void initN() { foreach (ref row; canvas) { row[] = ' '; row[5] = 'x'; } } private vo...
Preserve the algorithm and functionality while converting the code from Go to D.
package main import ( "fmt" "sort" "strings" ) type card struct { face byte suit byte } const faces = "23456789tjqka" const suits = "shdc" func isStraight(cards []card) bool { sorted := make([]card, 5) copy(sorted, cards) sort.Slice(sorted, func(i, j int) bool { return sorted...
import std.stdio, std.string, std.algorithm, std.range; string analyzeHand(in string inHand) pure { enum handLen = 5; static immutable face = "A23456789TJQK", suit = "SHCD"; static immutable errorMessage = "invalid hand."; const hand = inHand.toUpper.split.sort().release; if (hand.length != hand...
Port the following code from Go to D with equivalent syntax and logic.
package main import ( "fmt" "sort" "strings" ) type card struct { face byte suit byte } const faces = "23456789tjqka" const suits = "shdc" func isStraight(cards []card) bool { sorted := make([]card, 5) copy(sorted, cards) sort.Slice(sorted, func(i, j int) bool { return sorted...
import std.stdio, std.string, std.algorithm, std.range; string analyzeHand(in string inHand) pure { enum handLen = 5; static immutable face = "A23456789TJQK", suit = "SHCD"; static immutable errorMessage = "invalid hand."; const hand = inHand.toUpper.split.sort().release; if (hand.length != hand...
Change the programming language of this snippet from Go to D without modifying what it does.
package main import ( "github.com/fogleman/gg" "strings" ) func wordFractal(i int) string { if i < 2 { if i == 1 { return "1" } return "" } var f1 strings.Builder f1.WriteString("1") var f2 strings.Builder f2.WriteString("0") for j := i - 2; j >=...
import std.range, grayscale_image, turtle; void drawFibonacci(Color)(Image!Color img, ref Turtle t, in string word, in real step) { foreach (immutable i, immutable c; word) { t.forward(img, step); if (c == '0') { if ((i + 1) % 2 == 0) t.left(90)...
Preserve the algorithm and functionality while converting the code from Go to D.
package main import "fmt" import "math/rand" func main(){ var a1,a2,a3,y,match,j,k int var inp string y=1 for y==1{ fmt.Println("Enter your sequence:") fmt.Scanln(&inp) var Ai [3] int var user [3] int for j=0;j<3;j++{ if(inp[j]==104){ user[j]=1 }else{ user[j]=0 } } for k=0;k<3;k++{ Ai[k]=rand.Intn(2) } for user[0]==Ai[...
void main() { import std.stdio, std.random, std.algorithm, std.string, std.conv, std.range, core.thread; immutable first = uniform(0, 2) == 0; string you, me; if (first) { me = 3.iota.map!(_ => "HT"[uniform(0, $)]).text; writefln("I choose first and will win on first seeing ...
Produce a functionally identical D code for the snippet given in Go.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color....
void main() { import grayscale_image; enum order = 8, margin = 10, width = 2 ^^ order; auto im = new Image!Gray(width + 2 * margin, width + 2 * margin); im.clear(Gray.white); foreach (immutable y; 0 .. width) foreach (immutable x; 0 .. width) if ((x & y) == 0...
Generate a D translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color....
void main() { import grayscale_image; enum order = 8, margin = 10, width = 2 ^^ order; auto im = new Image!Gray(width + 2 * margin, width + 2 * margin); im.clear(Gray.white); foreach (immutable y; 0 .. width) foreach (immutable x; 0 .. width) if ((x & y) == 0...
Convert this Go block to D, preserving its control flow and logic.
package main import ( "fmt" "strings" ) func printBlock(data string, le int) { a := []byte(data) sumBytes := 0 for _, b := range a { sumBytes += int(b - 48) } fmt.Printf("\nblocks %c, cells %d\n", a, le) if le-sumBytes <= 0 { fmt.Println("No solution") return ...
import std.stdio, std.array, std.algorithm, std.exception, std.conv, std.concurrency, std.range; struct Solution { uint pos, len; } Generator!(Solution[]) nonoBlocks(in uint[] blocks, in uint cells) { return new typeof(return)({ if (blocks.empty || blocks[0] == 0) { yield([Solution(0, 0...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import ( "fmt" "strings" ) func printBlock(data string, le int) { a := []byte(data) sumBytes := 0 for _, b := range a { sumBytes += int(b - 48) } fmt.Printf("\nblocks %c, cells %d\n", a, le) if le-sumBytes <= 0 { fmt.Println("No solution") return ...
import std.stdio, std.array, std.algorithm, std.exception, std.conv, std.concurrency, std.range; struct Solution { uint pos, len; } Generator!(Solution[]) nonoBlocks(in uint[] blocks, in uint cells) { return new typeof(return)({ if (blocks.empty || blocks[0] == 0) { yield([Solution(0, 0...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import "fmt" type Range struct { start, end uint64 print bool } func main() { rgs := []Range{ {2, 1000, true}, {1000, 4000, true}, {2, 1e4, false}, {2, 1e5, false}, {2, 1e6, false}, {2, 1e7, false}, {2, 1e8, false}, {2, 1e9...
import std.stdio; struct Interval { int start, end; bool print; } void main() { Interval[] intervals = [ {2, 1_000, true}, {1_000, 4_000, true}, {2, 10_000, false}, {2, 100_000, false}, {2, 1_000_000, false}, {2, 10_000_000, false}, {2, 100_000_000, ...
Port the following code from Go to D with equivalent syntax and logic.
package main import "fmt" type Range struct { start, end uint64 print bool } func main() { rgs := []Range{ {2, 1000, true}, {1000, 4000, true}, {2, 1e4, false}, {2, 1e5, false}, {2, 1e6, false}, {2, 1e7, false}, {2, 1e8, false}, {2, 1e9...
import std.stdio; struct Interval { int start, end; bool print; } void main() { Interval[] intervals = [ {2, 1_000, true}, {1_000, 4_000, true}, {2, 10_000, false}, {2, 100_000, false}, {2, 1_000_000, false}, {2, 10_000_000, false}, {2, 100_000_000, ...
Keep all operations the same but rewrite the snippet in D.
package main import "fmt" func main() { coconuts := 11 outer: for ns := 2; ns < 10; ns++ { hidden := make([]int, ns) coconuts = (coconuts/ns)*ns + 1 for { nc := coconuts for s := 1; s <= ns; s++ { if nc%ns == 1 { hidden[s-1] =...
import std.stdio; void main() { auto coconuts = 11; outer: foreach (ns; 2..10) { int[] hidden = new int[ns]; coconuts = (coconuts / ns) * ns + 1; while (true) { auto nc = coconuts; foreach (s; 1..ns+1) { if (nc % ns == 1) { ...
Translate the given Go code snippet into D without altering its behavior.
package main import "fmt" func main() { coconuts := 11 outer: for ns := 2; ns < 10; ns++ { hidden := make([]int, ns) coconuts = (coconuts/ns)*ns + 1 for { nc := coconuts for s := 1; s <= ns; s++ { if nc%ns == 1 { hidden[s-1] =...
import std.stdio; void main() { auto coconuts = 11; outer: foreach (ns; 2..10) { int[] hidden = new int[ns]; coconuts = (coconuts / ns) * ns + 1; while (true) { auto nc = coconuts; foreach (s; 1..ns+1) { if (nc % ns == 1) { ...
Please provide an equivalent version of this Go code in D.
package main import ( "fmt" "strings" "time" ) func main() { watches := []string{ "First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First", } for { t := time.Now() h := t.Hour() m := t.Minute() s := t.Second() if (m == 0 || m...
import std.stdio, core.thread, std.datetime; class NauticalBell : Thread { private shared bool stopped; this() { super(&run); } void run() { uint numBells; auto time = cast(TimeOfDay)Clock.currTime(); auto next = TimeOfDay(); void setNextBellTime() { ...
Ensure the translated D code behaves exactly like the original Go snippet.
package main import ( "fmt" "strings" "time" ) func main() { watches := []string{ "First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First", } for { t := time.Now() h := t.Hour() m := t.Minute() s := t.Second() if (m == 0 || m...
import std.stdio, core.thread, std.datetime; class NauticalBell : Thread { private shared bool stopped; this() { super(&run); } void run() { uint numBells; auto time = cast(TimeOfDay)Clock.currTime(); auto next = TimeOfDay(); void setNextBellTime() { ...
Convert the following code from Go to D, ensuring the logic remains intact.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math/rand" "os" "time" ) const ( imageWidth = 300 imageHeight = 200 nSites = 10 ) func main() { writePngFile(generateVoronoi(randomSites())) } func generateVoronoi(sx, sy []int) image.Im...
import std.random, std.algorithm, std.range, bitmap; struct Point { uint x, y; } enum randomPoints = (in size_t nPoints, in size_t nx, in size_t ny) => nPoints.iota .map!((int) => Point(uniform(0, nx), uniform(0, ny))) .array; Image!RGB generateVoronoi(in Point[] pts, in size_t ...
Preserve the algorithm and functionality while converting the code from Go to D.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math/rand" "os" "time" ) const ( imageWidth = 300 imageHeight = 200 nSites = 10 ) func main() { writePngFile(generateVoronoi(randomSites())) } func generateVoronoi(sx, sy []int) image.Im...
import std.random, std.algorithm, std.range, bitmap; struct Point { uint x, y; } enum randomPoints = (in size_t nPoints, in size_t nx, in size_t ny) => nPoints.iota .map!((int) => Point(uniform(0, nx), uniform(0, ny))) .array; Image!RGB generateVoronoi(in Point[] pts, in size_t ...
Change the following Go code into D without altering its purpose.
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, UseSSL: false, BindDN: "uid=readonlyuser,ou=People,dc=examp...
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")); int b = ldap.bind_s(r[0].dn, "password"); scope(exit) ldap.unbind; if (b) { writeln("error on binding"); return; } ... }
Produce a functionally identical D code for the snippet given in Go.
package main import "fmt" type Item struct { name string weight, value, qty int } var items = []Item{ {"map", 9, 150, 1}, {"compass", 13, 35, 1}, {"water", 153, 200, 2}, {"sandwich", 50, 60, 2}, {"glucose", 15, 60, 2}, {"tin", 68, 45, 3}, {"banana", 27, 60, 3}, {"apple", 39, 40, 3},...
import std.stdio, std.typecons, std.functional; immutable struct Item { string name; int weight, value, quantity; } immutable Item[] items = [ {"map", 9, 150, 1}, {"compass", 13, 35, 1}, {"water", 153, 200, 3}, {"sandwich", 50, 60, 2}, {"glucose", 15, 60, 2}, {"tin...
Change the programming language of this snippet from Go to D without modifying what it does.
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
import std.stdio, std.getopt; void main(string[] args) { string data = "file.dat"; int length = 24; bool verbose; enum Color { no, yes } Color color; args.getopt("length", &length, "file", &data, "verbose", &verbose, "color", &color)...
Maintain the same structure and functionality when rewriting this code in D.
package main import ( "flag" "fmt" ) func main() { b := flag.Bool("b", false, "just a boolean") s := flag.String("s", "", "any ol' string") n := flag.Int("n", 0, "your lucky number") flag.Parse() fmt.Println("b:", *b) fmt.Println("s:", *s) fmt.Println("n:", *n) }
import std.stdio, std.getopt; void main(string[] args) { string data = "file.dat"; int length = 24; bool verbose; enum Color { no, yes } Color color; args.getopt("length", &length, "file", &data, "verbose", &verbose, "color", &color)...
Port the provided Go code into D while preserving the original functionality.
package main import ( "fmt" "sort" "strconv" "strings" ) var board [][]int var start, given []int func setup(input []string) { puzzle := make([][]string, len(input)) for i := 0; i < len(input); i++ { puzzle[i] = strings.Fields(input[i]) } nCols := len(puzzle[0]) nRows...
import std.stdio, std.array, std.conv, std.algorithm, std.string; int[][] board; int[] given, start; void setup(string s) { auto lines = s.splitLines; auto cols = lines[0].split.length; auto rows = lines.length; given.length = 0; board = new int[][](rows + 2, cols + 2); foreach (row; board) ...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "sort" "strconv" "strings" ) var board [][]int var start, given []int func setup(input []string) { puzzle := make([][]string, len(input)) for i := 0; i < len(input); i++ { puzzle[i] = strings.Fields(input[i]) } nCols := len(puzzle[0]) nRows...
import std.stdio, std.array, std.conv, std.algorithm, std.string; int[][] board; int[] given, start; void setup(string s) { auto lines = s.splitLines; auto cols = lines[0].split.length; auto rows = lines.length; given.length = 0; board = new int[][](rows + 2, cols + 2); foreach (row; board) ...
Rewrite this program in D while keeping its functionality equivalent to the Go version.
package main import "fmt" type link struct { int next *link } func linkInts(s []int) *link { if len(s) == 0 { return nil } return &link{s[0], linkInts(s[1:])} } func (l *link) String() string { if l == nil { return "nil" } r := fmt.Sprintf("[%d", l.int) for l = l....
import std.stdio, std.container; DList!T strandSort(T)(DList!T list) { static DList!T merge(DList!T left, DList!T right) { DList!T result; while (!left.empty && !right.empty) { if (left.front <= right.front) { result.insertBack(left.front); left.removeFro...
Change the following Go code into D without altering its purpose.
package main import ( "encoding/xml" "fmt" "log" "os" ) type Inventory struct { XMLName xml.Name `xml:"inventory"` Title string `xml:"title,attr"` Sections []struct { XMLName xml.Name `xml:"section"` Name string `xml:"name,attr"` Items []struct { XMLName xml.Name `xml:"item"` Name ...
import kxml.xml; char[]xmlinput = "<inventory title=\"OmniCorp Store #45x10^3\"> <section name=\"health\"> <item upc=\"123456789\" stock=\"12\"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc=\"445322344\" stock=\"18\...
Generate a D translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "sort" ) type rankable interface { Len() int RankEqual(int, int) bool } func StandardRank(d rankable) []float64 { r := make([]float64, d.Len()) var k int for i := range r { if i == 0 || !d.RankEqual(i, i-1) { k = i + 1 } r[i] = float64(k) } return r } func ModifiedRank(...
import std.algorithm; import std.stdio; void main() { immutable scores = [ "Solomon": 44, "Jason": 42, "Errol": 42, "Garry": 41, "Bernard": 41, "Barry": 41, "Stephen": 39 ]; scores.standardRank; scores.modifiedRank; scores.denseRank; scor...
Write the same code in D as shown below in Go.
package main import ( "bufio" "fmt" "io" "log" "os" "strings" "unicode" ) type line struct { kind lineKind option string value string disabled bool } type lineKind int const ( _ lineKind = iota ignore parseError comment blank value ) func (l line) String() string { switch l.kind { cas...
import std.stdio, std.file, std.string, std.regex, std.path, std.typecons; final class Config { enum EntryType { empty, enabled, disabled, comment, ignore } static protected struct Entry { EntryType type; string name, value; } protected Entry[] entries; protected string path...
Can you help me rewrite this code in D instead of Go, keeping it the same logically?
package main import ( "fmt" "strings" ) func main() { key := ` 8752390146 ET AON RIS 5BC/FGHJKLM 0PQD.VWXYZU` p := "you have put on 7.5 pounds since I saw you." fmt.Println(p) c := enc(key, p) fmt.Println(c) fmt.Println(dec(key, c)) } func enc(bd, pt string) (ct string) { enc :=...
import std.stdio, std.algorithm, std.string, std.array; immutable T = ["79|0|1|2|3|4|5|6|7|8|9", "|H|O|L||M|E|S||R|T", "3|A|B|C|D|F|G|I|J|K|N", "7|P|Q|U|V|W|X|Y|Z|.|/"] .map!(r => r.split("|")).array; enum straddle = (in string s) pure => toUpper(s) .split("") .cartesianProdu...
Produce a language-to-language conversion: from Go to D, same semantics.
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; ...