Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this C# function in Go with identical behavior. | using System;
using System.ComponentModel;
using System.Windows.Forms;
class RosettaInteractionForm : Form
{
class NumberModel: INotifyPropertyChanged
{
Random rnd = new Random();
public event PropertyChangedEventHandler PropertyChanged = delegate {};
int _value;
public int Value
{
get { return _value; }
set
{
_value = value;
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
public void ResetToRandom(){
Value = rnd.Next(5000);
}
}
NumberModel model = new NumberModel{ Value = 0};
RosettaInteractionForm()
{
var tbNumber = new MaskedTextBox
{
Mask="0000",
ResetOnSpace = false,
Dock = DockStyle.Top
};
tbNumber.DataBindings.Add("Text", model, "Value");
var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom};
btIncrement.Click += delegate
{
model.Value++;
};
var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom};
btDecrement.Click += delegate
{
model.Value--;
};
var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom };
btRandom.Click += delegate
{
if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
model.ResetToRandom();
};
Controls.Add(tbNumber);
Controls.Add(btIncrement);
Controls.Add(btDecrement);
Controls.Add(btRandom);
}
static void Main()
{
Application.Run(new RosettaInteractionForm());
}
}
| package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
func validateInput(window *gtk.Window, str string) (int64, bool) {
i, err := strconv.ParseInt(str, 10, 64)
if err != nil {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
"Invalid value",
)
dialog.Run()
dialog.Destroy()
return 0, false
}
return i, true
}
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetTitle("Rosetta Code")
window.SetPosition(gtk.WIN_POS_CENTER)
window.Connect("destroy", func() {
gtk.MainQuit()
})
box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create box:")
box.SetBorderWidth(1)
label, err := gtk.LabelNew("Value:")
check(err, "Unable to create label:")
entry, err := gtk.EntryNew()
check(err, "Unable to create entry:")
entry.SetText("0")
entry.Connect("activate", func() {
str, _ := entry.GetText()
validateInput(window, str)
})
ib, err := gtk.ButtonNewWithLabel("Increment")
check(err, "Unable to create increment button:")
ib.Connect("clicked", func() {
str, _ := entry.GetText()
if i, ok := validateInput(window, str); ok {
entry.SetText(strconv.FormatInt(i+1, 10))
}
})
rb, err := gtk.ButtonNewWithLabel("Random")
check(err, "Unable to create random button:")
rb.Connect("clicked", func() {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO,
"Set random value",
)
answer := dialog.Run()
dialog.Destroy()
if answer == gtk.RESPONSE_YES {
entry.SetText(strconv.Itoa(rand.Intn(10000)))
}
})
box.PackStart(label, false, false, 2)
box.PackStart(entry, false, false, 2)
box.PackStart(ib, false, false, 2)
box.PackStart(rb, false, false, 2)
window.Add(box)
window.ShowAll()
gtk.Main()
}
|
Preserve the algorithm and functionality while converting the code from C# to Go. | class Program
{
private static Random rnd = new Random();
public static int one_of_n(int n)
{
int currentChoice = 1;
for (int i = 2; i <= n; i++)
{
double outerLimit = 1D / (double)i;
if (rnd.NextDouble() < outerLimit)
currentChoice = i;
}
return currentChoice;
}
static void Main(string[] args)
{
Dictionary<int, int> results = new Dictionary<int, int>();
for (int i = 1; i < 11; i++)
results.Add(i, 0);
for (int i = 0; i < 1000000; i++)
{
int result = one_of_n(10);
results[result] = results[result] + 1;
}
for (int i = 1; i < 11; i++)
Console.WriteLine("{0}\t{1}", i, results[i]);
Console.ReadLine();
}
}
| package main
import (
"bufio"
"fmt"
"io"
"math/rand"
"time"
)
func choseLineRandomly(r io.Reader) (s string, ln int, err error) {
br := bufio.NewReader(r)
s, err = br.ReadString('\n')
if err != nil {
return
}
ln = 1
lnLast := 1.
var sLast string
for {
sLast, err = br.ReadString('\n')
if err == io.EOF {
return s, ln, nil
}
if err != nil {
break
}
lnLast++
if rand.Float64() < 1/lnLast {
s = sLast
ln = int(lnLast)
}
}
return
}
func oneOfN(n int, file io.Reader) int {
_, ln, err := choseLineRandomly(file)
if err != nil {
panic(err)
}
return ln
}
type simReader int
func (r *simReader) Read(b []byte) (int, error) {
if *r <= 0 {
return 0, io.EOF
}
b[0] = '\n'
*r--
return 1, nil
}
func main() {
n := 10
freq := make([]int, n)
rand.Seed(time.Now().UnixNano())
for times := 0; times < 1e6; times++ {
sr := simReader(n)
freq[oneOfN(n, &sr)-1]++
}
fmt.Println(freq)
}
|
Preserve the algorithm and functionality while converting the code from C# to Go. | using System;
namespace AdditionChains {
class Program {
static int[] Prepend(int n, int[] seq) {
int[] result = new int[seq.Length + 1];
Array.Copy(seq, 0, result, 1, seq.Length);
result[0] = n;
return result;
}
static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {
if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);
if (seq[0] == n) return new Tuple<int, int>(pos, 1);
if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);
return new Tuple<int, int>(min_len, 0);
}
static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {
if (i > pos) return new Tuple<int, int>(min_len, 0);
Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);
Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);
if (res2.Item1 < res1.Item1) return res2;
if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);
throw new Exception("TryPerm exception");
}
static Tuple<int, int> InitTryPerm(int x) {
return TryPerm(0, 0, new int[] { 1 }, x, 12);
}
static void FindBrauer(int num) {
Tuple<int, int> res = InitTryPerm(num);
Console.WriteLine();
Console.WriteLine("N = {0}", num);
Console.WriteLine("Minimum length of chains: L(n)= {0}", res.Item1);
Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2);
}
static void Main(string[] args) {
int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };
Array.ForEach(nums, n => FindBrauer(n));
}
}
}
| package main
import "fmt"
var example []int
func reverse(s []int) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
func checkSeq(pos, n, minLen int, seq []int) (int, int) {
switch {
case pos > minLen || seq[0] > n:
return minLen, 0
case seq[0] == n:
example = seq
return pos, 1
case pos < minLen:
return tryPerm(0, pos, n, minLen, seq)
default:
return minLen, 0
}
}
func tryPerm(i, pos, n, minLen int, seq []int) (int, int) {
if i > pos {
return minLen, 0
}
seq2 := make([]int, len(seq)+1)
copy(seq2[1:], seq)
seq2[0] = seq[0] + seq[i]
res11, res12 := checkSeq(pos+1, n, minLen, seq2)
res21, res22 := tryPerm(i+1, pos, n, res11, seq)
switch {
case res21 < res11:
return res21, res22
case res21 == res11:
return res21, res12 + res22
default:
fmt.Println("Error in tryPerm")
return 0, 0
}
}
func initTryPerm(x, minLen int) (int, int) {
return tryPerm(0, 0, x, minLen, []int{1})
}
func findBrauer(num, minLen, nbLimit int) {
actualMin, brauer := initTryPerm(num, minLen)
fmt.Println("\nN =", num)
fmt.Printf("Minimum length of chains : L(%d) = %d\n", num, actualMin)
fmt.Println("Number of minimum length Brauer chains :", brauer)
if brauer > 0 {
reverse(example)
fmt.Println("Brauer example :", example)
}
example = nil
if num <= nbLimit {
nonBrauer := findNonBrauer(num, actualMin+1, brauer)
fmt.Println("Number of minimum length non-Brauer chains :", nonBrauer)
if nonBrauer > 0 {
fmt.Println("Non-Brauer example :", example)
}
example = nil
} else {
println("Non-Brauer analysis suppressed")
}
}
func isAdditionChain(a []int) bool {
for i := 2; i < len(a); i++ {
if a[i] > a[i-1]*2 {
return false
}
ok := false
jloop:
for j := i - 1; j >= 0; j-- {
for k := j; k >= 0; k-- {
if a[j]+a[k] == a[i] {
ok = true
break jloop
}
}
}
if !ok {
return false
}
}
if example == nil && !isBrauer(a) {
example = make([]int, len(a))
copy(example, a)
}
return true
}
func isBrauer(a []int) bool {
for i := 2; i < len(a); i++ {
ok := false
for j := i - 1; j >= 0; j-- {
if a[i-1]+a[j] == a[i] {
ok = true
break
}
}
if !ok {
return false
}
}
return true
}
func nextChains(index, le int, seq []int, pcount *int) {
for {
if index < le-1 {
nextChains(index+1, le, seq, pcount)
}
if seq[index]+le-1-index >= seq[le-1] {
return
}
seq[index]++
for i := index + 1; i < le-1; i++ {
seq[i] = seq[i-1] + 1
}
if isAdditionChain(seq) {
(*pcount)++
}
}
}
func findNonBrauer(num, le, brauer int) int {
seq := make([]int, le)
seq[0] = 1
seq[le-1] = num
for i := 1; i < le-1; i++ {
seq[i] = seq[i-1] + 1
}
count := 0
if isAdditionChain(seq) {
count = 1
}
nextChains(2, le, seq, &count)
return count - brauer
}
func main() {
nums := []int{7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}
fmt.Println("Searching for Brauer chains up to a minimum length of 12:")
for _, num := range nums {
findBrauer(num, 12, 79)
}
}
|
Change the programming language of this snippet from C# to Go without modifying what it does. | using System;
namespace Repeat {
class Program {
static void Repeat(int count, Action<int> fn) {
if (null == fn) {
throw new ArgumentNullException("fn");
}
for (int i = 0; i < count; i++) {
fn.Invoke(i + 1);
}
}
static void Main(string[] args) {
Repeat(3, x => Console.WriteLine("Example {0}", x));
}
}
}
| package main
import "fmt"
func repeat(n int, f func()) {
for i := 0; i < n; i++ {
f()
}
}
func fn() {
fmt.Println("Example")
}
func main() {
repeat(4, fn)
}
|
Convert this C# block to Go, preserving its control flow and logic. | using System;
namespace Repeat {
class Program {
static void Repeat(int count, Action<int> fn) {
if (null == fn) {
throw new ArgumentNullException("fn");
}
for (int i = 0; i < count; i++) {
fn.Invoke(i + 1);
}
}
static void Main(string[] args) {
Repeat(3, x => Console.WriteLine("Example {0}", x));
}
}
}
| package main
import "fmt"
func repeat(n int, f func()) {
for i := 0; i < n; i++ {
f()
}
}
func fn() {
fmt.Println("Example")
}
func main() {
repeat(4, fn)
}
|
Write the same algorithm in Go as shown in this C# implementation. | public class Program
{
static void Main()
{
System.Console.WriteLine(42.ModInverse(2017));
}
}
public static class IntExtensions
{
public static int ModInverse(this int a, int m)
{
if (m == 1) return 0;
int m0 = m;
(int x, int y) = (1, 0);
while (a > 1) {
int q = a / m;
(a, m) = (m, a % m);
(x, y) = (y, x - q * y);
}
return x < 0 ? x + m0 : x;
}
}
| package main
import (
"fmt"
"math/big"
)
func main() {
a := big.NewInt(42)
m := big.NewInt(2017)
k := new(big.Int).ModInverse(a, m)
fmt.Println(k)
}
|
Port the provided C# code into Go while preserving the original functionality. | using System.Text;
using System.Net.Sockets;
using System.Net;
namespace WebServer
{
class GoodByeWorld
{
static void Main(string[] args)
{
const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n";
const int port = 8080;
bool serverRunning = true;
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
while (serverRunning)
{
Socket socketConnection = tcpListener.AcceptSocket();
byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);
socketConnection.Send(bMsg);
socketConnection.Disconnect(true);
}
}
}
}
| package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "Goodbye, World!")
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
|
Port the provided C# code into Go while preserving the original functionality. | using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
class Program
{
static string fmt(int[] a)
{
var sb = new System.Text.StringBuilder();
for (int i = 0; i < a.Length; i++)
sb.Append(string.Format("{0,5}{1}",
a[i], i % 10 == 9 ? "\n" : " "));
return sb.ToString();
}
static void Main(string[] args)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();
sw.Stop();
Write("The first 100 odd prime numbers:\n{0}\n",
fmt(pr.Take(100).ToArray()));
Write("The millionth odd prime number: {0}", pr.Last());
Write("\n{0} ms", sw.Elapsed.TotalMilliseconds);
}
}
class PG
{
public static IEnumerable<int> Sundaram(int n)
{
int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;
var comps = new bool[k + 1];
for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)
while ((t += d + 2) < k)
comps[t] = true;
for (; v < k; v++)
if (!comps[v])
yield return (v << 1) + 1;
}
}
| package main
import (
"fmt"
"math"
"rcu"
"time"
)
func sos(n int) []int {
if n < 3 {
return []int{}
}
var primes []int
k := (n-3)/2 + 1
marked := make([]bool, k)
limit := (int(math.Sqrt(float64(n)))-3)/2 + 1
for i := 0; i < limit; i++ {
p := 2*i + 3
s := (p*p - 3) / 2
for j := s; j < k; j += p {
marked[j] = true
}
}
for i := 0; i < k; i++ {
if !marked[i] {
primes = append(primes, 2*i+3)
}
}
return primes
}
func soe(n int) []int {
if n < 3 {
return []int{}
}
var primes []int
k := (n-3)/2 + 1
marked := make([]bool, k)
limit := (int(math.Sqrt(float64(n)))-3)/2 + 1
for i := 0; i < limit; i++ {
if !marked[i] {
p := 2*i + 3
s := (p*p - 3) / 2
for j := s; j < k; j += p {
marked[j] = true
}
}
}
for i := 0; i < k; i++ {
if !marked[i] {
primes = append(primes, 2*i+3)
}
}
return primes
}
func main() {
const limit = int(16e6)
start := time.Now()
primes := sos(limit)
elapsed := int(time.Since(start).Milliseconds())
climit := rcu.Commatize(limit)
celapsed := rcu.Commatize(elapsed)
million := rcu.Commatize(1e6)
millionth := rcu.Commatize(primes[1e6-1])
fmt.Printf("Using the Sieve of Sundaram generated primes up to %s in %s ms.\n\n", climit, celapsed)
fmt.Println("First 100 odd primes generated by the Sieve of Sundaram:")
for i, p := range primes[0:100] {
fmt.Printf("%3d ", p)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe %s Sundaram prime is %s\n", million, millionth)
start = time.Now()
primes = soe(limit)
elapsed = int(time.Since(start).Milliseconds())
celapsed = rcu.Commatize(elapsed)
millionth = rcu.Commatize(primes[1e6-1])
fmt.Printf("\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\n", celapsed)
fmt.Printf("\nAs a check, the %s Sundaram prime would again have been %s\n", million, millionth)
}
|
Ensure the translated Go code behaves exactly like the original C# snippet. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChemicalCalculator {
class Program {
static Dictionary<string, double> atomicMass = new Dictionary<string, double>() {
{"H", 1.008 },
{"He", 4.002602},
{"Li", 6.94},
{"Be", 9.0121831},
{"B", 10.81},
{"C", 12.011},
{"N", 14.007},
{"O", 15.999},
{"F", 18.998403163},
{"Ne", 20.1797},
{"Na", 22.98976928},
{"Mg", 24.305},
{"Al", 26.9815385},
{"Si", 28.085},
{"P", 30.973761998},
{"S", 32.06},
{"Cl", 35.45},
{"Ar", 39.948},
{"K", 39.0983},
{"Ca", 40.078},
{"Sc", 44.955908},
{"Ti", 47.867},
{"V", 50.9415},
{"Cr", 51.9961},
{"Mn", 54.938044},
{"Fe", 55.845},
{"Co", 58.933194},
{"Ni", 58.6934},
{"Cu", 63.546},
{"Zn", 65.38},
{"Ga", 69.723},
{"Ge", 72.630},
{"As", 74.921595},
{"Se", 78.971},
{"Br", 79.904},
{"Kr", 83.798},
{"Rb", 85.4678},
{"Sr", 87.62},
{"Y", 88.90584},
{"Zr", 91.224},
{"Nb", 92.90637},
{"Mo", 95.95},
{"Ru", 101.07},
{"Rh", 102.90550},
{"Pd", 106.42},
{"Ag", 107.8682},
{"Cd", 112.414},
{"In", 114.818},
{"Sn", 118.710},
{"Sb", 121.760},
{"Te", 127.60},
{"I", 126.90447},
{"Xe", 131.293},
{"Cs", 132.90545196},
{"Ba", 137.327},
{"La", 138.90547},
{"Ce", 140.116},
{"Pr", 140.90766},
{"Nd", 144.242},
{"Pm", 145},
{"Sm", 150.36},
{"Eu", 151.964},
{"Gd", 157.25},
{"Tb", 158.92535},
{"Dy", 162.500},
{"Ho", 164.93033},
{"Er", 167.259},
{"Tm", 168.93422},
{"Yb", 173.054},
{"Lu", 174.9668},
{"Hf", 178.49},
{"Ta", 180.94788},
{"W", 183.84},
{"Re", 186.207},
{"Os", 190.23},
{"Ir", 192.217},
{"Pt", 195.084},
{"Au", 196.966569},
{"Hg", 200.592},
{"Tl", 204.38},
{"Pb", 207.2},
{"Bi", 208.98040},
{"Po", 209},
{"At", 210},
{"Rn", 222},
{"Fr", 223},
{"Ra", 226},
{"Ac", 227},
{"Th", 232.0377},
{"Pa", 231.03588},
{"U", 238.02891},
{"Np", 237},
{"Pu", 244},
{"Am", 243},
{"Cm", 247},
{"Bk", 247},
{"Cf", 251},
{"Es", 252},
{"Fm", 257},
{"Uue", 315},
{"Ubn", 299},
};
static double Evaluate(string s) {
s += "[";
double sum = 0.0;
string symbol = "";
string number = "";
for (int i = 0; i < s.Length; ++i) {
var c = s[i];
if ('@' <= c && c <= '[') {
int n = 1;
if (number != "") {
n = int.Parse(number);
}
if (symbol != "") {
sum += atomicMass[symbol] * n;
}
if (c == '[') {
break;
}
symbol = c.ToString();
number = "";
} else if ('a' <= c && c <= 'z') {
symbol += c;
} else if ('0' <= c && c <= '9') {
number += c;
} else {
throw new Exception(string.Format("Unexpected symbol {0} in molecule", c));
}
}
return sum;
}
static string ReplaceFirst(string text, string search, string replace) {
int pos = text.IndexOf(search);
if (pos < 0) {
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
static string ReplaceParens(string s) {
char letter = 's';
while (true) {
var start = s.IndexOf('(');
if (start == -1) {
break;
}
for (int i = start + 1; i < s.Length; ++i) {
if (s[i] == ')') {
var expr = s.Substring(start + 1, i - start - 1);
var symbol = string.Format("@{0}", letter);
s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol);
atomicMass[symbol] = Evaluate(expr);
letter++;
break;
}
if (s[i] == '(') {
start = i;
continue;
}
}
}
return s;
}
static void Main() {
var molecules = new string[]{
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12",
"COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue"
};
foreach (var molecule in molecules) {
var mass = Evaluate(ReplaceParens(molecule));
Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass);
}
}
}
}
| package main
import (
"fmt"
"strconv"
"strings"
)
var atomicMass = map[string]float64{
"H": 1.008,
"He": 4.002602,
"Li": 6.94,
"Be": 9.0121831,
"B": 10.81,
"C": 12.011,
"N": 14.007,
"O": 15.999,
"F": 18.998403163,
"Ne": 20.1797,
"Na": 22.98976928,
"Mg": 24.305,
"Al": 26.9815385,
"Si": 28.085,
"P": 30.973761998,
"S": 32.06,
"Cl": 35.45,
"Ar": 39.948,
"K": 39.0983,
"Ca": 40.078,
"Sc": 44.955908,
"Ti": 47.867,
"V": 50.9415,
"Cr": 51.9961,
"Mn": 54.938044,
"Fe": 55.845,
"Co": 58.933194,
"Ni": 58.6934,
"Cu": 63.546,
"Zn": 65.38,
"Ga": 69.723,
"Ge": 72.630,
"As": 74.921595,
"Se": 78.971,
"Br": 79.904,
"Kr": 83.798,
"Rb": 85.4678,
"Sr": 87.62,
"Y": 88.90584,
"Zr": 91.224,
"Nb": 92.90637,
"Mo": 95.95,
"Ru": 101.07,
"Rh": 102.90550,
"Pd": 106.42,
"Ag": 107.8682,
"Cd": 112.414,
"In": 114.818,
"Sn": 118.710,
"Sb": 121.760,
"Te": 127.60,
"I": 126.90447,
"Xe": 131.293,
"Cs": 132.90545196,
"Ba": 137.327,
"La": 138.90547,
"Ce": 140.116,
"Pr": 140.90766,
"Nd": 144.242,
"Pm": 145,
"Sm": 150.36,
"Eu": 151.964,
"Gd": 157.25,
"Tb": 158.92535,
"Dy": 162.500,
"Ho": 164.93033,
"Er": 167.259,
"Tm": 168.93422,
"Yb": 173.054,
"Lu": 174.9668,
"Hf": 178.49,
"Ta": 180.94788,
"W": 183.84,
"Re": 186.207,
"Os": 190.23,
"Ir": 192.217,
"Pt": 195.084,
"Au": 196.966569,
"Hg": 200.592,
"Tl": 204.38,
"Pb": 207.2,
"Bi": 208.98040,
"Po": 209,
"At": 210,
"Rn": 222,
"Fr": 223,
"Ra": 226,
"Ac": 227,
"Th": 232.0377,
"Pa": 231.03588,
"U": 238.02891,
"Np": 237,
"Pu": 244,
"Am": 243,
"Cm": 247,
"Bk": 247,
"Cf": 251,
"Es": 252,
"Fm": 257,
"Uue": 315,
"Ubn": 299,
}
func replaceParens(s string) string {
var letter byte = 'a'
for {
start := strings.IndexByte(s, '(')
if start == -1 {
break
}
restart:
for i := start + 1; i < len(s); i++ {
if s[i] == ')' {
expr := s[start+1 : i]
symbol := fmt.Sprintf("@%c", letter)
s = strings.Replace(s, s[start:i+1], symbol, 1)
atomicMass[symbol] = evaluate(expr)
letter++
break
}
if s[i] == '(' {
start = i
goto restart
}
}
}
return s
}
func evaluate(s string) float64 {
s += string('[')
var symbol, number string
sum := 0.0
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c >= '@' && c <= '[':
n := 1
if number != "" {
n, _ = strconv.Atoi(number)
}
if symbol != "" {
sum += atomicMass[symbol] * float64(n)
}
if c == '[' {
break
}
symbol = string(c)
number = ""
case c >= 'a' && c <= 'z':
symbol += string(c)
case c >= '0' && c <= '9':
number += string(c)
default:
panic(fmt.Sprintf("Unexpected symbol %c in molecule", c))
}
}
return sum
}
func main() {
molecules := []string{
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3",
"C6H4O2(OH)4", "C27H46O", "Uue",
}
for _, molecule := range molecules {
mass := evaluate(replaceParens(molecule))
fmt.Printf("%17s -> %7.3f\n", molecule, mass)
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. |
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
| 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=example,dc=com",
BindPassword: "readonlypassword",
UserFilter: "(uid=%s)",
GroupFilter: "(memberUid=%s)",
Attributes: []string{"givenName", "sn", "mail", "uid"},
}
defer client.Close()
err := client.Connect()
if err != nil {
log.Fatalf("Failed to connect : %+v", err)
}
}
|
Write the same algorithm in Go as shown in this C# implementation. | using System;
namespace PythagoreanQuadruples {
class Program {
const int MAX = 2200;
const int MAX2 = MAX * MAX * 2;
static void Main(string[] args) {
bool[] found = new bool[MAX + 1];
bool[] a2b2 = new bool[MAX2 + 1];
int s = 3;
for(int a = 1; a <= MAX; a++) {
int a2 = a * a;
for (int b=a; b<=MAX; b++) {
a2b2[a2 + b * b] = true;
}
}
for (int c = 1; c <= MAX; c++) {
int s1 = s;
s += 2;
int s2 = s;
for (int d = c + 1; d <= MAX; d++) {
if (a2b2[s1]) found[d] = true;
s1 += s2;
s2 += 2;
}
}
Console.WriteLine("The values of d <= {0} which can't be represented:", MAX);
for (int d = 1; d < MAX; d++) {
if (!found[d]) Console.Write("{0} ", d);
}
Console.WriteLine();
}
}
}
| 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; c <= N; c++ {
s1 = s
s += 2
s2 = s
for d := c + 1; d <= N; d++ {
if ab[s1] {
r[d] = true
}
s1 += s2
s2 += 2
}
}
for d := 1; d <= N; d++ {
if !r[d] {
fmt.Printf("%d ", d)
}
}
fmt.Println()
}
|
Convert this C# snippet to Go and keep its semantics consistent. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;
public enum Colour { Red, Green, White, Yellow, Blue }
public enum Nationality { Englishman, Swede, Dane, Norwegian,German }
public enum Pet { Dog, Birds, Cats, Horse, Zebra }
public enum Drink { Coffee, Tea, Milk, Beer, Water }
public enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince}
public static class ZebraPuzzle
{
private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved;
static ZebraPuzzle()
{
var solve = from colours in Permute<Colour>()
where (colours,Colour.White).IsRightOf(colours, Colour.Green)
from nations in Permute<Nationality>()
where nations[0] == Nationality.Norwegian
where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red)
where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue)
from drinks in Permute<Drink>()
where drinks[2] == Drink.Milk
where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green)
where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane)
from pets in Permute<Pet>()
where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede)
from smokes in Permute<Smoke>()
where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds)
where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow)
where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats)
where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse)
where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer)
where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German)
where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend)
select (colours, drinks, smokes, pets, nations);
_solved = solve.First();
}
private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj);
private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1;
private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v);
private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a, U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v);
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)
{
if (values.Count() == 1)
return values.ToSingleton();
return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));
}
public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray());
private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; }
private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>();
public static new String ToString()
{
var sb = new StringBuilder();
sb.AppendLine("House Colour Drink Nationality Smokes Pet");
sb.AppendLine("───── ────── ──────── ─────────── ────────── ─────");
var (colours, drinks, smokes, pets, nations) = _solved;
for (var i = 0; i < 5; i++)
sb.AppendLine($"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}");
return sb.ToString();
}
public static void Main(string[] arguments)
{
var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)];
WriteLine($"The zebra owner is {owner}");
Write(ToString());
Read();
}
}
| package main
import (
"fmt"
"log"
"strings"
)
type HouseSet [5]*House
type House struct {
n Nationality
c Colour
a Animal
d Drink
s Smoke
}
type Nationality int8
type Colour int8
type Animal int8
type Drink int8
type Smoke int8
const (
English Nationality = iota
Swede
Dane
Norwegian
German
)
const (
Red Colour = iota
Green
White
Yellow
Blue
)
const (
Dog Animal = iota
Birds
Cats
Horse
Zebra
)
const (
Tea Drink = iota
Coffee
Milk
Beer
Water
)
const (
PallMall Smoke = iota
Dunhill
Blend
BlueMaster
Prince
)
var nationalities = [...]string{"English", "Swede", "Dane", "Norwegian", "German"}
var colours = [...]string{"red", "green", "white", "yellow", "blue"}
var animals = [...]string{"dog", "birds", "cats", "horse", "zebra"}
var drinks = [...]string{"tea", "coffee", "milk", "beer", "water"}
var smokes = [...]string{"Pall Mall", "Dunhill", "Blend", "Blue Master", "Prince"}
func (n Nationality) String() string { return nationalities[n] }
func (c Colour) String() string { return colours[c] }
func (a Animal) String() string { return animals[a] }
func (d Drink) String() string { return drinks[d] }
func (s Smoke) String() string { return smokes[s] }
func (h House) String() string {
return fmt.Sprintf("%-9s %-6s %-5s %-6s %s", h.n, h.c, h.a, h.d, h.s)
}
func (hs HouseSet) String() string {
lines := make([]string, 0, len(hs))
for i, h := range hs {
s := fmt.Sprintf("%d %s", i, h)
lines = append(lines, s)
}
return strings.Join(lines, "\n")
}
func simpleBruteForce() (int, HouseSet) {
var v []House
for n := range nationalities {
for c := range colours {
for a := range animals {
for d := range drinks {
for s := range smokes {
h := House{
n: Nationality(n),
c: Colour(c),
a: Animal(a),
d: Drink(d),
s: Smoke(s),
}
if !h.Valid() {
continue
}
v = append(v, h)
}
}
}
}
}
n := len(v)
log.Println("Generated", n, "valid houses")
combos := 0
first := 0
valid := 0
var validSet HouseSet
for a := 0; a < n; a++ {
if v[a].n != Norwegian {
continue
}
for b := 0; b < n; b++ {
if b == a {
continue
}
if v[b].anyDups(&v[a]) {
continue
}
for c := 0; c < n; c++ {
if c == b || c == a {
continue
}
if v[c].d != Milk {
continue
}
if v[c].anyDups(&v[b], &v[a]) {
continue
}
for d := 0; d < n; d++ {
if d == c || d == b || d == a {
continue
}
if v[d].anyDups(&v[c], &v[b], &v[a]) {
continue
}
for e := 0; e < n; e++ {
if e == d || e == c || e == b || e == a {
continue
}
if v[e].anyDups(&v[d], &v[c], &v[b], &v[a]) {
continue
}
combos++
set := HouseSet{&v[a], &v[b], &v[c], &v[d], &v[e]}
if set.Valid() {
valid++
if valid == 1 {
first = combos
}
validSet = set
}
}
}
}
}
}
log.Println("Tested", first, "different combinations of valid houses before finding solution")
log.Println("Tested", combos, "different combinations of valid houses in total")
return valid, validSet
}
func (h *House) anyDups(list ...*House) bool {
for _, b := range list {
if h.n == b.n || h.c == b.c || h.a == b.a || h.d == b.d || h.s == b.s {
return true
}
}
return false
}
func (h *House) Valid() bool {
if h.n == English && h.c != Red || h.n != English && h.c == Red {
return false
}
if h.n == Swede && h.a != Dog || h.n != Swede && h.a == Dog {
return false
}
if h.n == Dane && h.d != Tea || h.n != Dane && h.d == Tea {
return false
}
if h.c == Green && h.d != Coffee || h.c != Green && h.d == Coffee {
return false
}
if h.a == Birds && h.s != PallMall || h.a != Birds && h.s == PallMall {
return false
}
if h.c == Yellow && h.s != Dunhill || h.c != Yellow && h.s == Dunhill {
return false
}
if h.a == Cats && h.s == Blend {
return false
}
if h.a == Horse && h.s == Dunhill {
return false
}
if h.d == Beer && h.s != BlueMaster || h.d != Beer && h.s == BlueMaster {
return false
}
if h.n == German && h.s != Prince || h.n != German && h.s == Prince {
return false
}
if h.n == Norwegian && h.c == Blue {
return false
}
if h.d == Water && h.s == Blend {
return false
}
return true
}
func (hs *HouseSet) Valid() bool {
ni := make(map[Nationality]int, 5)
ci := make(map[Colour]int, 5)
ai := make(map[Animal]int, 5)
di := make(map[Drink]int, 5)
si := make(map[Smoke]int, 5)
for i, h := range hs {
ni[h.n] = i
ci[h.c] = i
ai[h.a] = i
di[h.d] = i
si[h.s] = i
}
if ci[Green]+1 != ci[White] {
return false
}
if dist(ai[Cats], si[Blend]) != 1 {
return false
}
if dist(ai[Horse], si[Dunhill]) != 1 {
return false
}
if dist(ni[Norwegian], ci[Blue]) != 1 {
return false
}
if dist(di[Water], si[Blend]) != 1 {
return false
}
if hs[2].d != Milk {
return false
}
if hs[0].n != Norwegian {
return false
}
return true
}
func dist(a, b int) int {
if a > b {
return a - b
}
return b - a
}
func main() {
log.SetFlags(0)
n, sol := simpleBruteForce()
fmt.Println(n, "solution found")
fmt.Println(sol)
}
|
Change the programming language of this snippet from C# to Go without modifying what it does. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Net;
class Program {
static List<string> GetTitlesFromCategory(string category) {
string searchQueryFormat = "http:
List<string> results = new List<string>();
string cmcontinue = string.Empty;
do {
string cmContinueKeyValue;
if (cmcontinue.Length > 0)
cmContinueKeyValue = String.Format("&cmcontinue={0}", cmcontinue);
else
cmContinueKeyValue = String.Empty;
string query = String.Format(searchQueryFormat, category, cmContinueKeyValue);
string content = new WebClient().DownloadString(query);
results.AddRange(new Regex("\"title\":\"(.+?)\"").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value));
cmcontinue = Regex.Match(content, @"{""cmcontinue"":""([^""]+)""}", RegexOptions.IgnoreCase).Groups["1"].Value;
} while (cmcontinue.Length > 0);
return results;
}
static string[] GetUnimplementedTasksFromLanguage(string language) {
List<string> alltasks = GetTitlesFromCategory("Programming_Tasks");
List<string> lang = GetTitlesFromCategory(language);
return alltasks.Where(x => !lang.Contains(x)).ToArray();
}
static void Main(string[] args) {
string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]);
foreach (string i in unimpl) Console.WriteLine(i);
}
}
| package main
import (
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
)
const language = "Go"
var baseQuery = "http:
"&format=xml&list=categorymembers&cmlimit=100"
func req(u string, foundCm func(string)) string {
resp, err := http.Get(u)
if err != nil {
fmt.Println(err)
return ""
}
defer resp.Body.Close()
for p := xml.NewDecoder(resp.Body); ; {
t, err := p.RawToken()
switch s, ok := t.(xml.StartElement); {
case err == io.EOF:
return ""
case err != nil:
fmt.Println(err)
return ""
case !ok:
continue
case s.Name.Local == "cm":
for _, a := range s.Attr {
if a.Name.Local == "title" {
foundCm(a.Value)
}
}
case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
s.Attr[0].Name.Local == "cmcontinue":
return url.QueryEscape(s.Attr[0].Value)
}
}
return ""
}
func main() {
langMap := make(map[string]bool)
storeLang := func(cm string) { langMap[cm] = true }
languageQuery := baseQuery + "&cmtitle=Category:" + language
continueAt := req(languageQuery, storeLang)
for continueAt > "" {
continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
}
if len(langMap) == 0 {
fmt.Println("no tasks implemented for", language)
return
}
printUnImp := func(cm string) {
if !langMap[cm] {
fmt.Println(cm)
}
}
taskQuery := baseQuery + "&cmtitle=Category:Programming_Tasks"
continueAt = req(taskQuery, printUnImp)
for continueAt > "" {
continueAt = req(taskQuery+"&cmcontinue="+continueAt, printUnImp)
}
}
|
Keep all operations the same but rewrite the snippet in Go. | using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
double x, xi, y, yi, z, zi;
x = 2.0;
xi = 0.5;
y = 4.0;
yi = 0.25;
z = x + y;
zi = 1.0 / (x + y);
var numlist = new[] { x, y, z };
var numlisti = new[] { xi, yi, zi };
var multiplied = numlist.Zip(numlisti, (n1, n2) =>
{
Func<double, double> multiplier = m => n1 * n2 * m;
return multiplier;
});
foreach (var multiplier in multiplied)
Console.WriteLine(multiplier(0.5));
}
}
| package main
import "fmt"
func main() {
x := 2.
xi := .5
y := 4.
yi := .25
z := x + y
zi := 1 / (x + y)
numbers := []float64{x, y, z}
inverses := []float64{xi, yi, zi}
mfs := make([]func(float64) float64, len(numbers))
for i := range mfs {
mfs[i] = multiplier(numbers[i], inverses[i])
}
for _, mf := range mfs {
fmt.Println(mf(1))
}
}
func multiplier(n1, n2 float64) func(float64) float64 {
n1n2 := n1 * n2
return func(m float64) float64 {
return n1n2 * m
}
}
|
Transform the following C# implementation into Go, maintaining the same output and logic. | using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
double x, xi, y, yi, z, zi;
x = 2.0;
xi = 0.5;
y = 4.0;
yi = 0.25;
z = x + y;
zi = 1.0 / (x + y);
var numlist = new[] { x, y, z };
var numlisti = new[] { xi, yi, zi };
var multiplied = numlist.Zip(numlisti, (n1, n2) =>
{
Func<double, double> multiplier = m => n1 * n2 * m;
return multiplier;
});
foreach (var multiplier in multiplied)
Console.WriteLine(multiplier(0.5));
}
}
| package main
import "fmt"
func main() {
x := 2.
xi := .5
y := 4.
yi := .25
z := x + y
zi := 1 / (x + y)
numbers := []float64{x, y, z}
inverses := []float64{xi, yi, zi}
mfs := make([]func(float64) float64, len(numbers))
for i := range mfs {
mfs[i] = multiplier(numbers[i], inverses[i])
}
for _, mf := range mfs {
fmt.Println(mf(1))
}
}
func multiplier(n1, n2 float64) func(float64) float64 {
n1n2 := n1 * n2
return func(m float64) float64 {
return n1n2 * m
}
}
|
Can you help me rewrite this code in Go instead of C#, keeping it the same logically? | using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
double x, xi, y, yi, z, zi;
x = 2.0;
xi = 0.5;
y = 4.0;
yi = 0.25;
z = x + y;
zi = 1.0 / (x + y);
var numlist = new[] { x, y, z };
var numlisti = new[] { xi, yi, zi };
var multiplied = numlist.Zip(numlisti, (n1, n2) =>
{
Func<double, double> multiplier = m => n1 * n2 * m;
return multiplier;
});
foreach (var multiplier in multiplied)
Console.WriteLine(multiplier(0.5));
}
}
| package main
import "fmt"
func main() {
x := 2.
xi := .5
y := 4.
yi := .25
z := x + y
zi := 1 / (x + y)
numbers := []float64{x, y, z}
inverses := []float64{xi, yi, zi}
mfs := make([]func(float64) float64, len(numbers))
for i := range mfs {
mfs[i] = multiplier(numbers[i], inverses[i])
}
for _, mf := range mfs {
fmt.Println(mf(1))
}
}
func multiplier(n1, n2 float64) func(float64) float64 {
n1n2 := n1 * n2
return func(m float64) float64 {
return n1n2 * m
}
}
|
Change the programming language of this snippet from C# to Go without modifying what it does. | using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SokobanSolver
{
public class SokobanSolver
{
private class Board
{
public string Cur { get; internal set; }
public string Sol { get; internal set; }
public int X { get; internal set; }
public int Y { get; internal set; }
public Board(string cur, string sol, int x, int y)
{
Cur = cur;
Sol = sol;
X = x;
Y = y;
}
}
private string destBoard, currBoard;
private int playerX, playerY, nCols;
SokobanSolver(string[] board)
{
nCols = board[0].Length;
StringBuilder destBuf = new StringBuilder();
StringBuilder currBuf = new StringBuilder();
for (int r = 0; r < board.Length; r++)
{
for (int c = 0; c < nCols; c++)
{
char ch = board[r][c];
destBuf.Append(ch != '$' && ch != '@' ? ch : ' ');
currBuf.Append(ch != '.' ? ch : ' ');
if (ch == '@')
{
this.playerX = c;
this.playerY = r;
}
}
}
destBoard = destBuf.ToString();
currBoard = currBuf.ToString();
}
private string Move(int x, int y, int dx, int dy, string trialBoard)
{
int newPlayerPos = (y + dy) * nCols + x + dx;
if (trialBoard[newPlayerPos] != ' ')
return null;
char[] trial = trialBoard.ToCharArray();
trial[y * nCols + x] = ' ';
trial[newPlayerPos] = '@';
return new string(trial);
}
private string Push(int x, int y, int dx, int dy, string trialBoard)
{
int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;
if (trialBoard[newBoxPos] != ' ')
return null;
char[] trial = trialBoard.ToCharArray();
trial[y * nCols + x] = ' ';
trial[(y + dy) * nCols + x + dx] = '@';
trial[newBoxPos] = '$';
return new string(trial);
}
private bool IsSolved(string trialBoard)
{
for (int i = 0; i < trialBoard.Length; i++)
if ((destBoard[i] == '.')
!= (trialBoard[i] == '$'))
return false;
return true;
}
private string Solve()
{
char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } };
int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } };
ISet<string> history = new HashSet<string>();
LinkedList<Board> open = new LinkedList<Board>();
history.Add(currBoard);
open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));
while (!open.Count.Equals(0))
{
Board item = open.First();
open.RemoveFirst();
string cur = item.Cur;
string sol = item.Sol;
int x = item.X;
int y = item.Y;
for (int i = 0; i < dirs.GetLength(0); i++)
{
string trial = cur;
int dx = dirs[i, 0];
int dy = dirs[i, 1];
if (trial[(y + dy) * nCols + x + dx] == '$')
{
if ((trial = Push(x, y, dx, dy, trial)) != null)
{
if (!history.Contains(trial))
{
string newSol = sol + dirLabels[i, 1];
if (IsSolved(trial))
return newSol;
open.AddLast(new Board(trial, newSol, x + dx, y + dy));
history.Add(trial);
}
}
}
else if ((trial = Move(x, y, dx, dy, trial)) != null)
{
if (!history.Contains(trial))
{
string newSol = sol + dirLabels[i, 0];
open.AddLast(new Board(trial, newSol, x + dx, y + dy));
history.Add(trial);
}
}
}
}
return "No solution";
}
public static void Main(string[] a)
{
string level = "#######," +
"# #," +
"# #," +
"#. # #," +
"#. $$ #," +
"#.$$ #," +
"#.# @#," +
"#######";
System.Console.WriteLine("Level:\n");
foreach (string line in level.Split(','))
{
System.Console.WriteLine(line);
}
System.Console.WriteLine("\nSolution:\n");
System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve());
}
}
}
| package main
import (
"fmt"
"strings"
)
func main() {
level := `
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######`
fmt.Printf("level:%s\n", level)
fmt.Printf("solution:\n%s\n", solve(level))
}
func solve(board string) string {
buffer = make([]byte, len(board))
width := strings.Index(board[1:], "\n") + 1
dirs := []struct {
move, push string
dPos int
}{
{"u", "U", -width},
{"r", "R", 1},
{"d", "D", width},
{"l", "L", -1},
}
visited := map[string]bool{board: true}
open := []state{state{board, "", strings.Index(board, "@")}}
for len(open) > 0 {
s1 := &open[0]
open = open[1:]
for _, dir := range dirs {
var newBoard, newSol string
newPos := s1.pos + dir.dPos
switch s1.board[newPos] {
case '$', '*':
newBoard = s1.push(dir.dPos)
if newBoard == "" || visited[newBoard] {
continue
}
newSol = s1.cSol + dir.push
if strings.IndexAny(newBoard, ".+") < 0 {
return newSol
}
case ' ', '.':
newBoard = s1.move(dir.dPos)
if visited[newBoard] {
continue
}
newSol = s1.cSol + dir.move
default:
continue
}
open = append(open, state{newBoard, newSol, newPos})
visited[newBoard] = true
}
}
return "No solution"
}
type state struct {
board string
cSol string
pos int
}
var buffer []byte
func (s *state) move(dPos int) string {
copy(buffer, s.board)
if buffer[s.pos] == '@' {
buffer[s.pos] = ' '
} else {
buffer[s.pos] = '.'
}
newPos := s.pos + dPos
if buffer[newPos] == ' ' {
buffer[newPos] = '@'
} else {
buffer[newPos] = '+'
}
return string(buffer)
}
func (s *state) push(dPos int) string {
newPos := s.pos + dPos
boxPos := newPos + dPos
switch s.board[boxPos] {
case ' ', '.':
default:
return ""
}
copy(buffer, s.board)
if buffer[s.pos] == '@' {
buffer[s.pos] = ' '
} else {
buffer[s.pos] = '.'
}
if buffer[newPos] == '$' {
buffer[newPos] = '@'
} else {
buffer[newPos] = '+'
}
if buffer[boxPos] == ' ' {
buffer[boxPos] = '$'
} else {
buffer[boxPos] = '*'
}
return string(buffer)
}
|
Maintain the same structure and functionality when rewriting this code in Go. | using System;
using BI = System.Numerics.BigInteger;
using static System.Console;
class Program {
static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {
q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }
static string dump(int digs, bool show = false) {
int gb = 1, dg = ++digs + gb, z;
BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,
t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;
for (BI n = 0; n < dg; n++) {
if (n > 0) t3 *= BI.Pow(n, 6);
te = t1 * t2 / t3;
if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);
else te /= BI.Pow (10, -z);
if (show && n < 10)
WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t);
su += te; if (te < 10) {
if (show) WriteLine("\n{0} iterations required for {1} digits " +
"after the decimal point.\n", n, --digs); break; }
for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;
t2 += 126 + 532 * (d += 2);
}
string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) /
su / 32 * 3 * BI.Pow((BI)10, dg + 5)));
return s[0] + "." + s.Substring(1, digs); }
static void Main(string[] args) {
WriteLine(dump(70, true)); }
}
| package main
import (
"fmt"
"math/big"
"strings"
)
func factorial(n int64) *big.Int {
var z big.Int
return z.MulRange(1, n)
}
var one = big.NewInt(1)
var three = big.NewInt(3)
var six = big.NewInt(6)
var ten = big.NewInt(10)
var seventy = big.NewInt(70)
func almkvistGiullera(n int64, print bool) *big.Rat {
t1 := big.NewInt(32)
t1.Mul(factorial(6*n), t1)
t2 := big.NewInt(532*n*n + 126*n + 9)
t3 := new(big.Int)
t3.Exp(factorial(n), six, nil)
t3.Mul(t3, three)
ip := new(big.Int)
ip.Mul(t1, t2)
ip.Quo(ip, t3)
pw := 6*n + 3
t1.SetInt64(pw)
tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))
if print {
fmt.Printf("%d %44d %3d %-35s\n", n, ip, -pw, tm.FloatString(33))
}
return tm
}
func main() {
fmt.Println("N Integer Portion Pow Nth Term (33 dp)")
fmt.Println(strings.Repeat("-", 89))
for n := int64(0); n < 10; n++ {
almkvistGiullera(n, true)
}
sum := new(big.Rat)
prev := new(big.Rat)
pow70 := new(big.Int).Exp(ten, seventy, nil)
prec := new(big.Rat).SetFrac(one, pow70)
n := int64(0)
for {
term := almkvistGiullera(n, false)
sum.Add(sum, term)
z := new(big.Rat).Sub(sum, prev)
z.Abs(z)
if z.Cmp(prec) < 0 {
break
}
prev.Set(sum)
n++
}
sum.Inv(sum)
pi := new(big.Float).SetPrec(256).SetRat(sum)
pi.Sqrt(pi)
fmt.Println("\nPi to 70 decimal places is:")
fmt.Println(pi.Text('f', 70))
}
|
Ensure the translated Go code behaves exactly like the original C# snippet. | using System;
using BI = System.Numerics.BigInteger;
using static System.Console;
class Program {
static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {
q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }
static string dump(int digs, bool show = false) {
int gb = 1, dg = ++digs + gb, z;
BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,
t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;
for (BI n = 0; n < dg; n++) {
if (n > 0) t3 *= BI.Pow(n, 6);
te = t1 * t2 / t3;
if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);
else te /= BI.Pow (10, -z);
if (show && n < 10)
WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t);
su += te; if (te < 10) {
if (show) WriteLine("\n{0} iterations required for {1} digits " +
"after the decimal point.\n", n, --digs); break; }
for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;
t2 += 126 + 532 * (d += 2);
}
string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) /
su / 32 * 3 * BI.Pow((BI)10, dg + 5)));
return s[0] + "." + s.Substring(1, digs); }
static void Main(string[] args) {
WriteLine(dump(70, true)); }
}
| package main
import (
"fmt"
"math/big"
"strings"
)
func factorial(n int64) *big.Int {
var z big.Int
return z.MulRange(1, n)
}
var one = big.NewInt(1)
var three = big.NewInt(3)
var six = big.NewInt(6)
var ten = big.NewInt(10)
var seventy = big.NewInt(70)
func almkvistGiullera(n int64, print bool) *big.Rat {
t1 := big.NewInt(32)
t1.Mul(factorial(6*n), t1)
t2 := big.NewInt(532*n*n + 126*n + 9)
t3 := new(big.Int)
t3.Exp(factorial(n), six, nil)
t3.Mul(t3, three)
ip := new(big.Int)
ip.Mul(t1, t2)
ip.Quo(ip, t3)
pw := 6*n + 3
t1.SetInt64(pw)
tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))
if print {
fmt.Printf("%d %44d %3d %-35s\n", n, ip, -pw, tm.FloatString(33))
}
return tm
}
func main() {
fmt.Println("N Integer Portion Pow Nth Term (33 dp)")
fmt.Println(strings.Repeat("-", 89))
for n := int64(0); n < 10; n++ {
almkvistGiullera(n, true)
}
sum := new(big.Rat)
prev := new(big.Rat)
pow70 := new(big.Int).Exp(ten, seventy, nil)
prec := new(big.Rat).SetFrac(one, pow70)
n := int64(0)
for {
term := almkvistGiullera(n, false)
sum.Add(sum, term)
z := new(big.Rat).Sub(sum, prev)
z.Abs(z)
if z.Cmp(prec) < 0 {
break
}
prev.Set(sum)
n++
}
sum.Inv(sum)
pi := new(big.Float).SetPrec(256).SetRat(sum)
pi.Sqrt(pi)
fmt.Println("\nPi to 70 decimal places is:")
fmt.Println(pi.Text('f', 70))
}
|
Convert the following code from C# to Go, ensuring the logic remains intact. | using System.Collections.Generic; using System.Linq; using static System.Console;
class Program {
static bool soas(int n, IEnumerable<int> f) {
if (n <= 0) return false; if (f.Contains(n)) return true;
switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;
case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);
return soas(d, rf) || soas(n, rf); } return true; }
static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();
return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f)); }
static void Main() {
int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)
if (ip(i) || i == 1) Write("{0,3} {1}", i, ++c % 10 == 0 ? "\n" : "");
Write("\nFound {0} practical numbers between 1 and {1} inclusive.\n", c, m);
do Write("\n{0,5} is a{1}practical number.",
m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? " " : "n im"); while (m < 1e4); } }
| package main
import (
"fmt"
"rcu"
)
func powerset(set []int) [][]int {
if len(set) == 0 {
return [][]int{{}}
}
head := set[0]
tail := set[1:]
p1 := powerset(tail)
var p2 [][]int
for _, s := range powerset(tail) {
h := []int{head}
h = append(h, s...)
p2 = append(p2, h)
}
return append(p1, p2...)
}
func isPractical(n int) bool {
if n == 1 {
return true
}
divs := rcu.ProperDivisors(n)
subsets := powerset(divs)
found := make([]bool, n)
count := 0
for _, subset := range subsets {
sum := rcu.SumInts(subset)
if sum > 0 && sum < n && !found[sum] {
found[sum] = true
count++
if count == n-1 {
return true
}
}
}
return false
}
func main() {
fmt.Println("In the range 1..333, there are:")
var practical []int
for i := 1; i <= 333; i++ {
if isPractical(i) {
practical = append(practical, i)
}
}
fmt.Println(" ", len(practical), "practical numbers")
fmt.Println(" The first ten are", practical[0:10])
fmt.Println(" The final ten are", practical[len(practical)-10:])
fmt.Println("\n666 is practical:", isPractical(666))
}
|
Convert this C# snippet to Go and keep its semantics consistent. | using System.Linq;
using System.Collections.Generic;
using TG = System.Tuple<int, int>;
using static System.Console;
class Program
{
static void Main(string[] args)
{
const int mil = (int)1e6;
foreach (var amt in new int[] { 1, 2, 6, 12, 18 })
{
int lmt = mil * amt, lg = 0, ng, d, ld = 0;
var desc = new string[] { "A", "", "De" };
int[] mx = new int[] { 0, 0, 0 },
bi = new int[] { 0, 0, 0 },
c = new int[] { 2, 2, 2 };
WriteLine("For primes up to {0:n0}:", lmt);
var pr = PG.Primes(lmt).ToArray();
for (int i = 0; i < pr.Length; i++)
{
ng = pr[i].Item2; d = ng.CompareTo(lg) + 1;
if (ld == d)
c[2 - d]++;
else
{
if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; }
c[d] = 2;
}
ld = d; lg = ng;
}
for (int r = 0; r <= 2; r += 2)
{
Write("{0}scending, found run of {1} consecutive primes:\n {2} ",
desc[r], mx[r] + 1, pr[bi[r]++].Item1);
foreach (var itm in pr.Skip(bi[r]).Take(mx[r]))
Write("({0}) {1} ", itm.Item2, itm.Item1); WriteLine(r == 0 ? "" : "\n");
}
}
}
}
class PG
{
public static IEnumerable<TG> Primes(int lim)
{
bool[] flags = new bool[lim + 1];
int j = 3, lj = 2;
for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
if (!flags[j])
{
yield return new TG(j, j - lj);
lj = j;
for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true;
}
for (; j <= lim; j += 2)
if (!flags[j])
{
yield return new TG(j, j - lj);
lj = j;
}
}
}
| package main
import (
"fmt"
"rcu"
)
const LIMIT = 999999
var primes = rcu.Primes(LIMIT)
func longestSeq(dir string) {
pd := 0
longSeqs := [][]int{{2}}
currSeq := []int{2}
for i := 1; i < len(primes); i++ {
d := primes[i] - primes[i-1]
if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) {
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
currSeq = []int{primes[i-1], primes[i]}
} else {
currSeq = append(currSeq, primes[i])
}
pd = d
}
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":")
for _, ls := range longSeqs {
var diffs []int
for i := 1; i < len(ls); i++ {
diffs = append(diffs, ls[i]-ls[i-1])
}
for i := 0; i < len(ls)-1; i++ {
fmt.Print(ls[i], " (", diffs[i], ") ")
}
fmt.Println(ls[len(ls)-1])
}
fmt.Println()
}
func main() {
fmt.Println("For primes < 1 million:\n")
for _, dir := range []string{"ascending", "descending"} {
longestSeq(dir)
}
}
|
Transform the following C# implementation into Go, maintaining the same output and logic. | using System; using static System.Console;
class Program {
const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];
static void Main(string[] args) {
f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)
f[b] = f[a] * (b + 1);
int pc = 0, nth = 0, lv = 0;
for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {
if (i < first) Write("{0,5:n0}{1}", i, pc++ % 5 == 4 ? "\n" : " ");
nth++; lv = i; }
Write("\nCount of Erdős primes between 1 and {0:n0}: {1}\n{2} Erdős prime (the last one under {3:n0}): {4:n0}", first, pc, ord(nth), lmt, lv); }
static string ord(int n) {
return string.Format("{0:n0}", n) + new string[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[n % 10]; }
static bool is_erdos_prime(int p) {
if (!is_pr(p)) return false; int m = 0, t;
while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;
return true;
bool is_pr(int x) {
if (x < 4) return x > 1; if ((x & 1) == 0) return false;
for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;
return true; } } }
| package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := 4; i < limit; i += 2 {
c[i] = true
}
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := int(1e6)
c := sieve(limit - 1)
var erdos []int
for i := 2; i < limit; {
if !c[i] {
found := true
for j, fact := 1, 1; fact < i; {
if !c[i-fact] {
found = false
break
}
j++
fact = fact * j
}
if found {
erdos = append(erdos, i)
}
}
if i > 2 {
i += 2
} else {
i += 1
}
}
lowerLimit := 2500
var erdosLower []int
for _, e := range erdos {
if e < lowerLimit {
erdosLower = append(erdosLower, e)
} else {
break
}
}
fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit))
for i, e := range erdosLower {
fmt.Printf("%6d", e)
if (i+1)%10 == 0 {
fmt.Println()
}
}
show := 7875
fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1]))
}
|
Port the provided C# code into Go while preserving the original functionality. | using System; using static System.Console;
class Program {
const int lmt = (int)1e6, first = 2500; static int[] f = new int[10];
static void Main(string[] args) {
f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++)
f[b] = f[a] * (b + 1);
int pc = 0, nth = 0, lv = 0;
for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) {
if (i < first) Write("{0,5:n0}{1}", i, pc++ % 5 == 4 ? "\n" : " ");
nth++; lv = i; }
Write("\nCount of Erdős primes between 1 and {0:n0}: {1}\n{2} Erdős prime (the last one under {3:n0}): {4:n0}", first, pc, ord(nth), lmt, lv); }
static string ord(int n) {
return string.Format("{0:n0}", n) + new string[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[n % 10]; }
static bool is_erdos_prime(int p) {
if (!is_pr(p)) return false; int m = 0, t;
while ((t = p - f[m++]) > 0) if (is_pr(t)) return false;
return true;
bool is_pr(int x) {
if (x < 4) return x > 1; if ((x & 1) == 0) return false;
for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false;
return true; } } }
| package main
import "fmt"
func sieve(limit int) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := 4; i < limit; i += 2 {
c[i] = true
}
p := 3
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
limit := int(1e6)
c := sieve(limit - 1)
var erdos []int
for i := 2; i < limit; {
if !c[i] {
found := true
for j, fact := 1, 1; fact < i; {
if !c[i-fact] {
found = false
break
}
j++
fact = fact * j
}
if found {
erdos = append(erdos, i)
}
}
if i > 2 {
i += 2
} else {
i += 1
}
}
lowerLimit := 2500
var erdosLower []int
for _, e := range erdos {
if e < lowerLimit {
erdosLower = append(erdosLower, e)
} else {
break
}
}
fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit))
for i, e := range erdosLower {
fmt.Printf("%6d", e)
if (i+1)%10 == 0 {
fmt.Println()
}
}
show := 7875
fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1]))
}
|
Preserve the algorithm and functionality while converting the code from C# to Go. | using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};
private (int dx, int dy)[] moves;
public static void Main()
{
var numbrixSolver = new Solver(numbrixMoves);
Print(numbrixSolver.Solve(false, new [,] {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 46, 45, 0, 55, 74, 0, 0 },
{ 0, 38, 0, 0, 43, 0, 0, 78, 0 },
{ 0, 35, 0, 0, 0, 0, 0, 71, 0 },
{ 0, 0, 33, 0, 0, 0, 59, 0, 0 },
{ 0, 17, 0, 0, 0, 0, 0, 67, 0 },
{ 0, 18, 0, 0, 11, 0, 0, 64, 0 },
{ 0, 0, 24, 21, 0, 1, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
}));
Print(numbrixSolver.Solve(false, new [,] {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 11, 12, 15, 18, 21, 62, 61, 0 },
{ 0, 6, 0, 0, 0, 0, 0, 60, 0 },
{ 0, 33, 0, 0, 0, 0, 0, 57, 0 },
{ 0, 32, 0, 0, 0, 0, 0, 56, 0 },
{ 0, 37, 0, 1, 0, 0, 0, 73, 0 },
{ 0, 38, 0, 0, 0, 0, 0, 72, 0 },
{ 0, 43, 44, 47, 48, 51, 76, 77, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
}));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
}
| 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,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00",
}
var example2 = []string{
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00",
}
var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var (
grid [][]int
clues []int
totalToFill = 0
)
func solve(r, c, count, nextClue int) bool {
if count > totalToFill {
return true
}
back := grid[r][c]
if back != 0 && back != count {
return false
}
if back == 0 && nextClue < len(clues) && clues[nextClue] == count {
return false
}
if back == count {
nextClue++
}
grid[r][c] = count
for _, move := range moves {
if solve(r+move[1], c+move[0], count+1, nextClue) {
return true
}
}
grid[r][c] = back
return false
}
func printResult(n int) {
fmt.Println("Solution for example", n, "\b:")
for _, row := range grid {
for _, i := range row {
if i == -1 {
continue
}
fmt.Printf("%2d ", i)
}
fmt.Println()
}
}
func main() {
for n, board := range [2][]string{example1, example2} {
nRows := len(board) + 2
nCols := len(strings.Split(board[0], ",")) + 2
startRow, startCol := 0, 0
grid = make([][]int, nRows)
totalToFill = (nRows - 2) * (nCols - 2)
var lst []int
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
if r >= 1 && r < nRows-1 {
row := strings.Split(board[r-1], ",")
for c := 1; c < nCols-1; c++ {
val, _ := strconv.Atoi(row[c-1])
if val > 0 {
lst = append(lst, val)
}
if val == 1 {
startRow, startCol = r, c
}
grid[r][c] = val
}
}
}
sort.Ints(lst)
clues = lst
if solve(startRow, startCol, 1, 0) {
printResult(n + 1)
}
}
}
|
Write the same algorithm in Go as shown in this C# implementation. | using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)};
private (int dx, int dy)[] moves;
public static void Main()
{
var numbrixSolver = new Solver(numbrixMoves);
Print(numbrixSolver.Solve(false, new [,] {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 46, 45, 0, 55, 74, 0, 0 },
{ 0, 38, 0, 0, 43, 0, 0, 78, 0 },
{ 0, 35, 0, 0, 0, 0, 0, 71, 0 },
{ 0, 0, 33, 0, 0, 0, 59, 0, 0 },
{ 0, 17, 0, 0, 0, 0, 0, 67, 0 },
{ 0, 18, 0, 0, 11, 0, 0, 64, 0 },
{ 0, 0, 24, 21, 0, 1, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
}));
Print(numbrixSolver.Solve(false, new [,] {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 11, 12, 15, 18, 21, 62, 61, 0 },
{ 0, 6, 0, 0, 0, 0, 0, 60, 0 },
{ 0, 33, 0, 0, 0, 0, 0, 57, 0 },
{ 0, 32, 0, 0, 0, 0, 0, 56, 0 },
{ 0, 37, 0, 1, 0, 0, 0, 73, 0 },
{ 0, 38, 0, 0, 0, 0, 0, 72, 0 },
{ 0, 43, 44, 47, 48, 51, 76, 77, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
}));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
}
| 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,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00",
}
var example2 = []string{
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00",
}
var moves = [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var (
grid [][]int
clues []int
totalToFill = 0
)
func solve(r, c, count, nextClue int) bool {
if count > totalToFill {
return true
}
back := grid[r][c]
if back != 0 && back != count {
return false
}
if back == 0 && nextClue < len(clues) && clues[nextClue] == count {
return false
}
if back == count {
nextClue++
}
grid[r][c] = count
for _, move := range moves {
if solve(r+move[1], c+move[0], count+1, nextClue) {
return true
}
}
grid[r][c] = back
return false
}
func printResult(n int) {
fmt.Println("Solution for example", n, "\b:")
for _, row := range grid {
for _, i := range row {
if i == -1 {
continue
}
fmt.Printf("%2d ", i)
}
fmt.Println()
}
}
func main() {
for n, board := range [2][]string{example1, example2} {
nRows := len(board) + 2
nCols := len(strings.Split(board[0], ",")) + 2
startRow, startCol := 0, 0
grid = make([][]int, nRows)
totalToFill = (nRows - 2) * (nCols - 2)
var lst []int
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
if r >= 1 && r < nRows-1 {
row := strings.Split(board[r-1], ",")
for c := 1; c < nCols-1; c++ {
val, _ := strconv.Atoi(row[c-1])
if val > 0 {
lst = append(lst, val)
}
if val == 1 {
startRow, startCol = r, c
}
grid[r][c] = val
}
}
}
sort.Ints(lst)
clues = lst
if solve(startRow, startCol, 1, 0) {
printResult(n + 1)
}
}
}
|
Change the programming language of this snippet from C# to Go without modifying what it does. | using System;
public delegate Church Church(Church f);
public static class ChurchNumeral
{
public static readonly Church ChurchZero = _ => x => x;
public static readonly Church ChurchOne = f => f;
public static Church Successor(this Church n) => f => x => f(n(f)(x));
public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));
public static Church Multiply(this Church m, Church n) => f => m(n(f));
public static Church Exponent(this Church m, Church n) => n(m);
public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);
public static Church Predecessor(this Church n) =>
f => x => n(g => h => h(g(f)))(_ => x)(a => a);
public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);
static Church looper(this Church v, Church d) =>
v(_ => v.divr(d).Successor())(ChurchZero);
static Church divr(this Church n, Church d) =>
n.Subtract(d).looper(d);
public static Church Divide(this Church dvdnd, Church dvsr) =>
(dvdnd.Successor()).divr(dvsr);
public static Church FromInt(int i) =>
i <= 0 ? ChurchZero : Successor(FromInt(i - 1));
public static int ToInt(this Church ch) {
int count = 0;
ch(x => { count++; return x; })(null);
return count;
}
public static void Main() {
Church c3 = FromInt(3);
Church c4 = c3.Successor();
Church c11 = FromInt(11);
Church c12 = c11.Successor();
int sum = c3.Add(c4).ToInt();
int product = c3.Multiply(c4).ToInt();
int exp43 = c4.Exponent(c3).ToInt();
int exp34 = c3.Exponent(c4).ToInt();
int tst0 = ChurchZero.IsZero().ToInt();
int pred4 = c4.Predecessor().ToInt();
int sub43 = c4.Subtract(c3).ToInt();
int div11by3 = c11.Divide(c3).ToInt();
int div12by3 = c12.Divide(c3).ToInt();
Console.Write($"{sum} {product} {exp43} {exp34} {tst0} ");
Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}");
}
}
| package main
import "fmt"
type any = interface{}
type fn func(any) any
type church func(fn) fn
func zero(f fn) fn {
return func(x any) any {
return x
}
}
func (c church) succ() church {
return func(f fn) fn {
return func(x any) any {
return f(c(f)(x))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
}
|
Can you help me rewrite this code in Go instead of C#, keeping it the same logically? | using System;
public delegate Church Church(Church f);
public static class ChurchNumeral
{
public static readonly Church ChurchZero = _ => x => x;
public static readonly Church ChurchOne = f => f;
public static Church Successor(this Church n) => f => x => f(n(f)(x));
public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));
public static Church Multiply(this Church m, Church n) => f => m(n(f));
public static Church Exponent(this Church m, Church n) => n(m);
public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);
public static Church Predecessor(this Church n) =>
f => x => n(g => h => h(g(f)))(_ => x)(a => a);
public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);
static Church looper(this Church v, Church d) =>
v(_ => v.divr(d).Successor())(ChurchZero);
static Church divr(this Church n, Church d) =>
n.Subtract(d).looper(d);
public static Church Divide(this Church dvdnd, Church dvsr) =>
(dvdnd.Successor()).divr(dvsr);
public static Church FromInt(int i) =>
i <= 0 ? ChurchZero : Successor(FromInt(i - 1));
public static int ToInt(this Church ch) {
int count = 0;
ch(x => { count++; return x; })(null);
return count;
}
public static void Main() {
Church c3 = FromInt(3);
Church c4 = c3.Successor();
Church c11 = FromInt(11);
Church c12 = c11.Successor();
int sum = c3.Add(c4).ToInt();
int product = c3.Multiply(c4).ToInt();
int exp43 = c4.Exponent(c3).ToInt();
int exp34 = c3.Exponent(c4).ToInt();
int tst0 = ChurchZero.IsZero().ToInt();
int pred4 = c4.Predecessor().ToInt();
int sub43 = c4.Subtract(c3).ToInt();
int div11by3 = c11.Divide(c3).ToInt();
int div12by3 = c12.Divide(c3).ToInt();
Console.Write($"{sum} {product} {exp43} {exp34} {tst0} ");
Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}");
}
}
| package main
import "fmt"
type any = interface{}
type fn func(any) any
type church func(fn) fn
func zero(f fn) fn {
return func(x any) any {
return x
}
}
func (c church) succ() church {
return func(f fn) fn {
return func(x any) any {
return f(c(f)(x))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
}
|
Write a version of this C# function in Go with identical behavior. | using System;
public delegate Church Church(Church f);
public static class ChurchNumeral
{
public static readonly Church ChurchZero = _ => x => x;
public static readonly Church ChurchOne = f => f;
public static Church Successor(this Church n) => f => x => f(n(f)(x));
public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x));
public static Church Multiply(this Church m, Church n) => f => m(n(f));
public static Church Exponent(this Church m, Church n) => n(m);
public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne);
public static Church Predecessor(this Church n) =>
f => x => n(g => h => h(g(f)))(_ => x)(a => a);
public static Church Subtract(this Church m, Church n) => n(Predecessor)(m);
static Church looper(this Church v, Church d) =>
v(_ => v.divr(d).Successor())(ChurchZero);
static Church divr(this Church n, Church d) =>
n.Subtract(d).looper(d);
public static Church Divide(this Church dvdnd, Church dvsr) =>
(dvdnd.Successor()).divr(dvsr);
public static Church FromInt(int i) =>
i <= 0 ? ChurchZero : Successor(FromInt(i - 1));
public static int ToInt(this Church ch) {
int count = 0;
ch(x => { count++; return x; })(null);
return count;
}
public static void Main() {
Church c3 = FromInt(3);
Church c4 = c3.Successor();
Church c11 = FromInt(11);
Church c12 = c11.Successor();
int sum = c3.Add(c4).ToInt();
int product = c3.Multiply(c4).ToInt();
int exp43 = c4.Exponent(c3).ToInt();
int exp34 = c3.Exponent(c4).ToInt();
int tst0 = ChurchZero.IsZero().ToInt();
int pred4 = c4.Predecessor().ToInt();
int sub43 = c4.Subtract(c3).ToInt();
int div11by3 = c11.Divide(c3).ToInt();
int div12by3 = c12.Divide(c3).ToInt();
Console.Write($"{sum} {product} {exp43} {exp34} {tst0} ");
Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}");
}
}
| package main
import "fmt"
type any = interface{}
type fn func(any) any
type church func(fn) fn
func zero(f fn) fn {
return func(x any) any {
return x
}
}
func (c church) succ() church {
return func(f fn) fn {
return func(x any) any {
return f(c(f)(x))
}
}
}
func (c church) add(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(f)(d(f)(x))
}
}
}
func (c church) mul(d church) church {
return func(f fn) fn {
return func(x any) any {
return c(d(f))(x)
}
}
}
func (c church) pow(d church) church {
di := d.toInt()
prod := c
for i := 1; i < di; i++ {
prod = prod.mul(c)
}
return prod
}
func (c church) toInt() int {
return c(incr)(0).(int)
}
func intToChurch(i int) church {
if i == 0 {
return zero
} else {
return intToChurch(i - 1).succ()
}
}
func incr(i any) any {
return i.(int) + 1
}
func main() {
z := church(zero)
three := z.succ().succ().succ()
four := three.succ()
fmt.Println("three ->", three.toInt())
fmt.Println("four ->", four.toInt())
fmt.Println("three + four ->", three.add(four).toInt())
fmt.Println("three * four ->", three.mul(four).toInt())
fmt.Println("three ^ four ->", three.pow(four).toInt())
fmt.Println("four ^ three ->", four.pow(three).toInt())
fmt.Println("5 -> five ->", intToChurch(5).toInt())
}
|
Change the programming language of this snippet from C# to Go without modifying what it does. | using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},
private (int dx, int dy)[] moves;
public static void Main()
{
Print(new Solver(hopidoMoves).Solve(false,
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."
));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
}
| 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, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
|
Maintain the same structure and functionality when rewriting this code in Go. | using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)},
private (int dx, int dy)[] moves;
public static void Main()
{
Print(new Solver(hopidoMoves).Solve(false,
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."
));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
}
| 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, count int) bool {
if count > totalToFill {
return true
}
nbrs := neighbors(r, c)
if len(nbrs) == 0 && count != totalToFill {
return false
}
sort.Slice(nbrs, func(i, j int) bool {
return nbrs[i][2] < nbrs[j][2]
})
for _, nb := range nbrs {
r = nb[0]
c = nb[1]
grid[r][c] = count
if solve(r, c, count+1) {
return true
}
grid[r][c] = 0
}
return false
}
func neighbors(r, c int) (nbrs [][3]int) {
for _, m := range moves {
x := m[0]
y := m[1]
if grid[r+y][c+x] == 0 {
num := countNeighbors(r+y, c+x) - 1
nbrs = append(nbrs, [3]int{r + y, c + x, num})
}
}
return
}
func countNeighbors(r, c int) int {
num := 0
for _, m := range moves {
if grid[r+m[1]][c+m[0]] == 0 {
num++
}
}
return num
}
func printResult() {
for _, row := range grid {
for _, i := range row {
if i == -1 {
fmt.Print(" ")
} else {
fmt.Printf("%2d ", i)
}
}
fmt.Println()
}
}
func main() {
nRows := len(board) + 6
nCols := len(board[0]) + 6
grid = make([][]int, nRows)
for r := 0; r < nRows; r++ {
grid[r] = make([]int, nCols)
for c := 0; c < nCols; c++ {
grid[r][c] = -1
}
for c := 3; c < nCols-3; c++ {
if r >= 3 && r < nRows-3 {
if board[r-3][c-3] == '0' {
grid[r][c] = 0
totalToFill++
}
}
}
}
pos, r, c := -1, 0, 0
for {
for {
pos++
r = pos / nCols
c = pos % nCols
if grid[r][c] != -1 {
break
}
}
grid[r][c] = 1
if solve(r, c, 2) {
break
}
grid[r][c] = 0
if pos >= nRows*nCols {
break
}
}
printResult()
}
|
Maintain the same structure and functionality when rewriting this code in Go. | using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class NonogramSolver
{
public static void Main2() {
foreach (var (x, y) in new [] {
("C BA CB BB F AE F A B", "AB CA AE GA E C D C"),
("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"),
("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"),
("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM")
})
{
Solve(x, y);
Console.WriteLine();
}
}
static void Solve(string rowLetters, string columnLetters) {
var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();
var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();
Solve(r, c);
}
static void Solve(int[][] rowRuns, int[][] columnRuns) {
int len = columnRuns.Length;
var rows = rowRuns.Select(row => Generate(len, row)).ToList();
var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();
Reduce(rows, columns);
foreach (var list in rows) {
if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());
else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());
}
}
static List<BitSet> Generate(int length, params int[] runs) {
var list = new List<BitSet>();
BitSet initial = BitSet.Empty;
int[] sums = new int[runs.Length];
sums[0] = 0;
for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;
for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);
Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);
return list;
}
static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {
if (index == runs.Length) {
result.Add(current);
return;
}
while (current.Value < max.Value) {
Generate(result, max, runs, sums, current, index + 1, shift);
current = current.ShiftLeftAt(sums[index] + shift);
shift++;
}
}
static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {
for (int count = 1; count > 0; ) {
foreach (var (rowIndex, row) in rows.WithIndex()) {
var allOn = row.Aggregate((a, b) => a & b);
var allOff = row.Aggregate((a, b) => a | b);
foreach (var (columnIndex, column) in columns.WithIndex()) {
count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));
count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));
}
}
foreach (var (columnIndex, column) in columns.WithIndex()) {
var allOn = column.Aggregate((a, b) => a & b);
var allOff = column.Aggregate((a, b) => a | b);
foreach (var (rowIndex, row) in rows.WithIndex()) {
count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));
count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));
}
}
}
}
static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {
int i = 0;
foreach (T element in source) {
yield return (i++, element);
}
}
static string Reverse(this string s) {
char[] array = s.ToCharArray();
Array.Reverse(array);
return new string(array);
}
static string Spaced(this IEnumerable<char> s) => string.Join(" ", s);
struct BitSet
{
public static BitSet Empty => default;
private readonly int bits;
public int Value => bits;
private BitSet(int bits) => this.bits = bits;
public BitSet Add(int item) => new BitSet(bits | (1 << item));
public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));
public bool Contains(int item) => (bits & (1 << item)) != 0;
public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));
public override string ToString() => Convert.ToString(bits, 2);
public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);
public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);
}
}
| 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 bs[i] || other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func iff(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}
func newPuzzle(data [2]string) {
rowData := strings.Fields(data[0])
colData := strings.Fields(data[1])
rows := getCandidates(rowData, len(colData))
cols := getCandidates(colData, len(rowData))
for {
numChanged := reduceMutual(cols, rows)
if numChanged == -1 {
fmt.Println("No solution")
return
}
if numChanged == 0 {
break
}
}
for _, row := range rows {
for i := 0; i < len(cols); i++ {
fmt.Printf(iff(row[0][i], "# ", ". "))
}
fmt.Println()
}
fmt.Println()
}
func getCandidates(data []string, le int) [][]BitSet {
var result [][]BitSet
for _, s := range data {
var lst []BitSet
a := []byte(s)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 'A' + 1)
}
prep := make([]string, len(a))
for i, b := range a {
prep[i] = strings.Repeat("1", int(b-'A'+1))
}
for _, r := range genSequence(prep, le-sumBytes+1) {
bits := []byte(r[1:])
bitset := make(BitSet, len(bits))
for i, b := range bits {
bitset[i] = b == '1'
}
lst = append(lst, bitset)
}
result = append(result, lst)
}
return result
}
func genSequence(ones []string, numZeros int) []string {
le := len(ones)
if le == 0 {
return []string{strings.Repeat("0", numZeros)}
}
var result []string
for x := 1; x < numZeros-le+2; x++ {
skipOne := ones[1:]
for _, tail := range genSequence(skipOne, numZeros-x) {
result = append(result, strings.Repeat("0", x)+ones[0]+tail)
}
}
return result
}
func reduceMutual(cols, rows [][]BitSet) int {
countRemoved1 := reduce(cols, rows)
if countRemoved1 == -1 {
return -1
}
countRemoved2 := reduce(rows, cols)
if countRemoved2 == -1 {
return -1
}
return countRemoved1 + countRemoved2
}
func reduce(a, b [][]BitSet) int {
countRemoved := 0
for i := 0; i < len(a); i++ {
commonOn := make(BitSet, len(b))
for j := 0; j < len(b); j++ {
commonOn[j] = true
}
commonOff := make(BitSet, len(b))
for _, candidate := range a[i] {
commonOn.and(candidate)
commonOff.or(candidate)
}
for j := 0; j < len(b); j++ {
fi, fj := i, j
for k := len(b[j]) - 1; k >= 0; k-- {
cnd := b[j][k]
if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {
lb := len(b[j])
copy(b[j][k:], b[j][k+1:])
b[j][lb-1] = nil
b[j] = b[j][:lb-1]
countRemoved++
}
}
if len(b[j]) == 0 {
return -1
}
}
}
return countRemoved
}
func main() {
p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}
p2 := [2]string{
"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA",
}
p3 := [2]string{
"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " +
"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " +
"AAAAD BDG CEF CBDB BBB FC",
}
p4 := [2]string{
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM",
}
for _, puzzleData := range [][2]string{p1, p2, p3, p4} {
newPuzzle(puzzleData)
}
}
|
Translate the given C# code snippet into Go without altering its behavior. | using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class NonogramSolver
{
public static void Main2() {
foreach (var (x, y) in new [] {
("C BA CB BB F AE F A B", "AB CA AE GA E C D C"),
("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"),
("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"),
("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM")
})
{
Solve(x, y);
Console.WriteLine();
}
}
static void Solve(string rowLetters, string columnLetters) {
var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray();
var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray();
Solve(r, c);
}
static void Solve(int[][] rowRuns, int[][] columnRuns) {
int len = columnRuns.Length;
var rows = rowRuns.Select(row => Generate(len, row)).ToList();
var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList();
Reduce(rows, columns);
foreach (var list in rows) {
if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced());
else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced());
}
}
static List<BitSet> Generate(int length, params int[] runs) {
var list = new List<BitSet>();
BitSet initial = BitSet.Empty;
int[] sums = new int[runs.Length];
sums[0] = 0;
for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1;
for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]);
Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0);
return list;
}
static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) {
if (index == runs.Length) {
result.Add(current);
return;
}
while (current.Value < max.Value) {
Generate(result, max, runs, sums, current, index + 1, shift);
current = current.ShiftLeftAt(sums[index] + shift);
shift++;
}
}
static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) {
for (int count = 1; count > 0; ) {
foreach (var (rowIndex, row) in rows.WithIndex()) {
var allOn = row.Aggregate((a, b) => a & b);
var allOff = row.Aggregate((a, b) => a | b);
foreach (var (columnIndex, column) in columns.WithIndex()) {
count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex));
count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex));
}
}
foreach (var (columnIndex, column) in columns.WithIndex()) {
var allOn = column.Aggregate((a, b) => a & b);
var allOff = column.Aggregate((a, b) => a | b);
foreach (var (rowIndex, row) in rows.WithIndex()) {
count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex));
count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex));
}
}
}
}
static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) {
int i = 0;
foreach (T element in source) {
yield return (i++, element);
}
}
static string Reverse(this string s) {
char[] array = s.ToCharArray();
Array.Reverse(array);
return new string(array);
}
static string Spaced(this IEnumerable<char> s) => string.Join(" ", s);
struct BitSet
{
public static BitSet Empty => default;
private readonly int bits;
public int Value => bits;
private BitSet(int bits) => this.bits = bits;
public BitSet Add(int item) => new BitSet(bits | (1 << item));
public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1)));
public bool Contains(int item) => (bits & (1 << item)) != 0;
public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1)));
public override string ToString() => Convert.ToString(bits, 2);
public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits);
public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits);
}
}
| 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 bs[i] || other[i] {
bs[i] = true
} else {
bs[i] = false
}
}
}
func iff(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}
func newPuzzle(data [2]string) {
rowData := strings.Fields(data[0])
colData := strings.Fields(data[1])
rows := getCandidates(rowData, len(colData))
cols := getCandidates(colData, len(rowData))
for {
numChanged := reduceMutual(cols, rows)
if numChanged == -1 {
fmt.Println("No solution")
return
}
if numChanged == 0 {
break
}
}
for _, row := range rows {
for i := 0; i < len(cols); i++ {
fmt.Printf(iff(row[0][i], "# ", ". "))
}
fmt.Println()
}
fmt.Println()
}
func getCandidates(data []string, le int) [][]BitSet {
var result [][]BitSet
for _, s := range data {
var lst []BitSet
a := []byte(s)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 'A' + 1)
}
prep := make([]string, len(a))
for i, b := range a {
prep[i] = strings.Repeat("1", int(b-'A'+1))
}
for _, r := range genSequence(prep, le-sumBytes+1) {
bits := []byte(r[1:])
bitset := make(BitSet, len(bits))
for i, b := range bits {
bitset[i] = b == '1'
}
lst = append(lst, bitset)
}
result = append(result, lst)
}
return result
}
func genSequence(ones []string, numZeros int) []string {
le := len(ones)
if le == 0 {
return []string{strings.Repeat("0", numZeros)}
}
var result []string
for x := 1; x < numZeros-le+2; x++ {
skipOne := ones[1:]
for _, tail := range genSequence(skipOne, numZeros-x) {
result = append(result, strings.Repeat("0", x)+ones[0]+tail)
}
}
return result
}
func reduceMutual(cols, rows [][]BitSet) int {
countRemoved1 := reduce(cols, rows)
if countRemoved1 == -1 {
return -1
}
countRemoved2 := reduce(rows, cols)
if countRemoved2 == -1 {
return -1
}
return countRemoved1 + countRemoved2
}
func reduce(a, b [][]BitSet) int {
countRemoved := 0
for i := 0; i < len(a); i++ {
commonOn := make(BitSet, len(b))
for j := 0; j < len(b); j++ {
commonOn[j] = true
}
commonOff := make(BitSet, len(b))
for _, candidate := range a[i] {
commonOn.and(candidate)
commonOff.or(candidate)
}
for j := 0; j < len(b); j++ {
fi, fj := i, j
for k := len(b[j]) - 1; k >= 0; k-- {
cnd := b[j][k]
if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) {
lb := len(b[j])
copy(b[j][k:], b[j][k+1:])
b[j][lb-1] = nil
b[j] = b[j][:lb-1]
countRemoved++
}
}
if len(b[j]) == 0 {
return -1
}
}
}
return countRemoved
}
func main() {
p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"}
p2 := [2]string{
"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA",
}
p3 := [2]string{
"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " +
"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " +
"AAAAD BDG CEF CBDB BBB FC",
}
p4 := [2]string{
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM",
}
for _, puzzleData := range [][2]string{p1, p2, p3, p4} {
newPuzzle(puzzleData)
}
}
|
Write a version of this C# function in Go with identical behavior. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Wordseach
{
static class Program
{
readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}};
class Grid
{
public char[,] Cells = new char[nRows, nCols];
public List<string> Solutions = new List<string>();
public int NumAttempts;
}
readonly static int nRows = 10;
readonly static int nCols = 10;
readonly static int gridSize = nRows * nCols;
readonly static int minWords = 25;
readonly static Random rand = new Random();
static void Main(string[] args)
{
PrintResult(CreateWordSearch(ReadWords("unixdict.txt")));
}
private static List<string> ReadWords(string filename)
{
int maxLen = Math.Max(nRows, nCols);
return System.IO.File.ReadAllLines(filename)
.Select(s => s.Trim().ToLower())
.Where(s => Regex.IsMatch(s, "^[a-z]{3," + maxLen + "}$"))
.ToList();
}
private static Grid CreateWordSearch(List<string> words)
{
int numAttempts = 0;
while (++numAttempts < 100)
{
words.Shuffle();
var grid = new Grid();
int messageLen = PlaceMessage(grid, "Rosetta Code");
int target = gridSize - messageLen;
int cellsFilled = 0;
foreach (var word in words)
{
cellsFilled += TryPlaceWord(grid, word);
if (cellsFilled == target)
{
if (grid.Solutions.Count >= minWords)
{
grid.NumAttempts = numAttempts;
return grid;
}
else break;
}
}
}
return null;
}
private static int TryPlaceWord(Grid grid, string word)
{
int randDir = rand.Next(dirs.GetLength(0));
int randPos = rand.Next(gridSize);
for (int dir = 0; dir < dirs.GetLength(0); dir++)
{
dir = (dir + randDir) % dirs.GetLength(0);
for (int pos = 0; pos < gridSize; pos++)
{
pos = (pos + randPos) % gridSize;
int lettersPlaced = TryLocation(grid, word, dir, pos);
if (lettersPlaced > 0)
return lettersPlaced;
}
}
return 0;
}
private static int TryLocation(Grid grid, string word, int dir, int pos)
{
int r = pos / nCols;
int c = pos % nCols;
int len = word.Length;
if ((dirs[dir, 0] == 1 && (len + c) > nCols)
|| (dirs[dir, 0] == -1 && (len - 1) > c)
|| (dirs[dir, 1] == 1 && (len + r) > nRows)
|| (dirs[dir, 1] == -1 && (len - 1) > r))
return 0;
int rr, cc, i, overlaps = 0;
for (i = 0, rr = r, cc = c; i < len; i++)
{
if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i])
{
return 0;
}
cc += dirs[dir, 0];
rr += dirs[dir, 1];
}
for (i = 0, rr = r, cc = c; i < len; i++)
{
if (grid.Cells[rr, cc] == word[i])
overlaps++;
else
grid.Cells[rr, cc] = word[i];
if (i < len - 1)
{
cc += dirs[dir, 0];
rr += dirs[dir, 1];
}
}
int lettersPlaced = len - overlaps;
if (lettersPlaced > 0)
{
grid.Solutions.Add($"{word,-10} ({c},{r})({cc},{rr})");
}
return lettersPlaced;
}
private static int PlaceMessage(Grid grid, string msg)
{
msg = Regex.Replace(msg.ToUpper(), "[^A-Z]", "");
int messageLen = msg.Length;
if (messageLen > 0 && messageLen < gridSize)
{
int gapSize = gridSize / messageLen;
for (int i = 0; i < messageLen; i++)
{
int pos = i * gapSize + rand.Next(gapSize);
grid.Cells[pos / nCols, pos % nCols] = msg[i];
}
return messageLen;
}
return 0;
}
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rand.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
private static void PrintResult(Grid grid)
{
if (grid == null || grid.NumAttempts == 0)
{
Console.WriteLine("No grid to display");
return;
}
int size = grid.Solutions.Count;
Console.WriteLine("Attempts: " + grid.NumAttempts);
Console.WriteLine("Number of words: " + size);
Console.WriteLine("\n 0 1 2 3 4 5 6 7 8 9");
for (int r = 0; r < nRows; r++)
{
Console.Write("\n{0} ", r);
for (int c = 0; c < nCols; c++)
Console.Write(" {0} ", grid.Cells[r, c]);
}
Console.WriteLine("\n");
for (int i = 0; i < size - 1; i += 2)
{
Console.WriteLine("{0} {1}", grid.Solutions[i],
grid.Solutions[i + 1]);
}
if (size % 2 == 1)
Console.WriteLine(grid.Solutions[size - 1]);
Console.ReadLine();
}
}
}
| package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"regexp"
"strings"
"time"
)
var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}
const (
nRows = 10
nCols = nRows
gridSize = nRows * nCols
minWords = 25
)
var (
re1 = regexp.MustCompile(fmt.Sprintf("^[a-z]{3,%d}$", nRows))
re2 = regexp.MustCompile("[^A-Z]")
)
type grid struct {
numAttempts int
cells [nRows][nCols]byte
solutions []string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func readWords(fileName string) []string {
file, err := os.Open(fileName)
check(err)
defer file.Close()
var words []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
word := strings.ToLower(strings.TrimSpace(scanner.Text()))
if re1.MatchString(word) {
words = append(words, word)
}
}
check(scanner.Err())
return words
}
func createWordSearch(words []string) *grid {
var gr *grid
outer:
for i := 1; i < 100; i++ {
gr = new(grid)
messageLen := gr.placeMessage("Rosetta Code")
target := gridSize - messageLen
cellsFilled := 0
rand.Shuffle(len(words), func(i, j int) {
words[i], words[j] = words[j], words[i]
})
for _, word := range words {
cellsFilled += gr.tryPlaceWord(word)
if cellsFilled == target {
if len(gr.solutions) >= minWords {
gr.numAttempts = i
break outer
} else {
break
}
}
}
}
return gr
}
func (gr *grid) placeMessage(msg string) int {
msg = strings.ToUpper(msg)
msg = re2.ReplaceAllLiteralString(msg, "")
messageLen := len(msg)
if messageLen > 0 && messageLen < gridSize {
gapSize := gridSize / messageLen
for i := 0; i < messageLen; i++ {
pos := i*gapSize + rand.Intn(gapSize)
gr.cells[pos/nCols][pos%nCols] = msg[i]
}
return messageLen
}
return 0
}
func (gr *grid) tryPlaceWord(word string) int {
randDir := rand.Intn(len(dirs))
randPos := rand.Intn(gridSize)
for dir := 0; dir < len(dirs); dir++ {
dir = (dir + randDir) % len(dirs)
for pos := 0; pos < gridSize; pos++ {
pos = (pos + randPos) % gridSize
lettersPlaced := gr.tryLocation(word, dir, pos)
if lettersPlaced > 0 {
return lettersPlaced
}
}
}
return 0
}
func (gr *grid) tryLocation(word string, dir, pos int) int {
r := pos / nCols
c := pos % nCols
le := len(word)
if (dirs[dir][0] == 1 && (le+c) > nCols) ||
(dirs[dir][0] == -1 && (le-1) > c) ||
(dirs[dir][1] == 1 && (le+r) > nRows) ||
(dirs[dir][1] == -1 && (le-1) > r) {
return 0
}
overlaps := 0
rr := r
cc := c
for i := 0; i < le; i++ {
if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {
return 0
}
cc += dirs[dir][0]
rr += dirs[dir][1]
}
rr = r
cc = c
for i := 0; i < le; i++ {
if gr.cells[rr][cc] == word[i] {
overlaps++
} else {
gr.cells[rr][cc] = word[i]
}
if i < le-1 {
cc += dirs[dir][0]
rr += dirs[dir][1]
}
}
lettersPlaced := le - overlaps
if lettersPlaced > 0 {
sol := fmt.Sprintf("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr)
gr.solutions = append(gr.solutions, sol)
}
return lettersPlaced
}
func printResult(gr *grid) {
if gr.numAttempts == 0 {
fmt.Println("No grid to display")
return
}
size := len(gr.solutions)
fmt.Println("Attempts:", gr.numAttempts)
fmt.Println("Number of words:", size)
fmt.Println("\n 0 1 2 3 4 5 6 7 8 9")
for r := 0; r < nRows; r++ {
fmt.Printf("\n%d ", r)
for c := 0; c < nCols; c++ {
fmt.Printf(" %c ", gr.cells[r][c])
}
}
fmt.Println("\n")
for i := 0; i < size-1; i += 2 {
fmt.Printf("%s %s\n", gr.solutions[i], gr.solutions[i+1])
}
if size%2 == 1 {
fmt.Println(gr.solutions[size-1])
}
}
func main() {
rand.Seed(time.Now().UnixNano())
unixDictPath := "/usr/share/dict/words"
printResult(createWordSearch(readWords(unixDictPath)))
}
|
Write the same code in Go as shown below in C#. | using System;
using System.Reflection;
public class MyClass
{
private int answer = 42;
}
public class Program
{
public static void Main()
{
var myInstance = new MyClass();
var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
var answer = fieldInfo.GetValue(myInstance);
Console.WriteLine(answer);
}
}
| package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int
unexported int
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&obj)
fmt.Println("obj:", obj)
anotherExample()
}
func examineAndModify(any interface{}) {
v := reflect.ValueOf(any)
v = v.Elem()
fmt.Println(" v:", v, "=", v.Interface())
t := v.Type()
fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
fmt.Printf(" %2d: %-10s %-4s %t\n", i,
t.Field(i).Name, f.Type(), f.CanSet())
}
v.Field(0).SetInt(16)
vp := v.Field(1).Addr()
up := unsafe.Pointer(vp.Pointer())
p := (*int)(up)
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
*p = 43
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
}
func anotherExample() {
r := bufio.NewReader(os.Stdin)
errp := (*error)(unsafe.Pointer(
reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
*errp = errors.New("unsafely injected error value into bufio inner workings")
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
}
|
Generate a Go translation of this C# snippet without changing its computational steps. | using System;
using System.Reflection;
public class MyClass
{
private int answer = 42;
}
public class Program
{
public static void Main()
{
var myInstance = new MyClass();
var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
var answer = fieldInfo.GetValue(myInstance);
Console.WriteLine(answer);
}
}
| package main
import (
"bufio"
"errors"
"fmt"
"os"
"reflect"
"unsafe"
)
type foobar struct {
Exported int
unexported int
}
func main() {
obj := foobar{12, 42}
fmt.Println("obj:", obj)
examineAndModify(&obj)
fmt.Println("obj:", obj)
anotherExample()
}
func examineAndModify(any interface{}) {
v := reflect.ValueOf(any)
v = v.Elem()
fmt.Println(" v:", v, "=", v.Interface())
t := v.Type()
fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
fmt.Printf(" %2d: %-10s %-4s %t\n", i,
t.Field(i).Name, f.Type(), f.CanSet())
}
v.Field(0).SetInt(16)
vp := v.Field(1).Addr()
up := unsafe.Pointer(vp.Pointer())
p := (*int)(up)
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
*p = 43
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
}
func anotherExample() {
r := bufio.NewReader(os.Stdin)
errp := (*error)(unsafe.Pointer(
reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
*errp = errors.New("unsafely injected error value into bufio inner workings")
_, err := r.ReadByte()
fmt.Println("bufio.ReadByte returned error:", err)
}
|
Write the same code in Go as shown below in C#. | using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
namespace Object_serialization
{
[Serializable] public class Being
{
public bool Alive { get; set; }
}
[Serializable] public class Animal: Being
{
public Animal() { }
public Animal(long id, string name, bool alive = true)
{
Id = id;
Name = name;
Alive = alive;
}
public long Id { get; set; }
public string Name { get; set; }
public void Print() { Console.WriteLine("{0}, id={1} is {2}",
Name, Id, Alive ? "alive" : "dead"); }
}
internal class Program
{
private static void Main()
{
string path =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"\\objects.dat";
var n = new List<Animal>
{
new Animal(1, "Fido"),
new Animal(2, "Lupo"),
new Animal(7, "Wanda"),
new Animal(3, "Kiki", alive: false)
};
foreach(Animal animal in n)
animal.Print();
using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))
new BinaryFormatter().Serialize(stream, n);
n.Clear();
Console.WriteLine("---------------");
List<Animal> m;
using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
m = (List<Animal>) new BinaryFormatter().Deserialize(stream);
foreach(Animal animal in m)
animal.Print();
}
}
}
| package main
import (
"encoding/gob"
"fmt"
"os"
)
type printable interface {
print()
}
func main() {
animals := []printable{
&Animal{Alive: true},
&Cat{},
&Lab{
Dog: Dog{Animal: Animal{Alive: true}},
Color: "yellow",
},
&Collie{Dog: Dog{
Animal: Animal{Alive: true},
ObedienceTrained: true,
}},
}
fmt.Println("created:")
for _, a := range animals {
a.print()
}
f, err := os.Create("objects.dat")
if err != nil {
fmt.Println(err)
return
}
for _, a := range animals {
gob.Register(a)
}
err = gob.NewEncoder(f).Encode(animals)
if err != nil {
fmt.Println(err)
return
}
f.Close()
f, err = os.Open("objects.dat")
if err != nil {
fmt.Println(err)
return
}
var clones []printable
gob.NewDecoder(f).Decode(&clones)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("\nloaded from objects.dat:")
for _, c := range clones {
c.print()
}
}
type Animal struct {
Alive bool
}
func (a *Animal) print() {
if a.Alive {
fmt.Println(" live animal, unspecified type")
} else {
fmt.Println(" dead animal, unspecified type")
}
}
type Dog struct {
Animal
ObedienceTrained bool
}
func (d *Dog) print() {
switch {
case !d.Alive:
fmt.Println(" dead dog")
case d.ObedienceTrained:
fmt.Println(" trained dog")
default:
fmt.Println(" dog, not trained")
}
}
type Cat struct {
Animal
LitterBoxTrained bool
}
func (c *Cat) print() {
switch {
case !c.Alive:
fmt.Println(" dead cat")
case c.LitterBoxTrained:
fmt.Println(" litter box trained cat")
default:
fmt.Println(" cat, not litter box trained")
}
}
type Lab struct {
Dog
Color string
}
func (l *Lab) print() {
var r string
if l.Color == "" {
r = "lab, color unspecified"
} else {
r = l.Color + " lab"
}
switch {
case !l.Alive:
fmt.Println(" dead", r)
case l.ObedienceTrained:
fmt.Println(" trained", r)
default:
fmt.Printf(" %s, not trained\n", r)
}
}
type Collie struct {
Dog
CatchesFrisbee bool
}
func (c *Collie) print() {
switch {
case !c.Alive:
fmt.Println(" dead collie")
case c.ObedienceTrained && c.CatchesFrisbee:
fmt.Println(" trained collie, catches frisbee")
case c.ObedienceTrained && !c.CatchesFrisbee:
fmt.Println(" trained collie, but doesn't catch frisbee")
case !c.ObedienceTrained && c.CatchesFrisbee:
fmt.Println(" collie, not trained, but catches frisbee")
case !c.ObedienceTrained && !c.CatchesFrisbee:
fmt.Println(" collie, not trained, doesn't catch frisbee")
}
}
|
Convert the following code from C# to Go, ensuring the logic remains intact. | using System;
using System.Collections.Generic;
namespace Eertree {
class Node {
public Node(int length) {
this.Length = length;
this.Edges = new Dictionary<char, int>();
}
public Node(int length, Dictionary<char, int> edges, int suffix) {
this.Length = length;
this.Edges = edges;
this.Suffix = suffix;
}
public int Length { get; set; }
public Dictionary<char, int> Edges { get; set; }
public int Suffix { get; set; }
}
class Program {
const int EVEN_ROOT = 0;
const int ODD_ROOT = 1;
static List<Node> Eertree(string s) {
List<Node> tree = new List<Node> {
new Node(0, new Dictionary<char, int>(), ODD_ROOT),
new Node(-1, new Dictionary<char, int>(), ODD_ROOT)
};
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.Length; i++) {
char c = s[i];
for (n = suffix; ; n = tree[n].Suffix) {
k = tree[n].Length;
int b = i - k - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
if (tree[n].Edges.ContainsKey(c)) {
suffix = tree[n].Edges[c];
continue;
}
suffix = tree.Count;
tree.Add(new Node(k + 2));
tree[n].Edges[c] = suffix;
if (tree[suffix].Length == 1) {
tree[suffix].Suffix = 0;
continue;
}
while (true) {
n = tree[n].Suffix;
int b = i - tree[n].Length - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
tree[suffix].Suffix = tree[n].Edges[c];
}
return tree;
}
static List<string> SubPalindromes(List<Node> tree) {
List<string> s = new List<string>();
SubPalindromes_children(0, "", tree, s);
foreach (var c in tree[1].Edges.Keys) {
int m = tree[1].Edges[c];
string ct = c.ToString();
s.Add(ct);
SubPalindromes_children(m, ct, tree, s);
}
return s;
}
static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {
foreach (var c in tree[n].Edges.Keys) {
int m = tree[n].Edges[c];
string p1 = c + p + c;
s.Add(p1);
SubPalindromes_children(m, p1, tree, s);
}
}
static void Main(string[] args) {
List<Node> tree = Eertree("eertree");
List<string> result = SubPalindromes(tree);
string listStr = string.Join(", ", result);
Console.WriteLine("[{0}]", listStr);
}
}
}
| package main
import "fmt"
func main() {
tree := eertree([]byte("eertree"))
fmt.Println(subPalindromes(tree))
}
type edges map[byte]int
type node struct {
length int
edges
suffix int
}
const evenRoot = 0
const oddRoot = 1
func eertree(s []byte) []node {
tree := []node{
evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},
oddRoot: {length: -1, suffix: oddRoot, edges: edges{}},
}
suffix := oddRoot
var n, k int
for i, c := range s {
for n = suffix; ; n = tree[n].suffix {
k = tree[n].length
if b := i - k - 1; b >= 0 && s[b] == c {
break
}
}
if e, ok := tree[n].edges[c]; ok {
suffix = e
continue
}
suffix = len(tree)
tree = append(tree, node{length: k + 2, edges: edges{}})
tree[n].edges[c] = suffix
if tree[suffix].length == 1 {
tree[suffix].suffix = 0
continue
}
for {
n = tree[n].suffix
if b := i - tree[n].length - 1; b >= 0 && s[b] == c {
break
}
}
tree[suffix].suffix = tree[n].edges[c]
}
return tree
}
func subPalindromes(tree []node) (s []string) {
var children func(int, string)
children = func(n int, p string) {
for c, n := range tree[n].edges {
c := string(c)
p := c + p + c
s = append(s, p)
children(n, p)
}
}
children(0, "")
for c, n := range tree[1].edges {
c := string(c)
s = append(s, c)
children(n, c)
}
return
}
|
Produce a functionally identical Go code for the snippet given in C#. | using System;
using System.Collections.Generic;
namespace Eertree {
class Node {
public Node(int length) {
this.Length = length;
this.Edges = new Dictionary<char, int>();
}
public Node(int length, Dictionary<char, int> edges, int suffix) {
this.Length = length;
this.Edges = edges;
this.Suffix = suffix;
}
public int Length { get; set; }
public Dictionary<char, int> Edges { get; set; }
public int Suffix { get; set; }
}
class Program {
const int EVEN_ROOT = 0;
const int ODD_ROOT = 1;
static List<Node> Eertree(string s) {
List<Node> tree = new List<Node> {
new Node(0, new Dictionary<char, int>(), ODD_ROOT),
new Node(-1, new Dictionary<char, int>(), ODD_ROOT)
};
int suffix = ODD_ROOT;
int n, k;
for (int i = 0; i < s.Length; i++) {
char c = s[i];
for (n = suffix; ; n = tree[n].Suffix) {
k = tree[n].Length;
int b = i - k - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
if (tree[n].Edges.ContainsKey(c)) {
suffix = tree[n].Edges[c];
continue;
}
suffix = tree.Count;
tree.Add(new Node(k + 2));
tree[n].Edges[c] = suffix;
if (tree[suffix].Length == 1) {
tree[suffix].Suffix = 0;
continue;
}
while (true) {
n = tree[n].Suffix;
int b = i - tree[n].Length - 1;
if (b >= 0 && s[b] == c) {
break;
}
}
tree[suffix].Suffix = tree[n].Edges[c];
}
return tree;
}
static List<string> SubPalindromes(List<Node> tree) {
List<string> s = new List<string>();
SubPalindromes_children(0, "", tree, s);
foreach (var c in tree[1].Edges.Keys) {
int m = tree[1].Edges[c];
string ct = c.ToString();
s.Add(ct);
SubPalindromes_children(m, ct, tree, s);
}
return s;
}
static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {
foreach (var c in tree[n].Edges.Keys) {
int m = tree[n].Edges[c];
string p1 = c + p + c;
s.Add(p1);
SubPalindromes_children(m, p1, tree, s);
}
}
static void Main(string[] args) {
List<Node> tree = Eertree("eertree");
List<string> result = SubPalindromes(tree);
string listStr = string.Join(", ", result);
Console.WriteLine("[{0}]", listStr);
}
}
}
| package main
import "fmt"
func main() {
tree := eertree([]byte("eertree"))
fmt.Println(subPalindromes(tree))
}
type edges map[byte]int
type node struct {
length int
edges
suffix int
}
const evenRoot = 0
const oddRoot = 1
func eertree(s []byte) []node {
tree := []node{
evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},
oddRoot: {length: -1, suffix: oddRoot, edges: edges{}},
}
suffix := oddRoot
var n, k int
for i, c := range s {
for n = suffix; ; n = tree[n].suffix {
k = tree[n].length
if b := i - k - 1; b >= 0 && s[b] == c {
break
}
}
if e, ok := tree[n].edges[c]; ok {
suffix = e
continue
}
suffix = len(tree)
tree = append(tree, node{length: k + 2, edges: edges{}})
tree[n].edges[c] = suffix
if tree[suffix].length == 1 {
tree[suffix].suffix = 0
continue
}
for {
n = tree[n].suffix
if b := i - tree[n].length - 1; b >= 0 && s[b] == c {
break
}
}
tree[suffix].suffix = tree[n].edges[c]
}
return tree
}
func subPalindromes(tree []node) (s []string) {
var children func(int, string)
children = func(n int, p string) {
for c, n := range tree[n].edges {
c := string(c)
p := c + p + c
s = append(s, p)
children(n, p)
}
}
children(0, "")
for c, n := range tree[1].edges {
c := string(c)
s = append(s, c)
children(n, c)
}
return
}
|
Convert the following code from C# to Go, ensuring the logic remains intact. | using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program
{
public static void Main()
{
WriteLine("Long years in the 21st century:");
WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));
}
public static IEnumerable<int> To(this int start, int end) {
for (int i = start; i < end; i++) yield return i;
}
}
| package main
import (
"fmt"
"time"
)
func main() {
centuries := []string{"20th", "21st", "22nd"}
starts := []int{1900, 2000, 2100}
for i := 0; i < len(centuries); i++ {
var longYears []int
fmt.Printf("\nLong years in the %s century:\n", centuries[i])
for j := starts[i]; j < starts[i] + 100; j++ {
t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)
if _, week := t.ISOWeek(); week == 53 {
longYears = append(longYears, j)
}
}
fmt.Println(longYears)
}
}
|
Port the provided C# code into Go while preserving the original functionality. | using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program
{
public static void Main()
{
WriteLine("Long years in the 21st century:");
WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));
}
public static IEnumerable<int> To(this int start, int end) {
for (int i = start; i < end; i++) yield return i;
}
}
| package main
import (
"fmt"
"time"
)
func main() {
centuries := []string{"20th", "21st", "22nd"}
starts := []int{1900, 2000, 2100}
for i := 0; i < len(centuries); i++ {
var longYears []int
fmt.Printf("\nLong years in the %s century:\n", centuries[i])
for j := starts[i]; j < starts[i] + 100; j++ {
t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC)
if _, week := t.ISOWeek(); week == 53 {
longYears = append(longYears, j)
}
}
fmt.Println(longYears)
}
}
|
Write the same algorithm in Go as shown in this C# implementation. | using System;
using System.Collections.Generic;
using System.Linq;
namespace ZumkellerNumbers {
class Program {
static List<int> GetDivisors(int n) {
List<int> divs = new List<int> {
1, n
};
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
int j = n / i;
divs.Add(i);
if (i != j) {
divs.Add(j);
}
}
}
return divs;
}
static bool IsPartSum(List<int> divs, int sum) {
if (sum == 0) {
return true;
}
var le = divs.Count;
if (le == 0) {
return false;
}
var last = divs[le - 1];
List<int> newDivs = new List<int>();
for (int i = 0; i < le - 1; i++) {
newDivs.Add(divs[i]);
}
if (last > sum) {
return IsPartSum(newDivs, sum);
}
return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last);
}
static bool IsZumkeller(int n) {
var divs = GetDivisors(n);
var sum = divs.Sum();
if (sum % 2 == 1) {
return false;
}
if (n % 2 == 1) {
var abundance = sum - 2 * n;
return abundance > 0 && abundance % 2 == 0;
}
return IsPartSum(divs, sum / 2);
}
static void Main() {
Console.WriteLine("The first 220 Zumkeller numbers are:");
int i = 2;
for (int count = 0; count < 220; i++) {
if (IsZumkeller(i)) {
Console.Write("{0,3} ", i);
count++;
if (count % 20 == 0) {
Console.WriteLine();
}
}
}
Console.WriteLine("\nThe first 40 odd Zumkeller numbers are:");
i = 3;
for (int count = 0; count < 40; i += 2) {
if (IsZumkeller(i)) {
Console.Write("{0,5} ", i);
count++;
if (count % 10 == 0) {
Console.WriteLine();
}
}
}
Console.WriteLine("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:");
i = 3;
for (int count = 0; count < 40; i += 2) {
if (i % 10 != 5 && IsZumkeller(i)) {
Console.Write("{0,7} ", i);
count++;
if (count % 8 == 0) {
Console.WriteLine();
}
}
}
}
}
}
| package main
import "fmt"
func getDivisors(n int) []int {
divs := []int{1, n}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs = append(divs, j)
}
}
}
return divs
}
func sum(divs []int) int {
sum := 0
for _, div := range divs {
sum += div
}
return sum
}
func isPartSum(divs []int, sum int) bool {
if sum == 0 {
return true
}
le := len(divs)
if le == 0 {
return false
}
last := divs[le-1]
divs = divs[0 : le-1]
if last > sum {
return isPartSum(divs, sum)
}
return isPartSum(divs, sum) || isPartSum(divs, sum-last)
}
func isZumkeller(n int) bool {
divs := getDivisors(n)
sum := sum(divs)
if sum%2 == 1 {
return false
}
if n%2 == 1 {
abundance := sum - 2*n
return abundance > 0 && abundance%2 == 0
}
return isPartSum(divs, sum/2)
}
func main() {
fmt.Println("The first 220 Zumkeller numbers are:")
for i, count := 2, 0; count < 220; i++ {
if isZumkeller(i) {
fmt.Printf("%3d ", i)
count++
if count%20 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nThe first 40 odd Zumkeller numbers are:")
for i, count := 3, 0; count < 40; i += 2 {
if isZumkeller(i) {
fmt.Printf("%5d ", i)
count++
if count%10 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
for i, count := 3, 0; count < 40; i += 2 {
if (i % 10 != 5) && isZumkeller(i) {
fmt.Printf("%7d ", i)
count++
if count%8 == 0 {
fmt.Println()
}
}
}
fmt.Println()
}
|
Change the following C# code into Go without altering its purpose. | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = new Dictionary<string, object> {
["price"] = 15.25,
["color"] = "red",
["year"] = 1974
};
var mergedData = new Dictionary<string, object>();
foreach (var entry in baseData.Concat(updateData)) {
mergedData[entry.Key] = entry.Value;
}
foreach (var entry in mergedData) {
Console.WriteLine(entry);
}
}
}
| package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
|
Generate an equivalent Go version of this C# code. | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = new Dictionary<string, object> {
["price"] = 15.25,
["color"] = "red",
["year"] = 1974
};
var mergedData = new Dictionary<string, object>();
foreach (var entry in baseData.Concat(updateData)) {
mergedData[entry.Key] = entry.Value;
}
foreach (var entry in mergedData) {
Console.WriteLine(entry);
}
}
}
| package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
|
Produce a language-to-language conversion: from C# to Go, same semantics. | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = new Dictionary<string, object> {
["price"] = 15.25,
["color"] = "red",
["year"] = 1974
};
var mergedData = new Dictionary<string, object>();
foreach (var entry in baseData.Concat(updateData)) {
mergedData[entry.Key] = entry.Value;
}
foreach (var entry in mergedData) {
Console.WriteLine(entry);
}
}
}
| package main
import "fmt"
type assoc map[string]interface{}
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
|
Please provide an equivalent version of this C# code in Go. | using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static BI IntSqRoot(BI v, BI res) {
BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;
dl = d; d = term - res; } return term; }
static string doOne(int b, int digs) {
int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),
bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);
bs += b * BI.Parse('1' + new string('0', digs));
bs >>= 1; bs += 4; string st = bs.ToString();
return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); }
static string divIt(BI a, BI b, int digs) {
int al = a.ToString().Length, bl = b.ToString().Length;
a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);
string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); }
static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
string res = ""; for (int i = 0; i < x.Length; i++) res +=
string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; }
static void Main(string[] args) {
WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc");
int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) {
BI[] lst = new BI[15]; lst[0] = lst[1] = 1;
for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];
n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {
lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;
on = n; n = b * n + nm1; nm1 = on; }
WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb"
.Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); }
n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {
lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;
on = n; n += nm1; nm1 = on; }
WriteLine("\nAu to 256 digits:"); WriteLine(t);
WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); }
}
| package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d, %d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(", %d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
}
|
Write the same code in Go as shown below in C#. | using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static BI IntSqRoot(BI v, BI res) {
BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;
dl = d; d = term - res; } return term; }
static string doOne(int b, int digs) {
int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),
bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);
bs += b * BI.Parse('1' + new string('0', digs));
bs >>= 1; bs += 4; string st = bs.ToString();
return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); }
static string divIt(BI a, BI b, int digs) {
int al = a.ToString().Length, bl = b.ToString().Length;
a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);
string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); }
static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
string res = ""; for (int i = 0; i < x.Length; i++) res +=
string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; }
static void Main(string[] args) {
WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc");
int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) {
BI[] lst = new BI[15]; lst[0] = lst[1] = 1;
for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];
n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {
lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;
on = n; n = b * n + nm1; nm1 = on; }
WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb"
.Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); }
n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {
lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;
on = n; n += nm1; nm1 = on; }
WriteLine("\nAu to 256 digits:"); WriteLine(t);
WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); }
}
| package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d, %d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(", %d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
}
|
Change the following C# code into Go without altering its purpose. | int a=0,b=1/a;
| package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)}
|
Ensure the translated Go code behaves exactly like the original C# snippet. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MarkovChainTextGenerator {
class Program {
static string Join(string a, string b) {
return a + " " + b;
}
static string Markov(string filePath, int keySize, int outputSize) {
if (keySize < 1) throw new ArgumentException("Key size can't be less than 1");
string body;
using (StreamReader sr = new StreamReader(filePath)) {
body = sr.ReadToEnd();
}
var words = body.Split();
if (outputSize < keySize || words.Length < outputSize) {
throw new ArgumentException("Output size is out of range");
}
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
for (int i = 0; i < words.Length - keySize; i++) {
var key = words.Skip(i).Take(keySize).Aggregate(Join);
string value;
if (i + keySize < words.Length) {
value = words[i + keySize];
} else {
value = "";
}
if (dict.ContainsKey(key)) {
dict[key].Add(value);
} else {
dict.Add(key, new List<string>() { value });
}
}
Random rand = new Random();
List<string> output = new List<string>();
int n = 0;
int rn = rand.Next(dict.Count);
string prefix = dict.Keys.Skip(rn).Take(1).Single();
output.AddRange(prefix.Split());
while (true) {
var suffix = dict[prefix];
if (suffix.Count == 1) {
if (suffix[0] == "") {
return output.Aggregate(Join);
}
output.Add(suffix[0]);
} else {
rn = rand.Next(suffix.Count);
output.Add(suffix[rn]);
}
if (output.Count >= outputSize) {
return output.Take(outputSize).Aggregate(Join);
}
n++;
prefix = output.Skip(n).Take(keySize).Aggregate(Join);
}
}
static void Main(string[] args) {
Console.WriteLine(Markov("alice_oz.txt", 3, 200));
}
}
}
| package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"math/rand"
"os"
"strings"
"time"
"unicode"
"unicode/utf8"
)
func main() {
log.SetFlags(0)
log.SetPrefix("markov: ")
input := flag.String("in", "alice_oz.txt", "input file")
n := flag.Int("n", 2, "number of words to use as prefix")
runs := flag.Int("runs", 1, "number of runs to generate")
wordsPerRun := flag.Int("words", 300, "number of words per run")
startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix")
stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)")
flag.Parse()
rand.Seed(time.Now().UnixNano())
m, err := NewMarkovFromFile(*input, *n)
if err != nil {
log.Fatal(err)
}
for i := 0; i < *runs; i++ {
err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)
if err != nil {
log.Fatal(err)
}
fmt.Println()
}
}
type Markov struct {
n int
capitalized int
suffix map[string][]string
}
func NewMarkovFromFile(filename string, n int) (*Markov, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return NewMarkov(f, n)
}
func NewMarkov(r io.Reader, n int) (*Markov, error) {
m := &Markov{
n: n,
suffix: make(map[string][]string),
}
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
window := make([]string, 0, n)
for sc.Scan() {
word := sc.Text()
if len(window) > 0 {
prefix := strings.Join(window, " ")
m.suffix[prefix] = append(m.suffix[prefix], word)
if isCapitalized(prefix) {
m.capitalized++
}
}
window = appendMax(n, window, word)
}
if err := sc.Err(); err != nil {
return nil, err
}
return m, nil
}
func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {
bw := bufio.NewWriter(w)
var i int
if startCapital {
i = rand.Intn(m.capitalized)
} else {
i = rand.Intn(len(m.suffix))
}
var prefix string
for prefix = range m.suffix {
if startCapital && !isCapitalized(prefix) {
continue
}
if i == 0 {
break
}
i--
}
bw.WriteString(prefix)
prefixWords := strings.Fields(prefix)
n -= len(prefixWords)
for {
suffixChoices := m.suffix[prefix]
if len(suffixChoices) == 0 {
break
}
i = rand.Intn(len(suffixChoices))
suffix := suffixChoices[i]
bw.WriteByte(' ')
if _, err := bw.WriteString(suffix); err != nil {
break
}
n--
if n < 0 && (!stopSentence || isSentenceEnd(suffix)) {
break
}
prefixWords = appendMax(m.n, prefixWords, suffix)
prefix = strings.Join(prefixWords, " ")
}
return bw.Flush()
}
func isCapitalized(s string) bool {
r, _ := utf8.DecodeRuneInString(s)
return unicode.IsUpper(r)
}
func isSentenceEnd(s string) bool {
r, _ := utf8.DecodeLastRuneInString(s)
return r == '.' || r == '?' || r == '!'
}
func appendMax(max int, slice []string, value string) []string {
if len(slice)+1 > max {
n := copy(slice, slice[1:])
slice = slice[:n]
}
return append(slice, value)
}
|
Convert the following code from C# to Go, ensuring the logic remains intact. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MarkovChainTextGenerator {
class Program {
static string Join(string a, string b) {
return a + " " + b;
}
static string Markov(string filePath, int keySize, int outputSize) {
if (keySize < 1) throw new ArgumentException("Key size can't be less than 1");
string body;
using (StreamReader sr = new StreamReader(filePath)) {
body = sr.ReadToEnd();
}
var words = body.Split();
if (outputSize < keySize || words.Length < outputSize) {
throw new ArgumentException("Output size is out of range");
}
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
for (int i = 0; i < words.Length - keySize; i++) {
var key = words.Skip(i).Take(keySize).Aggregate(Join);
string value;
if (i + keySize < words.Length) {
value = words[i + keySize];
} else {
value = "";
}
if (dict.ContainsKey(key)) {
dict[key].Add(value);
} else {
dict.Add(key, new List<string>() { value });
}
}
Random rand = new Random();
List<string> output = new List<string>();
int n = 0;
int rn = rand.Next(dict.Count);
string prefix = dict.Keys.Skip(rn).Take(1).Single();
output.AddRange(prefix.Split());
while (true) {
var suffix = dict[prefix];
if (suffix.Count == 1) {
if (suffix[0] == "") {
return output.Aggregate(Join);
}
output.Add(suffix[0]);
} else {
rn = rand.Next(suffix.Count);
output.Add(suffix[rn]);
}
if (output.Count >= outputSize) {
return output.Take(outputSize).Aggregate(Join);
}
n++;
prefix = output.Skip(n).Take(keySize).Aggregate(Join);
}
}
static void Main(string[] args) {
Console.WriteLine(Markov("alice_oz.txt", 3, 200));
}
}
}
| package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"math/rand"
"os"
"strings"
"time"
"unicode"
"unicode/utf8"
)
func main() {
log.SetFlags(0)
log.SetPrefix("markov: ")
input := flag.String("in", "alice_oz.txt", "input file")
n := flag.Int("n", 2, "number of words to use as prefix")
runs := flag.Int("runs", 1, "number of runs to generate")
wordsPerRun := flag.Int("words", 300, "number of words per run")
startOnCapital := flag.Bool("capital", false, "start output with a capitalized prefix")
stopAtSentence := flag.Bool("sentence", false, "end output at a sentence ending punctuation mark (after n words)")
flag.Parse()
rand.Seed(time.Now().UnixNano())
m, err := NewMarkovFromFile(*input, *n)
if err != nil {
log.Fatal(err)
}
for i := 0; i < *runs; i++ {
err = m.Output(os.Stdout, *wordsPerRun, *startOnCapital, *stopAtSentence)
if err != nil {
log.Fatal(err)
}
fmt.Println()
}
}
type Markov struct {
n int
capitalized int
suffix map[string][]string
}
func NewMarkovFromFile(filename string, n int) (*Markov, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return NewMarkov(f, n)
}
func NewMarkov(r io.Reader, n int) (*Markov, error) {
m := &Markov{
n: n,
suffix: make(map[string][]string),
}
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
window := make([]string, 0, n)
for sc.Scan() {
word := sc.Text()
if len(window) > 0 {
prefix := strings.Join(window, " ")
m.suffix[prefix] = append(m.suffix[prefix], word)
if isCapitalized(prefix) {
m.capitalized++
}
}
window = appendMax(n, window, word)
}
if err := sc.Err(); err != nil {
return nil, err
}
return m, nil
}
func (m *Markov) Output(w io.Writer, n int, startCapital, stopSentence bool) error {
bw := bufio.NewWriter(w)
var i int
if startCapital {
i = rand.Intn(m.capitalized)
} else {
i = rand.Intn(len(m.suffix))
}
var prefix string
for prefix = range m.suffix {
if startCapital && !isCapitalized(prefix) {
continue
}
if i == 0 {
break
}
i--
}
bw.WriteString(prefix)
prefixWords := strings.Fields(prefix)
n -= len(prefixWords)
for {
suffixChoices := m.suffix[prefix]
if len(suffixChoices) == 0 {
break
}
i = rand.Intn(len(suffixChoices))
suffix := suffixChoices[i]
bw.WriteByte(' ')
if _, err := bw.WriteString(suffix); err != nil {
break
}
n--
if n < 0 && (!stopSentence || isSentenceEnd(suffix)) {
break
}
prefixWords = appendMax(m.n, prefixWords, suffix)
prefix = strings.Join(prefixWords, " ")
}
return bw.Flush()
}
func isCapitalized(s string) bool {
r, _ := utf8.DecodeRuneInString(s)
return unicode.IsUpper(r)
}
func isSentenceEnd(s string) bool {
r, _ := utf8.DecodeLastRuneInString(s)
return r == '.' || r == '?' || r == '!'
}
func appendMax(max int, slice []string, value string) []string {
if len(slice)+1 > max {
n := copy(slice, slice[1:])
slice = slice[:n]
}
return append(slice, value)
}
|
Generate an equivalent Go version of this C# code. | using static System.Linq.Enumerable;
using static System.String;
using static System.Console;
using System.Collections.Generic;
using System;
using EdgeList = System.Collections.Generic.List<(int node, double weight)>;
public static class Dijkstra
{
public static void Main() {
Graph graph = new Graph(6);
Func<char, int> id = c => c - 'a';
Func<int , char> name = i => (char)(i + 'a');
foreach (var (start, end, cost) in new [] {
('a', 'b', 7),
('a', 'c', 9),
('a', 'f', 14),
('b', 'c', 10),
('b', 'd', 15),
('c', 'd', 11),
('c', 'f', 2),
('d', 'e', 6),
('e', 'f', 9),
}) {
graph.AddEdge(id(start), id(end), cost);
}
var path = graph.FindPath(id('a'));
for (int d = id('b'); d <= id('f'); d++) {
WriteLine(Join(" -> ", Path(id('a'), d).Select(p => $"{name(p.node)}({p.distance})").Reverse()));
}
IEnumerable<(double distance, int node)> Path(int start, int destination) {
yield return (path[destination].distance, destination);
for (int i = destination; i != start; i = path[i].prev) {
yield return (path[path[i].prev].distance, path[i].prev);
}
}
}
}
sealed class Graph
{
private readonly List<EdgeList> adjacency;
public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();
public int Count => adjacency.Count;
public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);
public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;
public bool AddEdge(int s, int e, double weight) {
if (HasEdge(s, e)) return false;
adjacency[s].Add((e, weight));
return true;
}
public (double distance, int prev)[] FindPath(int start) {
var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();
info[start].distance = 0;
var visited = new System.Collections.BitArray(adjacency.Count);
var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));
heap.Push((start, 0));
while (heap.Count > 0) {
var current = heap.Pop();
if (visited[current.node]) continue;
var edges = adjacency[current.node];
for (int n = 0; n < edges.Count; n++) {
int v = edges[n].node;
if (visited[v]) continue;
double alt = info[current.node].distance + edges[n].weight;
if (alt < info[v].distance) {
info[v] = (alt, current.node);
heap.Push((v, alt));
}
}
visited[current.node] = true;
}
return info;
}
}
sealed class Heap<T>
{
private readonly IComparer<T> comparer;
private readonly List<T> list = new List<T> { default };
public Heap() : this(default(IComparer<T>)) { }
public Heap(IComparer<T> comparer) {
this.comparer = comparer ?? Comparer<T>.Default;
}
public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }
public int Count => list.Count - 1;
public void Push(T element) {
list.Add(element);
SiftUp(list.Count - 1);
}
public T Pop() {
T result = list[1];
list[1] = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
SiftDown(1);
return result;
}
private static int Parent(int i) => i / 2;
private static int Left(int i) => i * 2;
private static int Right(int i) => i * 2 + 1;
private void SiftUp(int i) {
while (i > 1) {
int parent = Parent(i);
if (comparer.Compare(list[i], list[parent]) > 0) return;
(list[parent], list[i]) = (list[i], list[parent]);
i = parent;
}
}
private void SiftDown(int i) {
for (int left = Left(i); left < list.Count; left = Left(i)) {
int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;
int right = Right(i);
if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;
if (smallest == i) return;
(list[i], list[smallest]) = (list[smallest], list[i]);
i = smallest;
}
}
}
| package main
import (
"container/heap"
"fmt"
)
type PriorityQueue struct {
items []Vertex
m map[Vertex]int
pr map[Vertex]int
}
func (pq *PriorityQueue) Len() int { return len(pq.items) }
func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }
func (pq *PriorityQueue) Swap(i, j int) {
pq.items[i], pq.items[j] = pq.items[j], pq.items[i]
pq.m[pq.items[i]] = i
pq.m[pq.items[j]] = j
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(pq.items)
item := x.(Vertex)
pq.m[item] = n
pq.items = append(pq.items, item)
}
func (pq *PriorityQueue) Pop() interface{} {
old := pq.items
n := len(old)
item := old[n-1]
pq.m[item] = -1
pq.items = old[0 : n-1]
return item
}
func (pq *PriorityQueue) update(item Vertex, priority int) {
pq.pr[item] = priority
heap.Fix(pq, pq.m[item])
}
func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {
heap.Push(pq, item)
pq.update(item, priority)
}
const (
Infinity = int(^uint(0) >> 1)
Uninitialized = -1
)
func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {
vs := g.Vertices()
dist = make(map[Vertex]int, len(vs))
prev = make(map[Vertex]Vertex, len(vs))
sid := source
dist[sid] = 0
q := &PriorityQueue{
items: make([]Vertex, 0, len(vs)),
m: make(map[Vertex]int, len(vs)),
pr: make(map[Vertex]int, len(vs)),
}
for _, v := range vs {
if v != sid {
dist[v] = Infinity
}
prev[v] = Uninitialized
q.addWithPriority(v, dist[v])
}
for len(q.items) != 0 {
u := heap.Pop(q).(Vertex)
for _, v := range g.Neighbors(u) {
alt := dist[u] + g.Weight(u, v)
if alt < dist[v] {
dist[v] = alt
prev[v] = u
q.update(v, alt)
}
}
}
return dist, prev
}
type Graph interface {
Vertices() []Vertex
Neighbors(v Vertex) []Vertex
Weight(u, v Vertex) int
}
type Vertex int
type sg struct {
ids map[string]Vertex
names map[Vertex]string
edges map[Vertex]map[Vertex]int
}
func newsg(ids map[string]Vertex) sg {
g := sg{ids: ids}
g.names = make(map[Vertex]string, len(ids))
for k, v := range ids {
g.names[v] = k
}
g.edges = make(map[Vertex]map[Vertex]int)
return g
}
func (g sg) edge(u, v string, w int) {
if _, ok := g.edges[g.ids[u]]; !ok {
g.edges[g.ids[u]] = make(map[Vertex]int)
}
g.edges[g.ids[u]][g.ids[v]] = w
}
func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {
s = g.names[v]
for prev[v] >= 0 {
v = prev[v]
s = g.names[v] + s
}
return s
}
func (g sg) Vertices() []Vertex {
vs := make([]Vertex, 0, len(g.ids))
for _, v := range g.ids {
vs = append(vs, v)
}
return vs
}
func (g sg) Neighbors(u Vertex) []Vertex {
vs := make([]Vertex, 0, len(g.edges[u]))
for v := range g.edges[u] {
vs = append(vs, v)
}
return vs
}
func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }
func main() {
g := newsg(map[string]Vertex{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
})
g.edge("a", "b", 7)
g.edge("a", "c", 9)
g.edge("a", "f", 14)
g.edge("b", "c", 10)
g.edge("b", "d", 15)
g.edge("c", "d", 11)
g.edge("c", "f", 2)
g.edge("d", "e", 6)
g.edge("e", "f", 9)
dist, prev := Dijkstra(g, g.ids["a"])
fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev))
fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev))
}
|
Can you help me rewrite this code in Go instead of C#, keeping it the same logically? | using System;
using System.Text;
namespace GeometricAlgebra {
struct Vector {
private readonly double[] dims;
public Vector(double[] da) {
dims = da;
}
public static Vector operator -(Vector v) {
return v * -1.0;
}
public static Vector operator +(Vector lhs, Vector rhs) {
var result = new double[32];
Array.Copy(lhs.dims, 0, result, 0, lhs.Length);
for (int i = 0; i < result.Length; i++) {
result[i] = lhs[i] + rhs[i];
}
return new Vector(result);
}
public static Vector operator *(Vector lhs, Vector rhs) {
var result = new double[32];
for (int i = 0; i < lhs.Length; i++) {
if (lhs[i] != 0.0) {
for (int j = 0; j < lhs.Length; j++) {
if (rhs[j] != 0.0) {
var s = ReorderingSign(i, j) * lhs[i] * rhs[j];
var k = i ^ j;
result[k] += s;
}
}
}
}
return new Vector(result);
}
public static Vector operator *(Vector v, double scale) {
var result = (double[])v.dims.Clone();
for (int i = 0; i < result.Length; i++) {
result[i] *= scale;
}
return new Vector(result);
}
public double this[int key] {
get {
return dims[key];
}
set {
dims[key] = value;
}
}
public int Length {
get {
return dims.Length;
}
}
public Vector Dot(Vector rhs) {
return (this * rhs + rhs * this) * 0.5;
}
private static int BitCount(int i) {
i -= ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
i = (i + (i >> 4)) & 0x0F0F0F0F;
i += (i >> 8);
i += (i >> 16);
return i & 0x0000003F;
}
private static double ReorderingSign(int i, int j) {
int k = i >> 1;
int sum = 0;
while (k != 0) {
sum += BitCount(k & j);
k >>= 1;
}
return ((sum & 1) == 0) ? 1.0 : -1.0;
}
public override string ToString() {
var it = dims.GetEnumerator();
StringBuilder sb = new StringBuilder("[");
if (it.MoveNext()) {
sb.Append(it.Current);
}
while (it.MoveNext()) {
sb.Append(", ");
sb.Append(it.Current);
}
sb.Append(']');
return sb.ToString();
}
}
class Program {
static double[] DoubleArray(uint size) {
double[] result = new double[size];
for (int i = 0; i < size; i++) {
result[i] = 0.0;
}
return result;
}
static Vector E(int n) {
if (n > 4) {
throw new ArgumentException("n must be less than 5");
}
var result = new Vector(DoubleArray(32));
result[1 << n] = 1.0;
return result;
}
static readonly Random r = new Random();
static Vector RandomVector() {
var result = new Vector(DoubleArray(32));
for (int i = 0; i < 5; i++) {
var singleton = new double[] { r.NextDouble() };
result += new Vector(singleton) * E(i);
}
return result;
}
static Vector RandomMultiVector() {
var result = new Vector(DoubleArray(32));
for (int i = 0; i < result.Length; i++) {
result[i] = r.NextDouble();
}
return result;
}
static void Main() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i < j) {
if (E(i).Dot(E(j))[0] != 0.0) {
Console.WriteLine("Unexpected non-null sclar product.");
return;
}
} else if (i == j) {
if ((E(i).Dot(E(j)))[0] == 0.0) {
Console.WriteLine("Unexpected null sclar product.");
}
}
}
}
var a = RandomMultiVector();
var b = RandomMultiVector();
var c = RandomMultiVector();
var x = RandomVector();
Console.WriteLine((a * b) * c);
Console.WriteLine(a * (b * c));
Console.WriteLine();
Console.WriteLine(a * (b + c));
Console.WriteLine(a * b + a * c);
Console.WriteLine();
Console.WriteLine((a + b) * c);
Console.WriteLine(a * c + b * c);
Console.WriteLine();
Console.WriteLine(x * x);
}
}
}
| package main
import (
"fmt"
"math/rand"
"time"
)
type vector []float64
func e(n uint) vector {
if n > 4 {
panic("n must be less than 5")
}
result := make(vector, 32)
result[1<<n] = 1.0
return result
}
func cdot(a, b vector) vector {
return mul(vector{0.5}, add(mul(a, b), mul(b, a)))
}
func neg(x vector) vector {
return mul(vector{-1}, x)
}
func bitCount(i int) int {
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
i = (i + (i >> 4)) & 0x0F0F0F0F
i = i + (i >> 8)
i = i + (i >> 16)
return i & 0x0000003F
}
func reorderingSign(i, j int) float64 {
i >>= 1
sum := 0
for i != 0 {
sum += bitCount(i & j)
i >>= 1
}
cond := (sum & 1) == 0
if cond {
return 1.0
}
return -1.0
}
func add(a, b vector) vector {
result := make(vector, 32)
copy(result, a)
for i, _ := range b {
result[i] += b[i]
}
return result
}
func mul(a, b vector) vector {
result := make(vector, 32)
for i, _ := range a {
if a[i] != 0 {
for j, _ := range b {
if b[j] != 0 {
s := reorderingSign(i, j) * a[i] * b[j]
k := i ^ j
result[k] += s
}
}
}
}
return result
}
func randomVector() vector {
result := make(vector, 32)
for i := uint(0); i < 5; i++ {
result = add(result, mul(vector{rand.Float64()}, e(i)))
}
return result
}
func randomMultiVector() vector {
result := make(vector, 32)
for i := 0; i < 32; i++ {
result[i] = rand.Float64()
}
return result
}
func main() {
rand.Seed(time.Now().UnixNano())
for i := uint(0); i < 5; i++ {
for j := uint(0); j < 5; j++ {
if i < j {
if cdot(e(i), e(j))[0] != 0 {
fmt.Println("Unexpected non-null scalar product.")
return
}
} else if i == j {
if cdot(e(i), e(j))[0] == 0 {
fmt.Println("Unexpected null scalar product.")
}
}
}
}
a := randomMultiVector()
b := randomMultiVector()
c := randomMultiVector()
x := randomVector()
fmt.Println(mul(mul(a, b), c))
fmt.Println(mul(a, mul(b, c)))
fmt.Println(mul(a, add(b, c)))
fmt.Println(add(mul(a, b), mul(a, c)))
fmt.Println(mul(add(a, b), c))
fmt.Println(add(mul(a, c), mul(b, c)))
fmt.Println(mul(x, x))
}
|
Convert this C# snippet to Go and keep its semantics consistent. | using System;
using System.Collections.Generic;
namespace SuffixTree {
class Node {
public string sub;
public List<int> ch = new List<int>();
public Node() {
sub = "";
}
public Node(string sub, params int[] children) {
this.sub = sub;
ch.AddRange(children);
}
}
class SuffixTree {
readonly List<Node> nodes = new List<Node>();
public SuffixTree(string str) {
nodes.Add(new Node());
for (int i = 0; i < str.Length; i++) {
AddSuffix(str.Substring(i));
}
}
public void Visualize() {
if (nodes.Count == 0) {
Console.WriteLine("<empty>");
return;
}
void f(int n, string pre) {
var children = nodes[n].ch;
if (children.Count == 0) {
Console.WriteLine("- {0}", nodes[n].sub);
return;
}
Console.WriteLine("+ {0}", nodes[n].sub);
var it = children.GetEnumerator();
if (it.MoveNext()) {
do {
var cit = it;
if (!cit.MoveNext()) break;
Console.Write("{0}+-", pre);
f(it.Current, pre + "| ");
} while (it.MoveNext());
}
Console.Write("{0}+-", pre);
f(children[children.Count-1], pre+" ");
}
f(0, "");
}
private void AddSuffix(string suf) {
int n = 0;
int i = 0;
while (i < suf.Length) {
char b = suf[i];
int x2 = 0;
int n2;
while (true) {
var children = nodes[n].ch;
if (x2 == children.Count) {
n2 = nodes.Count;
nodes.Add(new Node(suf.Substring(i)));
nodes[n].ch.Add(n2);
return;
}
n2 = children[x2];
if (nodes[n2].sub[0] == b) {
break;
}
x2++;
}
var sub2 = nodes[n2].sub;
int j = 0;
while (j < sub2.Length) {
if (suf[i + j] != sub2[j]) {
var n3 = n2;
n2 = nodes.Count;
nodes.Add(new Node(sub2.Substring(0, j), n3));
nodes[n3].sub = sub2.Substring(j);
nodes[n].ch[x2] = n2;
break;
}
j++;
}
i += j;
n = n2;
}
}
}
class Program {
static void Main() {
new SuffixTree("banana$").Visualize();
}
}
}
| package main
import "fmt"
func main() {
vis(buildTree("banana$"))
}
type tree []node
type node struct {
sub string
ch []int
}
func buildTree(s string) tree {
t := tree{node{}}
for i := range s {
t = t.addSuffix(s[i:])
}
return t
}
func (t tree) addSuffix(suf string) tree {
n := 0
for i := 0; i < len(suf); {
b := suf[i]
ch := t[n].ch
var x2, n2 int
for ; ; x2++ {
if x2 == len(ch) {
n2 = len(t)
t = append(t, node{sub: suf[i:]})
t[n].ch = append(t[n].ch, n2)
return t
}
n2 = ch[x2]
if t[n2].sub[0] == b {
break
}
}
sub2 := t[n2].sub
j := 0
for ; j < len(sub2); j++ {
if suf[i+j] != sub2[j] {
n3 := n2
n2 = len(t)
t = append(t, node{sub2[:j], []int{n3}})
t[n3].sub = sub2[j:]
t[n].ch[x2] = n2
break
}
}
i += j
n = n2
}
return t
}
func vis(t tree) {
if len(t) == 0 {
fmt.Println("<empty>")
return
}
var f func(int, string)
f = func(n int, pre string) {
children := t[n].ch
if len(children) == 0 {
fmt.Println("╴", t[n].sub)
return
}
fmt.Println("┐", t[n].sub)
last := len(children) - 1
for _, ch := range children[:last] {
fmt.Print(pre, "├─")
f(ch, pre+"│ ")
}
fmt.Print(pre, "└─")
f(children[last], pre+" ")
}
f(0, "")
}
|
Transform the following C# implementation into Go, maintaining the same output and logic. | using System;
using System.Collections.Generic;
namespace SuffixTree {
class Node {
public string sub;
public List<int> ch = new List<int>();
public Node() {
sub = "";
}
public Node(string sub, params int[] children) {
this.sub = sub;
ch.AddRange(children);
}
}
class SuffixTree {
readonly List<Node> nodes = new List<Node>();
public SuffixTree(string str) {
nodes.Add(new Node());
for (int i = 0; i < str.Length; i++) {
AddSuffix(str.Substring(i));
}
}
public void Visualize() {
if (nodes.Count == 0) {
Console.WriteLine("<empty>");
return;
}
void f(int n, string pre) {
var children = nodes[n].ch;
if (children.Count == 0) {
Console.WriteLine("- {0}", nodes[n].sub);
return;
}
Console.WriteLine("+ {0}", nodes[n].sub);
var it = children.GetEnumerator();
if (it.MoveNext()) {
do {
var cit = it;
if (!cit.MoveNext()) break;
Console.Write("{0}+-", pre);
f(it.Current, pre + "| ");
} while (it.MoveNext());
}
Console.Write("{0}+-", pre);
f(children[children.Count-1], pre+" ");
}
f(0, "");
}
private void AddSuffix(string suf) {
int n = 0;
int i = 0;
while (i < suf.Length) {
char b = suf[i];
int x2 = 0;
int n2;
while (true) {
var children = nodes[n].ch;
if (x2 == children.Count) {
n2 = nodes.Count;
nodes.Add(new Node(suf.Substring(i)));
nodes[n].ch.Add(n2);
return;
}
n2 = children[x2];
if (nodes[n2].sub[0] == b) {
break;
}
x2++;
}
var sub2 = nodes[n2].sub;
int j = 0;
while (j < sub2.Length) {
if (suf[i + j] != sub2[j]) {
var n3 = n2;
n2 = nodes.Count;
nodes.Add(new Node(sub2.Substring(0, j), n3));
nodes[n3].sub = sub2.Substring(j);
nodes[n].ch[x2] = n2;
break;
}
j++;
}
i += j;
n = n2;
}
}
}
class Program {
static void Main() {
new SuffixTree("banana$").Visualize();
}
}
}
| package main
import "fmt"
func main() {
vis(buildTree("banana$"))
}
type tree []node
type node struct {
sub string
ch []int
}
func buildTree(s string) tree {
t := tree{node{}}
for i := range s {
t = t.addSuffix(s[i:])
}
return t
}
func (t tree) addSuffix(suf string) tree {
n := 0
for i := 0; i < len(suf); {
b := suf[i]
ch := t[n].ch
var x2, n2 int
for ; ; x2++ {
if x2 == len(ch) {
n2 = len(t)
t = append(t, node{sub: suf[i:]})
t[n].ch = append(t[n].ch, n2)
return t
}
n2 = ch[x2]
if t[n2].sub[0] == b {
break
}
}
sub2 := t[n2].sub
j := 0
for ; j < len(sub2); j++ {
if suf[i+j] != sub2[j] {
n3 := n2
n2 = len(t)
t = append(t, node{sub2[:j], []int{n3}})
t[n3].sub = sub2[j:]
t[n].ch[x2] = n2
break
}
}
i += j
n = n2
}
return t
}
func vis(t tree) {
if len(t) == 0 {
fmt.Println("<empty>")
return
}
var f func(int, string)
f = func(n int, pre string) {
children := t[n].ch
if len(children) == 0 {
fmt.Println("╴", t[n].sub)
return
}
fmt.Println("┐", t[n].sub)
last := len(children) - 1
for _, ch := range children[:last] {
fmt.Print(pre, "├─")
f(ch, pre+"│ ")
}
fmt.Print(pre, "└─")
f(children[last], pre+" ")
}
f(0, "")
}
|
Write the same algorithm in Go as shown in this C# implementation. | using System;
using System.Collections.Generic;
namespace AssocArrays
{
class Program
{
static void Main(string[] args)
{
Dictionary<string,int> assocArray = new Dictionary<string,int>();
assocArray["Hello"] = 1;
assocArray.Add("World", 2);
assocArray["!"] = 3;
foreach (KeyValuePair<string, int> kvp in assocArray)
{
Console.WriteLine(kvp.Key + " : " + kvp.Value);
}
foreach (string key in assocArray.Keys)
{
Console.WriteLine(key);
}
foreach (int val in assocArray.Values)
{
Console.WriteLine(val.ToString());
}
}
}
}
| myMap := map[string]int {
"hello": 13,
"world": 31,
"!" : 71 }
for key, value := range myMap {
fmt.Printf("key = %s, value = %d\n", key, value)
}
for key := range myMap {
fmt.Printf("key = %s\n", key)
}
for _, value := range myMap {
fmt.Printf("value = %d\n", value)
}
|
Can you help me rewrite this code in Go instead of C#, keeping it the same logically? | using System;
using System.Globalization;
struct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 10;
public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);
public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE);
static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE;
readonly int _value;
public int Value => this._value == 0 ? MIN_VALUE : this._value;
public LimitedInt(int value)
{
if (!IsValidValue(value))
throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}.");
this._value = value;
}
#region IComparable
public int CompareTo(object obj)
{
if (obj is LimitedInt l) return this.Value.CompareTo(l);
throw new ArgumentException("Object must be of type " + nameof(LimitedInt), nameof(obj));
}
#endregion
#region IComparable<LimitedInt>
public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value);
#endregion
#region IConvertible
public TypeCode GetTypeCode() => this.Value.GetTypeCode();
bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider);
byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider);
char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider);
DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider);
decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider);
double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider);
short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider);
int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider);
long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider);
sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider);
float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider);
string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider);
object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider);
ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider);
uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider);
ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider);
#endregion
#region IEquatable<LimitedInt>
public bool Equals(LimitedInt other) => this == other;
#endregion
#region IFormattable
public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider);
#endregion
#region operators
public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value;
public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value;
public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value;
public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value;
public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value;
public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value;
public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1);
public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1);
public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value);
public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value);
public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value);
public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value);
public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value);
public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value);
public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value);
public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value);
public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value;
public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right);
public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right);
public static implicit operator int(LimitedInt value) => value.Value;
public static explicit operator LimitedInt(int value)
{
if (!IsValidValue(value)) throw new OverflowException();
return new LimitedInt(value);
}
#endregion
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
=> this.Value.TryFormat(destination, out charsWritten, format, provider);
public override int GetHashCode() => this.Value.GetHashCode();
public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l);
public override string ToString() => this.Value.ToString();
#region static methods
public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result);
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result);
public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider);
public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider);
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result);
public static int Parse(string s) => int.Parse(s);
public static int Parse(string s, NumberStyles style) => int.Parse(s, style);
public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider);
public static bool TryParse(string s, ref int result) => int.TryParse(s, out result);
#endregion
}
| package main
import "fmt"
type TinyInt int
func NewTinyInt(i int) TinyInt {
if i < 1 {
i = 1
} else if i > 10 {
i = 10
}
return TinyInt(i)
}
func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) + int(t2))
}
func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) - int(t2))
}
func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) * int(t2))
}
func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) / int(t2))
}
func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) % int(t2))
}
func (t TinyInt) Inc() TinyInt {
return t.Add(TinyInt(1))
}
func (t TinyInt) Dec() TinyInt {
return t.Sub(TinyInt(1))
}
func main() {
t1 := NewTinyInt(6)
t2 := NewTinyInt(3)
fmt.Println("t1 =", t1)
fmt.Println("t2 =", t2)
fmt.Println("t1 + t2 =", t1.Add(t2))
fmt.Println("t1 - t2 =", t1.Sub(t2))
fmt.Println("t1 * t2 =", t1.Mul(t2))
fmt.Println("t1 / t2 =", t1.Div(t2))
fmt.Println("t1 % t2 =", t1.Rem(t2))
fmt.Println("t1 + 1 =", t1.Inc())
fmt.Println("t1 - 1 =", t1.Dec())
}
|
Ensure the translated Go code behaves exactly like the original C# snippet. | using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};
private (int dx, int dy)[] moves;
public static void Main()
{
var knightSolver = new Solver(knightMoves);
Print(knightSolver.Solve(true,
".000....",
".0.00...",
".0000000",
"000..0.0",
"0.0..000",
"1000000.",
"..00.0..",
"...000.."));
Print(knightSolver.Solve(true,
".....0.0.....",
".....0.0.....",
"....00000....",
".....000.....",
"..0..0.0..0..",
"00000...00000",
"..00.....00..",
"00000...00000",
"..0..0.0..0..",
".....000.....",
"....00000....",
".....0.0.....",
".....0.0....."
));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
}
| package main
import "fmt"
var moves = [][2]int{
{-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},
}
var board1 = " xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
var board2 = ".....s.x....." +
".....x.x....." +
"....xxxxx...." +
".....xxx....." +
"..x..x.x..x.." +
"xxxxx...xxxxx" +
"..xx.....xx.." +
"xxxxx...xxxxx" +
"..x..x.x..x.." +
".....xxx....." +
"....xxxxx...." +
".....x.x....." +
".....x.x....."
func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {
if idx > cnt {
return true
}
for i := 0; i < len(moves); i++ {
x := sx + moves[i][0]
y := sy + moves[i][1]
if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {
pz[x][y] = idx
if solve(pz, sz, x, y, idx+1, cnt) {
return true
}
pz[x][y] = 0
}
}
return false
}
func findSolution(b string, sz int) {
pz := make([][]int, sz)
for i := 0; i < sz; i++ {
pz[i] = make([]int, sz)
for j := 0; j < sz; j++ {
pz[i][j] = -1
}
}
var x, y, idx, cnt int
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
switch b[idx] {
case 'x':
pz[i][j] = 0
cnt++
case 's':
pz[i][j] = 1
cnt++
x, y = i, j
}
idx++
}
}
if solve(pz, sz, x, y, 2, cnt) {
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
if pz[i][j] != -1 {
fmt.Printf("%02d ", pz[i][j])
} else {
fmt.Print("-- ")
}
}
fmt.Println()
}
} else {
fmt.Println("Cannot solve this puzzle!")
}
}
func main() {
findSolution(board1, 8)
fmt.Println()
findSolution(board2, 13)
}
|
Generate an equivalent Go version of this C# code. | using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};
private (int dx, int dy)[] moves;
public static void Main()
{
var knightSolver = new Solver(knightMoves);
Print(knightSolver.Solve(true,
".000....",
".0.00...",
".0000000",
"000..0.0",
"0.0..000",
"1000000.",
"..00.0..",
"...000.."));
Print(knightSolver.Solve(true,
".....0.0.....",
".....0.0.....",
"....00000....",
".....000.....",
"..0..0.0..0..",
"00000...00000",
"..00.....00..",
"00000...00000",
"..0..0.0..0..",
".....000.....",
"....00000....",
".....0.0.....",
".....0.0....."
));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
}
| package main
import "fmt"
var moves = [][2]int{
{-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1},
}
var board1 = " xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
var board2 = ".....s.x....." +
".....x.x....." +
"....xxxxx...." +
".....xxx....." +
"..x..x.x..x.." +
"xxxxx...xxxxx" +
"..xx.....xx.." +
"xxxxx...xxxxx" +
"..x..x.x..x.." +
".....xxx....." +
"....xxxxx...." +
".....x.x....." +
".....x.x....."
func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool {
if idx > cnt {
return true
}
for i := 0; i < len(moves); i++ {
x := sx + moves[i][0]
y := sy + moves[i][1]
if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 {
pz[x][y] = idx
if solve(pz, sz, x, y, idx+1, cnt) {
return true
}
pz[x][y] = 0
}
}
return false
}
func findSolution(b string, sz int) {
pz := make([][]int, sz)
for i := 0; i < sz; i++ {
pz[i] = make([]int, sz)
for j := 0; j < sz; j++ {
pz[i][j] = -1
}
}
var x, y, idx, cnt int
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
switch b[idx] {
case 'x':
pz[i][j] = 0
cnt++
case 's':
pz[i][j] = 1
cnt++
x, y = i, j
}
idx++
}
}
if solve(pz, sz, x, y, 2, cnt) {
for j := 0; j < sz; j++ {
for i := 0; i < sz; i++ {
if pz[i][j] != -1 {
fmt.Printf("%02d ", pz[i][j])
} else {
fmt.Print("-- ")
}
}
fmt.Println()
}
} else {
fmt.Println("Cannot solve this puzzle!")
}
}
func main() {
findSolution(board1, 8)
fmt.Println()
findSolution(board2, 13)
}
|
Write the same code in Go as shown below in C#. | using System;
using System.Collections.Generic;
using System.Linq;
namespace HashJoin
{
public class AgeName
{
public AgeName(byte age, string name)
{
Age = age;
Name = name;
}
public byte Age { get; private set; }
public string Name { get; private set; }
}
public class NameNemesis
{
public NameNemesis(string name, string nemesis)
{
Name = name;
Nemesis = nemesis;
}
public string Name { get; private set; }
public string Nemesis { get; private set; }
}
public class DataContext
{
public DataContext()
{
AgeName = new List<AgeName>();
NameNemesis = new List<NameNemesis>();
}
public List<AgeName> AgeName { get; set; }
public List<NameNemesis> NameNemesis { get; set; }
}
public class AgeNameNemesis
{
public AgeNameNemesis(byte age, string name, string nemesis)
{
Age = age;
Name = name;
Nemesis = nemesis;
}
public byte Age { get; private set; }
public string Name { get; private set; }
public string Nemesis { get; private set; }
}
class Program
{
public static void Main()
{
var data = GetData();
var result = ExecuteHashJoin(data);
WriteResultToConsole(result);
}
private static void WriteResultToConsole(List<AgeNameNemesis> result)
{
result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}",
ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis));
}
private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data)
{
return (data.AgeName.Join(data.NameNemesis,
ageName => ageName.Name, nameNemesis => nameNemesis.Name,
(ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis)))
.ToList();
}
private static DataContext GetData()
{
var context = new DataContext();
context.AgeName.AddRange(new [] {
new AgeName(27, "Jonah"),
new AgeName(18, "Alan"),
new AgeName(28, "Glory"),
new AgeName(18, "Popeye"),
new AgeName(28, "Alan")
});
context.NameNemesis.AddRange(new[]
{
new NameNemesis("Jonah", "Whales"),
new NameNemesis("Jonah", "Spiders"),
new NameNemesis("Alan", "Ghosts"),
new NameNemesis("Alan", "Zombies"),
new NameNemesis("Glory", "Buffy")
});
return context;
}
}
}
| 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", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
}
h := map[string][]int{}
for i, r := range tableA {
h[r.key] = append(h[r.key], i)
}
for _, x := range tableB {
for _, a := range h[x.key] {
fmt.Println(tableA[a], x)
}
}
}
|
Produce a language-to-language conversion: from C# to Go, same semantics. | using System; using static System.Console; using System.Collections;
using System.Linq; using System.Collections.Generic;
class Program { static void Main(string[] args) {
int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();
var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();
lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)
res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))
Write("{0,4} {1}", item, ++c % 20 == 0 ? "\n" : "");
Write("\n\nCounted {0} odd squarefree semiprimes under {1}", c, lmt); } }
class PG { public static IEnumerable<int> Primes(int lim) {
var flags = new bool[lim + 1]; int j = 3;
for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
if (!flags[j]) { yield return j;
for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }
for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
| package main
import (
"fmt"
"rcu"
"sort"
)
func main() {
primes := rcu.Primes(333)
var oss []int
for i := 1; i < len(primes)-1; i++ {
for j := i + 1; j < len(primes); j++ {
n := primes[i] * primes[j]
if n >= 1000 {
break
}
oss = append(oss, n)
}
}
sort.Ints(oss)
fmt.Println("Odd squarefree semiprimes under 1,000:")
for i, n := range oss {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\n%d such numbers found.\n", len(oss))
}
|
Generate an equivalent Go version of this C# code. | using System; using static System.Console; using System.Collections;
using System.Linq; using System.Collections.Generic;
class Program { static void Main(string[] args) {
int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();
var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First();
lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++)
res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt))
Write("{0,4} {1}", item, ++c % 20 == 0 ? "\n" : "");
Write("\n\nCounted {0} odd squarefree semiprimes under {1}", c, lmt); } }
class PG { public static IEnumerable<int> Primes(int lim) {
var flags = new bool[lim + 1]; int j = 3;
for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
if (!flags[j]) { yield return j;
for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }
for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
| package main
import (
"fmt"
"rcu"
"sort"
)
func main() {
primes := rcu.Primes(333)
var oss []int
for i := 1; i < len(primes)-1; i++ {
for j := i + 1; j < len(primes); j++ {
n := primes[i] * primes[j]
if n >= 1000 {
break
}
oss = append(oss, n)
}
}
sort.Ints(oss)
fmt.Println("Odd squarefree semiprimes under 1,000:")
for i, n := range oss {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n\n%d such numbers found.\n", len(oss))
}
|
Port the following code from C# to Go with equivalent syntax and logic. | using System;
using System.Collections.Generic;
using System.Linq;
namespace SyntheticDivision
{
class Program
{
static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)
{
List<int> output = dividend.ToList();
int normalizer = divisor[0];
for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)
{
output[i] /= normalizer;
int coef = output[i];
if (coef != 0)
{
for (int j = 1; j < divisor.Count(); j++)
output[i + j] += -divisor[j] * coef;
}
}
int separator = output.Count() - (divisor.Count() - 1);
return (
output.GetRange(0, separator),
output.GetRange(separator, output.Count() - separator)
);
}
static void Main(string[] args)
{
List<int> N = new List<int>{ 1, -12, 0, -42 };
List<int> D = new List<int> { 1, -3 };
var (quotient, remainder) = extendedSyntheticDivision(N, D);
Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" ,
string.Join(",", N),
string.Join(",", D),
string.Join(",", quotient),
string.Join(",", remainder)
);
}
}
}
| package main
import (
"fmt"
"math/big"
)
func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {
out := make([]*big.Rat, len(dividend))
for i, c := range dividend {
out[i] = new(big.Rat).Set(c)
}
for i := 0; i < len(dividend)-(len(divisor)-1); i++ {
out[i].Quo(out[i], divisor[0])
if coef := out[i]; coef.Sign() != 0 {
var a big.Rat
for j := 1; j < len(divisor); j++ {
out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))
}
}
}
separator := len(out) - (len(divisor) - 1)
return out[:separator], out[separator:]
}
func main() {
N := []*big.Rat{
big.NewRat(1, 1),
big.NewRat(-12, 1),
big.NewRat(0, 1),
big.NewRat(-42, 1)}
D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}
Q, R := div(N, D)
fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C# version. | using System;
using System.Collections.Generic;
using System.Linq;
namespace SyntheticDivision
{
class Program
{
static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)
{
List<int> output = dividend.ToList();
int normalizer = divisor[0];
for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)
{
output[i] /= normalizer;
int coef = output[i];
if (coef != 0)
{
for (int j = 1; j < divisor.Count(); j++)
output[i + j] += -divisor[j] * coef;
}
}
int separator = output.Count() - (divisor.Count() - 1);
return (
output.GetRange(0, separator),
output.GetRange(separator, output.Count() - separator)
);
}
static void Main(string[] args)
{
List<int> N = new List<int>{ 1, -12, 0, -42 };
List<int> D = new List<int> { 1, -3 };
var (quotient, remainder) = extendedSyntheticDivision(N, D);
Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" ,
string.Join(",", N),
string.Join(",", D),
string.Join(",", quotient),
string.Join(",", remainder)
);
}
}
}
| package main
import (
"fmt"
"math/big"
)
func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) {
out := make([]*big.Rat, len(dividend))
for i, c := range dividend {
out[i] = new(big.Rat).Set(c)
}
for i := 0; i < len(dividend)-(len(divisor)-1); i++ {
out[i].Quo(out[i], divisor[0])
if coef := out[i]; coef.Sign() != 0 {
var a big.Rat
for j := 1; j < len(divisor); j++ {
out[i+j].Add(out[i+j], a.Mul(a.Neg(divisor[j]), coef))
}
}
}
separator := len(out) - (len(divisor) - 1)
return out[:separator], out[separator:]
}
func main() {
N := []*big.Rat{
big.NewRat(1, 1),
big.NewRat(-12, 1),
big.NewRat(0, 1),
big.NewRat(-42, 1)}
D := []*big.Rat{big.NewRat(1, 1), big.NewRat(-3, 1)}
Q, R := div(N, D)
fmt.Printf("%v / %v = %v remainder %v\n", N, D, Q, R)
}
|
Ensure the translated Go code behaves exactly like the original C# snippet. | using System;
using System.Dynamic;
class Example : DynamicObject
{
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = null;
Console.WriteLine("This is {0}.", binder.Name);
return true;
}
}
class Program
{
static void Main(string[] args)
{
dynamic ex = new Example();
ex.Foo();
ex.Bar();
}
}
| 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:", n)
return 0
}
func main() {
var e example
fmt.Println(e.CallMethod("Foo"))
fmt.Println(e.CallMethod("Bar"))
}
|
Translate the given C# code snippet into Go without altering its behavior. | using System;
using System.Collections.Generic;
using System.Linq;
namespace LatinSquares {
using matrix = List<List<int>>;
class Program {
static void Swap<T>(ref T a, ref T b) {
var t = a;
a = b;
b = t;
}
static matrix DList(int n, int start) {
start--;
var a = Enumerable.Range(0, n).ToArray();
a[start] = a[0];
a[0] = start;
Array.Sort(a, 1, a.Length - 1);
var first = a[1];
matrix r = new matrix();
void recurse(int last) {
if (last == first) {
for (int j = 1; j < a.Length; j++) {
var v = a[j];
if (j == v) {
return;
}
}
var b = a.Select(v => v + 1).ToArray();
r.Add(b.ToList());
return;
}
for (int i = last; i >= 1; i--) {
Swap(ref a[i], ref a[last]);
recurse(last - 1);
Swap(ref a[i], ref a[last]);
}
}
recurse(n - 1);
return r;
}
static ulong ReducedLatinSquares(int n, bool echo) {
if (n <= 0) {
if (echo) {
Console.WriteLine("[]\n");
}
return 0;
} else if (n == 1) {
if (echo) {
Console.WriteLine("[1]\n");
}
return 1;
}
matrix rlatin = new matrix();
for (int i = 0; i < n; i++) {
rlatin.Add(new List<int>());
for (int j = 0; j < n; j++) {
rlatin[i].Add(0);
}
}
for (int j = 0; j < n; j++) {
rlatin[0][j] = j + 1;
}
ulong count = 0;
void recurse(int i) {
var rows = DList(n, i);
for (int r = 0; r < rows.Count; r++) {
rlatin[i - 1] = rows[r];
for (int k = 0; k < i - 1; k++) {
for (int j = 1; j < n; j++) {
if (rlatin[k][j] == rlatin[i - 1][j]) {
if (r < rows.Count - 1) {
goto outer;
}
if (i > 2) {
return;
}
}
}
}
if (i < n) {
recurse(i + 1);
} else {
count++;
if (echo) {
PrintSquare(rlatin, n);
}
}
outer: { }
}
}
recurse(2);
return count;
}
static void PrintSquare(matrix latin, int n) {
foreach (var row in latin) {
var it = row.GetEnumerator();
Console.Write("[");
if (it.MoveNext()) {
Console.Write(it.Current);
}
while (it.MoveNext()) {
Console.Write(", {0}", it.Current);
}
Console.WriteLine("]");
}
Console.WriteLine();
}
static ulong Factorial(ulong n) {
if (n <= 0) {
return 1;
}
ulong prod = 1;
for (ulong i = 2; i < n + 1; i++) {
prod *= i;
}
return prod;
}
static void Main() {
Console.WriteLine("The four reduced latin squares of order 4 are:\n");
ReducedLatinSquares(4, true);
Console.WriteLine("The size of the set of reduced latin squares for the following orders");
Console.WriteLine("and hence the total number of latin squares of these orders are:\n");
for (int n = 1; n < 7; n++) {
ulong nu = (ulong)n;
var size = ReducedLatinSquares(n, false);
var f = Factorial(nu - 1);
f *= f * nu * size;
Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f);
}
}
}
}
| package main
import (
"fmt"
"sort"
)
type matrix [][]int
func dList(n, start int) (r matrix) {
start--
a := make([]int, n)
for i := range a {
a[i] = i
}
a[0], a[start] = start, a[0]
sort.Ints(a[1:])
first := a[1]
var recurse func(last int)
recurse = func(last int) {
if last == first {
for j, v := range a[1:] {
if j+1 == v {
return
}
}
b := make([]int, n)
copy(b, a)
for i := range b {
b[i]++
}
r = append(r, b)
return
}
for i := last; i >= 1; i-- {
a[i], a[last] = a[last], a[i]
recurse(last - 1)
a[i], a[last] = a[last], a[i]
}
}
recurse(n - 1)
return
}
func reducedLatinSquare(n int, echo bool) uint64 {
if n <= 0 {
if echo {
fmt.Println("[]\n")
}
return 0
} else if n == 1 {
if echo {
fmt.Println("[1]\n")
}
return 1
}
rlatin := make(matrix, n)
for i := 0; i < n; i++ {
rlatin[i] = make([]int, n)
}
for j := 0; j < n; j++ {
rlatin[0][j] = j + 1
}
count := uint64(0)
var recurse func(i int)
recurse = func(i int) {
rows := dList(n, i)
outer:
for r := 0; r < len(rows); r++ {
copy(rlatin[i-1], rows[r])
for k := 0; k < i-1; k++ {
for j := 1; j < n; j++ {
if rlatin[k][j] == rlatin[i-1][j] {
if r < len(rows)-1 {
continue outer
} else if i > 2 {
return
}
}
}
}
if i < n {
recurse(i + 1)
} else {
count++
if echo {
printSquare(rlatin, n)
}
}
}
return
}
recurse(2)
return count
}
func printSquare(latin matrix, n int) {
for i := 0; i < n; i++ {
fmt.Println(latin[i])
}
fmt.Println()
}
func factorial(n uint64) uint64 {
if n == 0 {
return 1
}
prod := uint64(1)
for i := uint64(2); i <= n; i++ {
prod *= i
}
return prod
}
func main() {
fmt.Println("The four reduced latin squares of order 4 are:\n")
reducedLatinSquare(4, true)
fmt.Println("The size of the set of reduced latin squares for the following orders")
fmt.Println("and hence the total number of latin squares of these orders are:\n")
for n := uint64(1); n <= 6; n++ {
size := reducedLatinSquare(int(n), false)
f := factorial(n - 1)
f *= f * n * size
fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f)
}
}
|
Change the programming language of this snippet from C# to Go without modifying what it does. | class Segment
{
public Segment(PointF p1, PointF p2)
{
P1 = p1;
P2 = p2;
}
public readonly PointF P1;
public readonly PointF P2;
public float Length()
{
return (float)Math.Sqrt(LengthSquared());
}
public float LengthSquared()
{
return (P1.X - P2.X) * (P1.X - P2.X)
+ (P1.Y - P2.Y) * (P1.Y - P2.Y);
}
}
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
type xy struct {
x, y float64
}
const n = 1000
const scale = 100.
func d(p1, p2 xy) float64 {
return math.Hypot(p2.x-p1.x, p2.y-p1.y)
}
func main() {
rand.Seed(time.Now().Unix())
points := make([]xy, n)
for i := range points {
points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}
}
p1, p2 := closestPair(points)
fmt.Println(p1, p2)
fmt.Println("distance:", d(p1, p2))
}
func closestPair(points []xy) (p1, p2 xy) {
if len(points) < 2 {
panic("at least two points expected")
}
min := 2 * scale
for i, q1 := range points[:len(points)-1] {
for _, q2 := range points[i+1:] {
if dq := d(q1, q2); dq < min {
p1, p2 = q1, q2
min = dq
}
}
}
return
}
|
Generate a Go translation of this C# snippet without changing its computational steps. | int i = 5;
int* p = &i;
| package main
import (
"fmt"
"unsafe"
)
func main() {
myVar := 3.14
myPointer := &myVar
fmt.Println("Address:", myPointer, &myVar)
fmt.Printf("Address: %p %p\n", myPointer, &myVar)
var addr64 int64
var addr32 int32
ptr := unsafe.Pointer(myPointer)
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
addr64 = int64(uintptr(ptr))
fmt.Printf("Pointer stored in int64: %#016x\n", addr64)
}
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {
addr32 = int32(uintptr(ptr))
fmt.Printf("Pointer stored in int32: %#08x\n", addr32)
}
addr := uintptr(ptr)
fmt.Printf("Pointer stored in uintptr: %#08x\n", addr)
fmt.Println("value as float:", myVar)
i := (*int32)(unsafe.Pointer(&myVar))
fmt.Printf("value as int32: %#08x\n", *i)
}
|
Translate this program into Go but keep the logic exactly as in C#. | class Animal
{
}
class Dog : Animal
{
}
class Lab : Dog
{
}
class Collie : Dog
{
}
class Cat : Animal
{
}
| package main
type animal struct {
alive bool
}
type dog struct {
animal
obedienceTrained bool
}
type cat struct {
animal
litterBoxTrained bool
}
type lab struct {
dog
color string
}
type collie struct {
dog
catchesFrisbee bool
}
func main() {
var pet lab
pet.alive = true
pet.obedienceTrained = false
pet.color = "yellow"
}
|
Write the same code in Go as shown below in C#. | System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo";
|
var x map[string]int
x = make(map[string]int)
x = make(map[string]int, 42)
x["foo"] = 3
y1 := x["bar"]
y2, ok := x["bar"]
delete(x, "foo")
x = map[string]int{
"foo": 2, "bar": 42, "baz": -1,
}
|
Translate the given C# code snippet into Go without altering its behavior. |
public MainWindow()
{
InitializeComponent();
RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);
imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);
DrawHue(100);
}
void DrawHue(int saturation)
{
var bmp = (WriteableBitmap)imgMain.Source;
int centerX = (int)bmp.Width / 2;
int centerY = (int)bmp.Height / 2;
int radius = Math.Min(centerX, centerY);
int radius2 = radius - 40;
bmp.Lock();
unsafe{
var buf = bmp.BackBuffer;
IntPtr pixLineStart;
for(int y=0; y < bmp.Height; y++){
pixLineStart = buf + bmp.BackBufferStride * y;
double dy = (y - centerY);
for(int x=0; x < bmp.Width; x++){
double dx = (x - centerX);
double dist = Math.Sqrt(dx * dx + dy * dy);
if (radius2 <= dist && dist <= radius) {
double theta = Math.Atan2(dy, dx);
double hue = (theta + Math.PI) / (2.0 * Math.PI);
*((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);
}
}
}
}
bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));
bmp.Unlock();
}
static int HSB_to_RGB(int h, int s, int v)
{
var rgb = new int[3];
var baseColor = (h + 60) % 360 / 120;
var shift = (h + 60) % 360 - (120 * baseColor + 60 );
var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;
rgb[baseColor] = 255;
rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);
for (var i = 0; i < 3; i++)
rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));
for (var i = 0; i < 3; i++)
rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);
return RGB2int(rgb[0], rgb[1], rgb[2]);
}
public static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;
| package main
import (
"github.com/fogleman/gg"
"math"
)
const tau = 2 * math.Pi
func hsb2rgb(hue, sat, bri float64) (r, g, b int) {
u := int(bri*255 + 0.5)
if sat == 0 {
r, g, b = u, u, u
} else {
h := (hue - math.Floor(hue)) * 6
f := h - math.Floor(h)
p := int(bri*(1-sat)*255 + 0.5)
q := int(bri*(1-sat*f)*255 + 0.5)
t := int(bri*(1-sat*(1-f))*255 + 0.5)
switch int(h) {
case 0:
r, g, b = u, t, p
case 1:
r, g, b = q, u, p
case 2:
r, g, b = p, u, t
case 3:
r, g, b = p, q, u
case 4:
r, g, b = t, p, u
case 5:
r, g, b = u, p, q
}
}
return
}
func colorWheel(dc *gg.Context) {
width, height := dc.Width(), dc.Height()
centerX, centerY := width/2, height/2
radius := centerX
if centerY < radius {
radius = centerY
}
for y := 0; y < height; y++ {
dy := float64(y - centerY)
for x := 0; x < width; x++ {
dx := float64(x - centerX)
dist := math.Sqrt(dx*dx + dy*dy)
if dist <= float64(radius) {
theta := math.Atan2(dy, dx)
hue := (theta + math.Pi) / tau
r, g, b := hsb2rgb(hue, 1, 1)
dc.SetRGB255(r, g, b)
dc.SetPixel(x, y)
}
}
}
}
func main() {
const width, height = 480, 480
dc := gg.NewContext(width, height)
dc.SetRGB(1, 1, 1)
dc.Clear()
colorWheel(dc)
dc.SavePNG("color_wheel.png")
}
|
Maintain the same structure and functionality when rewriting this code in Go. | using System;
class Point
{
protected int x, y;
public Point() : this(0) {}
public Point(int x) : this(x,0) {}
public Point(int x, int y) { this.x = x; this.y = y; }
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
public virtual void print() { System.Console.WriteLine("Point"); }
}
public class Circle : Point
{
private int r;
public Circle(Point p) : this(p,0) { }
public Circle(Point p, int r) : base(p) { this.r = r; }
public Circle() : this(0) { }
public Circle(int x) : this(x,0) { }
public Circle(int x, int y) : this(x,y,0) { }
public Circle(int x, int y, int r) : base(x,y) { this.r = r; }
public int R { get { return r; } set { r = value; } }
public override void print() { System.Console.WriteLine("Circle"); }
public static void main(String args[])
{
Point p = new Point();
Point c = new Circle();
p.print();
c.print();
}
}
| package main
import "fmt"
type point struct {
x, y float64
}
type circle struct {
x, y, r float64
}
type printer interface {
print()
}
func (p *point) print() {
fmt.Println(p.x, p.y)
}
func (c *circle) print() {
fmt.Println(c.x, c.y, c.r)
}
func main() {
var i printer
i = newPoint(3, 4)
i.print()
i = newCircle(5, 12, 13)
i.print()
}
func (p *point) getX() float64 { return p.x }
func (p *point) getY() float64 { return p.y }
func (p *point) setX(v float64) { p.x = v }
func (p *point) setY(v float64) { p.y = v }
func (c *circle) getX() float64 { return c.x }
func (c *circle) getY() float64 { return c.y }
func (c *circle) getR() float64 { return c.r }
func (c *circle) setX(v float64) { c.x = v }
func (c *circle) setY(v float64) { c.y = v }
func (c *circle) setR(v float64) { c.r = v }
func (p *point) clone() *point { r := *p; return &r }
func (c *circle) clone() *circle { r := *c; return &r }
func (p *point) set(q *point) { *p = *q }
func (c *circle) set(d *circle) { *c = *d }
func newPoint(x, y float64) *point {
return &point{x, y}
}
func newCircle(x, y, r float64) *circle {
return &circle{x, y, r}
}
|
Produce a language-to-language conversion: from C# to Go, same semantics. | using System;
class Point
{
protected int x, y;
public Point() : this(0) {}
public Point(int x) : this(x,0) {}
public Point(int x, int y) { this.x = x; this.y = y; }
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
public virtual void print() { System.Console.WriteLine("Point"); }
}
public class Circle : Point
{
private int r;
public Circle(Point p) : this(p,0) { }
public Circle(Point p, int r) : base(p) { this.r = r; }
public Circle() : this(0) { }
public Circle(int x) : this(x,0) { }
public Circle(int x, int y) : this(x,y,0) { }
public Circle(int x, int y, int r) : base(x,y) { this.r = r; }
public int R { get { return r; } set { r = value; } }
public override void print() { System.Console.WriteLine("Circle"); }
public static void main(String args[])
{
Point p = new Point();
Point c = new Circle();
p.print();
c.print();
}
}
| package main
import "fmt"
type point struct {
x, y float64
}
type circle struct {
x, y, r float64
}
type printer interface {
print()
}
func (p *point) print() {
fmt.Println(p.x, p.y)
}
func (c *circle) print() {
fmt.Println(c.x, c.y, c.r)
}
func main() {
var i printer
i = newPoint(3, 4)
i.print()
i = newCircle(5, 12, 13)
i.print()
}
func (p *point) getX() float64 { return p.x }
func (p *point) getY() float64 { return p.y }
func (p *point) setX(v float64) { p.x = v }
func (p *point) setY(v float64) { p.y = v }
func (c *circle) getX() float64 { return c.x }
func (c *circle) getY() float64 { return c.y }
func (c *circle) getR() float64 { return c.r }
func (c *circle) setX(v float64) { c.x = v }
func (c *circle) setY(v float64) { c.y = v }
func (c *circle) setR(v float64) { c.r = v }
func (p *point) clone() *point { r := *p; return &r }
func (c *circle) clone() *circle { r := *c; return &r }
func (p *point) set(q *point) { *p = *q }
func (c *circle) set(d *circle) { *c = *d }
func newPoint(x, y float64) *point {
return &point{x, y}
}
func newCircle(x, y, r float64) *circle {
return &circle{x, y, r}
}
|
Generate a Go translation of this C# snippet without changing its computational steps. | using System;
using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static void Main(string[] args) {
BI i, j, k, d; i = 2; int n = -1; int n0 = -1;
j = (BI)Floor(Sqrt((double)i)); k = j; d = j;
DateTime st = DateTime.Now;
if (args.Length > 0) int.TryParse(args[0], out n);
if (n > 0) n0 = n; else n = 1;
do {
Write(d); i = (i - k * d) * 100; k = 20 * j;
for (d = 1; d <= 10; d++)
if ((k + d) * d > i) { d -= 1; break; }
j = j * 10 + d; k += d; if (n0 > 0) n--;
} while (n > 0);
if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); }
}
| 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 *= 100
count--
}
i := big.NewInt(int64(n))
j := new(big.Int).Sqrt(i)
count += len(j.String())
k := new(big.Int).Set(j)
d := new(big.Int).Set(j)
t := new(big.Int)
digits := 0
var sb strings.Builder
for digits < limit {
sb.WriteString(d.String())
t.Mul(k, d)
i.Sub(i, t)
i.Mul(i, hundred)
k.Mul(j, twenty)
d.Set(one)
for d.Cmp(ten) <= 0 {
t.Add(k, d)
t.Mul(t, d)
if t.Cmp(i) > 0 {
d.Sub(d, one)
break
}
d.Add(d, one)
}
j.Mul(j, ten)
j.Add(j, d)
k.Add(k, d)
digits = digits + 1
}
root := strings.TrimRight(sb.String(), "0")
if len(root) == 0 {
root = "0"
}
if count > 0 {
root = root[0:count] + "." + root[count:]
} else if count == 0 {
root = "0." + root
} else {
root = "0." + strings.Repeat("0", -count) + root
}
root = strings.TrimSuffix(root, ".")
fmt.Println(root)
}
func main() {
numbers := []float64{2, 0.2, 10.89, 625, 0.0001}
digits := []int{500, 80, 8, 8, 8}
for i, n := range numbers {
fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n)
sqrt(n, digits[i])
fmt.Println()
}
}
|
Produce a functionally identical Go code for the snippet given in C#. | using System;
using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static void Main(string[] args) {
BI i, j, k, d; i = 2; int n = -1; int n0 = -1;
j = (BI)Floor(Sqrt((double)i)); k = j; d = j;
DateTime st = DateTime.Now;
if (args.Length > 0) int.TryParse(args[0], out n);
if (n > 0) n0 = n; else n = 1;
do {
Write(d); i = (i - k * d) * 100; k = 20 * j;
for (d = 1; d <= 10; d++)
if ((k + d) * d > i) { d -= 1; break; }
j = j * 10 + d; k += d; if (n0 > 0) n--;
} while (n > 0);
if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); }
}
| 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 *= 100
count--
}
i := big.NewInt(int64(n))
j := new(big.Int).Sqrt(i)
count += len(j.String())
k := new(big.Int).Set(j)
d := new(big.Int).Set(j)
t := new(big.Int)
digits := 0
var sb strings.Builder
for digits < limit {
sb.WriteString(d.String())
t.Mul(k, d)
i.Sub(i, t)
i.Mul(i, hundred)
k.Mul(j, twenty)
d.Set(one)
for d.Cmp(ten) <= 0 {
t.Add(k, d)
t.Mul(t, d)
if t.Cmp(i) > 0 {
d.Sub(d, one)
break
}
d.Add(d, one)
}
j.Mul(j, ten)
j.Add(j, d)
k.Add(k, d)
digits = digits + 1
}
root := strings.TrimRight(sb.String(), "0")
if len(root) == 0 {
root = "0"
}
if count > 0 {
root = root[0:count] + "." + root[count:]
} else if count == 0 {
root = "0." + root
} else {
root = "0." + strings.Repeat("0", -count) + root
}
root = strings.TrimSuffix(root, ".")
fmt.Println(root)
}
func main() {
numbers := []float64{2, 0.2, 10.89, 625, 0.0001}
digits := []int{500, 80, 8, 8, 8}
for i, n := range numbers {
fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n)
sqrt(n, digits[i])
fmt.Println()
}
}
|
Transform the following C# implementation into Go, maintaining the same output and logic. | using System;
class Program {
static void fun(char sp) {
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) {
var s = x.ToString();
for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0) goto nxt;
if (x % 3 == 0) continue;
for (int i = 1; i * i < x; ) {
if (x % (i += 4) == 0) goto nxt;
if (x % (i += 2) == 0) goto nxt;
}
sw.Stop(); Console.WriteLine("{0}..7: {1,10:n0} {2} μs", sp, x, sw.Elapsed.TotalMilliseconds * 1000); break;
nxt: ;
}
}
static void Main(string[] args) {
fun('1');
fun('0');
}
}
| package main
import (
"fmt"
"rcu"
)
func factorial(n int) int {
fact := 1
for i := 2; i <= n; i++ {
fact *= i
}
return fact
}
func permutations(input []int) [][]int {
perms := [][]int{input}
a := make([]int, len(input))
copy(a, input)
var n = len(input) - 1
for c := 1; c < factorial(n+1); c++ {
i := n - 1
j := n
for a[i] > a[i+1] {
i--
}
for a[j] < a[i] {
j--
}
a[i], a[j] = a[j], a[i]
j = n
i += 1
for i < j {
a[i], a[j] = a[j], a[i]
i++
j--
}
b := make([]int, len(input))
copy(b, a)
perms = append(perms, b)
}
return perms
}
func main() {
outer:
for _, start := range []int{1, 0} {
fmt.Printf("The largest pandigital decimal prime which uses all the digits %d..n once is:\n", start)
for _, n := range []int{7, 4} {
m := n + 1 - start
list := make([]int, m)
for i := 0; i < m; i++ {
list[i] = i + start
}
perms := permutations(list)
for i := len(perms) - 1; i >= 0; i-- {
le := len(perms[i])
if perms[i][le-1]%2 == 0 || perms[i][le-1] == 5 || (start == 0 && perms[i][0] == 0) {
continue
}
p := 0
pow := 1
for j := le - 1; j >= 0; j-- {
p += perms[i][j] * pow
pow *= 10
}
if rcu.IsPrime(p) {
fmt.Println(rcu.Commatize(p) + "\n")
continue outer
}
}
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C# version. | using System;
class Program {
static void fun(char sp) {
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int x = sp == '1' ? 7654321 : 76543201; ; x -= 18) {
var s = x.ToString();
for (var ch = sp; ch < '8'; ch++) if (s.IndexOf(ch) < 0) goto nxt;
if (x % 3 == 0) continue;
for (int i = 1; i * i < x; ) {
if (x % (i += 4) == 0) goto nxt;
if (x % (i += 2) == 0) goto nxt;
}
sw.Stop(); Console.WriteLine("{0}..7: {1,10:n0} {2} μs", sp, x, sw.Elapsed.TotalMilliseconds * 1000); break;
nxt: ;
}
}
static void Main(string[] args) {
fun('1');
fun('0');
}
}
| package main
import (
"fmt"
"rcu"
)
func factorial(n int) int {
fact := 1
for i := 2; i <= n; i++ {
fact *= i
}
return fact
}
func permutations(input []int) [][]int {
perms := [][]int{input}
a := make([]int, len(input))
copy(a, input)
var n = len(input) - 1
for c := 1; c < factorial(n+1); c++ {
i := n - 1
j := n
for a[i] > a[i+1] {
i--
}
for a[j] < a[i] {
j--
}
a[i], a[j] = a[j], a[i]
j = n
i += 1
for i < j {
a[i], a[j] = a[j], a[i]
i++
j--
}
b := make([]int, len(input))
copy(b, a)
perms = append(perms, b)
}
return perms
}
func main() {
outer:
for _, start := range []int{1, 0} {
fmt.Printf("The largest pandigital decimal prime which uses all the digits %d..n once is:\n", start)
for _, n := range []int{7, 4} {
m := n + 1 - start
list := make([]int, m)
for i := 0; i < m; i++ {
list[i] = i + start
}
perms := permutations(list)
for i := len(perms) - 1; i >= 0; i-- {
le := len(perms[i])
if perms[i][le-1]%2 == 0 || perms[i][le-1] == 5 || (start == 0 && perms[i][0] == 0) {
continue
}
p := 0
pow := 1
for j := le - 1; j >= 0; j-- {
p += perms[i][j] * pow
pow *= 10
}
if rcu.IsPrime(p) {
fmt.Println(rcu.Commatize(p) + "\n")
continue outer
}
}
}
}
}
|
Change the programming language of this snippet from C# to Go without modifying what it does. | using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;
class Program {
static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static string from10(int b) { string res = ""; int re; while (b > 0) {
b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }
static int to10(string s) { int res = 0; foreach (char i in s)
res = res * ba + chars.IndexOf(i); return res; }
static bool nd(string s) { if (s.Length < 2) return true;
char l = s[0]; for (int i = 1; i < s.Length; i++)
if (chars.IndexOf(l) > chars.IndexOf(s[i]))
return false; else l = s[i] ; return true; }
static void Main(string[] args) { int c, lim = 1000; string s;
foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {
ba = b; c = 0; foreach (var a in PG.Primes(lim))
if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : "");
WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } }
class PG { public static IEnumerable<int> Primes(int lim) {
var flags = new bool[lim + 1]; int j; yield return 2;
for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;
for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
if (!flags[j]) { yield return j;
for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }
for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
| package main
import (
"fmt"
"rcu"
)
func nonDescending(p int) bool {
var digits []int
for p > 0 {
digits = append(digits, p%10)
p = p / 10
}
for i := 0; i < len(digits)-1; i++ {
if digits[i+1] > digits[i] {
return false
}
}
return true
}
func main() {
primes := rcu.Primes(999)
var nonDesc []int
for _, p := range primes {
if nonDescending(p) {
nonDesc = append(nonDesc, p)
}
}
fmt.Println("Primes below 1,000 with digits in non-decreasing order:")
for i, n := range nonDesc {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n%d such primes found.\n", len(nonDesc))
}
|
Convert this C# snippet to Go and keep its semantics consistent. | using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;
class Program {
static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static string from10(int b) { string res = ""; int re; while (b > 0) {
b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; }
static int to10(string s) { int res = 0; foreach (char i in s)
res = res * ba + chars.IndexOf(i); return res; }
static bool nd(string s) { if (s.Length < 2) return true;
char l = s[0]; for (int i = 1; i < s.Length; i++)
if (chars.IndexOf(l) > chars.IndexOf(s[i]))
return false; else l = s[i] ; return true; }
static void Main(string[] args) { int c, lim = 1000; string s;
foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) {
ba = b; c = 0; foreach (var a in PG.Primes(lim))
if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : "");
WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } }
class PG { public static IEnumerable<int> Primes(int lim) {
var flags = new bool[lim + 1]; int j; yield return 2;
for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3;
for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
if (!flags[j]) { yield return j;
for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; }
for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
| package main
import (
"fmt"
"rcu"
)
func nonDescending(p int) bool {
var digits []int
for p > 0 {
digits = append(digits, p%10)
p = p / 10
}
for i := 0; i < len(digits)-1; i++ {
if digits[i+1] > digits[i] {
return false
}
}
return true
}
func main() {
primes := rcu.Primes(999)
var nonDesc []int
for _, p := range primes {
if nonDescending(p) {
nonDesc = append(nonDesc, p)
}
}
fmt.Println("Primes below 1,000 with digits in non-decreasing order:")
for i, n := range nonDesc {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n%d such primes found.\n", len(nonDesc))
}
|
Produce a functionally identical Go code for the snippet given in C#. | using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static bool soms(int n, IEnumerable<int> f) {
if (n <= 0) return false;
if (f.Contains(n)) return true;
switch(n.CompareTo(f.Sum())) {
case 1: return false;
case 0: return true;
case -1:
var rf = f.Reverse().Skip(1).ToList();
return soms(n - f.Last(), rf) || soms(n, rf);
}
return false;
}
static void Main() {
var sw = System.Diagnostics.Stopwatch.StartNew();
int c = 0, r, i, g; var s = new List<int>(); var a = new List<int>();
var sf = "stopped checking after finding {0} sequential non-gaps after the final gap of {1}";
for (i = 1, g = 1; g >= (i >> 1); i++) {
if ((r = (int)Math.Sqrt(i)) * r == i) s.Add(i);
if (!soms(i, s)) a.Add(g = i);
}
sw.Stop();
Console.WriteLine("Numbers which are not the sum of distinct squares:");
Console.WriteLine(string.Join(", ", a));
Console.WriteLine(sf, i - g, g);
Console.Write("found {0} total in {1} ms",
a.Count, sw.Elapsed.TotalMilliseconds);
}
}
| package main
import (
"fmt"
"math"
"rcu"
)
func contains(a []int, n int) bool {
for _, e := range a {
if e == n {
return true
}
}
return false
}
func soms(n int, f []int) bool {
if n <= 0 {
return false
}
if contains(f, n) {
return true
}
sum := rcu.SumInts(f)
if n > sum {
return false
}
if n == sum {
return true
}
rf := make([]int, len(f))
copy(rf, f)
for i, j := 0, len(rf)-1; i < j; i, j = i+1, j-1 {
rf[i], rf[j] = rf[j], rf[i]
}
rf = rf[1:]
return soms(n-f[len(f)-1], rf) || soms(n, rf)
}
func main() {
var s, a []int
sf := "\nStopped checking after finding %d sequential non-gaps after the final gap of %d\n"
i, g := 1, 1
for g >= (i >> 1) {
r := int(math.Sqrt(float64(i)))
if r*r == i {
s = append(s, i)
}
if !soms(i, s) {
g = i
a = append(a, g)
}
i++
}
fmt.Println("Numbers which are not the sum of distinct squares:")
fmt.Println(a)
fmt.Printf(sf, i-g, g)
fmt.Printf("Found %d in total\n", len(a))
}
var r int
|
Rewrite the snippet below in Go so it works the same as the original C# code. | using System;
using System.Collections.Generic;
class Program
{
static List<uint> sieve(uint max, bool ordinary = false)
{
uint k = ((max - 3) >> 1) + 1,
lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1;
var pl = new List<uint> { };
var ic = new bool[k];
for (uint i = 0, p = 3; i < lmt; i++, p += 2) if (!ic[i])
for (uint j = (p * p - 3) >> 1; j < k; j += p) ic[j] = true;
if (ordinary)
{
pl.Add(2);
for (uint i = 0, j = 3; i < k; i++, j += 2)
if (!ic[i]) pl.Add(j);
}
else
for (uint i = 0, j = 3, t = j; i < k; i++, t = j += 2)
if (!ic[i])
{
while ((t /= 10) > 0)
if (((t % 10) & 1) == 1) goto skip;
pl.Add(j);
skip:;
}
return pl;
}
static void Main(string[] args)
{
var pl = sieve((uint)1e9);
uint c = 0, l = 10, p = 1;
Console.WriteLine("List of one-odd-digit primes < 1,000:");
for (int i = 0; pl[i] < 1000; i++)
Console.Write("{0,3}{1}", pl[i], i % 9 == 8 ? "\n" : " ");
string fmt = "\nFound {0:n0} one-odd-digit primes < 10^{1} ({2:n0})";
foreach (var itm in pl)
if (itm < l) c++;
else Console.Write(fmt, c++, p++, l, l *= 10);
Console.Write(fmt, c++, p++, l);
}
}
| package main
import (
"fmt"
"rcu"
)
func allButOneEven(prime int) bool {
digits := rcu.Digits(prime, 10)
digits = digits[:len(digits)-1]
allEven := true
for _, d := range digits {
if d&1 == 1 {
allEven = false
break
}
}
return allEven
}
func main() {
const (
LIMIT = 999
LIMIT2 = 9999999999
MAX_DIGITS = 3
)
primes := rcu.Primes(LIMIT)
var results []int
for _, prime := range primes[1:] {
if allButOneEven(prime) {
results = append(results, prime)
}
}
fmt.Println("Primes under", rcu.Commatize(LIMIT+1), "which contain only one odd digit:")
for i, p := range results {
fmt.Printf("%*s ", MAX_DIGITS, rcu.Commatize(p))
if (i+1)%9 == 0 {
fmt.Println()
}
}
fmt.Println("\nFound", len(results), "such primes.\n")
primes = rcu.Primes(LIMIT2)
count := 0
pow := 10
for _, prime := range primes[1:] {
if allButOneEven(prime) {
count++
}
if prime > pow {
fmt.Printf("There are %7s such primes under %s\n", rcu.Commatize(count), rcu.Commatize(pow))
pow *= 10
}
}
fmt.Printf("There are %7s such primes under %s\n", rcu.Commatize(count), rcu.Commatize(pow))
}
|
Write the same algorithm in Go as shown in this C# implementation. | using System;
using System.Collections.Generic;
class Program
{
static List<uint> sieve(uint max, bool ordinary = false)
{
uint k = ((max - 3) >> 1) + 1,
lmt = ((uint)(Math.Sqrt(max++) - 3) >> 1) + 1;
var pl = new List<uint> { };
var ic = new bool[k];
for (uint i = 0, p = 3; i < lmt; i++, p += 2) if (!ic[i])
for (uint j = (p * p - 3) >> 1; j < k; j += p) ic[j] = true;
if (ordinary)
{
pl.Add(2);
for (uint i = 0, j = 3; i < k; i++, j += 2)
if (!ic[i]) pl.Add(j);
}
else
for (uint i = 0, j = 3, t = j; i < k; i++, t = j += 2)
if (!ic[i])
{
while ((t /= 10) > 0)
if (((t % 10) & 1) == 1) goto skip;
pl.Add(j);
skip:;
}
return pl;
}
static void Main(string[] args)
{
var pl = sieve((uint)1e9);
uint c = 0, l = 10, p = 1;
Console.WriteLine("List of one-odd-digit primes < 1,000:");
for (int i = 0; pl[i] < 1000; i++)
Console.Write("{0,3}{1}", pl[i], i % 9 == 8 ? "\n" : " ");
string fmt = "\nFound {0:n0} one-odd-digit primes < 10^{1} ({2:n0})";
foreach (var itm in pl)
if (itm < l) c++;
else Console.Write(fmt, c++, p++, l, l *= 10);
Console.Write(fmt, c++, p++, l);
}
}
| package main
import (
"fmt"
"rcu"
)
func allButOneEven(prime int) bool {
digits := rcu.Digits(prime, 10)
digits = digits[:len(digits)-1]
allEven := true
for _, d := range digits {
if d&1 == 1 {
allEven = false
break
}
}
return allEven
}
func main() {
const (
LIMIT = 999
LIMIT2 = 9999999999
MAX_DIGITS = 3
)
primes := rcu.Primes(LIMIT)
var results []int
for _, prime := range primes[1:] {
if allButOneEven(prime) {
results = append(results, prime)
}
}
fmt.Println("Primes under", rcu.Commatize(LIMIT+1), "which contain only one odd digit:")
for i, p := range results {
fmt.Printf("%*s ", MAX_DIGITS, rcu.Commatize(p))
if (i+1)%9 == 0 {
fmt.Println()
}
}
fmt.Println("\nFound", len(results), "such primes.\n")
primes = rcu.Primes(LIMIT2)
count := 0
pow := 10
for _, prime := range primes[1:] {
if allButOneEven(prime) {
count++
}
if prime > pow {
fmt.Printf("There are %7s such primes under %s\n", rcu.Commatize(count), rcu.Commatize(pow))
pow *= 10
}
}
fmt.Printf("There are %7s such primes under %s\n", rcu.Commatize(count), rcu.Commatize(pow))
}
|
Can you help me rewrite this code in Go instead of C#, keeping it the same logically? | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class Reflection
{
public static void Main() {
var t = new TestClass();
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var prop in GetPropertyValues(t, flags)) {
Console.WriteLine(prop);
}
foreach (var field in GetFieldValues(t, flags)) {
Console.WriteLine(field);
}
}
public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>
from p in typeof(T).GetProperties(flags)
where p.GetIndexParameters().Length == 0
select (p.Name, p.GetValue(obj, null));
public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>
typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));
class TestClass
{
private int privateField = 7;
public int PublicNumber { get; } = 4;
private int PrivateNumber { get; } = 2;
}
}
| package main
import (
"fmt"
"image"
"reflect"
)
type t struct {
X int
next *t
}
func main() {
report(t{})
report(image.Point{})
}
func report(x interface{}) {
t := reflect.TypeOf(x)
n := t.NumField()
fmt.Printf("Type %v has %d fields:\n", t, n)
fmt.Println("Name Type Exported")
for i := 0; i < n; i++ {
f := t.Field(i)
fmt.Printf("%-8s %-8v %-8t\n",
f.Name,
f.Type,
f.PkgPath == "",
)
}
fmt.Println()
}
|
Convert the following code from C# to Go, ensuring the logic remains intact. | using System;
using System.Collections.Generic;
using System.Linq;
public static class MinimalSteps
{
public static void Main() {
var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });
var lookup = CreateLookup(2_000, divisors, subtractors);
Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]");
PrintRange(lookup, 10);
PrintMaxMins(lookup);
lookup = CreateLookup(20_000, divisors, subtractors);
PrintMaxMins(lookup);
Console.WriteLine();
subtractors = new [] { 2 };
lookup = CreateLookup(2_000, divisors, subtractors);
Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]");
PrintRange(lookup, 10);
PrintMaxMins(lookup);
lookup = CreateLookup(20_000, divisors, subtractors);
PrintMaxMins(lookup);
}
private static void PrintRange((char op, int param, int steps)[] lookup, int limit) {
for (int goal = 1; goal <= limit; goal++) {
var x = lookup[goal];
if (x.param == 0) {
Console.WriteLine($"{goal} cannot be reached with these numbers.");
continue;
}
Console.Write($"{goal} takes {x.steps} {(x.steps == 1 ? "step" : "steps")}: ");
for (int n = goal; n > 1; ) {
Console.Write($"{n},{x.op}{x.param}=> ");
n = x.op == '/' ? n / x.param : n - x.param;
x = lookup[n];
}
Console.WriteLine("1");
}
}
private static void PrintMaxMins((char op, int param, int steps)[] lookup) {
var maxSteps = lookup.Max(x => x.steps);
var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList();
Console.WriteLine(items.Count == 1
? $"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}"
: $"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}"
);
}
private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors)
{
var lookup = new (char op, int param, int steps)[goal+1];
lookup[1] = ('/', 1, 0);
for (int n = 1; n < lookup.Length; n++) {
var ln = lookup[n];
if (ln.param == 0) continue;
for (int d = 0; d < divisors.Length; d++) {
int target = n * divisors[d];
if (target > goal) break;
if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1);
}
for (int s = 0; s < subtractors.Length; s++) {
int target = n + subtractors[s];
if (target > goal) break;
if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1);
}
}
return lookup;
}
private static string Delimit<T>(this IEnumerable<T> source) => string.Join(", ", source);
}
| package main
import (
"fmt"
"strings"
)
const limit = 50000
var (
divs, subs []int
mins [][]string
)
func minsteps(n int) {
if n == 1 {
mins[1] = []string{}
return
}
min := limit
var p, q int
var op byte
for _, div := range divs {
if n%div == 0 {
d := n / div
steps := len(mins[d]) + 1
if steps < min {
min = steps
p, q, op = d, div, '/'
}
}
}
for _, sub := range subs {
if d := n - sub; d >= 1 {
steps := len(mins[d]) + 1
if steps < min {
min = steps
p, q, op = d, sub, '-'
}
}
}
mins[n] = append(mins[n], fmt.Sprintf("%c%d -> %d", op, q, p))
mins[n] = append(mins[n], mins[p]...)
}
func main() {
for r := 0; r < 2; r++ {
divs = []int{2, 3}
if r == 0 {
subs = []int{1}
} else {
subs = []int{2}
}
mins = make([][]string, limit+1)
fmt.Printf("With: Divisors: %v, Subtractors: %v =>\n", divs, subs)
fmt.Println(" Minimum number of steps to diminish the following numbers down to 1 is:")
for i := 1; i <= limit; i++ {
minsteps(i)
if i <= 10 {
steps := len(mins[i])
plural := "s"
if steps == 1 {
plural = " "
}
fmt.Printf(" %2d: %d step%s: %s\n", i, steps, plural, strings.Join(mins[i], ", "))
}
}
for _, lim := range []int{2000, 20000, 50000} {
max := 0
for _, min := range mins[0 : lim+1] {
m := len(min)
if m > max {
max = m
}
}
var maxs []int
for i, min := range mins[0 : lim+1] {
if len(min) == max {
maxs = append(maxs, i)
}
}
nums := len(maxs)
verb, verb2, plural := "are", "have", "s"
if nums == 1 {
verb, verb2, plural = "is", "has", ""
}
fmt.Printf(" There %s %d number%s in the range 1-%d ", verb, nums, plural, lim)
fmt.Printf("that %s maximum 'minimal steps' of %d:\n", verb2, max)
fmt.Println(" ", maxs)
}
fmt.Println()
}
}
|
Write the same algorithm in Go as shown in this C# implementation. | using System;
class ColumnAlignerProgram
{
delegate string Justification(string s, int width);
static string[] AlignColumns(string[] lines, Justification justification)
{
const char Separator = '$';
string[][] table = new string[lines.Length][];
int columns = 0;
for (int i = 0; i < lines.Length; i++)
{
string[] row = lines[i].TrimEnd(Separator).Split(Separator);
if (columns < row.Length) columns = row.Length;
table[i] = row;
}
string[][] formattedTable = new string[table.Length][];
for (int i = 0; i < formattedTable.Length; i++)
{
formattedTable[i] = new string[columns];
}
for (int j = 0; j < columns; j++)
{
int columnWidth = 0;
for (int i = 0; i < table.Length; i++)
{
if (j < table[i].Length && columnWidth < table[i][j].Length)
columnWidth = table[i][j].Length;
}
for (int i = 0; i < formattedTable.Length; i++)
{
if (j < table[i].Length)
formattedTable[i][j] = justification(table[i][j], columnWidth);
else
formattedTable[i][j] = new String(' ', columnWidth);
}
}
string[] result = new string[formattedTable.Length];
for (int i = 0; i < result.Length; i++)
{
result[i] = String.Join(" ", formattedTable[i]);
}
return result;
}
static string JustifyLeft(string s, int width) { return s.PadRight(width); }
static string JustifyRight(string s, int width) { return s.PadLeft(width); }
static string JustifyCenter(string s, int width)
{
return s.PadLeft((width + s.Length) / 2).PadRight(width);
}
static void Main()
{
string[] input = {
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
"column$are$separated$by$at$least$one$space.",
"Further,$allow$for$each$word$in$a$column$to$be$either$left$",
"justified,$right$justified,$or$center$justified$within$its$column.",
};
foreach (string line in AlignColumns(input, JustifyCenter))
{
Console.WriteLine(line);
}
}
}
| package main
import (
"fmt"
"strings"
)
const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.`
type formatter struct {
text [][]string
width []int
}
func newFormatter(text string) *formatter {
var f formatter
for _, line := range strings.Split(text, "\n") {
words := strings.Split(line, "$")
for words[len(words)-1] == "" {
words = words[:len(words)-1]
}
f.text = append(f.text, words)
for i, word := range words {
if i == len(f.width) {
f.width = append(f.width, len(word))
} else if len(word) > f.width[i] {
f.width[i] = len(word)
}
}
}
return &f
}
const (
left = iota
middle
right
)
func (f formatter) print(j int) {
for _, line := range f.text {
for i, word := range line {
fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s",
len(word)+(f.width[i]-len(word))*j/2, word))
}
fmt.Println("")
}
fmt.Println("")
}
func main() {
f := newFormatter(text)
f.print(left)
f.print(middle)
f.print(right)
}
|
Rewrite the snippet below in Go so it works the same as the original C# code. | using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: {0}", u.DnsSafeHost);
Console.WriteLine("Port: {0}", u.Port);
Console.WriteLine("Path: {0}", u.LocalPath);
Console.WriteLine("Query: {0}", u.Query);
Console.WriteLine("Fragment: {0}", u.Fragment);
Console.WriteLine();
}
static void Main(string[] args)
{
ParseUrl("foo:
ParseUrl("urn:example:animal:ferret:nose");
ParseUrl("jdbc:mysql:
ParseUrl("ftp:
ParseUrl("http:
ParseUrl("ldap:
ParseUrl("mailto:John.Doe@example.com");
ParseUrl("news:comp.infosystems.www.servers.unix");
ParseUrl("tel:+1-816-555-1212");
ParseUrl("telnet:
ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2");
}
}
}
| package main
import (
"fmt"
"log"
"net"
"net/url"
)
func main() {
for _, in := range []string{
"foo:
"urn:example:animal:ferret:nose",
"jdbc:mysql:
"ftp:
"http:
"ldap:
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet:
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh:
"https:
"http:
} {
fmt.Println(in)
u, err := url.Parse(in)
if err != nil {
log.Println(err)
continue
}
if in != u.String() {
fmt.Printf("Note: reassmebles as %q\n", u)
}
printURL(u)
}
}
func printURL(u *url.URL) {
fmt.Println(" Scheme:", u.Scheme)
if u.Opaque != "" {
fmt.Println(" Opaque:", u.Opaque)
}
if u.User != nil {
fmt.Println(" Username:", u.User.Username())
if pwd, ok := u.User.Password(); ok {
fmt.Println(" Password:", pwd)
}
}
if u.Host != "" {
if host, port, err := net.SplitHostPort(u.Host); err == nil {
fmt.Println(" Host:", host)
fmt.Println(" Port:", port)
} else {
fmt.Println(" Host:", u.Host)
}
}
if u.Path != "" {
fmt.Println(" Path:", u.Path)
}
if u.RawQuery != "" {
fmt.Println(" RawQuery:", u.RawQuery)
m, err := url.ParseQuery(u.RawQuery)
if err == nil {
for k, v := range m {
fmt.Printf(" Key: %q Values: %q\n", k, v)
}
}
}
if u.Fragment != "" {
fmt.Println(" Fragment:", u.Fragment)
}
}
|
Port the following code from C# to Go with equivalent syntax and logic. | using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: {0}", u.DnsSafeHost);
Console.WriteLine("Port: {0}", u.Port);
Console.WriteLine("Path: {0}", u.LocalPath);
Console.WriteLine("Query: {0}", u.Query);
Console.WriteLine("Fragment: {0}", u.Fragment);
Console.WriteLine();
}
static void Main(string[] args)
{
ParseUrl("foo:
ParseUrl("urn:example:animal:ferret:nose");
ParseUrl("jdbc:mysql:
ParseUrl("ftp:
ParseUrl("http:
ParseUrl("ldap:
ParseUrl("mailto:John.Doe@example.com");
ParseUrl("news:comp.infosystems.www.servers.unix");
ParseUrl("tel:+1-816-555-1212");
ParseUrl("telnet:
ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2");
}
}
}
| package main
import (
"fmt"
"log"
"net"
"net/url"
)
func main() {
for _, in := range []string{
"foo:
"urn:example:animal:ferret:nose",
"jdbc:mysql:
"ftp:
"http:
"ldap:
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet:
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh:
"https:
"http:
} {
fmt.Println(in)
u, err := url.Parse(in)
if err != nil {
log.Println(err)
continue
}
if in != u.String() {
fmt.Printf("Note: reassmebles as %q\n", u)
}
printURL(u)
}
}
func printURL(u *url.URL) {
fmt.Println(" Scheme:", u.Scheme)
if u.Opaque != "" {
fmt.Println(" Opaque:", u.Opaque)
}
if u.User != nil {
fmt.Println(" Username:", u.User.Username())
if pwd, ok := u.User.Password(); ok {
fmt.Println(" Password:", pwd)
}
}
if u.Host != "" {
if host, port, err := net.SplitHostPort(u.Host); err == nil {
fmt.Println(" Host:", host)
fmt.Println(" Port:", port)
} else {
fmt.Println(" Host:", u.Host)
}
}
if u.Path != "" {
fmt.Println(" Path:", u.Path)
}
if u.RawQuery != "" {
fmt.Println(" RawQuery:", u.RawQuery)
m, err := url.ParseQuery(u.RawQuery)
if err == nil {
for k, v := range m {
fmt.Printf(" Key: %q Values: %q\n", k, v)
}
}
}
if u.Fragment != "" {
fmt.Println(" Fragment:", u.Fragment)
}
}
|
Rewrite the snippet below in Go so it works the same as the original C# code. | using System;
class Program {
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew();
int a, b, c, i, n, s3, ab; var res = new int[65];
for (n = 1, i = 0; n < 1850; n++) {
bool found = true;
for (a = 1; a < n; a++)
for (b = a + 1, ab = a * b + a + b; b < n; b++, ab += a + 1) {
if (ab > n) break;
for (c = b + 1, s3 = ab + (b + a) * b; c < n; c++, s3 += b + a) {
if (s3 == n) found = false;
if (s3 >= n) break;
}
}
if (found) res[i++] = n;
}
sw.Stop();
Console.WriteLine("The 65 known Idoneal numbers:");
for (i = 0; i < res.Length; i++)
Console.Write("{0,5}{1}", res[i], i % 13 == 12 ? "\n" : "");
Console.Write("Calculations took {0} ms", sw.Elapsed.TotalMilliseconds);
}
}
| package main
import "rcu"
func isIdoneal(n int) bool {
for a := 1; a < n; a++ {
for b := a + 1; b < n; b++ {
if a*b+a+b > n {
break
}
for c := b + 1; c < n; c++ {
sum := a*b + b*c + a*c
if sum == n {
return false
}
if sum > n {
break
}
}
}
}
return true
}
func main() {
var idoneals []int
for n := 1; n <= 1850; n++ {
if isIdoneal(n) {
idoneals = append(idoneals, n)
}
}
rcu.PrintTable(idoneals, 13, 4, false)
}
|
Produce a functionally identical Go code for the snippet given in C#. | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace Base58CheckEncoding {
class Program {
const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static BigInteger ToBigInteger(string value, int @base) {
const string HEX = "0123456789ABCDEF";
if (@base < 1 || @base > HEX.Length) {
throw new ArgumentException("Base is out of range.");
}
BigInteger bi = BigInteger.Zero;
foreach (char c in value) {
char c2 = Char.ToUpper(c);
int idx = HEX.IndexOf(c2);
if (idx == -1 || idx >= @base) {
throw new ArgumentOutOfRangeException("Illegal character encountered.");
}
bi = bi * @base + idx;
}
return bi;
}
static string ConvertToBase58(string hash, int @base = 16) {
BigInteger x;
if (@base == 16 && hash.Substring(0, 2) == "0x") {
x = ToBigInteger(hash.Substring(2), @base);
} else {
x = ToBigInteger(hash, @base);
}
StringBuilder sb = new StringBuilder();
while (x > 0) {
BigInteger r = x % 58;
sb.Append(ALPHABET[(int)r]);
x = x / 58;
}
char[] ca = sb.ToString().ToCharArray();
Array.Reverse(ca);
return new string(ca);
}
static void Main(string[] args) {
string s = "25420294593250030202636073700053352635053786165627414518";
string b = ConvertToBase58(s, 10);
Console.WriteLine("{0} -> {1}", s, b);
List<string> hashes = new List<string>() {
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e",
};
foreach (string hash in hashes) {
string b58 = ConvertToBase58(hash);
Console.WriteLine("{0,-56} -> {1}", hash, b58);
}
}
}
}
| package main
import (
"fmt"
"log"
"math/big"
"strings"
)
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
var big0 = new(big.Int)
var big58 = big.NewInt(58)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func convertToBase58(hash string, base int) (string, error) {
var x, ok = new(big.Int).SetString(hash, base)
if !ok {
return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base)
}
var sb strings.Builder
var rem = new(big.Int)
for x.Cmp(big0) == 1 {
x.QuoRem(x, big58, rem)
r := rem.Int64()
sb.WriteByte(alphabet[r])
}
return reverse(sb.String()), nil
}
func main() {
s := "25420294593250030202636073700053352635053786165627414518"
b, err := convertToBase58(s, 10)
if err != nil {
log.Fatal(err)
}
fmt.Println(s, "->", b)
hashes := [...]string{
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e",
}
for _, hash := range hashes {
b58, err := convertToBase58(hash, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-56s -> %s\n", hash, b58)
}
}
|
Write a version of this C# function in Go with identical behavior. | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace Base58CheckEncoding {
class Program {
const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static BigInteger ToBigInteger(string value, int @base) {
const string HEX = "0123456789ABCDEF";
if (@base < 1 || @base > HEX.Length) {
throw new ArgumentException("Base is out of range.");
}
BigInteger bi = BigInteger.Zero;
foreach (char c in value) {
char c2 = Char.ToUpper(c);
int idx = HEX.IndexOf(c2);
if (idx == -1 || idx >= @base) {
throw new ArgumentOutOfRangeException("Illegal character encountered.");
}
bi = bi * @base + idx;
}
return bi;
}
static string ConvertToBase58(string hash, int @base = 16) {
BigInteger x;
if (@base == 16 && hash.Substring(0, 2) == "0x") {
x = ToBigInteger(hash.Substring(2), @base);
} else {
x = ToBigInteger(hash, @base);
}
StringBuilder sb = new StringBuilder();
while (x > 0) {
BigInteger r = x % 58;
sb.Append(ALPHABET[(int)r]);
x = x / 58;
}
char[] ca = sb.ToString().ToCharArray();
Array.Reverse(ca);
return new string(ca);
}
static void Main(string[] args) {
string s = "25420294593250030202636073700053352635053786165627414518";
string b = ConvertToBase58(s, 10);
Console.WriteLine("{0} -> {1}", s, b);
List<string> hashes = new List<string>() {
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e",
};
foreach (string hash in hashes) {
string b58 = ConvertToBase58(hash);
Console.WriteLine("{0,-56} -> {1}", hash, b58);
}
}
}
}
| package main
import (
"fmt"
"log"
"math/big"
"strings"
)
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
var big0 = new(big.Int)
var big58 = big.NewInt(58)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func convertToBase58(hash string, base int) (string, error) {
var x, ok = new(big.Int).SetString(hash, base)
if !ok {
return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base)
}
var sb strings.Builder
var rem = new(big.Int)
for x.Cmp(big0) == 1 {
x.QuoRem(x, big58, rem)
r := rem.Int64()
sb.WriteByte(alphabet[r])
}
return reverse(sb.String()), nil
}
func main() {
s := "25420294593250030202636073700053352635053786165627414518"
b, err := convertToBase58(s, 10)
if err != nil {
log.Fatal(err)
}
fmt.Println(s, "->", b)
hashes := [...]string{
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e",
}
for _, hash := range hashes {
b58, err := convertToBase58(hash, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-56s -> %s\n", hash, b58)
}
}
|
Generate a Go translation of this C# snippet without changing its computational steps. | using System;
using System.Dynamic;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string varname = Console.ReadLine();
dynamic expando = new ExpandoObject();
var map = expando as IDictionary<string, object>;
map.Add(varname, "Hello world!");
Console.WriteLine(expando.foo);
}
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
n := 0
for n < 1 || n > 5 {
fmt.Print("How many integer variables do you want to create (max 5) : ")
scanner.Scan()
n, _ = strconv.Atoi(scanner.Text())
check(scanner.Err())
}
vars := make(map[string]int)
fmt.Println("OK, enter the variable names and their values, below")
for i := 1; i <= n; {
fmt.Println("\n Variable", i)
fmt.Print(" Name : ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
if _, ok := vars[name]; ok {
fmt.Println(" Sorry, you've already created a variable of that name, try again")
continue
}
var value int
var err error
for {
fmt.Print(" Value : ")
scanner.Scan()
value, err = strconv.Atoi(scanner.Text())
check(scanner.Err())
if err != nil {
fmt.Println(" Not a valid integer, try again")
} else {
break
}
}
vars[name] = value
i++
}
fmt.Println("\nEnter q to quit")
for {
fmt.Print("\nWhich variable do you want to inspect : ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
if s := strings.ToLower(name); s == "q" {
return
}
v, ok := vars[name]
if !ok {
fmt.Println("Sorry there's no variable of that name, try again")
} else {
fmt.Println("It's value is", v)
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | using System;
using System.IO;
using System.Security.Cryptography;
namespace DES {
class Program {
static string ByteArrayToString(byte[] ba) {
return BitConverter.ToString(ba).Replace("-", "");
}
static byte[] Encrypt(byte[] messageBytes, byte[] passwordBytes) {
byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, iv);
CryptoStreamMode mode = CryptoStreamMode.Write;
MemoryStream memStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
cryptoStream.Write(messageBytes, 0, messageBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] encryptedMessageBytes = new byte[memStream.Length];
memStream.Position = 0;
memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
return encryptedMessageBytes;
}
static byte[] Decrypt(byte[] encryptedMessageBytes, byte[] passwordBytes) {
byte[] iv = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, iv);
CryptoStreamMode mode = CryptoStreamMode.Write;
MemoryStream memStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] decryptedMessageBytes = new byte[memStream.Length];
memStream.Position = 0;
memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);
return decryptedMessageBytes;
}
static void Main(string[] args) {
byte[] keyBytes = new byte[] { 0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73 };
byte[] plainBytes = new byte[] { 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87 };
byte[] encStr = Encrypt(plainBytes, keyBytes);
Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr));
byte[] decBytes = Decrypt(encStr, keyBytes);
Console.WriteLine("Decoded: {0}", ByteArrayToString(decBytes));
}
}
}
| package main
import (
"crypto/des"
"encoding/hex"
"fmt"
"log"
)
func main() {
key, err := hex.DecodeString("0e329232ea6d0d73")
if err != nil {
log.Fatal(err)
}
c, err := des.NewCipher(key)
if err != nil {
log.Fatal(err)
}
src, err := hex.DecodeString("8787878787878787")
if err != nil {
log.Fatal(err)
}
dst := make([]byte, des.BlockSize)
c.Encrypt(dst, src)
fmt.Printf("%x\n", dst)
}
|
Translate this program into Go but keep the logic exactly as in C#. | using System;
namespace Rosetta
{
internal interface IFun
{
double F(int index, Vector x);
double df(int index, int derivative, Vector x);
double[] weights();
}
class Newton
{
internal Vector Do(int size, IFun fun, Vector start)
{
Vector X = start.Clone();
Vector F = new Vector(size);
Matrix J = new Matrix(size, size);
Vector D;
do
{
for (int i = 0; i < size; i++)
F[i] = fun.F(i, X);
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
J[i, j] = fun.df(i, j, X);
J.ElimPartial(F);
X -= F;
} while (F.norm(fun.weights()) > 1e-12);
return X;
}
}
}
| package main
import (
"fmt"
"math"
)
type vector = []float64
type matrix []vector
type fun = func(vector) float64
type funs = []fun
type jacobian = []funs
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func (m1 matrix) sub(m2 matrix) matrix {
rows, cols := len(m1), len(m1[0])
if rows != len(m2) || cols != len(m2[0]) {
panic("Matrices cannot be subtracted.")
}
result := make(matrix, rows)
for i := 0; i < rows; i++ {
result[i] = make(vector, cols)
for j := 0; j < cols; j++ {
result[i][j] = m1[i][j] - m2[i][j]
}
}
return result
}
func (m matrix) transpose() matrix {
rows, cols := len(m), len(m[0])
trans := make(matrix, cols)
for i := 0; i < cols; i++ {
trans[i] = make(vector, rows)
for j := 0; j < rows; j++ {
trans[i][j] = m[j][i]
}
}
return trans
}
func (m matrix) inverse() matrix {
le := len(m)
for _, v := range m {
if len(v) != le {
panic("Not a square matrix")
}
}
aug := make(matrix, le)
for i := 0; i < le; i++ {
aug[i] = make(vector, 2*le)
copy(aug[i], m[i])
aug[i][i+le] = 1
}
aug.toReducedRowEchelonForm()
inv := make(matrix, le)
for i := 0; i < le; i++ {
inv[i] = make(vector, le)
copy(inv[i], aug[i][le:])
}
return inv
}
func (m matrix) toReducedRowEchelonForm() {
lead := 0
rowCount, colCount := len(m), len(m[0])
for r := 0; r < rowCount; r++ {
if colCount <= lead {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if colCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
if div := m[r][lead]; div != 0 {
for j := 0; j < colCount; j++ {
m[r][j] /= div
}
}
for k := 0; k < rowCount; k++ {
if k != r {
mult := m[k][lead]
for j := 0; j < colCount; j++ {
m[k][j] -= m[r][j] * mult
}
}
}
lead++
}
}
func solve(fs funs, jacob jacobian, guesses vector) vector {
size := len(fs)
var gu1 vector
gu2 := make(vector, len(guesses))
copy(gu2, guesses)
jac := make(matrix, size)
for i := 0; i < size; i++ {
jac[i] = make(vector, size)
}
tol := 1e-8
maxIter := 12
iter := 0
for {
gu1 = gu2
g := matrix{gu1}.transpose()
t := make(vector, size)
for i := 0; i < size; i++ {
t[i] = fs[i](gu1)
}
f := matrix{t}.transpose()
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
jac[i][j] = jacob[i][j](gu1)
}
}
g1 := g.sub(jac.inverse().mul(f))
gu2 = make(vector, size)
for i := 0; i < size; i++ {
gu2[i] = g1[i][0]
}
iter++
any := false
for i, v := range gu2 {
if math.Abs(v)-gu1[i] > tol {
any = true
break
}
}
if !any || iter >= maxIter {
break
}
}
return gu2
}
func main() {
f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] }
f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] }
fs := funs{f1, f2}
jacob := jacobian{
funs{
func(x vector) float64 { return -2*x[0] + 1 },
func(x vector) float64 { return -1 },
},
funs{
func(x vector) float64 { return 5*x[1] - 2*x[0] },
func(x vector) float64 { return 1 + 5*x[0] },
},
}
guesses := vector{1.2, 1.2}
sol := solve(fs, jacob, guesses)
fmt.Printf("Approximate solutions are x = %.7f, y = %.7f\n", sol[0], sol[1])
fmt.Println()
f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 }
f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] }
f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] }
fs = funs{f3, f4, f5}
jacob = jacobian{
funs{
func(x vector) float64 { return 18 * x[0] },
func(x vector) float64 { return 72 * x[1] },
func(x vector) float64 { return 8 * x[2] },
},
funs{
func(x vector) float64 { return 2 * x[0] },
func(x vector) float64 { return -4 * x[1] },
func(x vector) float64 { return -20 },
},
funs{
func(x vector) float64 { return 2 * x[0] },
func(x vector) float64 { return -2 * x[1] },
func(x vector) float64 { return 2 * x[2] },
},
}
guesses = vector{1, 1, 0}
sol = solve(fs, jacob, guesses)
fmt.Printf("Approximate solutions are x = %.7f, y = %.7f, z = %.7f\n", sol[0], sol[1], sol[2])
}
|
Port the provided C# code into Go while preserving the original functionality. | using System;
namespace Rosetta
{
internal interface IFun
{
double F(int index, Vector x);
double df(int index, int derivative, Vector x);
double[] weights();
}
class Newton
{
internal Vector Do(int size, IFun fun, Vector start)
{
Vector X = start.Clone();
Vector F = new Vector(size);
Matrix J = new Matrix(size, size);
Vector D;
do
{
for (int i = 0; i < size; i++)
F[i] = fun.F(i, X);
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
J[i, j] = fun.df(i, j, X);
J.ElimPartial(F);
X -= F;
} while (F.norm(fun.weights()) > 1e-12);
return X;
}
}
}
| package main
import (
"fmt"
"math"
)
type vector = []float64
type matrix []vector
type fun = func(vector) float64
type funs = []fun
type jacobian = []funs
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func (m1 matrix) sub(m2 matrix) matrix {
rows, cols := len(m1), len(m1[0])
if rows != len(m2) || cols != len(m2[0]) {
panic("Matrices cannot be subtracted.")
}
result := make(matrix, rows)
for i := 0; i < rows; i++ {
result[i] = make(vector, cols)
for j := 0; j < cols; j++ {
result[i][j] = m1[i][j] - m2[i][j]
}
}
return result
}
func (m matrix) transpose() matrix {
rows, cols := len(m), len(m[0])
trans := make(matrix, cols)
for i := 0; i < cols; i++ {
trans[i] = make(vector, rows)
for j := 0; j < rows; j++ {
trans[i][j] = m[j][i]
}
}
return trans
}
func (m matrix) inverse() matrix {
le := len(m)
for _, v := range m {
if len(v) != le {
panic("Not a square matrix")
}
}
aug := make(matrix, le)
for i := 0; i < le; i++ {
aug[i] = make(vector, 2*le)
copy(aug[i], m[i])
aug[i][i+le] = 1
}
aug.toReducedRowEchelonForm()
inv := make(matrix, le)
for i := 0; i < le; i++ {
inv[i] = make(vector, le)
copy(inv[i], aug[i][le:])
}
return inv
}
func (m matrix) toReducedRowEchelonForm() {
lead := 0
rowCount, colCount := len(m), len(m[0])
for r := 0; r < rowCount; r++ {
if colCount <= lead {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if colCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
if div := m[r][lead]; div != 0 {
for j := 0; j < colCount; j++ {
m[r][j] /= div
}
}
for k := 0; k < rowCount; k++ {
if k != r {
mult := m[k][lead]
for j := 0; j < colCount; j++ {
m[k][j] -= m[r][j] * mult
}
}
}
lead++
}
}
func solve(fs funs, jacob jacobian, guesses vector) vector {
size := len(fs)
var gu1 vector
gu2 := make(vector, len(guesses))
copy(gu2, guesses)
jac := make(matrix, size)
for i := 0; i < size; i++ {
jac[i] = make(vector, size)
}
tol := 1e-8
maxIter := 12
iter := 0
for {
gu1 = gu2
g := matrix{gu1}.transpose()
t := make(vector, size)
for i := 0; i < size; i++ {
t[i] = fs[i](gu1)
}
f := matrix{t}.transpose()
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
jac[i][j] = jacob[i][j](gu1)
}
}
g1 := g.sub(jac.inverse().mul(f))
gu2 = make(vector, size)
for i := 0; i < size; i++ {
gu2[i] = g1[i][0]
}
iter++
any := false
for i, v := range gu2 {
if math.Abs(v)-gu1[i] > tol {
any = true
break
}
}
if !any || iter >= maxIter {
break
}
}
return gu2
}
func main() {
f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] }
f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] }
fs := funs{f1, f2}
jacob := jacobian{
funs{
func(x vector) float64 { return -2*x[0] + 1 },
func(x vector) float64 { return -1 },
},
funs{
func(x vector) float64 { return 5*x[1] - 2*x[0] },
func(x vector) float64 { return 1 + 5*x[0] },
},
}
guesses := vector{1.2, 1.2}
sol := solve(fs, jacob, guesses)
fmt.Printf("Approximate solutions are x = %.7f, y = %.7f\n", sol[0], sol[1])
fmt.Println()
f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 }
f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] }
f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] }
fs = funs{f3, f4, f5}
jacob = jacobian{
funs{
func(x vector) float64 { return 18 * x[0] },
func(x vector) float64 { return 72 * x[1] },
func(x vector) float64 { return 8 * x[2] },
},
funs{
func(x vector) float64 { return 2 * x[0] },
func(x vector) float64 { return -4 * x[1] },
func(x vector) float64 { return -20 },
},
funs{
func(x vector) float64 { return 2 * x[0] },
func(x vector) float64 { return -2 * x[1] },
func(x vector) float64 { return 2 * x[2] },
},
}
guesses = vector{1, 1, 0}
sol = solve(fs, jacob, guesses)
fmt.Printf("Approximate solutions are x = %.7f, y = %.7f, z = %.7f\n", sol[0], sol[1], sol[2])
}
|
Write a version of this C# function in Go with identical behavior. | using System;
namespace Rosetta
{
internal interface IFun
{
double F(int index, Vector x);
double df(int index, int derivative, Vector x);
double[] weights();
}
class Newton
{
internal Vector Do(int size, IFun fun, Vector start)
{
Vector X = start.Clone();
Vector F = new Vector(size);
Matrix J = new Matrix(size, size);
Vector D;
do
{
for (int i = 0; i < size; i++)
F[i] = fun.F(i, X);
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
J[i, j] = fun.df(i, j, X);
J.ElimPartial(F);
X -= F;
} while (F.norm(fun.weights()) > 1e-12);
return X;
}
}
}
| package main
import (
"fmt"
"math"
)
type vector = []float64
type matrix []vector
type fun = func(vector) float64
type funs = []fun
type jacobian = []funs
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
for k := 0; k < rows2; k++ {
result[i][j] += m1[i][k] * m2[k][j]
}
}
}
return result
}
func (m1 matrix) sub(m2 matrix) matrix {
rows, cols := len(m1), len(m1[0])
if rows != len(m2) || cols != len(m2[0]) {
panic("Matrices cannot be subtracted.")
}
result := make(matrix, rows)
for i := 0; i < rows; i++ {
result[i] = make(vector, cols)
for j := 0; j < cols; j++ {
result[i][j] = m1[i][j] - m2[i][j]
}
}
return result
}
func (m matrix) transpose() matrix {
rows, cols := len(m), len(m[0])
trans := make(matrix, cols)
for i := 0; i < cols; i++ {
trans[i] = make(vector, rows)
for j := 0; j < rows; j++ {
trans[i][j] = m[j][i]
}
}
return trans
}
func (m matrix) inverse() matrix {
le := len(m)
for _, v := range m {
if len(v) != le {
panic("Not a square matrix")
}
}
aug := make(matrix, le)
for i := 0; i < le; i++ {
aug[i] = make(vector, 2*le)
copy(aug[i], m[i])
aug[i][i+le] = 1
}
aug.toReducedRowEchelonForm()
inv := make(matrix, le)
for i := 0; i < le; i++ {
inv[i] = make(vector, le)
copy(inv[i], aug[i][le:])
}
return inv
}
func (m matrix) toReducedRowEchelonForm() {
lead := 0
rowCount, colCount := len(m), len(m[0])
for r := 0; r < rowCount; r++ {
if colCount <= lead {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if colCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
if div := m[r][lead]; div != 0 {
for j := 0; j < colCount; j++ {
m[r][j] /= div
}
}
for k := 0; k < rowCount; k++ {
if k != r {
mult := m[k][lead]
for j := 0; j < colCount; j++ {
m[k][j] -= m[r][j] * mult
}
}
}
lead++
}
}
func solve(fs funs, jacob jacobian, guesses vector) vector {
size := len(fs)
var gu1 vector
gu2 := make(vector, len(guesses))
copy(gu2, guesses)
jac := make(matrix, size)
for i := 0; i < size; i++ {
jac[i] = make(vector, size)
}
tol := 1e-8
maxIter := 12
iter := 0
for {
gu1 = gu2
g := matrix{gu1}.transpose()
t := make(vector, size)
for i := 0; i < size; i++ {
t[i] = fs[i](gu1)
}
f := matrix{t}.transpose()
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
jac[i][j] = jacob[i][j](gu1)
}
}
g1 := g.sub(jac.inverse().mul(f))
gu2 = make(vector, size)
for i := 0; i < size; i++ {
gu2[i] = g1[i][0]
}
iter++
any := false
for i, v := range gu2 {
if math.Abs(v)-gu1[i] > tol {
any = true
break
}
}
if !any || iter >= maxIter {
break
}
}
return gu2
}
func main() {
f1 := func(x vector) float64 { return -x[0]*x[0] + x[0] + 0.5 - x[1] }
f2 := func(x vector) float64 { return x[1] + 5*x[0]*x[1] - x[0]*x[0] }
fs := funs{f1, f2}
jacob := jacobian{
funs{
func(x vector) float64 { return -2*x[0] + 1 },
func(x vector) float64 { return -1 },
},
funs{
func(x vector) float64 { return 5*x[1] - 2*x[0] },
func(x vector) float64 { return 1 + 5*x[0] },
},
}
guesses := vector{1.2, 1.2}
sol := solve(fs, jacob, guesses)
fmt.Printf("Approximate solutions are x = %.7f, y = %.7f\n", sol[0], sol[1])
fmt.Println()
f3 := func(x vector) float64 { return 9*x[0]*x[0] + 36*x[1]*x[1] + 4*x[2]*x[2] - 36 }
f4 := func(x vector) float64 { return x[0]*x[0] - 2*x[1]*x[1] - 20*x[2] }
f5 := func(x vector) float64 { return x[0]*x[0] - x[1]*x[1] + x[2]*x[2] }
fs = funs{f3, f4, f5}
jacob = jacobian{
funs{
func(x vector) float64 { return 18 * x[0] },
func(x vector) float64 { return 72 * x[1] },
func(x vector) float64 { return 8 * x[2] },
},
funs{
func(x vector) float64 { return 2 * x[0] },
func(x vector) float64 { return -4 * x[1] },
func(x vector) float64 { return -20 },
},
funs{
func(x vector) float64 { return 2 * x[0] },
func(x vector) float64 { return -2 * x[1] },
func(x vector) float64 { return 2 * x[2] },
},
}
guesses = vector{1, 1, 0}
sol = solve(fs, jacob, guesses)
fmt.Printf("Approximate solutions are x = %.7f, y = %.7f, z = %.7f\n", sol[0], sol[1], sol[2])
}
|
Change the programming language of this snippet from C# to Go without modifying what it does. | using System;
using System.IO;
using System.Numerics;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
namespace Fibonacci {
class Program
{
private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };
private static NumberFormatInfo nfi = new NumberFormatInfo { NumberGroupSeparator = "_" };
private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)
{
if (A.GetLength(1) != B.GetLength(0))
{
throw new ArgumentException("Illegal matrix dimensions for multiplication.");
}
var C = new BigInteger[A.GetLength(0), B.GetLength(1)];
for (int i = 0; i < A.GetLength(0); ++i)
{
for (int j = 0; j < B.GetLength(1); ++j)
{
for (int k = 0; k < A.GetLength(1); ++k)
{
C[i, j] += A[i, k] * B[k, j];
}
}
}
return C;
}
private static BigInteger[,] Power(in BigInteger[,] A, ulong n)
{
if (A.GetLength(1) != A.GetLength(0))
{
throw new ArgumentException("Not a square matrix.");
}
var C = new BigInteger[A.GetLength(0), A.GetLength(1)];
for (int i = 0; i < A.GetLength(0); ++i)
{
C[i, i] = BigInteger.One;
}
if (0 == n) return C;
var S = new BigInteger[A.GetLength(0), A.GetLength(1)];
for (int i = 0; i < A.GetLength(0); ++i)
{
for (int j = 0; j < A.GetLength(1); ++j)
{
S[i, j] = A[i, j];
}
}
while (0 < n)
{
if (1 == n % 2) C = Multiply(C, S);
S = Multiply(S,S);
n /= 2;
}
return C;
}
public static BigInteger Fib(in ulong n)
{
var C = Power(F, n);
return C[0, 1];
}
public static void Task(in ulong p)
{
var ans = Fib(p).ToString();
var sp = p.ToString("N0", nfi);
if (ans.Length <= 40)
{
Console.WriteLine("Fibonacci({0}) = {1}", sp, ans);
}
else
{
Console.WriteLine("Fibonacci({0}) = {1} ... {2}", sp, ans[0..19], ans[^20..]);
}
}
public static void Main()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (ulong p = 10; p <= 10_000_000; p *= 10) {
Task(p);
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("Took " + elapsedTime);
}
}
}
| package main
import (
"fmt"
big "github.com/ncw/gmp"
"time"
)
type vector = []*big.Int
type matrix []vector
var (
zero = new(big.Int)
one = big.NewInt(1)
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
temp := new(big.Int)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
result[i][j] = new(big.Int)
for k := 0; k < rows2; k++ {
temp.Mul(m1[i][k], m2[k][j])
result[i][j].Add(result[i][j], temp)
}
}
}
return result
}
func identityMatrix(n uint64) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := uint64(0); i < n; i++ {
ident[i] = make(vector, n)
for j := uint64(0); j < n; j++ {
ident[i][j] = new(big.Int)
if i == j {
ident[i][j].Set(one)
}
}
}
return ident
}
func (m matrix) pow(n *big.Int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n.Cmp(zero) == -1:
panic("Negative exponents not supported")
case n.Cmp(zero) == 0:
return identityMatrix(uint64(le))
case n.Cmp(one) == 0:
return m
}
pow := identityMatrix(uint64(le))
base := m
e := new(big.Int).Set(n)
temp := new(big.Int)
for e.Cmp(zero) > 0 {
temp.And(e, one)
if temp.Cmp(one) == 0 {
pow = pow.mul(base)
}
e.Rsh(e, 1)
base = base.mul(base)
}
return pow
}
func fibonacci(n *big.Int) *big.Int {
if n.Cmp(zero) == 0 {
return zero
}
m := matrix{{one, one}, {one, zero}}
m = m.pow(n.Sub(n, one))
return m[0][0]
}
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() {
start := time.Now()
n := new(big.Int)
for i := uint64(10); i <= 1e7; i *= 10 {
n.SetUint64(i)
s := fibonacci(n).String()
fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n",
commatize(i), commatize(uint64(len(s))))
if len(s) > 20 {
fmt.Printf(" First 20 : %s\n", s[0:20])
if len(s) < 40 {
fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:])
} else {
fmt.Printf(" Final 20 : %s\n", s[len(s)-20:])
}
} else {
fmt.Printf(" All %-2d : %s\n", len(s), s)
}
fmt.Println()
}
sfxs := []string{"nd", "th"}
for i, e := range []uint{16, 32} {
n.Lsh(one, e)
s := fibonacci(n).String()
fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i],
commatize(uint64(len(s))))
fmt.Printf(" First 20 : %s\n", s[0:20])
fmt.Printf(" Final 20 : %s\n", s[len(s)-20:])
fmt.Println()
}
fmt.Printf("Took %s\n\n", time.Since(start))
}
|
Preserve the algorithm and functionality while converting the code from C# to Go. | using System;
using System.IO;
using System.Numerics;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
namespace Fibonacci {
class Program
{
private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };
private static NumberFormatInfo nfi = new NumberFormatInfo { NumberGroupSeparator = "_" };
private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)
{
if (A.GetLength(1) != B.GetLength(0))
{
throw new ArgumentException("Illegal matrix dimensions for multiplication.");
}
var C = new BigInteger[A.GetLength(0), B.GetLength(1)];
for (int i = 0; i < A.GetLength(0); ++i)
{
for (int j = 0; j < B.GetLength(1); ++j)
{
for (int k = 0; k < A.GetLength(1); ++k)
{
C[i, j] += A[i, k] * B[k, j];
}
}
}
return C;
}
private static BigInteger[,] Power(in BigInteger[,] A, ulong n)
{
if (A.GetLength(1) != A.GetLength(0))
{
throw new ArgumentException("Not a square matrix.");
}
var C = new BigInteger[A.GetLength(0), A.GetLength(1)];
for (int i = 0; i < A.GetLength(0); ++i)
{
C[i, i] = BigInteger.One;
}
if (0 == n) return C;
var S = new BigInteger[A.GetLength(0), A.GetLength(1)];
for (int i = 0; i < A.GetLength(0); ++i)
{
for (int j = 0; j < A.GetLength(1); ++j)
{
S[i, j] = A[i, j];
}
}
while (0 < n)
{
if (1 == n % 2) C = Multiply(C, S);
S = Multiply(S,S);
n /= 2;
}
return C;
}
public static BigInteger Fib(in ulong n)
{
var C = Power(F, n);
return C[0, 1];
}
public static void Task(in ulong p)
{
var ans = Fib(p).ToString();
var sp = p.ToString("N0", nfi);
if (ans.Length <= 40)
{
Console.WriteLine("Fibonacci({0}) = {1}", sp, ans);
}
else
{
Console.WriteLine("Fibonacci({0}) = {1} ... {2}", sp, ans[0..19], ans[^20..]);
}
}
public static void Main()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (ulong p = 10; p <= 10_000_000; p *= 10) {
Task(p);
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("Took " + elapsedTime);
}
}
}
| package main
import (
"fmt"
big "github.com/ncw/gmp"
"time"
)
type vector = []*big.Int
type matrix []vector
var (
zero = new(big.Int)
one = big.NewInt(1)
)
func (m1 matrix) mul(m2 matrix) matrix {
rows1, cols1 := len(m1), len(m1[0])
rows2, cols2 := len(m2), len(m2[0])
if cols1 != rows2 {
panic("Matrices cannot be multiplied.")
}
result := make(matrix, rows1)
temp := new(big.Int)
for i := 0; i < rows1; i++ {
result[i] = make(vector, cols2)
for j := 0; j < cols2; j++ {
result[i][j] = new(big.Int)
for k := 0; k < rows2; k++ {
temp.Mul(m1[i][k], m2[k][j])
result[i][j].Add(result[i][j], temp)
}
}
}
return result
}
func identityMatrix(n uint64) matrix {
if n < 1 {
panic("Size of identity matrix can't be less than 1")
}
ident := make(matrix, n)
for i := uint64(0); i < n; i++ {
ident[i] = make(vector, n)
for j := uint64(0); j < n; j++ {
ident[i][j] = new(big.Int)
if i == j {
ident[i][j].Set(one)
}
}
}
return ident
}
func (m matrix) pow(n *big.Int) matrix {
le := len(m)
if le != len(m[0]) {
panic("Not a square matrix")
}
switch {
case n.Cmp(zero) == -1:
panic("Negative exponents not supported")
case n.Cmp(zero) == 0:
return identityMatrix(uint64(le))
case n.Cmp(one) == 0:
return m
}
pow := identityMatrix(uint64(le))
base := m
e := new(big.Int).Set(n)
temp := new(big.Int)
for e.Cmp(zero) > 0 {
temp.And(e, one)
if temp.Cmp(one) == 0 {
pow = pow.mul(base)
}
e.Rsh(e, 1)
base = base.mul(base)
}
return pow
}
func fibonacci(n *big.Int) *big.Int {
if n.Cmp(zero) == 0 {
return zero
}
m := matrix{{one, one}, {one, zero}}
m = m.pow(n.Sub(n, one))
return m[0][0]
}
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() {
start := time.Now()
n := new(big.Int)
for i := uint64(10); i <= 1e7; i *= 10 {
n.SetUint64(i)
s := fibonacci(n).String()
fmt.Printf("The digits of the %sth Fibonacci number (%s) are:\n",
commatize(i), commatize(uint64(len(s))))
if len(s) > 20 {
fmt.Printf(" First 20 : %s\n", s[0:20])
if len(s) < 40 {
fmt.Printf(" Final %-2d : %s\n", len(s)-20, s[20:])
} else {
fmt.Printf(" Final 20 : %s\n", s[len(s)-20:])
}
} else {
fmt.Printf(" All %-2d : %s\n", len(s), s)
}
fmt.Println()
}
sfxs := []string{"nd", "th"}
for i, e := range []uint{16, 32} {
n.Lsh(one, e)
s := fibonacci(n).String()
fmt.Printf("The digits of the 2^%d%s Fibonacci number (%s) are:\n", e, sfxs[i],
commatize(uint64(len(s))))
fmt.Printf(" First 20 : %s\n", s[0:20])
fmt.Printf(" Final 20 : %s\n", s[len(s)-20:])
fmt.Println()
}
fmt.Printf("Took %s\n\n", time.Since(start))
}
|
Please provide an equivalent version of this C# code in Go. | using System;
class Program {
static bool isPal(int n) {
int rev = 0, lr = -1, rem;
while (n > rev) {
n = Math.DivRem(n, 10, out rem);
if (lr < 0 && rem == 0) return false;
lr = rev; rev = 10 * rev + rem;
if (n == rev || n == lr) return true;
} return false; }
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew();
int x = 900009, y = (int)Math.Sqrt(x), y10, max = 999, max9 = max - 9, z, p, bp = x, ld, c;
var a = new int[]{ 0,9,0,3,0,0,0,7,0,1 }; string bs = "";
y /= 11;
if ((y & 1) == 0) y--;
if (y % 5 == 0) y -= 2;
y *= 11;
while (y <= max) {
c = 0;
y10 = y * 10;
z = max9 + a[ld = y % 10];
p = y * z;
while (p >= bp) {
if (isPal(p)) {
if (p > bp) bp = p;
bs = string.Format("{0} x {1} = {2}", y, z - c, bp);
}
p -= y10; c += 10;
}
y += ld == 3 ? 44 : 22;
}
sw.Stop();
Console.Write("{0} {1} μs", bs, sw.Elapsed.TotalMilliseconds * 1000.0);
}
}
| package main
import "fmt"
func reverse(n uint64) uint64 {
r := uint64(0)
for n > 0 {
r = n%10 + r*10
n /= 10
}
return r
}
func main() {
pow := uint64(10)
nextN:
for n := 2; n < 10; n++ {
low := pow * 9
pow *= 10
high := pow - 1
fmt.Printf("Largest palindromic product of two %d-digit integers: ", n)
for i := high; i >= low; i-- {
j := reverse(i)
p := i*pow + j
for k := high; k > low; k -= 2 {
if k % 10 == 5 {
continue
}
l := p / k
if l > high {
break
}
if p%k == 0 {
fmt.Printf("%d x %d = %d\n", k, l, p)
continue nextN
}
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | static string[] inputs = {
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"\"-in Aus$+1411.8millions\"",
"===US$0017440 millions=== (in 2000 dollars)"
};
void Main()
{
inputs.Select(s => Commatize(s, 0, 3, ","))
.ToList()
.ForEach(Console.WriteLine);
}
string Commatize(string text, int startPosition, int interval, string separator)
{
var matches = Regex.Matches(text.Substring(startPosition), "[0-9]*");
var x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();
return string.Join("", x);
}
string Commatize(Match match, int interval, string separator, string original)
{
if (match.Length <= interval)
return original.Substring(match.Index,
match.Index == original.Length ? 0 : Math.Max(match.Length, 1));
return string.Join(separator, match.Value.Split(interval));
}
public static class Extension
{
public static string[] Split(this string source, int interval)
{
return SplitImpl(source, interval).ToArray();
}
static IEnumerable<string>SplitImpl(string source, int interval)
{
for (int i = 1; i < source.Length; i++)
{
if (i % interval != 0) continue;
yield return source.Substring(i - interval, interval);
}
}
}
| package main
import (
"fmt"
"regexp"
"strings"
)
var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func commatize(s string, startIndex, period int, sep string) string {
if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" {
return s
}
m := reg.FindString(s[startIndex:])
if m == "" {
return s
}
splits := strings.Split(m, ".")
ip := splits[0]
if len(ip) > period {
pi := reverse(ip)
for i := (len(ip) - 1) / period * period; i >= period; i -= period {
pi = pi[:i] + sep + pi[i:]
}
ip = reverse(pi)
}
if strings.Contains(m, ".") {
dp := splits[1]
if len(dp) > period {
for i := (len(dp) - 1) / period * period; i >= period; i -= period {
dp = dp[:i] + sep + dp[i:]
}
}
ip += "." + dp
}
return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)
}
func main() {
tests := [...]string{
"123456789.123456789",
".123456789",
"57256.1D-4",
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"-in Aus$+1411.8millions",
"===US$0017440 millions=== (in 2000 dollars)",
"123.e8000 is pretty big.",
"The land area of the earth is 57268900(29% of the surface) square miles.",
"Ain't no numbers in this here words, nohow, no way, Jose.",
"James was never known as 0000000007",
"Arthur Eddington wrote: I believe there are " +
"15747724136275002577605653961181555468044717914527116709366231425076185631031296" +
" protons in the universe.",
" $-140000±100 millions.",
"6/9/1946 was a good year for some.",
}
fmt.Println(commatize(tests[0], 0, 2, "*"))
fmt.Println(commatize(tests[1], 0, 3, "-"))
fmt.Println(commatize(tests[2], 0, 4, "__"))
fmt.Println(commatize(tests[3], 0, 5, " "))
fmt.Println(commatize(tests[4], 0, 3, "."))
for _, test := range tests[5:] {
fmt.Println(commatize(test, 0, 3, ","))
}
}
|
Generate a Go translation of this C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
namespace AruthmeticCoding {
using Freq = Dictionary<char, long>;
using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;
class Program {
static Freq CumulativeFreq(Freq freq) {
long total = 0;
Freq cf = new Freq();
for (int i = 0; i < 256; i++) {
char c = (char)i;
if (freq.ContainsKey(c)) {
long v = freq[c];
cf[c] = total;
total += v;
}
}
return cf;
}
static Triple ArithmeticCoding(string str, long radix) {
Freq freq = new Freq();
foreach (char c in str) {
if (freq.ContainsKey(c)) {
freq[c] += 1;
} else {
freq[c] = 1;
}
}
Freq cf = CumulativeFreq(freq);
BigInteger @base = str.Length;
BigInteger lower = 0;
BigInteger pf = 1;
foreach (char c in str) {
BigInteger x = cf[c];
lower = lower * @base + x * pf;
pf = pf * freq[c];
}
BigInteger upper = lower + pf;
int powr = 0;
BigInteger bigRadix = radix;
while (true) {
pf = pf / bigRadix;
if (pf == 0) break;
powr++;
}
BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr));
return new Triple(diff, powr, freq);
}
static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) {
BigInteger powr = radix;
BigInteger enc = num * BigInteger.Pow(powr, pwr);
long @base = freq.Values.Sum();
Freq cf = CumulativeFreq(freq);
Dictionary<long, char> dict = new Dictionary<long, char>();
foreach (char key in cf.Keys) {
long value = cf[key];
dict[value] = key;
}
long lchar = -1;
for (long i = 0; i < @base; i++) {
if (dict.ContainsKey(i)) {
lchar = dict[i];
} else if (lchar != -1) {
dict[i] = (char)lchar;
}
}
StringBuilder decoded = new StringBuilder((int)@base);
BigInteger bigBase = @base;
for (long i = @base - 1; i >= 0; --i) {
BigInteger pow = BigInteger.Pow(bigBase, (int)i);
BigInteger div = enc / pow;
char c = dict[(long)div];
BigInteger fv = freq[c];
BigInteger cv = cf[c];
BigInteger diff = enc - pow * cv;
enc = diff / fv;
decoded.Append(c);
}
return decoded.ToString();
}
static void Main(string[] args) {
long radix = 10;
string[] strings = { "DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT" };
foreach (string str in strings) {
Triple encoded = ArithmeticCoding(str, radix);
string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3);
Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", str, encoded.Item1, radix, encoded.Item2);
if (str != dec) {
throw new Exception("\tHowever that is incorrect!");
}
}
}
}
}
| package main
import (
"fmt"
"math/big"
)
func cumulative_freq(freq map[byte]int64) map[byte]int64 {
total := int64(0)
cf := make(map[byte]int64)
for i := 0; i < 256; i++ {
b := byte(i)
if v, ok := freq[b]; ok {
cf[b] = total
total += v
}
}
return cf
}
func arithmethic_coding(str string, radix int64) (*big.Int,
*big.Int, map[byte]int64) {
chars := []byte(str)
freq := make(map[byte]int64)
for _, c := range chars {
freq[c] += 1
}
cf := cumulative_freq(freq)
base := len(chars)
L := big.NewInt(0)
pf := big.NewInt(1)
bigBase := big.NewInt(int64(base))
for _, c := range chars {
x := big.NewInt(cf[c])
L.Mul(L, bigBase)
L.Add(L, x.Mul(x, pf))
pf.Mul(pf, big.NewInt(freq[c]))
}
U := big.NewInt(0)
U.Set(L)
U.Add(U, pf)
bigOne := big.NewInt(1)
bigZero := big.NewInt(0)
bigRadix := big.NewInt(radix)
tmp := big.NewInt(0).Set(pf)
powr := big.NewInt(0)
for {
tmp.Div(tmp, bigRadix)
if tmp.Cmp(bigZero) == 0 {
break
}
powr.Add(powr, bigOne)
}
diff := big.NewInt(0)
diff.Sub(U, bigOne)
diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))
return diff, powr, freq
}
func arithmethic_decoding(num *big.Int, radix int64,
pow *big.Int, freq map[byte]int64) string {
powr := big.NewInt(radix)
enc := big.NewInt(0).Set(num)
enc.Mul(enc, powr.Exp(powr, pow, nil))
base := int64(0)
for _, v := range freq {
base += v
}
cf := cumulative_freq(freq)
dict := make(map[int64]byte)
for k, v := range cf {
dict[v] = k
}
lchar := -1
for i := int64(0); i < base; i++ {
if v, ok := dict[i]; ok {
lchar = int(v)
} else if lchar != -1 {
dict[i] = byte(lchar)
}
}
decoded := make([]byte, base)
bigBase := big.NewInt(base)
for i := base - 1; i >= 0; i-- {
pow := big.NewInt(0)
pow.Exp(bigBase, big.NewInt(i), nil)
div := big.NewInt(0)
div.Div(enc, pow)
c := dict[div.Int64()]
fv := freq[c]
cv := cf[c]
prod := big.NewInt(0).Mul(pow, big.NewInt(cv))
diff := big.NewInt(0).Sub(enc, prod)
enc.Div(diff, big.NewInt(fv))
decoded[base-i-1] = c
}
return string(decoded)
}
func main() {
var radix = int64(10)
strSlice := []string{
`DABDDB`,
`DABDDBBDDBA`,
`ABRACADABRA`,
`TOBEORNOTTOBEORTOBEORNOT`,
}
for _, str := range strSlice {
enc, pow, freq := arithmethic_coding(str, radix)
dec := arithmethic_decoding(enc, radix, pow, freq)
fmt.Printf("%-25s=> %19s * %d^%s\n", str, enc, radix, pow)
if str != dec {
panic("\tHowever that is incorrect!")
}
}
}
|
Convert the following code from C# to Go, ensuring the logic remains intact. | using System;
using System.Collections.Generic;
class Node
{
public enum Colors
{
Black, White, Gray
}
public Colors color { get; set; }
public int N { get; }
public Node(int n)
{
N = n;
color = Colors.White;
}
}
class Graph
{
public HashSet<Node> V { get; }
public Dictionary<Node, HashSet<Node>> Adj { get; }
public void Kosaraju()
{
var L = new HashSet<Node>();
Action<Node> Visit = null;
Visit = (u) =>
{
if (u.color == Node.Colors.White)
{
u.color = Node.Colors.Gray;
foreach (var v in Adj[u])
Visit(v);
L.Add(u);
}
};
Action<Node, Node> Assign = null;
Assign = (u, root) =>
{
if (u.color != Node.Colors.Black)
{
if (u == root)
Console.Write("SCC: ");
Console.Write(u.N + " ");
u.color = Node.Colors.Black;
foreach (var v in Adj[u])
Assign(v, root);
if (u == root)
Console.WriteLine();
}
};
foreach (var u in V)
Visit(u);
foreach (var u in L)
Assign(u, u);
}
}
| package main
import "fmt"
var g = [][]int{
0: {1},
1: {2},
2: {0},
3: {1, 2, 4},
4: {3, 5},
5: {2, 6},
6: {5},
7: {4, 6, 7},
}
func main() {
fmt.Println(kosaraju(g))
}
func kosaraju(g [][]int) []int {
vis := make([]bool, len(g))
L := make([]int, len(g))
x := len(L)
t := make([][]int, len(g))
var Visit func(int)
Visit = func(u int) {
if !vis[u] {
vis[u] = true
for _, v := range g[u] {
Visit(v)
t[v] = append(t[v], u)
}
x--
L[x] = u
}
}
for u := range g {
Visit(u)
}
c := make([]int, len(g))
var Assign func(int, int)
Assign = func(u, root int) {
if vis[u] {
vis[u] = false
c[u] = root
for _, v := range t[u] {
Assign(v, root)
}
}
}
for _, u := range L {
Assign(u, u)
}
return c
}
|
Please provide an equivalent version of this C# code in Go. | using System;
using System.Collections.Generic;
class Node
{
public enum Colors
{
Black, White, Gray
}
public Colors color { get; set; }
public int N { get; }
public Node(int n)
{
N = n;
color = Colors.White;
}
}
class Graph
{
public HashSet<Node> V { get; }
public Dictionary<Node, HashSet<Node>> Adj { get; }
public void Kosaraju()
{
var L = new HashSet<Node>();
Action<Node> Visit = null;
Visit = (u) =>
{
if (u.color == Node.Colors.White)
{
u.color = Node.Colors.Gray;
foreach (var v in Adj[u])
Visit(v);
L.Add(u);
}
};
Action<Node, Node> Assign = null;
Assign = (u, root) =>
{
if (u.color != Node.Colors.Black)
{
if (u == root)
Console.Write("SCC: ");
Console.Write(u.N + " ");
u.color = Node.Colors.Black;
foreach (var v in Adj[u])
Assign(v, root);
if (u == root)
Console.WriteLine();
}
};
foreach (var u in V)
Visit(u);
foreach (var u in L)
Assign(u, u);
}
}
| package main
import "fmt"
var g = [][]int{
0: {1},
1: {2},
2: {0},
3: {1, 2, 4},
4: {3, 5},
5: {2, 6},
6: {5},
7: {4, 6, 7},
}
func main() {
fmt.Println(kosaraju(g))
}
func kosaraju(g [][]int) []int {
vis := make([]bool, len(g))
L := make([]int, len(g))
x := len(L)
t := make([][]int, len(g))
var Visit func(int)
Visit = func(u int) {
if !vis[u] {
vis[u] = true
for _, v := range g[u] {
Visit(v)
t[v] = append(t[v], u)
}
x--
L[x] = u
}
}
for u := range g {
Visit(u)
}
c := make([]int, len(g))
var Assign func(int, int)
Assign = func(u, root int) {
if vis[u] {
vis[u] = false
c[u] = root
for _, v := range t[u] {
Assign(v, root)
}
}
}
for _, u := range L {
Assign(u, u)
}
return c
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.