Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the provided VB code into Go while preserving the original functionality. | Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean
Dim Total As Long, Ei As Long, i As Integer
Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double
Debug.Print "[1] ""Data set:"" ";
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
Total = Total + ObservationFrequencies(i)
Debug.Print ObservationFrequencies(i); " ";
Next i
DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)
Ei = Total / (DegreesOfFreedom + 1)
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei
Next i
p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)
Debug.Print
Debug.Print " Chi-squared test for given frequencies"
Debug.Print "X-squared ="; ChiSquared; ", ";
Debug.Print "df ="; DegreesOfFreedom; ", ";
Debug.Print "p-value = "; Format(p_value, "0.0000")
Test4DiscreteUniformDistribution = p_value > Significance
End Function
Public Sub test()
Dim O() As Variant
O = [{199809,200665,199607,200270,199649}]
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """"
O = [{522573,244456,139979,71531,21461}]
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """"
End Sub
| package main
import (
"fmt"
"math"
)
type ifctn func(float64) float64
func simpson38(f ifctn, a, b float64, n int) float64 {
h := (b - a) / float64(n)
h1 := h / 3
sum := f(a) + f(b)
for j := 3*n - 1; j > 0; j-- {
if j%3 == 0 {
sum += 2 * f(a+h1*float64(j))
} else {
sum += 3 * f(a+h1*float64(j))
}
}
return h * sum / 8
}
func gammaIncQ(a, x float64) float64 {
aa1 := a - 1
var f ifctn = func(t float64) float64 {
return math.Pow(t, aa1) * math.Exp(-t)
}
y := aa1
h := 1.5e-2
for f(y)*(x-y) > 2e-8 && y < x {
y += .4
}
if y > x {
y = x
}
return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a)))
}
func chi2ud(ds []int) float64 {
var sum, expected float64
for _, d := range ds {
expected += float64(d)
}
expected /= float64(len(ds))
for _, d := range ds {
x := float64(d) - expected
sum += x * x
}
return sum / expected
}
func chi2p(dof int, distance float64) float64 {
return gammaIncQ(.5*float64(dof), .5*distance)
}
const sigLevel = .05
func main() {
for _, dset := range [][]int{
{199809, 200665, 199607, 200270, 199649},
{522573, 244456, 139979, 71531, 21461},
} {
utest(dset)
}
}
func utest(dset []int) {
fmt.Println("Uniform distribution test")
var sum int
for _, c := range dset {
sum += c
}
fmt.Println(" dataset:", dset)
fmt.Println(" samples: ", sum)
fmt.Println(" categories: ", len(dset))
dof := len(dset) - 1
fmt.Println(" degrees of freedom: ", dof)
dist := chi2ud(dset)
fmt.Println(" chi square test statistic: ", dist)
p := chi2p(dof, dist)
fmt.Println(" p-value of test statistic: ", p)
sig := p < sigLevel
fmt.Printf(" significant at %2.0f%% level? %t\n", sigLevel*100, sig)
fmt.Println(" uniform? ", !sig, "\n")
}
|
Keep all operations the same but rewrite the snippet in Go. | Module Module1
Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String)
Dim out As New List(Of String)
Dim comma = False
While Not String.IsNullOrEmpty(s)
Dim gs = GetItem(s, depth)
Dim g = gs.Item1
s = gs.Item2
If String.IsNullOrEmpty(s) Then
Exit While
End If
out.AddRange(g)
If s(0) = "}" Then
If comma Then
Return Tuple.Create(out, s.Substring(1))
End If
Return Tuple.Create(out.Select(Function(a) "{" + a + "}").ToList(), s.Substring(1))
End If
If s(0) = "," Then
comma = True
s = s.Substring(1)
End If
End While
Return Nothing
End Function
Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String)
Dim out As New List(Of String) From {""}
While Not String.IsNullOrEmpty(s)
Dim c = s(0)
If depth > 0 AndAlso (c = "," OrElse c = "}") Then
Return Tuple.Create(out, s)
End If
If c = "{" Then
Dim x = GetGroup(s.Substring(1), depth + 1)
If Not IsNothing(x) Then
Dim tout As New List(Of String)
For Each a In out
For Each b In x.Item1
tout.Add(a + b)
Next
Next
out = tout
s = x.Item2
Continue While
End If
End If
If c = "\" AndAlso s.Length > 1 Then
c += s(1)
s = s.Substring(1)
End If
out = out.Select(Function(a) a + c).ToList()
s = s.Substring(1)
End While
Return Tuple.Create(out, s)
End Function
Sub Main()
For Each s In {
"It{{em,alic}iz,erat}e{d,}, please.",
"~/{Downloads,Pictures}/*.{jpg,gif,png}",
"{,{,gotta have{ ,\, again\, }}more }cowbell!",
"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"
}
Dim fmt = "{0}" + vbNewLine + vbTab + "{1}"
Dim parts = GetItem(s)
Dim res = String.Join(vbNewLine + vbTab, parts.Item1)
Console.WriteLine(fmt, s, res)
Next
End Sub
End Module
| package expand
type Expander interface {
Expand() []string
}
type Text string
func (t Text) Expand() []string { return []string{string(t)} }
type Alternation []Expander
func (alt Alternation) Expand() []string {
var out []string
for _, e := range alt {
out = append(out, e.Expand()...)
}
return out
}
type Sequence []Expander
func (seq Sequence) Expand() []string {
if len(seq) == 0 {
return nil
}
out := seq[0].Expand()
for _, e := range seq[1:] {
out = combine(out, e.Expand())
}
return out
}
func combine(al, bl []string) []string {
out := make([]string, 0, len(al)*len(bl))
for _, a := range al {
for _, b := range bl {
out = append(out, a+b)
}
}
return out
}
const (
escape = '\\'
altStart = '{'
altEnd = '}'
altSep = ','
)
type piT struct{ pos, cnt, depth int }
type Brace string
func Expand(s string) []string { return Brace(s).Expand() }
func (b Brace) Expand() []string { return b.Expander().Expand() }
func (b Brace) Expander() Expander {
s := string(b)
var posInfo []piT
var stack []int
removePosInfo := func(i int) {
end := len(posInfo) - 1
copy(posInfo[i:end], posInfo[i+1:])
posInfo = posInfo[:end]
}
inEscape := false
for i, r := range s {
if inEscape {
inEscape = false
continue
}
switch r {
case escape:
inEscape = true
case altStart:
stack = append(stack, len(posInfo))
posInfo = append(posInfo, piT{i, 0, len(stack)})
case altEnd:
if len(stack) == 0 {
continue
}
si := len(stack) - 1
pi := stack[si]
if posInfo[pi].cnt == 0 {
removePosInfo(pi)
for pi < len(posInfo) {
if posInfo[pi].depth == len(stack) {
removePosInfo(pi)
} else {
pi++
}
}
} else {
posInfo = append(posInfo, piT{i, -2, len(stack)})
}
stack = stack[:si]
case altSep:
if len(stack) == 0 {
continue
}
posInfo = append(posInfo, piT{i, -1, len(stack)})
posInfo[stack[len(stack)-1]].cnt++
}
}
for len(stack) > 0 {
si := len(stack) - 1
pi := stack[si]
depth := posInfo[pi].depth
removePosInfo(pi)
for pi < len(posInfo) {
if posInfo[pi].depth == depth {
removePosInfo(pi)
} else {
pi++
}
}
stack = stack[:si]
}
return buildExp(s, 0, posInfo)
}
func buildExp(s string, off int, info []piT) Expander {
if len(info) == 0 {
return Text(s)
}
var seq Sequence
i := 0
var dj, j, depth int
for dk, piK := range info {
k := piK.pos - off
switch s[k] {
case altStart:
if depth == 0 {
dj = dk
j = k
depth = piK.depth
}
case altEnd:
if piK.depth != depth {
continue
}
if j > i {
seq = append(seq, Text(s[i:j]))
}
alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])
seq = append(seq, alt)
i = k + 1
depth = 0
}
}
if j := len(s); j > i {
seq = append(seq, Text(s[i:j]))
}
if len(seq) == 1 {
return seq[0]
}
return seq
}
func buildAlt(s string, depth, off int, info []piT) Alternation {
var alt Alternation
i := 0
var di int
for dk, piK := range info {
if piK.depth != depth {
continue
}
if k := piK.pos - off; s[k] == altSep {
sub := buildExp(s[i:k], i+off, info[di:dk])
alt = append(alt, sub)
i = k + 1
di = dk + 1
}
}
sub := buildExp(s[i:], i+off, info[di:])
alt = append(alt, sub)
return alt
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. |
Function no_arguments() As String
no_arguments = "ok"
End Function
Function fixed_number(argument1 As Integer, argument2 As Integer)
fixed_number = argument1 + argument2
End Function
Function optional_parameter(Optional argument1 = 1) As Integer
optional_parameter = argument1
End Function
Function variable_number(arguments As Variant) As Integer
variable_number = UBound(arguments)
End Function
Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer
named_arguments = argument1 + argument2
End Function
Function statement() As String
Debug.Print "function called as statement"
statement = "ok"
End Function
Function return_value() As String
return_value = "ok"
End Function
Sub foo()
Debug.Print "subroutine",
End Sub
Function bar() As String
bar = "function"
End Function
Function passed_by_value(ByVal s As String) As String
s = "written over"
passed_by_value = "passed by value"
End Function
Function passed_by_reference(ByRef s As String) As String
s = "written over"
passed_by_reference = "passed by reference"
End Function
Sub no_parentheses(myargument As String)
Debug.Print myargument,
End Sub
Public Sub calling_a_function()
Debug.Print "no arguments", , no_arguments
Debug.Print "no arguments", , no_arguments()
Debug.Print "fixed_number", , fixed_number(1, 1)
Debug.Print "optional parameter", optional_parameter
Debug.Print "optional parameter", optional_parameter(2)
Debug.Print "variable number", variable_number([{"hello", "there"}])
Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1)
statement
s = "no_arguments"
Debug.Print "first-class context", Application.Run(s)
returnvalue = return_value
Debug.Print "obtained return value", returnvalue
foo
Debug.Print , bar
Dim t As String
t = "unaltered"
Debug.Print passed_by_value(t), t
Debug.Print passed_by_reference(t), t
no_parentheses "calling a subroutine"
Debug.Print "does not require parentheses"
Call no_parentheses("deprecated use")
Debug.Print "of parentheses"
End Sub
| import (
"image"
"image/gif"
"io/ioutil"
"strings"
"unicode"
)
func f() (int, float64) { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int) {}
|
Please provide an equivalent version of this VB code in Go. |
Function no_arguments() As String
no_arguments = "ok"
End Function
Function fixed_number(argument1 As Integer, argument2 As Integer)
fixed_number = argument1 + argument2
End Function
Function optional_parameter(Optional argument1 = 1) As Integer
optional_parameter = argument1
End Function
Function variable_number(arguments As Variant) As Integer
variable_number = UBound(arguments)
End Function
Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer
named_arguments = argument1 + argument2
End Function
Function statement() As String
Debug.Print "function called as statement"
statement = "ok"
End Function
Function return_value() As String
return_value = "ok"
End Function
Sub foo()
Debug.Print "subroutine",
End Sub
Function bar() As String
bar = "function"
End Function
Function passed_by_value(ByVal s As String) As String
s = "written over"
passed_by_value = "passed by value"
End Function
Function passed_by_reference(ByRef s As String) As String
s = "written over"
passed_by_reference = "passed by reference"
End Function
Sub no_parentheses(myargument As String)
Debug.Print myargument,
End Sub
Public Sub calling_a_function()
Debug.Print "no arguments", , no_arguments
Debug.Print "no arguments", , no_arguments()
Debug.Print "fixed_number", , fixed_number(1, 1)
Debug.Print "optional parameter", optional_parameter
Debug.Print "optional parameter", optional_parameter(2)
Debug.Print "variable number", variable_number([{"hello", "there"}])
Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1)
statement
s = "no_arguments"
Debug.Print "first-class context", Application.Run(s)
returnvalue = return_value
Debug.Print "obtained return value", returnvalue
foo
Debug.Print , bar
Dim t As String
t = "unaltered"
Debug.Print passed_by_value(t), t
Debug.Print passed_by_reference(t), t
no_parentheses "calling a subroutine"
Debug.Print "does not require parentheses"
Call no_parentheses("deprecated use")
Debug.Print "of parentheses"
End Sub
| import (
"image"
"image/gif"
"io/ioutil"
"strings"
"unicode"
)
func f() (int, float64) { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int) {}
|
Generate an equivalent Go version of this VB code. | VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
ClientHeight = 2265
ClientLeft = 60
ClientTop = 600
ClientWidth = 2175
LinkTopic = "Form1"
ScaleHeight = 2265
ScaleWidth = 2175
StartUpPosition = 3
Begin VB.CommandButton cmdRnd
Caption = "Random"
Height = 495
Left = 120
TabIndex = 2
Top = 1680
Width = 1215
End
Begin VB.CommandButton cmdInc
Caption = "Increment"
Height = 495
Left = 120
TabIndex = 1
Top = 1080
Width = 1215
End
Begin VB.TextBox txtValue
Height = 495
Left = 120
TabIndex = 0
Text = "0"
Top = 240
Width = 1215
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private Sub Form_Load()
Randomize Timer
End Sub
Private Sub cmdRnd_Click()
If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11)
End Sub
Private Sub cmdInc_Click()
If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1
End Sub
Private Sub txtValue_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case 8, 43, 45, 48 To 57
Case Else
KeyAscii = 0
End Select
End Sub
| 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()
}
|
Write a version of this VB function in Go with identical behavior. | Dim chosen(10)
For j = 1 To 1000000
c = one_of_n(10)
chosen(c) = chosen(c) + 1
Next
For k = 1 To 10
WScript.StdOut.WriteLine k & ". " & chosen(k)
Next
Function one_of_n(n)
Randomize
For i = 1 To n
If Rnd(1) < 1/i Then
one_of_n = i
End If
Next
End Function
| 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)
}
|
Port the provided VB code into Go while preserving the original functionality. | Private Function ordinal(s As String) As String
Dim irregs As New Collection
irregs.Add "first", "one"
irregs.Add "second", "two"
irregs.Add "third", "three"
irregs.Add "fifth", "five"
irregs.Add "eighth", "eight"
irregs.Add "ninth", "nine"
irregs.Add "twelfth", "twelve"
Dim i As Integer
For i = Len(s) To 1 Step -1
ch = Mid(s, i, 1)
If ch = " " Or ch = "-" Then Exit For
Next i
On Error GoTo 1
ord = irregs(Right(s, Len(s) - i))
ordinal = Left(s, i) & ord
Exit Function
1:
If Right(s, 1) = "y" Then
s = Left(s, Len(s) - 1) & "ieth"
Else
s = s & "th"
End If
ordinal = s
End Function
Public Sub ordinals()
tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}]
init
For i = 1 To UBound(tests)
Debug.Print ordinal(spell(tests(i)))
Next i
End Sub
| import (
"fmt"
"strings"
)
func main() {
for _, n := range []int64{
1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
} {
fmt.Println(sayOrdinal(n))
}
}
var irregularOrdinals = map[string]string{
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
func sayOrdinal(n int64) string {
s := say(n)
i := strings.LastIndexAny(s, " -")
i++
if x, ok := irregularOrdinals[s[i:]]; ok {
s = s[:i] + x
} else if s[len(s)-1] == 'y' {
s = s[:i] + s[i:len(s)-1] + "ieth"
} else {
s = s[:i] + s[i:] + "th"
}
return s
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
|
Convert the following code from VB to Go, ensuring the logic remains intact. | Function IsSelfDescribing(n)
IsSelfDescribing = False
Set digit = CreateObject("Scripting.Dictionary")
For i = 1 To Len(n)
k = Mid(n,i,1)
If digit.Exists(k) Then
digit.Item(k) = digit.Item(k) + 1
Else
digit.Add k,1
End If
Next
c = 0
For j = 0 To Len(n)-1
l = Mid(n,j+1,1)
If digit.Exists(CStr(j)) Then
If digit.Item(CStr(j)) = CInt(l) Then
c = c + 1
End If
ElseIf l = 0 Then
c = c + 1
Else
Exit For
End If
Next
If c = Len(n) Then
IsSelfDescribing = True
End If
End Function
start_time = Now
s = ""
For m = 1 To 100000000
If IsSelfDescribing(m) Then
WScript.StdOut.WriteLine m
End If
Next
end_time = Now
WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
| package main
import (
"fmt"
"strconv"
"strings"
)
func sdn(n int64) bool {
if n >= 1e10 {
return false
}
s := strconv.FormatInt(n, 10)
for d, p := range s {
if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
return false
}
}
return true
}
func main() {
for n := int64(0); n < 1e10; n++ {
if sdn(n) {
fmt.Println(n)
}
}
}
|
Convert the following code from VB to Go, ensuring the logic remains intact. | Function IsSelfDescribing(n)
IsSelfDescribing = False
Set digit = CreateObject("Scripting.Dictionary")
For i = 1 To Len(n)
k = Mid(n,i,1)
If digit.Exists(k) Then
digit.Item(k) = digit.Item(k) + 1
Else
digit.Add k,1
End If
Next
c = 0
For j = 0 To Len(n)-1
l = Mid(n,j+1,1)
If digit.Exists(CStr(j)) Then
If digit.Item(CStr(j)) = CInt(l) Then
c = c + 1
End If
ElseIf l = 0 Then
c = c + 1
Else
Exit For
End If
Next
If c = Len(n) Then
IsSelfDescribing = True
End If
End Function
start_time = Now
s = ""
For m = 1 To 100000000
If IsSelfDescribing(m) Then
WScript.StdOut.WriteLine m
End If
Next
end_time = Now
WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
| package main
import (
"fmt"
"strconv"
"strings"
)
func sdn(n int64) bool {
if n >= 1e10 {
return false
}
s := strconv.FormatInt(n, 10)
for d, p := range s {
if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
return false
}
}
return true
}
func main() {
for n := int64(0); n < 1e10; n++ {
if sdn(n) {
fmt.Println(n)
}
}
}
|
Please provide an equivalent version of this VB code in Go. | Module Module1
Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)
Dim result As New List(Of Integer) From {
n
}
result.AddRange(seq)
Return result
End Function
Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)
If pos > min_len OrElse seq(0) > n Then
Return Tuple.Create(min_len, 0)
End If
If seq(0) = n Then
Return Tuple.Create(pos, 1)
End If
If pos < min_len Then
Return TryPerm(0, pos, seq, n, min_len)
End If
Return Tuple.Create(min_len, 0)
End Function
Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)
If i > pos Then
Return Tuple.Create(min_len, 0)
End If
Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)
Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)
If res2.Item1 < res1.Item1 Then
Return res2
End If
If res2.Item1 = res1.Item1 Then
Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)
End If
Throw New Exception("TryPerm exception")
End Function
Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)
Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)
End Function
Sub FindBrauer(num As Integer)
Dim res = InitTryPerm(num)
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)
Console.WriteLine()
End Sub
Sub Main()
Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}
Array.ForEach(nums, Sub(n) FindBrauer(n))
End Sub
End Module
| 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)
}
}
|
Generate a Go translation of this VB snippet without changing its computational steps. | Private Sub Repeat(rid As String, n As Integer)
For i = 1 To n
Application.Run rid
Next i
End Sub
Private Sub Hello()
Debug.Print "Hello"
End Sub
Public Sub main()
Repeat "Hello", 5
End Sub
| 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)
}
|
Translate this program into Go but keep the logic exactly as in VB. |
sub ensure_cscript()
if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then
createobject("wscript.shell").run "CSCRIPT //nologo """ &_
WScript.ScriptFullName &"""" ,,0
wscript.quit
end if
end sub
class bargraph
private bar,mn,mx,nn,cnt
Private sub class_initialize()
bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_
chrw(&h2586)&chrw(&h2587)&chrw(&h2588)
nn=8
end sub
public function bg (s)
a=split(replace(replace(s,","," ")," "," ")," ")
mn=999999:mx=-999999:cnt=ubound(a)+1
for i=0 to ubound(a)
a(i)=cdbl(trim(a(i)))
if a(i)>mx then mx=a(i)
if a(i)<mn then mn=a(i)
next
ss="Data: "
for i=0 to ubound(a) :ss=ss & right (" "& a(i),6) :next
ss=ss+vbcrlf + "sparkline: "
for i=0 to ubound(a)
x=scale(a(i))
ss=ss & string(6,mid(bar,x,1))
next
bg=ss &vbcrlf & "min: "&mn & " max: "& mx & _
" cnt: "& ubound(a)+1 &vbcrlf
end function
private function scale(x)
if x=<mn then
scale=1
elseif x>=mx then
scale=nn
else
scale=int(nn* (x-mn)/(mx-mn)+1)
end if
end function
end class
ensure_cscript
set b=new bargraph
wscript.stdout.writeblanklines 2
wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1")
wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5")
wscript.echo b.bg("0, 1, 19, 20")
wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999")
set b=nothing
wscript.echo "If bars don
"font to DejaVu Sans Mono or any other that has the bargrph characters" & _
vbcrlf
wscript.stdout.write "Press any key.." : wscript.stdin.read 1
| package main
import (
"bufio"
"errors"
"fmt"
"math"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
fmt.Println("Numbers please separated by space/commas:")
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
s, n, min, max, err := spark(sc.Text())
if err != nil {
fmt.Println(err)
return
}
if n == 1 {
fmt.Println("1 value =", min)
} else {
fmt.Println(n, "values. Min:", min, "Max:", max)
}
fmt.Println(s)
}
var sep = regexp.MustCompile(`[\s,]+`)
func spark(s0 string) (sp string, n int, min, max float64, err error) {
ss := sep.Split(s0, -1)
n = len(ss)
vs := make([]float64, n)
var v float64
min = math.Inf(1)
max = math.Inf(-1)
for i, s := range ss {
switch v, err = strconv.ParseFloat(s, 64); {
case err != nil:
case math.IsNaN(v):
err = errors.New("NaN not supported.")
case math.IsInf(v, 0):
err = errors.New("Inf not supported.")
default:
if v < min {
min = v
}
if v > max {
max = v
}
vs[i] = v
continue
}
return
}
if min == max {
sp = strings.Repeat("▄", n)
} else {
rs := make([]rune, n)
f := 8 / (max - min)
for j, v := range vs {
i := rune(f * (v - min))
if i > 7 {
i = 7
}
rs[j] = '▁' + i
}
sp = string(rs)
}
return
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | Private Function mul_inv(a As Long, n As Long) As Variant
If n < 0 Then n = -n
If a < 0 Then a = n - ((-a) Mod n)
Dim t As Long: t = 0
Dim nt As Long: nt = 1
Dim r As Long: r = n
Dim nr As Long: nr = a
Dim q As Long
Do While nr <> 0
q = r \ nr
tmp = t
t = nt
nt = tmp - q * nt
tmp = r
r = nr
nr = tmp - q * nr
Loop
If r > 1 Then
mul_inv = "a is not invertible"
Else
If t < 0 Then t = t + n
mul_inv = t
End If
End Function
Public Sub mi()
Debug.Print mul_inv(42, 2017)
Debug.Print mul_inv(40, 1)
Debug.Print mul_inv(52, -217)
Debug.Print mul_inv(-486, 217)
Debug.Print mul_inv(40, 2018)
End Sub
| 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)
}
|
Generate an equivalent Go version of this VB code. | Class HTTPSock
Inherits TCPSocket
Event Sub DataAvailable()
Dim headers As New InternetHeaders
headers.AppendHeader("Content-Length", Str(LenB("Goodbye, World!")))
headers.AppendHeader("Content-Type", "text/plain")
headers.AppendHeader("Content-Encoding", "identity")
headers.AppendHeader("Connection", "close")
Dim data As String = "HTTP/1.1 200 OK" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + "Goodbye, World!"
Me.Write(data)
Me.Close
End Sub
End Class
Class HTTPServ
Inherits ServerSocket
Event Sub AddSocket() As TCPSocket
Return New HTTPSock
End Sub
End Class
Class App
Inherits Application
Event Sub Run(Args() As String)
Dim sock As New HTTPServ
sock.Port = 8080
sock.Listen()
While True
App.DoEvents
Wend
End Sub
End Class
| 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))
}
|
Convert this VB snippet to Go and keep its semantics consistent. | Option Strict On
Option Explicit On
Imports System.IO
Module OwnDigitsPowerSum
Public Sub Main
Dim used(9) As Integer
Dim check(9) As Integer
Dim power(9, 9) As Long
For i As Integer = 0 To 9
check(i) = 0
Next i
For i As Integer = 1 To 9
power(1, i) = i
Next i
For j As Integer = 2 To 9
For i As Integer = 1 To 9
power(j, i) = power(j - 1, i) * i
Next i
Next j
Dim lowestDigit(9) As Integer
lowestDigit(1) = -1
lowestDigit(2) = -1
Dim p10 As Long = 100
For i As Integer = 3 To 9
For p As Integer = 2 To 9
Dim np As Long = power(i, p) * i
If Not ( np < p10) Then Exit For
lowestDigit(i) = p
Next p
p10 *= 10
Next i
Dim maxZeros(9, 9) As Integer
For i As Integer = 1 To 9
For j As Integer = 1 To 9
maxZeros(i, j) = 0
Next j
Next i
p10 = 1000
For w As Integer = 3 To 9
For d As Integer = lowestDigit(w) To 9
Dim nz As Integer = 9
Do
If nz < 0 Then
Exit Do
Else
Dim np As Long = power(w, d) * nz
IF Not ( np > p10) Then Exit Do
End If
nz -= 1
Loop
maxZeros(w, d) = If(nz > w, 0, w - nz)
Next d
p10 *= 10
Next w
Dim numbers(100) As Long
Dim nCount As Integer = 0
Dim tryCount As Integer = 0
Dim digits(9) As Integer
For d As Integer = 1 To 9
digits(d) = 9
Next d
For d As Integer = 0 To 8
used(d) = 0
Next d
used(9) = 9
Dim width As Integer = 9
Dim last As Integer = width
p10 = 100000000
Do While width > 2
tryCount += 1
Dim dps As Long = 0
check(0) = used(0)
For i As Integer = 1 To 9
check(i) = used(i)
If used(i) <> 0 Then
dps += used(i) * power(width, i)
End If
Next i
Dim n As Long = dps
Do
check(CInt(n Mod 10)) -= 1
n \= 10
Loop Until n <= 0
Dim reduceWidth As Boolean = dps <= p10
If Not reduceWidth Then
Dim zCount As Integer = 0
For i As Integer = 0 To 9
If check(i) <> 0 Then Exit For
zCount+= 1
Next i
If zCount = 10 Then
nCount += 1
numbers(nCount) = dps
End If
used(digits(last)) -= 1
digits(last) -= 1
If digits(last) = 0 Then
If used(0) >= maxZeros(width, digits(1)) Then
digits(last) = -1
End If
End If
If digits(last) >= 0 Then
used(digits(last)) += 1
Else
Dim prev As Integer = last
Do
prev -= 1
If prev < 1 Then
Exit Do
Else
used(digits(prev)) -= 1
digits(prev) -= 1
IF digits(prev) >= 0 Then Exit Do
End If
Loop
If prev > 0 Then
If prev = 1 Then
If digits(1) <= lowestDigit(width) Then
prev = 0
End If
End If
If prev <> 0 Then
used(digits(prev)) += 1
For i As Integer = prev + 1 To width
digits(i) = digits(prev)
used(digits(prev)) += 1
Next i
End If
End If
If prev <= 0 Then
reduceWidth = True
End If
End If
End If
If reduceWidth Then
last -= 1
width = last
If last > 0 Then
For d As Integer = 1 To last
digits(d) = 9
Next d
For d As Integer = last + 1 To 9
digits(d) = -1
Next d
For d As Integer = 0 To 8
used(d) = 0
Next d
used(9) = last
p10 \= 10
End If
End If
Loop
Console.Out.WriteLine("Own digits power sums for N = 3 to 9 inclusive:")
For i As Integer = nCount To 1 Step -1
Console.Out.WriteLine(numbers(i))
Next i
Console.Out.WriteLine("Considered " & tryCount & " digit combinations")
End Sub
End Module
| package main
import (
"fmt"
"math"
"rcu"
)
func main() {
powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
fmt.Println("Own digits power sums for N = 3 to 9 inclusive:")
for n := 3; n < 10; n++ {
for d := 2; d < 10; d++ {
powers[d] *= d
}
i := int(math.Pow(10, float64(n-1)))
max := i * 10
lastDigit := 0
sum := 0
var digits []int
for i < max {
if lastDigit == 0 {
digits = rcu.Digits(i, 10)
sum = 0
for _, d := range digits {
sum += powers[d]
}
} else if lastDigit == 1 {
sum++
} else {
sum += powers[lastDigit] - powers[lastDigit-1]
}
if sum == i {
fmt.Println(i)
if lastDigit == 0 {
fmt.Println(i + 1)
}
i += 10 - lastDigit
lastDigit = 0
} else if sum > i {
i += 10 - lastDigit
lastDigit = 0
} else if lastDigit < 9 {
i++
lastDigit++
} else {
i++
lastDigit = 0
}
}
}
}
|
Port the provided VB code into Go while preserving the original functionality. |
Public Sub printarray(A)
For i = LBound(A) To UBound(A)
Debug.Print A(i),
Next
Debug.Print
End Sub
Public Sub Flip(ByRef A, p1, p2, trace)
If trace Then Debug.Print "we
Cut = Int((p2 - p1 + 1) / 2)
For i = 0 To Cut - 1
temp = A(i)
A(i) = A(p2 - i)
A(p2 - i) = temp
Next
End Sub
Public Sub pancakesort(ByRef A(), Optional trace As Boolean = False)
lb = LBound(A)
ub = UBound(A)
Length = ub - lb + 1
If Length <= 1 Then
Exit Sub
End If
For i = ub To lb + 1 Step -1
P = lb
Maximum = A(P)
For j = lb + 1 To i
If A(j) > Maximum Then
P = j
Maximum = A(j)
End If
Next j
If P < i Then
If P > 1 Then
Flip A, lb, P, trace
If trace Then printarray A
End If
Flip A, lb, i, trace
If trace Then printarray A
End If
Next i
End Sub
Public Sub TestPancake(Optional trace As Boolean = False)
Dim A()
A = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)
Debug.Print "Initial array:"
printarray A
pancakesort A, trace
Debug.Print "Final array:"
printarray A
End Sub
| package main
import "fmt"
func main() {
list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
list.sort()
fmt.Println("sorted! ", list)
}
type pancake []int
func (a pancake) sort() {
for uns := len(a) - 1; uns > 0; uns-- {
lx, lg := 0, a[0]
for i := 1; i <= uns; i++ {
if a[i] > lg {
lx, lg = i, a[i]
}
}
a.flip(lx)
a.flip(uns)
}
}
func (a pancake) flip(r int) {
for l := 0; l < r; l, r = l+1, r-1 {
a[l], a[r] = a[r], a[l]
}
}
|
Change the programming language of this snippet from VB to Go without modifying what it does. |
Public Sub printarray(A)
For i = LBound(A) To UBound(A)
Debug.Print A(i),
Next
Debug.Print
End Sub
Public Sub Flip(ByRef A, p1, p2, trace)
If trace Then Debug.Print "we
Cut = Int((p2 - p1 + 1) / 2)
For i = 0 To Cut - 1
temp = A(i)
A(i) = A(p2 - i)
A(p2 - i) = temp
Next
End Sub
Public Sub pancakesort(ByRef A(), Optional trace As Boolean = False)
lb = LBound(A)
ub = UBound(A)
Length = ub - lb + 1
If Length <= 1 Then
Exit Sub
End If
For i = ub To lb + 1 Step -1
P = lb
Maximum = A(P)
For j = lb + 1 To i
If A(j) > Maximum Then
P = j
Maximum = A(j)
End If
Next j
If P < i Then
If P > 1 Then
Flip A, lb, P, trace
If trace Then printarray A
End If
Flip A, lb, i, trace
If trace Then printarray A
End If
Next i
End Sub
Public Sub TestPancake(Optional trace As Boolean = False)
Dim A()
A = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)
Debug.Print "Initial array:"
printarray A
pancakesort A, trace
Debug.Print "Final array:"
printarray A
End Sub
| package main
import "fmt"
func main() {
list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
list.sort()
fmt.Println("sorted! ", list)
}
type pancake []int
func (a pancake) sort() {
for uns := len(a) - 1; uns > 0; uns-- {
lx, lg := 0, a[0]
for i := 1; i <= uns; i++ {
if a[i] > lg {
lx, lg = i, a[i]
}
}
a.flip(lx)
a.flip(uns)
}
}
func (a pancake) flip(r int) {
for l := 0; l < r; l, r = l+1, r-1 {
a[l], a[r] = a[r], a[l]
}
}
|
Write the same code in Go as shown below in VB. | Module Module1
Dim atomicMass As New Dictionary(Of String, Double) From {
{"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.63},
{"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.9055},
{"Pd", 106.42},
{"Ag", 107.8682},
{"Cd", 112.414},
{"In", 114.818},
{"Sn", 118.71},
{"Sb", 121.76},
{"Te", 127.6},
{"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.5},
{"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.9804},
{"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}
}
Function Evaluate(s As String) As Double
s += "["
Dim sum = 0.0
Dim symbol = ""
Dim number = ""
For i = 1 To s.Length
Dim c = s(i - 1)
If "@" <= c AndAlso c <= "[" Then
Dim n = 1
If number <> "" Then
n = Integer.Parse(number)
End If
If symbol <> "" Then
sum += atomicMass(symbol) * n
End If
If c = "[" Then
Exit For
End If
symbol = c.ToString
number = ""
ElseIf "a" <= c AndAlso c <= "z" Then
symbol += c
ElseIf "0" <= c AndAlso c <= "9" Then
number += c
Else
Throw New Exception(String.Format("Unexpected symbol {0} in molecule", c))
End If
Next
Return sum
End Function
Function ReplaceFirst(text As String, search As String, replace As String) As String
Dim pos = text.IndexOf(search)
If pos < 0 Then
Return text
Else
Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)
End If
End Function
Function ReplaceParens(s As String) As String
Dim letter = "s"c
While True
Dim start = s.IndexOf("(")
If start = -1 Then
Exit While
End If
For i = start + 1 To s.Length - 1
If s(i) = ")" Then
Dim expr = s.Substring(start + 1, i - start - 1)
Dim symbol = String.Format("@{0}", letter)
s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)
atomicMass(symbol) = Evaluate(expr)
letter = Chr(Asc(letter) + 1)
Exit For
End If
If s(i) = "(" Then
start = i
Continue For
End If
Next
End While
Return s
End Function
Sub Main()
Dim molecules() As String = {
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12",
"COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue"
}
For Each molecule In molecules
Dim mass = Evaluate(ReplaceParens(molecule))
Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass)
Next
End Sub
End Module
| 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. | Module Module1
Dim atomicMass As New Dictionary(Of String, Double) From {
{"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.63},
{"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.9055},
{"Pd", 106.42},
{"Ag", 107.8682},
{"Cd", 112.414},
{"In", 114.818},
{"Sn", 118.71},
{"Sb", 121.76},
{"Te", 127.6},
{"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.5},
{"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.9804},
{"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}
}
Function Evaluate(s As String) As Double
s += "["
Dim sum = 0.0
Dim symbol = ""
Dim number = ""
For i = 1 To s.Length
Dim c = s(i - 1)
If "@" <= c AndAlso c <= "[" Then
Dim n = 1
If number <> "" Then
n = Integer.Parse(number)
End If
If symbol <> "" Then
sum += atomicMass(symbol) * n
End If
If c = "[" Then
Exit For
End If
symbol = c.ToString
number = ""
ElseIf "a" <= c AndAlso c <= "z" Then
symbol += c
ElseIf "0" <= c AndAlso c <= "9" Then
number += c
Else
Throw New Exception(String.Format("Unexpected symbol {0} in molecule", c))
End If
Next
Return sum
End Function
Function ReplaceFirst(text As String, search As String, replace As String) As String
Dim pos = text.IndexOf(search)
If pos < 0 Then
Return text
Else
Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)
End If
End Function
Function ReplaceParens(s As String) As String
Dim letter = "s"c
While True
Dim start = s.IndexOf("(")
If start = -1 Then
Exit While
End If
For i = start + 1 To s.Length - 1
If s(i) = ")" Then
Dim expr = s.Substring(start + 1, i - start - 1)
Dim symbol = String.Format("@{0}", letter)
s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol)
atomicMass(symbol) = Evaluate(expr)
letter = Chr(Asc(letter) + 1)
Exit For
End If
If s(i) = "(" Then
start = i
Continue For
End If
Next
End While
Return s
End Function
Sub Main()
Dim molecules() As String = {
"H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12",
"COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue"
}
For Each molecule In molecules
Dim mass = Evaluate(ReplaceParens(molecule))
Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass)
Next
End Sub
End Module
| 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)
}
}
|
Translate this program into Go but keep the logic exactly as in VB. | Const n = 2200
Public Sub pq()
Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3
Dim l(n) As Boolean, l_add(9680000) As Boolean
For x = 1 To n
x2 = x * x
For y = x To n
l_add(x2 + y * y) = True
Next y
Next x
For x = 1 To n
s1 = s
s = s + 2
s2 = s
For y = x + 1 To n
If l_add(s1) Then l(y) = True
s1 = s1 + s2
s2 = s2 + 2
Next
Next
For x = 1 To n
If Not l(x) Then Debug.Print x;
Next
Debug.Print
End Sub
| 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()
}
|
Write the same code in Go as shown below in VB. | Option Explicit
Randomize Timer
Function pad(s,n)
If n<0 Then pad= right(space(-n) & s ,-n) Else pad= left(s& space(n),n) End If
End Function
Sub print(s)
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
Function Rounds(maxsecs,wiz,a)
Dim mystep,maxstep,toend,j,i,x,d
If IsArray(a) Then d=True: print "seconds behind pending"
maxstep=100
For j=1 To maxsecs
For i=1 To wiz
If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1
maxstep=maxstep+1
Next
mystep=mystep+1
If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function
If d Then
If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)
End If
Next
Rounds=Array(maxsecs,maxstep)
End Function
Dim n,r,a,sumt,sums,ntests,t,maxsecs
ntests=10000
maxsecs=7000
t=timer
a=Array(600,609)
For n=1 To ntests
r=Rounds(maxsecs,5,a)
If r(0)<>maxsecs Then
sumt=sumt+r(0)
sums=sums+r(1)
End if
a=""
Next
print vbcrlf & "Done " & ntests & " tests in " & Timer-t & " seconds"
print "escaped in " & sumt/ntests & " seconds with " & sums/ntests & " stairs"
| package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
totalSecs := 0
totalSteps := 0
fmt.Println("Seconds steps behind steps ahead")
fmt.Println("------- ------------ -----------")
for trial := 1; trial < 10000; trial++ {
sbeh := 0
slen := 100
secs := 0
for sbeh < slen {
sbeh++
for wiz := 1; wiz < 6; wiz++ {
if rand.Intn(slen) < sbeh {
sbeh++
}
slen++
}
secs++
if trial == 1 && secs > 599 && secs < 610 {
fmt.Printf("%d %d %d\n", secs, sbeh, slen-sbeh)
}
}
totalSecs += secs
totalSteps += slen
}
fmt.Println("\nAverage secs taken:", float64(totalSecs)/10000)
fmt.Println("Average final length of staircase:", float64(totalSteps)/10000)
}
|
Please provide an equivalent version of this VB code in Go. | Option Explicit
Dim seed As Long
Sub Main()
Dim i As Integer
seed = 675248
For i = 1 To 5
Debug.Print Rand
Next i
End Sub
Function Rand() As Variant
Dim s As String
s = CStr(seed ^ 2)
Do While Len(s) <> 12
s = "0" + s
Loop
seed = Val(Mid(s, 4, 6))
Rand = seed
End Function
| package main
import "fmt"
func random(seed int) int {
return seed * seed / 1e3 % 1e6
}
func main() {
seed := 675248
for i := 1; i <= 5; i++ {
seed = random(seed)
fmt.Println(seed)
}
}
|
Please provide an equivalent version of this VB code in Go. | Option Explicit
Dim seed As Long
Sub Main()
Dim i As Integer
seed = 675248
For i = 1 To 5
Debug.Print Rand
Next i
End Sub
Function Rand() As Variant
Dim s As String
s = CStr(seed ^ 2)
Do While Len(s) <> 12
s = "0" + s
Loop
seed = Val(Mid(s, 4, 6))
Rand = seed
End Function
| package main
import "fmt"
func random(seed int) int {
return seed * seed / 1e3 % 1e6
}
func main() {
seed := 675248
for i := 1; i <= 5; i++ {
seed = random(seed)
fmt.Println(seed)
}
}
|
Generate a Go translation of this VB snippet without changing its computational steps. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objParamLookup = CreateObject("Scripting.Dictionary")
With objParamLookup
.Add "FAVOURITEFRUIT", "banana"
.Add "NEEDSPEELING", ""
.Add "SEEDSREMOVED", ""
.Add "NUMBEROFBANANAS", "1024"
.Add "NUMBEROFSTRAWBERRIES", "62000"
End With
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\IN_config.txt",1)
Output = ""
Isnumberofstrawberries = False
With objInFile
Do Until .AtEndOfStream
line = .ReadLine
If Left(line,1) = "#" Or line = "" Then
Output = Output & line & vbCrLf
ElseIf Left(line,1) = " " And InStr(line,"#") Then
Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf
ElseIf Replace(Replace(line,";","")," ","") <> "" Then
If InStr(1,line,"FAVOURITEFRUIT",1) Then
Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf
ElseIf InStr(1,line,"NEEDSPEELING",1) Then
Output = Output & "; " & "NEEDSPEELING" & vbCrLf
ElseIf InStr(1,line,"SEEDSREMOVED",1) Then
Output = Output & "SEEDSREMOVED" & vbCrLf
ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then
Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf
ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then
Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf
Isnumberofstrawberries = True
End If
End If
Loop
If Isnumberofstrawberries = False Then
Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf
Isnumberofstrawberries = True
End If
.Close
End With
Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\OUT_config.txt",2,True)
With objOutFile
.Write Output
.Close
End With
Set objFSO = Nothing
Set objParamLookup = Nothing
| package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
type line struct {
kind lineKind
option string
value string
disabled bool
}
type lineKind int
const (
_ lineKind = iota
ignore
parseError
comment
blank
value
)
func (l line) String() string {
switch l.kind {
case ignore, parseError, comment, blank:
return l.value
case value:
s := l.option
if l.disabled {
s = "; " + s
}
if l.value != "" {
s += " " + l.value
}
return s
}
panic("unexpected line kind")
}
func removeDross(s string) string {
return strings.Map(func(r rune) rune {
if r < 32 || r > 0x7f || unicode.IsControl(r) {
return -1
}
return r
}, s)
}
func parseLine(s string) line {
if s == "" {
return line{kind: blank}
}
if s[0] == '#' {
return line{kind: comment, value: s}
}
s = removeDross(s)
fields := strings.Fields(s)
if len(fields) == 0 {
return line{kind: blank}
}
semi := false
for len(fields[0]) > 0 && fields[0][0] == ';' {
semi = true
fields[0] = fields[0][1:]
}
if fields[0] == "" {
fields = fields[1:]
}
switch len(fields) {
case 0:
return line{kind: ignore}
case 1:
return line{
kind: value,
option: strings.ToUpper(fields[0]),
disabled: semi,
}
case 2:
return line{
kind: value,
option: strings.ToUpper(fields[0]),
value: fields[1],
disabled: semi,
}
}
return line{kind: parseError, value: s}
}
type Config struct {
options map[string]int
lines []line
}
func (c *Config) index(option string) int {
if i, ok := c.options[option]; ok {
return i
}
return -1
}
func (c *Config) addLine(l line) {
switch l.kind {
case ignore:
return
case value:
if c.index(l.option) >= 0 {
return
}
c.options[l.option] = len(c.lines)
c.lines = append(c.lines, l)
default:
c.lines = append(c.lines, l)
}
}
func ReadConfig(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r := bufio.NewReader(f)
c := &Config{options: make(map[string]int)}
for {
s, err := r.ReadString('\n')
if s != "" {
if err == nil {
s = s[:len(s)-1]
}
c.addLine(parseLine(s))
}
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
}
return c, nil
}
func (c *Config) Set(option string, val string) {
if i := c.index(option); i >= 0 {
line := &c.lines[i]
line.disabled = false
line.value = val
return
}
c.addLine(line{
kind: value,
option: option,
value: val,
})
}
func (c *Config) Enable(option string, enabled bool) {
if i := c.index(option); i >= 0 {
c.lines[i].disabled = !enabled
}
}
func (c *Config) Write(w io.Writer) {
for _, line := range c.lines {
fmt.Println(line)
}
}
func main() {
c, err := ReadConfig("/tmp/cfg")
if err != nil {
log.Fatalln(err)
}
c.Enable("NEEDSPEELING", false)
c.Set("SEEDSREMOVED", "")
c.Set("NUMBEROFBANANAS", "1024")
c.Set("NUMBEROFSTRAWBERRIES", "62000")
c.Write(os.Stdout)
}
|
Port the provided VB code into Go while preserving the original functionality. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objParamLookup = CreateObject("Scripting.Dictionary")
With objParamLookup
.Add "FAVOURITEFRUIT", "banana"
.Add "NEEDSPEELING", ""
.Add "SEEDSREMOVED", ""
.Add "NUMBEROFBANANAS", "1024"
.Add "NUMBEROFSTRAWBERRIES", "62000"
End With
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\IN_config.txt",1)
Output = ""
Isnumberofstrawberries = False
With objInFile
Do Until .AtEndOfStream
line = .ReadLine
If Left(line,1) = "#" Or line = "" Then
Output = Output & line & vbCrLf
ElseIf Left(line,1) = " " And InStr(line,"#") Then
Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf
ElseIf Replace(Replace(line,";","")," ","") <> "" Then
If InStr(1,line,"FAVOURITEFRUIT",1) Then
Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf
ElseIf InStr(1,line,"NEEDSPEELING",1) Then
Output = Output & "; " & "NEEDSPEELING" & vbCrLf
ElseIf InStr(1,line,"SEEDSREMOVED",1) Then
Output = Output & "SEEDSREMOVED" & vbCrLf
ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then
Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf
ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then
Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf
Isnumberofstrawberries = True
End If
End If
Loop
If Isnumberofstrawberries = False Then
Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf
Isnumberofstrawberries = True
End If
.Close
End With
Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\OUT_config.txt",2,True)
With objOutFile
.Write Output
.Close
End With
Set objFSO = Nothing
Set objParamLookup = Nothing
| package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
type line struct {
kind lineKind
option string
value string
disabled bool
}
type lineKind int
const (
_ lineKind = iota
ignore
parseError
comment
blank
value
)
func (l line) String() string {
switch l.kind {
case ignore, parseError, comment, blank:
return l.value
case value:
s := l.option
if l.disabled {
s = "; " + s
}
if l.value != "" {
s += " " + l.value
}
return s
}
panic("unexpected line kind")
}
func removeDross(s string) string {
return strings.Map(func(r rune) rune {
if r < 32 || r > 0x7f || unicode.IsControl(r) {
return -1
}
return r
}, s)
}
func parseLine(s string) line {
if s == "" {
return line{kind: blank}
}
if s[0] == '#' {
return line{kind: comment, value: s}
}
s = removeDross(s)
fields := strings.Fields(s)
if len(fields) == 0 {
return line{kind: blank}
}
semi := false
for len(fields[0]) > 0 && fields[0][0] == ';' {
semi = true
fields[0] = fields[0][1:]
}
if fields[0] == "" {
fields = fields[1:]
}
switch len(fields) {
case 0:
return line{kind: ignore}
case 1:
return line{
kind: value,
option: strings.ToUpper(fields[0]),
disabled: semi,
}
case 2:
return line{
kind: value,
option: strings.ToUpper(fields[0]),
value: fields[1],
disabled: semi,
}
}
return line{kind: parseError, value: s}
}
type Config struct {
options map[string]int
lines []line
}
func (c *Config) index(option string) int {
if i, ok := c.options[option]; ok {
return i
}
return -1
}
func (c *Config) addLine(l line) {
switch l.kind {
case ignore:
return
case value:
if c.index(l.option) >= 0 {
return
}
c.options[l.option] = len(c.lines)
c.lines = append(c.lines, l)
default:
c.lines = append(c.lines, l)
}
}
func ReadConfig(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
r := bufio.NewReader(f)
c := &Config{options: make(map[string]int)}
for {
s, err := r.ReadString('\n')
if s != "" {
if err == nil {
s = s[:len(s)-1]
}
c.addLine(parseLine(s))
}
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
}
return c, nil
}
func (c *Config) Set(option string, val string) {
if i := c.index(option); i >= 0 {
line := &c.lines[i]
line.disabled = false
line.value = val
return
}
c.addLine(line{
kind: value,
option: option,
value: val,
})
}
func (c *Config) Enable(option string, enabled bool) {
if i := c.index(option); i >= 0 {
c.lines[i].disabled = !enabled
}
}
func (c *Config) Write(w io.Writer) {
for _, line := range c.lines {
fmt.Println(line)
}
}
func main() {
c, err := ReadConfig("/tmp/cfg")
if err != nil {
log.Fatalln(err)
}
c.Enable("NEEDSPEELING", false)
c.Set("SEEDSREMOVED", "")
c.Set("NUMBEROFBANANAS", "1024")
c.Set("NUMBEROFSTRAWBERRIES", "62000")
c.Write(os.Stdout)
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | Option Base 1
Public Enum attr
Colour = 1
Nationality
Beverage
Smoke
Pet
End Enum
Public Enum Drinks_
Beer = 1
Coffee
Milk
Tea
Water
End Enum
Public Enum nations
Danish = 1
English
German
Norwegian
Swedish
End Enum
Public Enum colors
Blue = 1
Green
Red
White
Yellow
End Enum
Public Enum tobaccos
Blend = 1
BlueMaster
Dunhill
PallMall
Prince
End Enum
Public Enum animals
Bird = 1
Cat
Dog
Horse
Zebra
End Enum
Public permutation As New Collection
Public perm(5) As Variant
Const factorial5 = 120
Public Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant
Private Sub generate(n As Integer, A As Variant)
If n = 1 Then
permutation.Add A
Else
For i = 1 To n
generate n - 1, A
If n Mod 2 = 0 Then
tmp = A(i)
A(i) = A(n)
A(n) = tmp
Else
tmp = A(1)
A(1) = A(n)
A(n) = tmp
End If
Next i
End If
End Sub
Function house(i As Integer, name As Variant) As Integer
Dim x As Integer
For x = 1 To 5
If perm(i)(x) = name Then
house = x
Exit For
End If
Next x
End Function
Function left_of(h1 As Integer, h2 As Integer) As Boolean
left_of = (h1 - h2) = -1
End Function
Function next_to(h1 As Integer, h2 As Integer) As Boolean
next_to = Abs(h1 - h2) = 1
End Function
Private Sub print_house(i As Integer)
Debug.Print i & ": "; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _
Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i))
End Sub
Public Sub Zebra_puzzle()
Colours = [{"blue","green","red","white","yellow"}]
Nationalities = [{"Dane","English","German","Norwegian","Swede"}]
Drinks = [{"beer","coffee","milk","tea","water"}]
Smokes = [{"Blend","Blue Master","Dunhill","Pall Mall","Prince"}]
Pets = [{"birds","cats","dog","horse","zebra"}]
Dim solperms As New Collection
Dim solutions As Integer
Dim b(5) As Integer, i As Integer
For i = 1 To 5: b(i) = i: Next i
generate 5, b
For c = 1 To factorial5
perm(Colour) = permutation(c)
If left_of(house(Colour, Green), house(Colour, White)) Then
For n = 1 To factorial5
perm(Nationality) = permutation(n)
If house(Nationality, Norwegian) = 1 _
And house(Nationality, English) = house(Colour, Red) _
And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then
For d = 1 To factorial5
perm(Beverage) = permutation(d)
If house(Nationality, Danish) = house(Beverage, Tea) _
And house(Beverage, Coffee) = house(Colour, Green) _
And house(Beverage, Milk) = 3 Then
For s = 1 To factorial5
perm(Smoke) = permutation(s)
If house(Colour, Yellow) = house(Smoke, Dunhill) _
And house(Nationality, German) = house(Smoke, Prince) _
And house(Smoke, BlueMaster) = house(Beverage, Beer) _
And next_to(house(Beverage, Water), house(Smoke, Blend)) Then
For p = 1 To factorial5
perm(Pet) = permutation(p)
If house(Nationality, Swedish) = house(Pet, Dog) _
And house(Smoke, PallMall) = house(Pet, Bird) _
And next_to(house(Smoke, Blend), house(Pet, Cat)) _
And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then
For i = 1 To 5
print_house i
Next i
Debug.Print
solutions = solutions + 1
solperms.Add perm
End If
Next p
End If
Next s
End If
Next d
End If
Next n
End If
Next c
Debug.Print Format(solutions, "@"); " solution" & IIf(solutions > 1, "s", "") & " found"
For i = 1 To solperms.Count
For j = 1 To 5
perm(j) = solperms(i)(j)
Next j
Debug.Print "The " & Nationalities(perm(Nationality)(house(Pet, Zebra))) & " owns the Zebra"
Next i
End Sub
| 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)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the VB version. | Set http= CreateObject("WinHttp.WinHttpRequest.5.1")
Set oDic = WScript.CreateObject("scripting.dictionary")
start="https://rosettacode.org"
Const lang="VBScript"
Dim oHF
gettaskslist "about:/wiki/Category:Programming_Tasks" ,True
print odic.Count
gettaskslist "about:/wiki/Category:Draft_Programming_Tasks",True
print "total tasks " & odic.Count
gettaskslist "about:/wiki/Category:"&lang,False
print "total tasks not in " & lang & " " &odic.Count & vbcrlf
For Each d In odic.keys
print d &vbTab & Replace(odic(d),"about:", start)
next
WScript.Quit(1)
Sub print(s):
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.echo " Please run this script with CScript": WScript.quit
End Sub
Function getpage(name)
Set oHF=Nothing
Set oHF = CreateObject("HTMLFILE")
http.open "GET",name,False
http.send
oHF.write "<html><body></body></html>"
oHF.body.innerHTML = http.responsetext
Set getpage=Nothing
End Function
Sub gettaskslist(b,build)
nextpage=b
While nextpage <>""
nextpage=Replace(nextpage,"about:", start)
WScript.Echo nextpage
getpage(nextpage)
Set xtoc = oHF.getElementbyId("mw-pages")
nextpage=""
For Each ch In xtoc.children
If ch.innertext= "next page" Then
nextpage=ch.attributes("href").value
ElseIf ch.attributes("class").value="mw-content-ltr" Then
Set ytoc=ch.children(0)
Exit For
End If
Next
For Each ch1 In ytoc.children
For Each ch2 In ch1.children(1).children
Set ch=ch2.children(0)
If build Then
odic.Add ch.innertext , ch.attributes("href").value
else
odic.Remove ch.innertext
End if
Next
Next
Wend
End Sub
| 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)
}
}
|
Convert this VB block to Go, preserving its control flow and logic. | Set http= CreateObject("WinHttp.WinHttpRequest.5.1")
Set oDic = WScript.CreateObject("scripting.dictionary")
start="https://rosettacode.org"
Const lang="VBScript"
Dim oHF
gettaskslist "about:/wiki/Category:Programming_Tasks" ,True
print odic.Count
gettaskslist "about:/wiki/Category:Draft_Programming_Tasks",True
print "total tasks " & odic.Count
gettaskslist "about:/wiki/Category:"&lang,False
print "total tasks not in " & lang & " " &odic.Count & vbcrlf
For Each d In odic.keys
print d &vbTab & Replace(odic(d),"about:", start)
next
WScript.Quit(1)
Sub print(s):
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.echo " Please run this script with CScript": WScript.quit
End Sub
Function getpage(name)
Set oHF=Nothing
Set oHF = CreateObject("HTMLFILE")
http.open "GET",name,False
http.send
oHF.write "<html><body></body></html>"
oHF.body.innerHTML = http.responsetext
Set getpage=Nothing
End Function
Sub gettaskslist(b,build)
nextpage=b
While nextpage <>""
nextpage=Replace(nextpage,"about:", start)
WScript.Echo nextpage
getpage(nextpage)
Set xtoc = oHF.getElementbyId("mw-pages")
nextpage=""
For Each ch In xtoc.children
If ch.innertext= "next page" Then
nextpage=ch.attributes("href").value
ElseIf ch.attributes("class").value="mw-content-ltr" Then
Set ytoc=ch.children(0)
Exit For
End If
Next
For Each ch1 In ytoc.children
For Each ch2 In ch1.children(1).children
Set ch=ch2.children(0)
If build Then
odic.Add ch.innertext , ch.attributes("href").value
else
odic.Remove ch.innertext
End if
Next
Next
Wend
End Sub
| 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)
}
}
|
Generate a Go translation of this VB snippet without changing its computational steps. | Imports System, BI = System.Numerics.BigInteger, System.Console
Module Module1
Function isqrt(ByVal x As BI) As BI
Dim t As BI, q As BI = 1, r As BI = 0
While q <= x : q <<= 2 : End While
While q > 1 : q >>= 2 : t = x - r - q : r >>= 1
If t >= 0 Then x = t : r += q
End While : Return r
End Function
Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String
digs += 1
Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb
Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1
For n As BI = 0 To dg - 1
If n > 0 Then t3 = t3 * BI.Pow(n, 6)
te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6
If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)
If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t)
su += te : If te < 10 Then
digs -= 1
If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _
"after the decimal point." & vbLf, n, digs)
Exit For
End If
For j As BI = n * 6 + 1 To n * 6 + 6
t1 = t1 * j : Next
d += 2 : t2 += 126 + 532 * d
Next
Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _
/ su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))
Return s(0) & "." & s.Substring(1, digs)
End Function
Sub Main(ByVal args As String())
WriteLine(dump(70, true))
End Sub
End Module
| 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))
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | Imports System, BI = System.Numerics.BigInteger, System.Console
Module Module1
Function isqrt(ByVal x As BI) As BI
Dim t As BI, q As BI = 1, r As BI = 0
While q <= x : q <<= 2 : End While
While q > 1 : q >>= 2 : t = x - r - q : r >>= 1
If t >= 0 Then x = t : r += q
End While : Return r
End Function
Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String
digs += 1
Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb
Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1
For n As BI = 0 To dg - 1
If n > 0 Then t3 = t3 * BI.Pow(n, 6)
te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6
If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)
If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t)
su += te : If te < 10 Then
digs -= 1
If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _
"after the decimal point." & vbLf, n, digs)
Exit For
End If
For j As BI = n * 6 + 1 To n * 6 + 6
t1 = t1 * j : Next
d += 2 : t2 += 126 + 532 * d
Next
Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _
/ su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))
Return s(0) & "." & s.Substring(1, digs)
End Function
Sub Main(ByVal args As String())
WriteLine(dump(70, true))
End Sub
End Module
| 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))
}
|
Write the same code in Go as shown below in VB. | Imports System, BI = System.Numerics.BigInteger, System.Console
Module Module1
Function isqrt(ByVal x As BI) As BI
Dim t As BI, q As BI = 1, r As BI = 0
While q <= x : q <<= 2 : End While
While q > 1 : q >>= 2 : t = x - r - q : r >>= 1
If t >= 0 Then x = t : r += q
End While : Return r
End Function
Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String
digs += 1
Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb
Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1
For n As BI = 0 To dg - 1
If n > 0 Then t3 = t3 * BI.Pow(n, 6)
te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6
If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)
If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t)
su += te : If te < 10 Then
digs -= 1
If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _
"after the decimal point." & vbLf, n, digs)
Exit For
End If
For j As BI = n * 6 + 1 To n * 6 + 6
t1 = t1 * j : Next
d += 2 : t2 += 126 + 532 * d
Next
Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _
/ su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))
Return s(0) & "." & s.Substring(1, digs)
End Function
Sub Main(ByVal args As String())
WriteLine(dump(70, true))
End Sub
End Module
| 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))
}
|
Preserve the algorithm and functionality while converting the code from VB to Go. | Imports System.Collections.Generic, System.Linq, System.Console
Module Module1
Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean
If n <= 0 Then Return False Else If f.Contains(n) Then Return True
Select Case n.CompareTo(f.Sum())
Case 1 : Return False : Case 0 : Return True
Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0)
rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)
End Select : Return true
End Function
Function ip(ByVal n As Integer) As Boolean
Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()
Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))
End Function
Sub Main()
Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m
If ip(i) OrElse i = 1 Then c += 1 : Write("{0,3} {1}", i, If(c Mod 10 = 0, vbLf, ""))
i += If(i = 1, 1, 2) : End While
Write(vbLf & "Found {0} practical numbers between 1 and {1} inclusive." & vbLf, c, m)
Do : m = If(m < 500, m << 1, m * 10 + 6)
Write(vbLf & "{0,5} is a{1}practical number.", m, If(ip(m), " ", "n im")) : Loop While m < 1e4
End Sub
End Module
| 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))
}
|
Translate this program into Go but keep the logic exactly as in VB. | Module Module1
ReadOnly Dirs As Integer(,) = {
{1, 0}, {0, 1}, {1, 1},
{1, -1}, {-1, 0},
{0, -1}, {-1, -1}, {-1, 1}
}
Const RowCount = 10
Const ColCount = 10
Const GridSize = RowCount * ColCount
Const MinWords = 25
Class Grid
Public cells(RowCount - 1, ColCount - 1) As Char
Public solutions As New List(Of String)
Public numAttempts As Integer
Sub New()
For i = 0 To RowCount - 1
For j = 0 To ColCount - 1
cells(i, j) = ControlChars.NullChar
Next
Next
End Sub
End Class
Dim Rand As New Random()
Sub Main()
PrintResult(CreateWordSearch(ReadWords("unixdict.txt")))
End Sub
Function ReadWords(filename As String) As List(Of String)
Dim maxlen = Math.Max(RowCount, ColCount)
Dim words As New List(Of String)
Dim objReader As New IO.StreamReader(filename)
Dim line As String
Do While objReader.Peek() <> -1
line = objReader.ReadLine()
If line.Length > 3 And line.Length < maxlen Then
If line.All(Function(c) Char.IsLetter(c)) Then
words.Add(line)
End If
End If
Loop
Return words
End Function
Function CreateWordSearch(words As List(Of String)) As Grid
For numAttempts = 1 To 1000
Shuffle(words)
Dim grid As New Grid()
Dim messageLen = PlaceMessage(grid, "Rosetta Code")
Dim target = GridSize - messageLen
Dim cellsFilled = 0
For Each word In words
cellsFilled = cellsFilled + TryPlaceWord(grid, word)
If cellsFilled = target Then
If grid.solutions.Count >= MinWords Then
grid.numAttempts = numAttempts
Return grid
Else
Exit For
End If
End If
Next
Next
Return Nothing
End Function
Function PlaceMessage(grid As Grid, msg As String) As Integer
msg = msg.ToUpper()
msg = msg.Replace(" ", "")
If msg.Length > 0 And msg.Length < GridSize Then
Dim gapSize As Integer = GridSize / msg.Length
Dim pos = 0
Dim lastPos = -1
For i = 0 To msg.Length - 1
If i = 0 Then
pos = pos + Rand.Next(gapSize - 1)
Else
pos = pos + Rand.Next(2, gapSize - 1)
End If
Dim r As Integer = Math.Floor(pos / ColCount)
Dim c = pos Mod ColCount
grid.cells(r, c) = msg(i)
lastPos = pos
Next
Return msg.Length
End If
Return 0
End Function
Function TryPlaceWord(grid As Grid, word As String) As Integer
Dim randDir = Rand.Next(Dirs.GetLength(0))
Dim randPos = Rand.Next(GridSize)
For d = 0 To Dirs.GetLength(0) - 1
Dim dd = (d + randDir) Mod Dirs.GetLength(0)
For p = 0 To GridSize - 1
Dim pp = (p + randPos) Mod GridSize
Dim lettersPLaced = TryLocation(grid, word, dd, pp)
If lettersPLaced > 0 Then
Return lettersPLaced
End If
Next
Next
Return 0
End Function
Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer
Dim r As Integer = pos / ColCount
Dim c = pos Mod ColCount
Dim len = word.Length
If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then
Return 0
End If
If r = RowCount OrElse c = ColCount Then
Return 0
End If
Dim rr = r
Dim cc = c
For i = 0 To len - 1
If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then
Return 0
End If
cc = cc + Dirs(dir, 0)
rr = rr + Dirs(dir, 1)
Next
Dim overlaps = 0
rr = r
cc = c
For i = 0 To len - 1
If grid.cells(rr, cc) = word(i) Then
overlaps = overlaps + 1
Else
grid.cells(rr, cc) = word(i)
End If
If i < len - 1 Then
cc = cc + Dirs(dir, 0)
rr = rr + Dirs(dir, 1)
End If
Next
Dim lettersPlaced = len - overlaps
If lettersPlaced > 0 Then
grid.solutions.Add(String.Format("{0,-10} ({1},{2})({3},{4})", word, c, r, cc, rr))
End If
Return lettersPlaced
End Function
Sub PrintResult(grid As Grid)
If IsNothing(grid) OrElse grid.numAttempts = 0 Then
Console.WriteLine("No grid to display")
Return
End If
Console.WriteLine("Attempts: {0}", grid.numAttempts)
Console.WriteLine("Number of words: {0}", GridSize)
Console.WriteLine()
Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9")
For r = 0 To RowCount - 1
Console.WriteLine()
Console.Write("{0} ", r)
For c = 0 To ColCount - 1
Console.Write(" {0} ", grid.cells(r, c))
Next
Next
Console.WriteLine()
Console.WriteLine()
For i = 0 To grid.solutions.Count - 1
If i Mod 2 = 0 Then
Console.Write("{0}", grid.solutions(i))
Else
Console.WriteLine(" {0}", grid.solutions(i))
End If
Next
Console.WriteLine()
End Sub
Sub Shuffle(Of T)(list As IList(Of T))
Dim r As Random = New Random()
For i = 0 To list.Count - 1
Dim index As Integer = r.Next(i, list.Count)
If i <> index Then
Dim temp As T = list(i)
list(i) = list(index)
list(index) = temp
End If
Next
End Sub
End Module
| 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)))
}
|
Produce a functionally identical Go code for the snippet given in VB. | Imports System.Reflection
Public Class MyClazz
Private answer As Integer = 42
End Class
Public Class Program
Public Shared Sub Main()
Dim myInstance = New MyClazz()
Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)
Dim answer = fieldInfo.GetValue(myInstance)
Console.WriteLine(answer)
End Sub
End Class
| 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 algorithm in Go as shown in this VB implementation. | Imports System.Reflection
Public Class MyClazz
Private answer As Integer = 42
End Class
Public Class Program
Public Shared Sub Main()
Dim myInstance = New MyClazz()
Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)
Dim answer = fieldInfo.GetValue(myInstance)
Console.WriteLine(answer)
End Sub
End Class
| 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)
}
|
Please provide an equivalent version of this VB code in Go. | Module Module1
Class Node
Public Sub New(Len As Integer)
Length = Len
Edges = New Dictionary(Of Char, Integer)
End Sub
Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)
Length = len
Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)
Suffix = suf
End Sub
Property Edges As Dictionary(Of Char, Integer)
Property Length As Integer
Property Suffix As Integer
End Class
ReadOnly EVEN_ROOT As Integer = 0
ReadOnly ODD_ROOT As Integer = 1
Function Eertree(s As String) As List(Of Node)
Dim tree As New List(Of Node) From {
New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),
New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)
}
Dim suffix = ODD_ROOT
Dim n As Integer
Dim k As Integer
For i = 1 To s.Length
Dim c = s(i - 1)
n = suffix
While True
k = tree(n).Length
Dim b = i - k - 2
If b >= 0 AndAlso s(b) = c Then
Exit While
End If
n = tree(n).Suffix
End While
If tree(n).Edges.ContainsKey(c) Then
suffix = tree(n).Edges(c)
Continue For
End If
suffix = tree.Count
tree.Add(New Node(k + 2))
tree(n).Edges(c) = suffix
If tree(suffix).Length = 1 Then
tree(suffix).Suffix = 0
Continue For
End If
While True
n = tree(n).Suffix
Dim b = i - tree(n).Length - 2
If b >= 0 AndAlso s(b) = c Then
Exit While
End If
End While
Dim a = tree(n)
Dim d = a.Edges(c)
Dim e = tree(suffix)
e.Suffix = d
Next
Return tree
End Function
Function SubPalindromes(tree As List(Of Node)) As List(Of String)
Dim s As New List(Of String)
Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)
For Each c In tree(n).Edges.Keys
Dim m = tree(n).Edges(c)
Dim p1 = c + p + c
s.Add(p1)
children(m, p1)
Next
End Sub
children(0, "")
For Each c In tree(1).Edges.Keys
Dim m = tree(1).Edges(c)
Dim ct = c.ToString()
s.Add(ct)
children(m, ct)
Next
Return s
End Function
Sub Main()
Dim tree = Eertree("eertree")
Dim result = SubPalindromes(tree)
Dim listStr = String.Join(", ", result)
Console.WriteLine("[{0}]", listStr)
End Sub
End Module
| 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 this VB block to Go, preserving its control flow and logic. | Module Module1
Class Node
Public Sub New(Len As Integer)
Length = Len
Edges = New Dictionary(Of Char, Integer)
End Sub
Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer)
Length = len
Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg)
Suffix = suf
End Sub
Property Edges As Dictionary(Of Char, Integer)
Property Length As Integer
Property Suffix As Integer
End Class
ReadOnly EVEN_ROOT As Integer = 0
ReadOnly ODD_ROOT As Integer = 1
Function Eertree(s As String) As List(Of Node)
Dim tree As New List(Of Node) From {
New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT),
New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT)
}
Dim suffix = ODD_ROOT
Dim n As Integer
Dim k As Integer
For i = 1 To s.Length
Dim c = s(i - 1)
n = suffix
While True
k = tree(n).Length
Dim b = i - k - 2
If b >= 0 AndAlso s(b) = c Then
Exit While
End If
n = tree(n).Suffix
End While
If tree(n).Edges.ContainsKey(c) Then
suffix = tree(n).Edges(c)
Continue For
End If
suffix = tree.Count
tree.Add(New Node(k + 2))
tree(n).Edges(c) = suffix
If tree(suffix).Length = 1 Then
tree(suffix).Suffix = 0
Continue For
End If
While True
n = tree(n).Suffix
Dim b = i - tree(n).Length - 2
If b >= 0 AndAlso s(b) = c Then
Exit While
End If
End While
Dim a = tree(n)
Dim d = a.Edges(c)
Dim e = tree(suffix)
e.Suffix = d
Next
Return tree
End Function
Function SubPalindromes(tree As List(Of Node)) As List(Of String)
Dim s As New List(Of String)
Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String)
For Each c In tree(n).Edges.Keys
Dim m = tree(n).Edges(c)
Dim p1 = c + p + c
s.Add(p1)
children(m, p1)
Next
End Sub
children(0, "")
For Each c In tree(1).Edges.Keys
Dim m = tree(1).Edges(c)
Dim ct = c.ToString()
s.Add(ct)
children(m, ct)
Next
Return s
End Function
Sub Main()
Dim tree = Eertree("eertree")
Dim result = SubPalindromes(tree)
Dim listStr = String.Join(", ", result)
Console.WriteLine("[{0}]", listStr)
End Sub
End Module
| 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
}
|
Port the provided VB code into Go while preserving the original functionality. | DEFINT A-Z
DECLARE FUNCTION p% (Yr AS INTEGER)
DECLARE FUNCTION LongYear% (Yr AS INTEGER)
DIM iYi, iYf, i
CLS
PRINT "This program calculates which are 53-week years in a range."
PRINT
INPUT "Initial year"; iYi
INPUT "Final year (could be the same)"; iYf
IF iYf >= iYi THEN
FOR i = iYi TO iYf
IF LongYear(i) THEN
PRINT i; " ";
END IF
NEXT i
END IF
PRINT
PRINT
PRINT "End of program."
END
FUNCTION LongYear% (Yr AS INTEGER)
LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)
END FUNCTION
FUNCTION p% (Yr AS INTEGER)
p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7
END FUNCTION
| 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)
}
}
|
Generate a Go translation of this VB snippet without changing its computational steps. | Module Module1
Function GetDivisors(n As Integer) As List(Of Integer)
Dim divs As New List(Of Integer) From {
1, n
}
Dim i = 2
While i * i <= n
If n Mod i = 0 Then
Dim j = n \ i
divs.Add(i)
If i <> j Then
divs.Add(j)
End If
End If
i += 1
End While
Return divs
End Function
Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean
If sum = 0 Then
Return True
End If
Dim le = divs.Count
If le = 0 Then
Return False
End If
Dim last = divs(le - 1)
Dim newDivs As New List(Of Integer)
For i = 1 To le - 1
newDivs.Add(divs(i - 1))
Next
If last > sum Then
Return IsPartSum(newDivs, sum)
End If
Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last)
End Function
Function IsZumkeller(n As Integer) As Boolean
Dim divs = GetDivisors(n)
Dim sum = divs.Sum()
REM if sum is odd can
If sum Mod 2 = 1 Then
Return False
End If
REM if n is odd use
If n Mod 2 = 1 Then
Dim abundance = sum - 2 * n
Return abundance > 0 AndAlso abundance Mod 2 = 0
End If
REM if n and sum are both even check if there
Return IsPartSum(divs, sum \ 2)
End Function
Sub Main()
Console.WriteLine("The first 220 Zumkeller numbers are:")
Dim i = 2
Dim count = 0
While count < 220
If IsZumkeller(i) Then
Console.Write("{0,3} ", i)
count += 1
If count Mod 20 = 0 Then
Console.WriteLine()
End If
End If
i += 1
End While
Console.WriteLine()
Console.WriteLine("The first 40 odd Zumkeller numbers are:")
i = 3
count = 0
While count < 40
If IsZumkeller(i) Then
Console.Write("{0,5} ", i)
count += 1
If count Mod 10 = 0 Then
Console.WriteLine()
End If
End If
i += 2
End While
Console.WriteLine()
Console.WriteLine("The first 40 odd Zumkeller numbers which don
i = 3
count = 0
While count < 40
If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then
Console.Write("{0,7} ", i)
count += 1
If count Mod 8 = 0 Then
Console.WriteLine()
End If
End If
i += 2
End While
End Sub
End Module
| 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()
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Private Type Associative
Key As String
Value As Variant
End Type
Sub Main_Array_Associative()
Dim BaseArray(2) As Associative, UpdateArray(2) As Associative
FillArrays BaseArray, UpdateArray
ReDim Result(UBound(BaseArray)) As Associative
MergeArray Result, BaseArray, UpdateArray
PrintOut Result
End Sub
Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)
Dim i As Long, Respons As Long
Res = Base
For i = LBound(Update) To UBound(Update)
If Exist(Respons, Base, Update(i).Key) Then
Res(Respons).Value = Update(i).Value
Else
ReDim Preserve Res(UBound(Res) + 1)
Res(UBound(Res)).Key = Update(i).Key
Res(UBound(Res)).Value = Update(i).Value
End If
Next
End Sub
Private Function Exist(R As Long, B() As Associative, K As String) As Boolean
Dim i As Long
Do
If B(i).Key = K Then
Exist = True
R = i
End If
i = i + 1
Loop While i <= UBound(B) And Not Exist
End Function
Private Sub FillArrays(B() As Associative, U() As Associative)
B(0).Key = "name"
B(0).Value = "Rocket Skates"
B(1).Key = "price"
B(1).Value = 12.75
B(2).Key = "color"
B(2).Value = "yellow"
U(0).Key = "price"
U(0).Value = 15.25
U(1).Key = "color"
U(1).Value = "red"
U(2).Key = "year"
U(2).Value = 1974
End Sub
Private Sub PrintOut(A() As Associative)
Dim i As Long
Debug.Print "Key", "Value"
For i = LBound(A) To UBound(A)
Debug.Print A(i).Key, A(i).Value
Next i
Debug.Print "-----------------------------"
End Sub
| 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)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the VB version. | Private Type Associative
Key As String
Value As Variant
End Type
Sub Main_Array_Associative()
Dim BaseArray(2) As Associative, UpdateArray(2) As Associative
FillArrays BaseArray, UpdateArray
ReDim Result(UBound(BaseArray)) As Associative
MergeArray Result, BaseArray, UpdateArray
PrintOut Result
End Sub
Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)
Dim i As Long, Respons As Long
Res = Base
For i = LBound(Update) To UBound(Update)
If Exist(Respons, Base, Update(i).Key) Then
Res(Respons).Value = Update(i).Value
Else
ReDim Preserve Res(UBound(Res) + 1)
Res(UBound(Res)).Key = Update(i).Key
Res(UBound(Res)).Value = Update(i).Value
End If
Next
End Sub
Private Function Exist(R As Long, B() As Associative, K As String) As Boolean
Dim i As Long
Do
If B(i).Key = K Then
Exist = True
R = i
End If
i = i + 1
Loop While i <= UBound(B) And Not Exist
End Function
Private Sub FillArrays(B() As Associative, U() As Associative)
B(0).Key = "name"
B(0).Value = "Rocket Skates"
B(1).Key = "price"
B(1).Value = 12.75
B(2).Key = "color"
B(2).Value = "yellow"
U(0).Key = "price"
U(0).Value = 15.25
U(1).Key = "color"
U(1).Value = "red"
U(2).Key = "year"
U(2).Value = 1974
End Sub
Private Sub PrintOut(A() As Associative)
Dim i As Long
Debug.Print "Key", "Value"
For i = LBound(A) To UBound(A)
Debug.Print A(i).Key, A(i).Value
Next i
Debug.Print "-----------------------------"
End Sub
| 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)
}
|
Convert the following code from VB to Go, ensuring the logic remains intact. | Imports BI = System.Numerics.BigInteger
Module Module1
Function IntSqRoot(v As BI, res As BI) As BI
REM res is the initial guess
Dim term As BI = 0
Dim d As BI = 0
Dim dl As BI = 1
While dl <> d
term = v / res
res = (res + term) >> 1
dl = d
d = term - res
End While
Return term
End Function
Function DoOne(b As Integer, digs As Integer) As String
REM calculates result via square root, not iterations
Dim s = b * b + 4
digs += 1
Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))
Dim 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
Dim st = bs.ToString
digs -= 1
Return String.Format("{0}.{1}", st(0), st.Substring(1, digs))
End Function
Function DivIt(a As BI, b As BI, digs As Integer) As String
REM performs division
Dim al = a.ToString.Length
Dim bl = b.ToString.Length
digs += 1
a *= BI.Pow(10, digs << 1)
b *= BI.Pow(10, digs)
Dim s = (a / b + 5).ToString
digs -= 1
Return s(0) + "." + s.Substring(1, digs)
End Function
REM custom formatting
Function Joined(x() As BI) As String
Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
Dim res = ""
For i = 0 To x.Length - 1
res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i))
Next
Return res
End Function
Sub Main()
REM calculates and checks each "metal"
Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc")
Dim t = ""
Dim n As BI
Dim nm1 As BI
Dim k As Integer
Dim j As Integer
For b = 0 To 9
Dim lst(14) As BI
lst(0) = 1
lst(1) = 1
For i = 2 To 14
lst(i) = b * lst(i - 1) + lst(i - 2)
Next
REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15
n = lst(14)
nm1 = lst(13)
k = 0
j = 13
While k = 0
Dim lt = t
t = DivIt(n, nm1, 32)
If lt = t Then
k = If(b = 0, 1, j)
End If
Dim onn = n
n = b * n + nm1
nm1 = onn
j += 1
End While
Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{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))
Next
REM now calculate and check big one
n = 1
nm1 = 1
k = 0
j = 1
While k = 0
Dim lt = t
t = DivIt(n, nm1, 256)
If lt = t Then
k = j
End If
Dim onn = n
n += nm1
nm1 = onn
j += 1
End While
Console.WriteLine()
Console.WriteLine("Au to 256 digits:")
Console.WriteLine(t)
Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256))
End Sub
End Module
| 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 a version of this VB function in Go with identical behavior. | Imports BI = System.Numerics.BigInteger
Module Module1
Function IntSqRoot(v As BI, res As BI) As BI
REM res is the initial guess
Dim term As BI = 0
Dim d As BI = 0
Dim dl As BI = 1
While dl <> d
term = v / res
res = (res + term) >> 1
dl = d
d = term - res
End While
Return term
End Function
Function DoOne(b As Integer, digs As Integer) As String
REM calculates result via square root, not iterations
Dim s = b * b + 4
digs += 1
Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))
Dim 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
Dim st = bs.ToString
digs -= 1
Return String.Format("{0}.{1}", st(0), st.Substring(1, digs))
End Function
Function DivIt(a As BI, b As BI, digs As Integer) As String
REM performs division
Dim al = a.ToString.Length
Dim bl = b.ToString.Length
digs += 1
a *= BI.Pow(10, digs << 1)
b *= BI.Pow(10, digs)
Dim s = (a / b + 5).ToString
digs -= 1
Return s(0) + "." + s.Substring(1, digs)
End Function
REM custom formatting
Function Joined(x() As BI) As String
Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
Dim res = ""
For i = 0 To x.Length - 1
res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i))
Next
Return res
End Function
Sub Main()
REM calculates and checks each "metal"
Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc")
Dim t = ""
Dim n As BI
Dim nm1 As BI
Dim k As Integer
Dim j As Integer
For b = 0 To 9
Dim lst(14) As BI
lst(0) = 1
lst(1) = 1
For i = 2 To 14
lst(i) = b * lst(i - 1) + lst(i - 2)
Next
REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15
n = lst(14)
nm1 = lst(13)
k = 0
j = 13
While k = 0
Dim lt = t
t = DivIt(n, nm1, 32)
If lt = t Then
k = If(b = 0, 1, j)
End If
Dim onn = n
n = b * n + nm1
nm1 = onn
j += 1
End While
Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{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))
Next
REM now calculate and check big one
n = 1
nm1 = 1
k = 0
j = 1
While k = 0
Dim lt = t
t = DivIt(n, nm1, 256)
If lt = t Then
k = j
End If
Dim onn = n
n += nm1
nm1 = onn
j += 1
End While
Console.WriteLine()
Console.WriteLine("Au to 256 digits:")
Console.WriteLine(t)
Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256))
End Sub
End Module
| 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 a version of this VB function in Go with identical behavior. | Imports BI = System.Numerics.BigInteger
Module Module1
Function IntSqRoot(v As BI, res As BI) As BI
REM res is the initial guess
Dim term As BI = 0
Dim d As BI = 0
Dim dl As BI = 1
While dl <> d
term = v / res
res = (res + term) >> 1
dl = d
d = term - res
End While
Return term
End Function
Function DoOne(b As Integer, digs As Integer) As String
REM calculates result via square root, not iterations
Dim s = b * b + 4
digs += 1
Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs))
Dim 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
Dim st = bs.ToString
digs -= 1
Return String.Format("{0}.{1}", st(0), st.Substring(1, digs))
End Function
Function DivIt(a As BI, b As BI, digs As Integer) As String
REM performs division
Dim al = a.ToString.Length
Dim bl = b.ToString.Length
digs += 1
a *= BI.Pow(10, digs << 1)
b *= BI.Pow(10, digs)
Dim s = (a / b + 5).ToString
digs -= 1
Return s(0) + "." + s.Substring(1, digs)
End Function
REM custom formatting
Function Joined(x() As BI) As String
Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
Dim res = ""
For i = 0 To x.Length - 1
res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i))
Next
Return res
End Function
Sub Main()
REM calculates and checks each "metal"
Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc")
Dim t = ""
Dim n As BI
Dim nm1 As BI
Dim k As Integer
Dim j As Integer
For b = 0 To 9
Dim lst(14) As BI
lst(0) = 1
lst(1) = 1
For i = 2 To 14
lst(i) = b * lst(i - 1) + lst(i - 2)
Next
REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15
n = lst(14)
nm1 = lst(13)
k = 0
j = 13
While k = 0
Dim lt = t
t = DivIt(n, nm1, 32)
If lt = t Then
k = If(b = 0, 1, j)
End If
Dim onn = n
n = b * n + nm1
nm1 = onn
j += 1
End While
Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{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))
Next
REM now calculate and check big one
n = 1
nm1 = 1
k = 0
j = 1
While k = 0
Dim lt = t
t = DivIt(n, nm1, 256)
If lt = t Then
k = j
End If
Dim onn = n
n += nm1
nm1 = onn
j += 1
End While
Console.WriteLine()
Console.WriteLine("Au to 256 digits:")
Console.WriteLine(t)
Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256))
End Sub
End Module
| 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)
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | Class Branch
Public from As Node
Public towards As Node
Public length As Integer
Public distance As Integer
Public key As String
Class Node
Public key As String
Public correspondingBranch As Branch
Const INFINITY = 32767
Private Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node)
Dim a As New Collection
Dim b As New Collection
Dim c As New Collection
Dim I As New Collection
Dim II As New Collection
Dim III As New Collection
Dim u As Node, R_ As Node, dist As Integer
For Each n In Nodes
c.Add n, n.key
Next n
For Each e In Branches
III.Add e, e.key
Next e
a.Add P, P.key
c.Remove P.key
Set u = P
Do
For Each r In III
If r.from Is u Then
Set R_ = r.towards
If Belongs(R_, c) Then
c.Remove R_.key
b.Add R_, R_.key
Set R_.correspondingBranch = r
If u.correspondingBranch Is Nothing Then
R_.correspondingBranch.distance = r.length
Else
R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length
End If
III.Remove r.key
II.Add r, r.key
Else
If Belongs(R_, b) Then
If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then
II.Remove R_.correspondingBranch.key
II.Add r, r.key
Set R_.correspondingBranch = r
R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length
End If
End If
End If
End If
Next r
dist = INFINITY
Set u = Nothing
For Each n In b
If dist > n.correspondingBranch.distance Then
dist = n.correspondingBranch.distance
Set u = n
End If
Next n
b.Remove u.key
a.Add u, u.key
II.Remove u.correspondingBranch.key
I.Add u.correspondingBranch, u.correspondingBranch.key
Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q)
If Not Q Is Nothing Then GetPath Q
End Sub
Private Function Belongs(n As Node, col As Collection) As Boolean
Dim obj As Node
On Error GoTo err
Belongs = True
Set obj = col(n.key)
Exit Function
err:
Belongs = False
End Function
Private Sub GetPath(Target As Node)
Dim path As String
If Target.correspondingBranch Is Nothing Then
path = "no path"
Else
path = Target.key
Set u = Target
Do While Not u.correspondingBranch Is Nothing
path = u.correspondingBranch.from.key & " " & path
Set u = u.correspondingBranch.from
Loop
Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path
End If
End Sub
Public Sub test()
Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node
Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch
Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch
Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = "ab": ab.distance = INFINITY
Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = "ac": ac.distance = INFINITY
Set af.from = a: Set af.towards = f: af.length = 14: af.key = "af": af.distance = INFINITY
Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = "bc": bc.distance = INFINITY
Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = "bd": bd.distance = INFINITY
Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = "cd": cd.distance = INFINITY
Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = "cf": cf.distance = INFINITY
Set de.from = d: Set de.towards = e: de.length = 6: de.key = "de": de.distance = INFINITY
Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = "ef": ef.distance = INFINITY
a.key = "a"
b.key = "b"
c.key = "c"
d.key = "d"
e.key = "e"
f.key = "f"
Dim testNodes As New Collection
Dim testBranches As New Collection
testNodes.Add a, "a"
testNodes.Add b, "b"
testNodes.Add c, "c"
testNodes.Add d, "d"
testNodes.Add e, "e"
testNodes.Add f, "f"
testBranches.Add ab, "ab"
testBranches.Add ac, "ac"
testBranches.Add af, "af"
testBranches.Add bc, "bc"
testBranches.Add bd, "bd"
testBranches.Add cd, "cd"
testBranches.Add cf, "cf"
testBranches.Add de, "de"
testBranches.Add ef, "ef"
Debug.Print "From", "To", "Distance", "Path"
Dijkstra testNodes, testBranches, a, e
Dijkstra testNodes, testBranches, a
GetPath f
End Sub
| 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))
}
|
Please provide an equivalent version of this VB code in Go. | Option Strict On
Imports System.Text
Module Module1
Structure Vector
Private ReadOnly dims() As Double
Public Sub New(da() As Double)
dims = da
End Sub
Public Shared Operator -(v As Vector) As Vector
Return v * -1.0
End Operator
Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector
Dim result(31) As Double
Array.Copy(lhs.dims, 0, result, 0, lhs.Length)
For i = 1 To result.Length
Dim i2 = i - 1
result(i2) = lhs(i2) + rhs(i2)
Next
Return New Vector(result)
End Operator
Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector
Dim result(31) As Double
For i = 1 To lhs.Length
Dim i2 = i - 1
If lhs(i2) <> 0.0 Then
For j = 1 To lhs.Length
Dim j2 = j - 1
If rhs(j2) <> 0.0 Then
Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)
Dim k = i2 Xor j2
result(k) += s
End If
Next
End If
Next
Return New Vector(result)
End Operator
Public Shared Operator *(v As Vector, scale As Double) As Vector
Dim result = CType(v.dims.Clone, Double())
For i = 1 To result.Length
Dim i2 = i - 1
result(i2) *= scale
Next
Return New Vector(result)
End Operator
Default Public Property Index(key As Integer) As Double
Get
Return dims(key)
End Get
Set(value As Double)
dims(key) = value
End Set
End Property
Public ReadOnly Property Length As Integer
Get
Return dims.Length
End Get
End Property
Public Function Dot(rhs As Vector) As Vector
Return (Me * rhs + rhs * Me) * 0.5
End Function
Private Shared Function BitCount(i As Integer) As Integer
i -= ((i >> 1) And &H55555555)
i = (i And &H33333333) + ((i >> 2) And &H33333333)
i = (i + (i >> 4)) And &HF0F0F0F
i += (i >> 8)
i += (i >> 16)
Return i And &H3F
End Function
Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double
Dim k = i >> 1
Dim sum = 0
While k <> 0
sum += BitCount(k And j)
k >>= 1
End While
Return If((sum And 1) = 0, 1.0, -1.0)
End Function
Public Overrides Function ToString() As String
Dim it = dims.GetEnumerator
Dim sb As New StringBuilder("[")
If it.MoveNext() Then
sb.Append(it.Current)
End If
While it.MoveNext
sb.Append(", ")
sb.Append(it.Current)
End While
sb.Append("]")
Return sb.ToString
End Function
End Structure
Function DoubleArray(size As Integer) As Double()
Dim result(size - 1) As Double
For i = 1 To size
Dim i2 = i - 1
result(i2) = 0.0
Next
Return result
End Function
Function E(n As Integer) As Vector
If n > 4 Then
Throw New ArgumentException("n must be less than 5")
End If
Dim result As New Vector(DoubleArray(32))
result(1 << n) = 1.0
Return result
End Function
ReadOnly r As New Random()
Function RandomVector() As Vector
Dim result As New Vector(DoubleArray(32))
For i = 1 To 5
Dim i2 = i - 1
Dim singleton() As Double = {r.NextDouble()}
result += New Vector(singleton) * E(i2)
Next
Return result
End Function
Function RandomMultiVector() As Vector
Dim result As New Vector(DoubleArray(32))
For i = 1 To result.Length
Dim i2 = i - 1
result(i2) = r.NextDouble()
Next
Return result
End Function
Sub Main()
For i = 1 To 5
Dim i2 = i - 1
For j = 1 To 5
Dim j2 = j - 1
If i2 < j2 Then
If E(i2).Dot(E(j2))(0) <> 0.0 Then
Console.Error.WriteLine("Unexpected non-null scalar product")
Return
End If
ElseIf i2 = j2 Then
If E(i2).Dot(E(j2))(0) = 0.0 Then
Console.Error.WriteLine("Unexpected null scalar product")
Return
End If
End If
Next
Next
Dim a = RandomMultiVector()
Dim b = RandomMultiVector()
Dim c = RandomMultiVector()
Dim 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)
End Sub
End Module
| 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))
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. | Option Explicit
Sub Test()
Dim h As Object, i As Long, u, v, s
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
For Each s In h.Keys
Debug.Print s
Next
For Each s In h.Items
Debug.Print s
Next
u = h.Keys
v = h.Items
For i = 0 To h.Count - 1
Debug.Print u(i), v(i)
Next
End Sub
| 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)
}
|
Convert this VB snippet to Go and keep its semantics consistent. | Private mvarValue As Integer
Public Property Let Value(ByVal vData As Integer)
If (vData > 10) Or (vData < 1) Then
Error 380
Else
mvarValue = vData
End If
End Property
Public Property Get Value() As Integer
Value = mvarValue
End Property
Private Sub Class_Initialize()
mvarValue = 1
End Sub
| 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())
}
|
Generate an equivalent Go version of this VB code. | Dim t_age(4,1)
t_age(0,0) = 27 : t_age(0,1) = "Jonah"
t_age(1,0) = 18 : t_age(1,1) = "Alan"
t_age(2,0) = 28 : t_age(2,1) = "Glory"
t_age(3,0) = 18 : t_age(3,1) = "Popeye"
t_age(4,0) = 28 : t_age(4,1) = "Alan"
Dim t_nemesis(4,1)
t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales"
t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders"
t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts"
t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies"
t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy"
Call hash_join(t_age,1,t_nemesis,0)
Sub hash_join(table_1,index_1,table_2,index_2)
Set hash = CreateObject("Scripting.Dictionary")
For i = 0 To UBound(table_1)
hash.Add i,Array(table_1(i,0),table_1(i,1))
Next
For j = 0 To UBound(table_2)
For Each key In hash.Keys
If hash(key)(index_1) = table_2(j,index_2) Then
WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_
" = " & table_2(j,0) & "," & table_2(j,1)
End If
Next
Next
End Sub
| 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 functionally identical Go code for the snippet given in VB. | option explicit
const pi180= 0.01745329251994329576923690768489
const pi=3.1415926535897932384626433832795
class turtle
dim fso
dim fn
dim svg
dim iang
dim ori
dim incr
dim pdown
dim clr
dim x
dim y
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
end sub
public sub lt(i):
ori=(ori + i*iang)
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
x=400:y=400:incr=100
ori=90*pi180
iang=90*pi180
clr=0
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
const raiz2=1.4142135623730950488016887242097
sub media_sierp (niv,sz)
if niv=0 then x.fw sz: exit sub
media_sierp niv-1,sz
x.lt 1
x.fw sz*raiz2
x.lt 1
media_sierp niv-1,sz
x.rt 2
x.fw sz
x.rt 2
media_sierp niv-1,sz
x.lt 1
x.fw sz*raiz2
x.lt 1
media_sierp niv-1,sz
end sub
sub sierp(niv,sz)
media_sierp niv,sz
x.rt 2
x.fw sz
x.rt 2
media_sierp niv,sz
x.rt 2
x.fw sz
x.rt 2
end sub
dim x
set x=new turtle
x.iangle=45
x.orient=0
x.incr=1
x.x=100:x.y=270
sierp 5,4
set x=nothing
| package main
import (
"github.com/fogleman/gg"
"github.com/trubitsyn/go-lindenmayer"
"log"
"math"
)
const twoPi = 2 * math.Pi
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h, theta float64
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
cx, cy = 10, height/2+5
h = 6
sys := lindenmayer.Lsystem{
Variables: []rune{'X'},
Constants: []rune{'F', '+', '-'},
Axiom: "F+XF+F+XF",
Rules: []lindenmayer.Rule{
{"X", "XF-F+F-XF+F+XF-F+F-X"},
},
Angle: math.Pi / 2,
}
result := lindenmayer.Iterate(&sys, 5)
operations := map[rune]func(){
'F': func() {
newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)
dc.LineTo(newX, newY)
cx, cy = newX, newY
},
'+': func() {
theta = math.Mod(theta+sys.Angle, twoPi)
},
'-': func() {
theta = math.Mod(theta-sys.Angle, twoPi)
},
}
if err := lindenmayer.Process(result, operations); err != nil {
log.Fatal(err)
}
operations['+']()
operations['F']()
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_square_curve.png")
}
|
Change the programming language of this snippet from VB to Go without modifying what it does. | with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
set d= createobject("Scripting.Dictionary")
for each aa in a
x=trim(aa)
l=len(x)
if l>5 then
d.removeall
for i=1 to 3
m=mid(x,i,1)
if not d.exists(m) then d.add m,null
next
res=true
for i=l-2 to l
m=mid(x,i,1)
if not d.exists(m) then
res=false:exit for
else
d.remove(m)
end if
next
if res then
wscript.stdout.write left(x & space(15),15)
if left(x,3)=right(x,3) then wscript.stdout.write "*"
wscript.stdout.writeline
end if
end if
next
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
count := 0
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {
count++
fmt.Printf("%d: %s\n", count, s)
}
}
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | Module Module1
Structure Node
Private ReadOnly m_val As String
Private ReadOnly m_parsed As List(Of String)
Sub New(initial As String)
m_val = initial
m_parsed = New List(Of String)
End Sub
Sub New(s As String, p As List(Of String))
m_val = s
m_parsed = p
End Sub
Public Function Value() As String
Return m_val
End Function
Public Function Parsed() As List(Of String)
Return m_parsed
End Function
End Structure
Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String))
Dim matches As New List(Of List(Of String))
Dim q As New Queue(Of Node)
q.Enqueue(New Node(s))
While q.Count > 0
Dim node = q.Dequeue()
REM check if fully parsed
If node.Value.Length = 0 Then
matches.Add(node.Parsed)
Else
For Each word In dictionary
REM check for match
If node.Value.StartsWith(word) Then
Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length)
Dim parsedNew As New List(Of String)
parsedNew.AddRange(node.Parsed)
parsedNew.Add(word)
q.Enqueue(New Node(valNew, parsedNew))
End If
Next
End If
End While
Return matches
End Function
Sub Main()
Dim dict As New List(Of String) From {"a", "aa", "b", "ab", "aab"}
For Each testString In {"aab", "aa b"}
Dim matches = WordBreak(testString, dict)
Console.WriteLine("String = {0}, Dictionary = {1}. Solutions = {2}", testString, dict, matches.Count)
For Each match In matches
Console.WriteLine(" Word Break = [{0}]", String.Join(", ", match))
Next
Console.WriteLine()
Next
dict = New List(Of String) From {"abc", "a", "ac", "b", "c", "cb", "d"}
For Each testString In {"abcd", "abbc", "abcbcd", "acdbc", "abcdd"}
Dim matches = WordBreak(testString, dict)
Console.WriteLine("String = {0}, Dictionary = {1}. Solutions = {2}", testString, dict, matches.Count)
For Each match In matches
Console.WriteLine(" Word Break = [{0}]", String.Join(", ", match))
Next
Console.WriteLine()
Next
End Sub
End Module
| package main
import (
"fmt"
"strings"
)
type dict map[string]bool
func newDict(words ...string) dict {
d := dict{}
for _, w := range words {
d[w] = true
}
return d
}
func (d dict) wordBreak(s string) (broken []string, ok bool) {
if s == "" {
return nil, true
}
type prefix struct {
length int
broken []string
}
bp := []prefix{{0, nil}}
for end := 1; end <= len(s); end++ {
for i := len(bp) - 1; i >= 0; i-- {
w := s[bp[i].length:end]
if d[w] {
b := append(bp[i].broken, w)
if end == len(s) {
return b, true
}
bp = append(bp, prefix{end, b})
break
}
}
}
return nil, false
}
func main() {
d := newDict("a", "bc", "abc", "cd", "b")
for _, s := range []string{"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} {
if b, ok := d.wordBreak(s); ok {
fmt.Printf("%s: %s\n", s, strings.Join(b, " "))
} else {
fmt.Println("can't break")
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the VB version. | Option Strict On
Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))
Module Module1
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim u = a
a = b
b = u
End Sub
Sub PrintSquare(latin As Matrix)
For Each row In latin
Dim it = row.GetEnumerator
Console.Write("[")
If it.MoveNext Then
Console.Write(it.Current)
End If
While it.MoveNext
Console.Write(", ")
Console.Write(it.Current)
End While
Console.WriteLine("]")
Next
Console.WriteLine()
End Sub
Function DList(n As Integer, start As Integer) As Matrix
start -= 1 REM use 0 based indexes
Dim a = Enumerable.Range(0, n).ToArray
a(start) = a(0)
a(0) = start
Array.Sort(a, 1, a.Length - 1)
Dim first = a(1)
REM recursive closure permutes a[1:]
Dim r As New Matrix
Dim Recurse As Action(Of Integer) = Sub(last As Integer)
If last = first Then
REM bottom of recursion. you get here once for each permutation
REM test if permutation is deranged.
For j = 1 To a.Length - 1
Dim v = a(j)
If j = v Then
Return REM no, ignore it
End If
Next
REM yes, save a copy with 1 based indexing
Dim b = a.Select(Function(v) v + 1).ToArray
r.Add(b.ToList)
Return
End If
For i = last To 1 Step -1
Swap(a(i), a(last))
Recurse(last - 1)
Swap(a(i), a(last))
Next
End Sub
Recurse(n - 1)
Return r
End Function
Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong
If n <= 0 Then
If echo Then
Console.WriteLine("[]")
Console.WriteLine()
End If
Return 0
End If
If n = 1 Then
If echo Then
Console.WriteLine("[1]")
Console.WriteLine()
End If
Return 1
End If
Dim rlatin As New Matrix
For i = 0 To n - 1
rlatin.Add(New List(Of Integer))
For j = 0 To n - 1
rlatin(i).Add(0)
Next
Next
REM first row
For j = 0 To n - 1
rlatin(0)(j) = j + 1
Next
Dim count As ULong = 0
Dim Recurse As Action(Of Integer) = Sub(i As Integer)
Dim rows = DList(n, i)
For r = 0 To rows.Count - 1
rlatin(i - 1) = rows(r)
For k = 0 To i - 2
For j = 1 To n - 1
If rlatin(k)(j) = rlatin(i - 1)(j) Then
If r < rows.Count - 1 Then
GoTo outer
End If
If i > 2 Then
Return
End If
End If
Next
Next
If i < n Then
Recurse(i + 1)
Else
count += 1UL
If echo Then
PrintSquare(rlatin)
End If
End If
outer:
While False
REM empty
End While
Next
End Sub
REM remiain rows
Recurse(2)
Return count
End Function
Function Factorial(n As ULong) As ULong
If n <= 0 Then
Return 1
End If
Dim prod = 1UL
For i = 2UL To n
prod *= i
Next
Return prod
End Function
Sub Main()
Console.WriteLine("The four reduced latin squares of order 4 are:")
Console.WriteLine()
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:")
Console.WriteLine()
For n = 1 To 6
Dim nu As ULong = CULng(n)
Dim size = ReducedLatinSquares(n, False)
Dim f = Factorial(nu - 1UL)
f *= f * nu * size
Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f)
Next
End Sub
End Module
| 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)
}
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. |
Option Explicit
Const m_limit ="# #"
Const m_middle=" # # "
Dim a,bnum,i,check,odic
a=array(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",_
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",_
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",_
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",_
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",_
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",_
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",_
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",_
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",_
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ")
bnum=Array("0001101","0011001","0010011","0111101","0100011"," 0110001","0101111","0111011","0110111","0001011")
Set oDic = WScript.CreateObject("scripting.dictionary")
For i=0 To 9:
odic.Add bin2dec(bnum(i),Asc("1")),i+1
odic.Add bin2dec(bnum(i),Asc("0")),-i-1
Next
For i=0 To UBound(a) : print pad(i+1,-2) & ": "& upc(a(i)) :Next
WScript.Quit(1)
Function bin2dec(ByVal B,a)
Dim n
While len(b)
n =n *2 - (asc(b)=a)
b=mid(b,2)
Wend
bin2dec= n And 127
End Function
Sub print(s):
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else pad= left(s& space(n),n) end if :end function
Function iif(t,a,b) If t Then iif=a Else iif=b End If :End Function
Function getnum(s,r)
Dim n,s1,r1
s1=Left(s,7)
s=Mid(s,8)
r1=r
Do
If r Then s1=StrReverse(s1)
n=bin2dec(s1,asc("#"))
If odic.exists(n) Then
getnum=odic(n)
Exit Function
Else
If r1<>r Then getnum=0:Exit Function
r=Not r
End If
Loop
End Function
Function getmarker(s,m)
getmarker= (InStr(s,m)= 1)
s=Mid(s,Len(m)+1)
End Function
Function checksum(ByVal s)
Dim n,i : n=0
do
n=n+(Asc(s)-48)*3
s=Mid(s,2)
n=n+(Asc(s)-48)*1
s=Mid(s,2)
Loop until Len(s)=0
checksum= ((n mod 10)=0)
End function
Function upc(ByVal s1)
Dim i,n,s,out,rev,j
s=Trim(s1)
If getmarker(s,m_limit)=False Then upc= "bad start marker ":Exit function
rev=False
out=""
For j= 0 To 1
For i=0 To 5
n=getnum(s,rev)
If n=0 Then upc= pad(out,16) & pad ("bad code",-10) & pad("pos "& i+j*6+1,-11): Exit Function
out=out & Abs(n)-1
Next
If j=0 Then If getmarker(s,m_middle)=False Then upc= "bad middle marker " & out :Exit Function
Next
If getmarker(s,m_limit)=False Then upc= "bad end marker " :Exit function
If rev Then out=strreverse(out)
upc= pad(out,16) & pad(iif (checksum(out),"valid","not valid"),-10)& pad(iif(rev,"reversed",""),-11)
End Function
| package main
import (
"fmt"
"regexp"
)
var bits = []string{
"0 0 0 1 1 0 1 ",
"0 0 1 1 0 0 1 ",
"0 0 1 0 0 1 1 ",
"0 1 1 1 1 0 1 ",
"0 1 0 0 0 1 1 ",
"0 1 1 0 0 0 1 ",
"0 1 0 1 1 1 1 ",
"0 1 1 1 0 1 1 ",
"0 1 1 0 1 1 1 ",
"0 0 0 1 0 1 1 ",
}
var (
lhs = make(map[string]int)
rhs = make(map[string]int)
)
var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}
const (
s = "# #"
m = " # # "
e = "# #"
d = "(?:#| ){7}"
)
func init() {
for i := 0; i <= 9; i++ {
lt := make([]byte, 7)
rt := make([]byte, 7)
for j := 0; j < 14; j += 2 {
if bits[i][j] == '1' {
lt[j/2] = '#'
rt[j/2] = ' '
} else {
lt[j/2] = ' '
rt[j/2] = '#'
}
}
lhs[string(lt)] = i
rhs[string(rt)] = i
}
}
func reverse(s string) string {
b := []byte(s)
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
func main() {
barcodes := []string{
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
}
expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`,
s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)
rx := regexp.MustCompile(expr)
fmt.Println("UPC-A barcodes:")
for i, bc := range barcodes {
for j := 0; j <= 1; j++ {
if !rx.MatchString(bc) {
fmt.Printf("%2d: Invalid format\n", i+1)
break
}
codes := rx.FindStringSubmatch(bc)
digits := make([]int, 12)
var invalid, ok bool
for i := 1; i <= 6; i++ {
digits[i-1], ok = lhs[codes[i]]
if !ok {
invalid = true
}
digits[i+5], ok = rhs[codes[i+6]]
if !ok {
invalid = true
}
}
if invalid {
if j == 0 {
bc = reverse(bc)
continue
} else {
fmt.Printf("%2d: Invalid digit(s)\n", i+1)
break
}
}
sum := 0
for i, d := range digits {
sum += weights[i] * d
}
if sum%10 != 0 {
fmt.Printf("%2d: Checksum error\n", i+1)
break
} else {
ud := ""
if j == 1 {
ud = "(upside down)"
}
fmt.Printf("%2d: %v %s\n", i+1, digits, ud)
break
}
}
}
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Option Explicit
Private Type MyPoint
X As Single
Y As Single
End Type
Private Type MyPair
p1 As MyPoint
p2 As MyPoint
End Type
Sub Main()
Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long
Dim T#
Randomize Timer
Nb = 10
Do
ReDim points(1 To Nb)
For i = 1 To Nb
points(i).X = Rnd * Nb
points(i).Y = Rnd * Nb
Next
d = 1000000000000#
T = Timer
BF = BruteForce(points, d)
Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec."
Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y
Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y
Debug.Print "dist : " & d
Debug.Print "--------------------------------------------------"
Nb = Nb * 10
Loop While Nb <= 10000
End Sub
Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair
Dim i As Long, j As Long, d As Single, ClosestPair As MyPair
For i = 1 To UBound(p) - 1
For j = i + 1 To UBound(p)
d = Dist(p(i), p(j))
If d < mindist Then
mindist = d
ClosestPair.p1 = p(i)
ClosestPair.p2 = p(j)
End If
Next
Next
BruteForce = ClosestPair
End Function
Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single
Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)
End Function
| 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
}
|
Convert this VB snippet to Go and keep its semantics consistent. | Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
MyVar = 10
TheAddress = varptr(MyVar)
MEMSET(TheAddress, 102, SizeOf(byte))
showmessage "MyVar = " + str$(MyVar)
MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))
showmessage "SecVar = " + str$(SecVar)
| 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)
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
MyVar = 10
TheAddress = varptr(MyVar)
MEMSET(TheAddress, 102, SizeOf(byte))
showmessage "MyVar = " + str$(MyVar)
MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))
showmessage "SecVar = " + str$(SecVar)
| 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)
}
|
Change the programming language of this snippet from VB to Go without modifying what it does. | Class Animal
End Class
Class Dog
Inherits Animal
End Class
Class Lab
Inherits Dog
End Class
Class Collie
Inherits Dog
End Class
Class Cat
Inherits Animal
End Class
| 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"
}
|
Rewrite the snippet below in Go so it works the same as the original VB code. | Option Explicit
Sub Test()
Dim h As Object
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
Debug.Print h.Item("A")
h.Item("C") = 4
h.Key("C") = "D"
Debug.Print h.exists("C")
h.Remove "B"
Debug.Print h.Count
h.RemoveAll
Debug.Print h.Count
End Sub
|
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,
}
|
Rewrite the snippet below in Go so it works the same as the original VB code. | Option explicit
Class ImgClass
Private ImgL,ImgH,ImgDepth,bkclr,loc,tt
private xmini,xmaxi,ymini,ymaxi,dirx,diry
public ImgArray()
private filename
private Palette,szpal
public property get xmin():xmin=xmini:end property
public property get ymin():ymin=ymini:end property
public property get xmax():xmax=xmaxi:end property
public property get ymax():ymax=ymaxi:end property
public property let depth(x)
if x<>8 and x<>32 then err.raise 9
Imgdepth=x
end property
public sub set0 (x0,y0)
if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9
xmini=-x0
ymini=-y0
xmaxi=xmini+imgl-1
ymaxi=ymini+imgh-1
end sub
Public Default Function Init(name,w,h,orient,dep,bkg,mipal)
dim i,j
ImgL=w
ImgH=h
tt=timer
loc=getlocale
set0 0,0
redim imgArray(ImgL-1,ImgH-1)
bkclr=bkg
if bkg<>0 then
for i=0 to ImgL-1
for j=0 to ImgH-1
imgarray(i,j)=bkg
next
next
end if
Select Case orient
Case 1: dirx=1 : diry=1
Case 2: dirx=-1 : diry=1
Case 3: dirx=-1 : diry=-1
Case 4: dirx=1 : diry=-1
End select
filename=name
ImgDepth =dep
if imgdepth=8 then
loadpal(mipal)
end if
set init=me
end function
private sub loadpal(mipale)
if isarray(mipale) Then
palette=mipale
szpal=UBound(mipale)+1
Else
szpal=256
, not relevant
End if
End Sub
Private Sub Class_Terminate
if err<>0 then wscript.echo "Error " & err.number
wscript.echo "copying image to bmp file"
savebmp
wscript.echo "opening " & filename & " with your default bmp viewer"
CreateObject("Shell.Application").ShellExecute filename
wscript.echo timer-tt & " iseconds"
End Sub
function long2wstr( x)
dim k1,k2,x1
k1= (x and &hffff&)
k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0))
long2wstr=chrw(k1) & chrw(k2)
end function
function int2wstr(x)
int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))
End Function
Public Sub SaveBMP
Dim s,ostream, x,y,loc
const hdrs=54
dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4)
dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0
with CreateObject("ADODB.Stream")
.Charset = "UTF-16LE"
.Type = 2
.open
.writetext ChrW(&h4d42)
.writetext long2wstr(hdrs+palsize+bms)
.writetext long2wstr(0)
.writetext long2wstr (hdrs+palsize)
.writetext long2wstr(40)
.writetext long2wstr(Imgl)
.writetext long2wstr(imgh)
.writetext int2wstr(1)
.writetext int2wstr(imgdepth)
.writetext long2wstr(&H0)
.writetext long2wstr(bms)
.writetext long2wstr(&Hc4e)
.writetext long2wstr(&hc43)
.writetext long2wstr(szpal)
.writetext long2wstr(&H0)
Dim x1,x2,y1,y2
If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1
If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1
Select Case imgdepth
Case 32
For y=y1 To y2 step diry
For x=x1 To x2 Step dirx
.writetext long2wstr(Imgarray(x,y))
Next
Next
Case 8
For x=0 to szpal-1
.writetext long2wstr(palette(x))
Next
dim pad:pad=ImgL mod 4
For y=y1 to y2 step diry
For x=x1 To x2 step dirx*2
.writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))
Next
if pad and 1 then .writetext chrw(ImgArray(x2,y))
if pad >1 then .writetext chrw(0)
Next
Case Else
WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits"
End Select
Dim outf:Set outf= CreateObject("ADODB.Stream")
outf.Type = 1
outf.Open
.position=2
.CopyTo outf
.close
outf.savetofile filename,2
outf.close
end with
End Sub
end class
function hsv2rgb( Hue, Sat, Value)
dim Angle, Radius,Ur,Vr,Wr,Rdim
dim r,g,b, rgb
Angle = (Hue-150) *0.01745329251994329576923690768489
Ur = Value * 2.55
Radius = Ur * tan(Sat *0.01183199)
Vr = Radius * cos(Angle) *0.70710678
Wr = Radius * sin(Angle) *0.40824829
r = (Ur - Vr - Wr)
g = (Ur + Vr - Wr)
b = (Ur + Wr + Wr)
if r >255 then
Rdim = (Ur - 255) / (Vr + Wr)
r = 255
g = Ur + (Vr - Wr) * Rdim
b = Ur + 2 * Wr * Rdim
elseif r < 0 then
Rdim = Ur / (Vr + Wr)
r = 0
g = Ur + (Vr - Wr) * Rdim
b = Ur + 2 * Wr * Rdim
end if
if g >255 then
Rdim = (255 - Ur) / (Vr - Wr)
r = Ur - (Vr + Wr) * Rdim
g = 255
b = Ur + 2 * Wr * Rdim
elseif g<0 then
Rdim = -Ur / (Vr - Wr)
r = Ur - (Vr + Wr) * Rdim
g = 0
b = Ur + 2 * Wr * Rdim
end if
if b>255 then
Rdim = (255 - Ur) / (Wr + Wr)
r = Ur - (Vr + Wr) * Rdim
g = Ur + (Vr - Wr) * Rdim
b = 255
elseif b<0 then
Rdim = -Ur / (Wr + Wr)
r = Ur - (Vr + Wr) * Rdim
g = Ur + (Vr - Wr) * Rdim
b = 0
end If
hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)
end function
function ang(col,row)
if col =0 then
if row<0 then ang=90 else ang=270 end if
else
if col>0 then
ang=atn(-row/col)*57.2957795130
else
ang=(atn(row/-col)*57.2957795130)+180
end if
end if
ang=(ang+360) mod 360
end function
Dim X,row,col,fn,tt,hr,sat,row2
const h=160
const w=160
const rad=159
const r2=25500
tt=timer
fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\testwchr.bmp"
Set X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)
x.set0 w,h
for row=x.xmin+1 to x.xmax
row2=row*row
hr=int(Sqr(r2-row2))
For col=hr To 159
Dim a:a=((col\16 +row\16) And 1)* &hffffff
x.imgArray(col+160,row+160)=a
x.imgArray(-col+160,row+160)=a
next
for col=-hr to hr
sat=100-sqr(row2+col*col)/rad *50
x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)
next
next
Set X = Nothing
| 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")
}
|
Generate a Go translation of this VB snippet without changing its computational steps. | with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
dim b(25)
dim c(128)
with new regexp
.pattern="([^aeiou])"
.global=true
for each i in a
if len(trim(i))>10 then
set matches= .execute(i)
rep=false
for each m in matches
x=asc(m)
c(x)=c(x)+1
if c(x)>1 then rep=true :exit for
next
erase c
if not rep then
x1=matches.count
b(x1)=b(x1)&" "&i
end if
end if
next
end with
for i=25 to 0 step -1
if b(i)<>"" then wscript.echo i & " "& b(i) & vbcrlf
next
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func contains(list []int, value int) bool {
for _, v := range list {
if v == value {
return true
}
}
return false
}
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 10 {
words = append(words, s)
}
}
vowelIndices := []int{0, 4, 8, 14, 20}
wordGroups := make([][]string, 12)
for _, word := range words {
letters := make([]int, 26)
for _, c := range word {
index := c - 97
if index >= 0 && index < 26 {
letters[index]++
}
}
eligible := true
uc := 0
for i := 0; i < 26; i++ {
if !contains(vowelIndices, i) {
if letters[i] > 1 {
eligible = false
break
} else if letters[i] == 1 {
uc++
}
}
}
if eligible {
wordGroups[uc] = append(wordGroups[uc], word)
}
}
for i := 11; i >= 0; i-- {
count := len(wordGroups[i])
if count > 0 {
s := "s"
if count == 1 {
s = ""
}
fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i)
for j := 0; j < count; j++ {
fmt.Printf("%-15s", wordGroups[i][j])
if j > 0 && (j+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println()
if count%5 != 0 {
fmt.Println()
}
}
}
}
|
Convert this VB block to Go, preserving its control flow and logic. | Option Explicit
Public vTime As Single
Public PlaysCount As Long
Sub Main_MineSweeper()
Dim Userf As New cMinesweeper
Userf.Show 0, True
End Sub
| package main
import (
"bufio"
"fmt"
"math"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type cell struct {
isMine bool
display byte
}
const lMargin = 4
var (
grid [][]cell
mineCount int
minesMarked int
isGameOver bool
)
var scanner = bufio.NewScanner(os.Stdin)
func makeGrid(n, m int) {
if n <= 0 || m <= 0 {
panic("Grid dimensions must be positive.")
}
grid = make([][]cell, n)
for i := 0; i < n; i++ {
grid[i] = make([]cell, m)
for j := 0; j < m; j++ {
grid[i][j].display = '.'
}
}
min := int(math.Round(float64(n*m) * 0.1))
max := int(math.Round(float64(n*m) * 0.2))
mineCount = min + rand.Intn(max-min+1)
rm := mineCount
for rm > 0 {
x, y := rand.Intn(n), rand.Intn(m)
if !grid[x][y].isMine {
rm--
grid[x][y].isMine = true
}
}
minesMarked = 0
isGameOver = false
}
func displayGrid(isEndOfGame bool) {
if !isEndOfGame {
fmt.Println("Grid has", mineCount, "mine(s),", minesMarked, "mine(s) marked.")
}
margin := strings.Repeat(" ", lMargin)
fmt.Print(margin, " ")
for i := 1; i <= len(grid); i++ {
fmt.Print(i)
}
fmt.Println()
fmt.Println(margin, strings.Repeat("-", len(grid)))
for y := 0; y < len(grid[0]); y++ {
fmt.Printf("%*d:", lMargin, y+1)
for x := 0; x < len(grid); x++ {
fmt.Printf("%c", grid[x][y].display)
}
fmt.Println()
}
}
func endGame(msg string) {
isGameOver = true
fmt.Println(msg)
ans := ""
for ans != "y" && ans != "n" {
fmt.Print("Another game (y/n)? : ")
scanner.Scan()
ans = strings.ToLower(scanner.Text())
}
if scanner.Err() != nil || ans == "n" {
return
}
makeGrid(6, 4)
displayGrid(false)
}
func resign() {
found := 0
for y := 0; y < len(grid[0]); y++ {
for x := 0; x < len(grid); x++ {
if grid[x][y].isMine {
if grid[x][y].display == '?' {
grid[x][y].display = 'Y'
found++
} else if grid[x][y].display != 'x' {
grid[x][y].display = 'N'
}
}
}
}
displayGrid(true)
msg := fmt.Sprint("You found ", found, " out of ", mineCount, " mine(s).")
endGame(msg)
}
func usage() {
fmt.Println("h or ? - this help,")
fmt.Println("c x y - clear cell (x,y),")
fmt.Println("m x y - marks (toggles) cell (x,y),")
fmt.Println("n - start a new game,")
fmt.Println("q - quit/resign the game,")
fmt.Println("where x is the (horizontal) column number and y is the (vertical) row number.\n")
}
func markCell(x, y int) {
if grid[x][y].display == '?' {
minesMarked--
grid[x][y].display = '.'
} else if grid[x][y].display == '.' {
minesMarked++
grid[x][y].display = '?'
}
}
func countAdjMines(x, y int) int {
count := 0
for j := y - 1; j <= y+1; j++ {
if j >= 0 && j < len(grid[0]) {
for i := x - 1; i <= x+1; i++ {
if i >= 0 && i < len(grid) {
if grid[i][j].isMine {
count++
}
}
}
}
}
return count
}
func clearCell(x, y int) bool {
if x >= 0 && x < len(grid) && y >= 0 && y < len(grid[0]) {
if grid[x][y].display == '.' {
if !grid[x][y].isMine {
count := countAdjMines(x, y)
if count > 0 {
grid[x][y].display = string(48 + count)[0]
} else {
grid[x][y].display = ' '
clearCell(x+1, y)
clearCell(x+1, y+1)
clearCell(x, y+1)
clearCell(x-1, y+1)
clearCell(x-1, y)
clearCell(x-1, y-1)
clearCell(x, y-1)
clearCell(x+1, y-1)
}
} else {
grid[x][y].display = 'x'
fmt.Println("Kaboom! You lost!")
return false
}
}
}
return true
}
func testForWin() bool {
isCleared := false
if minesMarked == mineCount {
isCleared = true
for x := 0; x < len(grid); x++ {
for y := 0; y < len(grid[0]); y++ {
if grid[x][y].display == '.' {
isCleared = false
}
}
}
}
if isCleared {
fmt.Println("You won!")
}
return isCleared
}
func splitAction(action string) (int, int, bool) {
fields := strings.Fields(action)
if len(fields) != 3 {
return 0, 0, false
}
x, err := strconv.Atoi(fields[1])
if err != nil || x < 1 || x > len(grid) {
return 0, 0, false
}
y, err := strconv.Atoi(fields[2])
if err != nil || y < 1 || y > len(grid[0]) {
return 0, 0, false
}
return x, y, true
}
func main() {
rand.Seed(time.Now().UnixNano())
usage()
makeGrid(6, 4)
displayGrid(false)
for !isGameOver {
fmt.Print("\n>")
scanner.Scan()
action := strings.ToLower(scanner.Text())
if scanner.Err() != nil || len(action) == 0 {
continue
}
switch action[0] {
case 'h', '?':
usage()
case 'n':
makeGrid(6, 4)
displayGrid(false)
case 'c':
x, y, ok := splitAction(action)
if !ok {
continue
}
if clearCell(x-1, y-1) {
displayGrid(false)
if testForWin() {
resign()
}
} else {
resign()
}
case 'm':
x, y, ok := splitAction(action)
if !ok {
continue
}
markCell(x-1, y-1)
displayGrid(false)
if testForWin() {
resign()
}
case 'q':
resign()
}
}
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Imports System.Math, System.Console, BI = System.Numerics.BigInteger
Module Module1
Sub Main(ByVal args As String())
Dim i, j, k, d As BI : i = 2
j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j
Dim n As Integer = -1, n0 As Integer = -1,
st As DateTime = DateTime.Now
If args.Length > 0 Then Integer.TryParse(args(0), n)
If n > 0 Then n0 = n Else n = 1
Do
Write(d) : i = (i - k * d) * 100 : k = 20 * j
For d = 1 To 10
If (k + d) * d > i Then d -= 1 : Exit For
Next
j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1
Loop While n > 0
If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st)
End Sub
End Module
| 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()
}
}
|
Rewrite the snippet below in Go so it works the same as the original VB code. | Imports System.Math, System.Console, BI = System.Numerics.BigInteger
Module Module1
Sub Main(ByVal args As String())
Dim i, j, k, d As BI : i = 2
j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j
Dim n As Integer = -1, n0 As Integer = -1,
st As DateTime = DateTime.Now
If args.Length > 0 Then Integer.TryParse(args(0), n)
If n > 0 Then n0 = n Else n = 1
Do
Write(d) : i = (i - k * d) * 100 : k = 20 * j
For d = 1 To 10
If (k + d) * d > i Then d -= 1 : Exit For
Next
j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1
Loop While n > 0
If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st)
End Sub
End Module
| 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()
}
}
|
Port the provided VB code into Go while preserving the original functionality. | Imports System.Linq
Imports System.Collections.Generic
Imports System.Console
Imports System.Math
Module Module1
Dim ba As Integer
Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)
Dim flags(lim) As Boolean, j As Integer : Yield 2
For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3
Dim d As Integer = 8, sq As Integer = 9
While sq <= lim
If Not flags(j) Then
Yield j : Dim i As Integer = j << 1
For k As Integer = sq To lim step i : flags(k) = True : Next
End If
j += 2 : d += 8 : sq += d : End While
While j <= lim
If Not flags(j) Then Yield j
j += 2 : End While
End Function
Function from10(ByVal b As Integer) As String
Dim res As String = "", re As Integer
While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res
End Function
Function to10(ByVal s As String) As Integer
Dim res As Integer = 0
For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res
End Function
Function nd(ByVal s As String) As Boolean
If s.Length < 2 Then Return True
Dim l As Char = s(0)
For i As Integer = 1 To s.Length - 1
If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)
Next : Return True
End Function
Sub Main(ByVal args As String())
Dim c As Integer, lim As Integer = 1000, s As String
For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }
ba = b : c = 0 : For Each a As Integer In Primes(lim)
s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, ""))
Next
WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim))
Next
End Sub
End Module
| 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))
}
|
Rewrite this program in Go while keeping its functionality equivalent to the VB version. | Imports System.Linq
Imports System.Collections.Generic
Imports System.Console
Imports System.Math
Module Module1
Dim ba As Integer
Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)
Dim flags(lim) As Boolean, j As Integer : Yield 2
For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3
Dim d As Integer = 8, sq As Integer = 9
While sq <= lim
If Not flags(j) Then
Yield j : Dim i As Integer = j << 1
For k As Integer = sq To lim step i : flags(k) = True : Next
End If
j += 2 : d += 8 : sq += d : End While
While j <= lim
If Not flags(j) Then Yield j
j += 2 : End While
End Function
Function from10(ByVal b As Integer) As String
Dim res As String = "", re As Integer
While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res
End Function
Function to10(ByVal s As String) As Integer
Dim res As Integer = 0
For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res
End Function
Function nd(ByVal s As String) As Boolean
If s.Length < 2 Then Return True
Dim l As Char = s(0)
For i As Integer = 1 To s.Length - 1
If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)
Next : Return True
End Function
Sub Main(ByVal args As String())
Dim c As Integer, lim As Integer = 1000, s As String
For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }
ba = b : c = 0 : For Each a As Integer In Primes(lim)
s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, ""))
Next
WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim))
Next
End Sub
End Module
| 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))
}
|
Generate an equivalent Go version of this VB code. | Imports System.Reflection
Module Module1
Class TestClass
Private privateField = 7
Public ReadOnly Property PublicNumber = 4
Private ReadOnly Property PrivateNumber = 2
End Class
Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
Return From p In obj.GetType().GetProperties(flags)
Where p.GetIndexParameters().Length = 0
Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}
End Function
Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})
End Function
Sub Main()
Dim t As New TestClass()
Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance
For Each prop In GetPropertyValues(t, flags)
Console.WriteLine(prop)
Next
For Each field In GetFieldValues(t, flags)
Console.WriteLine(field)
Next
End Sub
End Module
| 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()
}
|
Write the same algorithm in Go as shown in this VB implementation. | Dim MText as QMemorystream
MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
MText.WriteLine "are$delineated$by$a$single$
MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
MText.WriteLine "column$are$separated$by$at$least$one$space."
MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column."
DefStr TextLeft, TextRight, TextCenter
DefStr MLine, LWord, Newline = chr$(13)+chr$(10)
DefInt ColWidth(100), ColCount
DefSng NrSpaces
MText.position = 0
for x = 0 to MText.linecount -1
MLine = MText.ReadLine
for y = 0 to Tally(MLine, "$")
LWord = Field$(MLine, "$", y+1)
ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))
next
next
MText.position = 0
for x = 0 to MText.linecount -1
MLine = MText.ReadLine
for y = 0 to Tally(MLine, "$")
LWord = Field$(MLine, "$", y+1)
NrSpaces = ColWidth(y) - len(LWord)
TextLeft = TextLeft + LWord + Space$(NrSpaces+1)
TextRight = TextRight + Space$(NrSpaces+1) + LWord
TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))
next
TextLeft = TextLeft + Newline
TextRight = TextRight + Newline
TextCenter = TextCenter + Newline
next
| 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)
}
|
Port the provided VB code into Go while preserving the original functionality. | Function parse_url(url)
parse_url = "URL: " & url
If InStr(url,"//") Then
scheme = Split(url,"//")
parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1)
domain = Split(scheme(1),"/")
If InStr(domain(0),"@") Then
cred = Split(domain(0),"@")
If InStr(cred(0),".") Then
username = Mid(cred(0),1,InStr(1,cred(0),".")-1)
password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),"."))
ElseIf InStr(cred(0),":") Then
username = Mid(cred(0),1,InStr(1,cred(0),":")-1)
password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":"))
End If
parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_
"Password: " & password
If InStr(cred(1),":") Then
host = Mid(cred(1),1,InStr(1,cred(1),":")-1)
port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & cred(1)
End If
ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then
host = Mid(domain(0),1,InStr(1,domain(0),":")-1)
port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then
host = Mid(domain(0),1,InStr(1,domain(0),"]"))
port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & domain(0)
End If
If UBound(domain) > 0 Then
For i = 1 To UBound(domain)
If i < UBound(domain) Then
path = path & domain(i) & "/"
ElseIf InStr(domain(i),"?") Then
path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1)
If InStr(domain(i),"#") Then
query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1)
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment
Else
query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?"))
path = path & vbcrlf & "Query: " & query
End If
ElseIf InStr(domain(i),"#") Then
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_
"Fragment: " & fragment
Else
path = path & domain(i)
End If
Next
parse_url = parse_url & vbCrLf & "Path: " & path
End If
ElseIf InStr(url,":") Then
scheme = Mid(url,1,InStr(1,url,":")-1)
path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":"))
parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path
Else
parse_url = parse_url & vbcrlf & "Invalid!!!"
End If
End Function
WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
| 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)
}
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Function parse_url(url)
parse_url = "URL: " & url
If InStr(url,"//") Then
scheme = Split(url,"//")
parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1)
domain = Split(scheme(1),"/")
If InStr(domain(0),"@") Then
cred = Split(domain(0),"@")
If InStr(cred(0),".") Then
username = Mid(cred(0),1,InStr(1,cred(0),".")-1)
password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),"."))
ElseIf InStr(cred(0),":") Then
username = Mid(cred(0),1,InStr(1,cred(0),":")-1)
password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":"))
End If
parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_
"Password: " & password
If InStr(cred(1),":") Then
host = Mid(cred(1),1,InStr(1,cred(1),":")-1)
port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & cred(1)
End If
ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then
host = Mid(domain(0),1,InStr(1,domain(0),":")-1)
port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then
host = Mid(domain(0),1,InStr(1,domain(0),"]"))
port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & domain(0)
End If
If UBound(domain) > 0 Then
For i = 1 To UBound(domain)
If i < UBound(domain) Then
path = path & domain(i) & "/"
ElseIf InStr(domain(i),"?") Then
path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1)
If InStr(domain(i),"#") Then
query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1)
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment
Else
query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?"))
path = path & vbcrlf & "Query: " & query
End If
ElseIf InStr(domain(i),"#") Then
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_
"Fragment: " & fragment
Else
path = path & domain(i)
End If
Next
parse_url = parse_url & vbCrLf & "Path: " & path
End If
ElseIf InStr(url,":") Then
scheme = Mid(url,1,InStr(1,url,":")-1)
path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":"))
parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path
Else
parse_url = parse_url & vbcrlf & "Invalid!!!"
End If
End Function
WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
| 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)
}
}
|
Change the programming language of this snippet from VB to Go without modifying what it does. | Imports System.Numerics
Imports System.Text
Module Module1
ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
ReadOnly HEX As String = "0123456789ABCDEF"
Function ToBigInteger(value As String, base As Integer) As BigInteger
If base < 1 OrElse base > HEX.Length Then
Throw New ArgumentException("Base is out of range.")
End If
Dim bi = BigInteger.Zero
For Each c In value
Dim c2 = Char.ToUpper(c)
Dim idx = HEX.IndexOf(c2)
If idx = -1 OrElse idx >= base Then
Throw New ArgumentException("Illegal character encountered.")
End If
bi = bi * base + idx
Next
Return bi
End Function
Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String
Dim x As BigInteger
If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then
x = ToBigInteger(hash.Substring(2), base)
Else
x = ToBigInteger(hash, base)
End If
Dim sb As New StringBuilder
While x > 0
Dim r = x Mod 58
sb.Append(ALPHABET(r))
x = x / 58
End While
Dim ca = sb.ToString().ToCharArray()
Array.Reverse(ca)
Return New String(ca)
End Function
Sub Main()
Dim s = "25420294593250030202636073700053352635053786165627414518"
Dim b = ConvertToBase58(s, 10)
Console.WriteLine("{0} -> {1}", s, b)
Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"}
For Each hash In hashes
Dim b58 = ConvertToBase58(hash)
Console.WriteLine("{0,-56} -> {1}", hash, b58)
Next
End Sub
End Module
| 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)
}
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Imports System.Numerics
Imports System.Text
Module Module1
ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
ReadOnly HEX As String = "0123456789ABCDEF"
Function ToBigInteger(value As String, base As Integer) As BigInteger
If base < 1 OrElse base > HEX.Length Then
Throw New ArgumentException("Base is out of range.")
End If
Dim bi = BigInteger.Zero
For Each c In value
Dim c2 = Char.ToUpper(c)
Dim idx = HEX.IndexOf(c2)
If idx = -1 OrElse idx >= base Then
Throw New ArgumentException("Illegal character encountered.")
End If
bi = bi * base + idx
Next
Return bi
End Function
Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String
Dim x As BigInteger
If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then
x = ToBigInteger(hash.Substring(2), base)
Else
x = ToBigInteger(hash, base)
End If
Dim sb As New StringBuilder
While x > 0
Dim r = x Mod 58
sb.Append(ALPHABET(r))
x = x / 58
End While
Dim ca = sb.ToString().ToCharArray()
Array.Reverse(ca)
Return New String(ca)
End Function
Sub Main()
Dim s = "25420294593250030202636073700053352635053786165627414518"
Dim b = ConvertToBase58(s, 10)
Console.WriteLine("{0} -> {1}", s, b)
Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"}
For Each hash In hashes
Dim b58 = ConvertToBase58(hash)
Console.WriteLine("{0,-56} -> {1}", hash, b58)
Next
End Sub
End Module
| 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)
}
}
|
Keep all operations the same but rewrite the snippet in Go. | Imports System.IO
Imports System.Security.Cryptography
Module Module1
Function ByteArrayToString(ba As Byte()) As String
Return BitConverter.ToString(ba).Replace("-", "")
End Function
Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()
Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}
Dim provider As New DESCryptoServiceProvider
Dim transform = provider.CreateEncryptor(passwordBytes, iv)
Dim mode = CryptoStreamMode.Write
Dim memStream As New MemoryStream
Dim cryptoStream As New CryptoStream(memStream, transform, mode)
cryptoStream.Write(messageBytes, 0, messageBytes.Length)
cryptoStream.FlushFinalBlock()
Dim encryptedMessageBytes(memStream.Length - 1) As Byte
memStream.Position = 0
memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)
Return encryptedMessageBytes
End Function
Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()
Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}
Dim provider As New DESCryptoServiceProvider
Dim transform = provider.CreateDecryptor(passwordBytes, iv)
Dim mode = CryptoStreamMode.Write
Dim memStream As New MemoryStream
Dim cryptoStream As New CryptoStream(memStream, transform, mode)
cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)
cryptoStream.FlushFinalBlock()
Dim decryptedMessageBytes(memStream.Length - 1) As Byte
memStream.Position = 0
memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)
Return decryptedMessageBytes
End Function
Sub Main()
Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}
Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}
Dim encStr = Encrypt(plainBytes, keyBytes)
Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr))
Dim decStr = Decrypt(encStr, keyBytes)
Console.WriteLine("Decoded: {0}", ByteArrayToString(decStr))
End Sub
End Module
| 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)
}
|
Write the same algorithm in Go as shown in this VB implementation. | Public Sub commatize(s As String, Optional sep As String = ",", Optional start As Integer = 1, Optional step As Integer = 3)
Dim l As Integer: l = Len(s)
For i = start To l
If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then
For j = i + 1 To l + 1
If j > l Then
For k = j - 1 - step To i Step -step
s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)
l = Len(s)
Next k
Exit For
Else
If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then
For k = j - 1 - step To i Step -step
s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)
l = Len(s)
Next k
Exit For
End If
End If
Next j
Exit For
End If
Next i
Debug.Print s
End Sub
Public Sub main()
commatize "pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 6, 5
commatize "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "."
commatize """-in Aus$+1411.8millions"""
commatize "===US$0017440 millions=== (in 2000 dollars)"
commatize "123.e8000 is pretty big."
commatize "The land area of the earth is 57268900(29% of the surface) square miles."
commatize "Ain
commatize "James was never known as 0000000007"
commatize "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe."
commatize " $-140000±100 millions."
commatize "6/9/1946 was a good year for some."
End Sub
| 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, ","))
}
}
|
Write a version of this VB function in Go with identical behavior. | Imports System.Numerics
Imports System.Text
Imports Freq = System.Collections.Generic.Dictionary(Of Char, Long)
Imports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))
Module Module1
Function CumulativeFreq(freq As Freq) As Freq
Dim total As Long = 0
Dim cf As New Freq
For i = 0 To 255
Dim c = Chr(i)
If freq.ContainsKey(c) Then
Dim v = freq(c)
cf(c) = total
total += v
End If
Next
Return cf
End Function
Function ArithmeticCoding(str As String, radix As Long) As Triple
Dim freq As New Freq
For Each c In str
If freq.ContainsKey(c) Then
freq(c) += 1
Else
freq(c) = 1
End If
Next
Dim cf = CumulativeFreq(freq)
Dim base As BigInteger = str.Length
Dim lower As BigInteger = 0
Dim pf As BigInteger = 1
For Each c In str
Dim x = cf(c)
lower = lower * base + x * pf
pf = pf * freq(c)
Next
Dim upper = lower + pf
Dim powr = 0
Dim bigRadix As BigInteger = radix
While True
pf = pf / bigRadix
If pf = 0 Then
Exit While
End If
powr = powr + 1
End While
Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))
Return New Triple(diff, powr, freq)
End Function
Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String
Dim powr As BigInteger = radix
Dim enc = num * BigInteger.Pow(powr, pwr)
Dim base = freq.Values.Sum()
Dim cf = CumulativeFreq(freq)
Dim dict As New Dictionary(Of Long, Char)
For Each key In cf.Keys
Dim value = cf(key)
dict(value) = key
Next
Dim lchar As Long = -1
For i As Long = 0 To base - 1
If dict.ContainsKey(i) Then
lchar = AscW(dict(i))
Else
dict(i) = ChrW(lchar)
End If
Next
Dim decoded As New StringBuilder
Dim bigBase As BigInteger = base
For i As Long = base - 1 To 0 Step -1
Dim pow = BigInteger.Pow(bigBase, i)
Dim div = enc / pow
Dim c = dict(div)
Dim fv = freq(c)
Dim cv = cf(c)
Dim diff = enc - pow * cv
enc = diff / fv
decoded.Append(c)
Next
Return decoded.ToString()
End Function
Sub Main()
Dim radix As Long = 10
Dim strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"}
For Each St In strings
Dim encoded = ArithmeticCoding(St, radix)
Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)
Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", St, encoded.Item1, radix, encoded.Item2)
If St <> dec Then
Throw New Exception(vbTab + "However that is incorrect!")
End If
Next
End Sub
End Module
| 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!")
}
}
}
|
Please provide an equivalent version of this VB code in Go. | Module Module1
Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)
Dim size = g.Count
Dim vis(size - 1) As Boolean
Dim l(size - 1) As Integer
Dim x = size
Dim t As New List(Of List(Of Integer))
For i = 1 To size
t.Add(New List(Of Integer))
Next
Dim visit As Action(Of Integer) = Sub(u As Integer)
If Not vis(u) Then
vis(u) = True
For Each v In g(u)
visit(v)
t(v).Add(u)
Next
x -= 1
l(x) = u
End If
End Sub
For i = 1 To size
visit(i - 1)
Next
Dim c(size - 1) As Integer
Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)
If vis(u) Then
vis(u) = False
c(u) = root
For Each v In t(u)
assign(v, root)
Next
End If
End Sub
For Each u In l
assign(u, u)
Next
Return c.ToList
End Function
Sub Main()
Dim g = New List(Of List(Of Integer)) From {
New List(Of Integer) From {1},
New List(Of Integer) From {2},
New List(Of Integer) From {0},
New List(Of Integer) From {1, 2, 4},
New List(Of Integer) From {3, 5},
New List(Of Integer) From {2, 6},
New List(Of Integer) From {5},
New List(Of Integer) From {4, 6, 7}
}
Dim output = Kosaraju(g)
Console.WriteLine("[{0}]", String.Join(", ", output))
End Sub
End Module
| 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 VB code in Go. | Module Module1
Dim symbols As Char() = "XYPFTVNLUZWI█".ToCharArray(),
nRows As Integer = 8, nCols As Integer = 8,
target As Integer = 12, blank As Integer = 12,
grid As Integer()() = New Integer(nRows - 1)() {},
placed As Boolean() = New Boolean(target - 1) {},
pens As List(Of List(Of Integer())), rand As Random,
seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586}
Sub Main()
Unpack(seeds) : rand = New Random() : ShuffleShapes(2)
For r As Integer = 0 To nRows - 1
grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next
For i As Integer = 0 To 3
Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols)
Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank
Next
If Solve(0, 0) Then
PrintResult()
Else
Console.WriteLine("no solution for this configuration:") : PrintResult()
End If
If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
End Sub
Sub ShuffleShapes(count As Integer)
For i As Integer = 0 To count : For j = 0 To pens.Count - 1
Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j
Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp
Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch
Next : Next
End Sub
Sub PrintResult()
For Each r As Integer() In grid : For Each i As Integer In r
Console.Write("{0} ", If(i < 0, ".", symbols(i)))
Next : Console.WriteLine() : Next
End Sub
Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean
If numPlaced = target Then Return True
Dim row As Integer = pos \ nCols, col As Integer = pos Mod nCols
If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced)
For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then
For Each orientation As Integer() In pens(i)
If Not TPO(orientation, row, col, i) Then Continue For
placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True
RmvO(orientation, row, col) : placed(i) = False
Next : End If : Next : Return False
End Function
Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer)
grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2
grid(row + ori(i))(col + ori(i + 1)) = -1 : Next
End Sub
Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer,
ByVal sIdx As Integer) As Boolean
For i As Integer = 0 To ori.Length - 1 Step 2
Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i)
If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse
grid(y)(x) <> -1 Then Return False
Next : grid(row)(col) = sIdx
For i As Integer = 0 To ori.Length - 1 Step 2
grid(row + ori(i))(col + ori(i + 1)) = sIdx
Next : Return True
End Function
Sub Unpack(sv As Integer())
pens = New List(Of List(Of Integer())) : For Each item In sv
Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item),
fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7
If i = 4 Then Mir(exi) Else Rot(exi)
fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi))
Next : pens.Add(Gen) : Next
End Sub
Function Expand(i As Integer) As List(Of Integer)
Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next
End Function
Function ToP(p As List(Of Integer)) As Integer()
Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1)
tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next
tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next
Dim res As New List(Of Integer) : For Each item In tmp.Skip(1)
Dim adj = If((item And 7) > 4, 8, 0)
res.Add((adj + item) \ 8) : res.Add((item And 7) - adj)
Next : Return res.ToArray()
End Function
Function TheSame(a As Integer(), b As Integer()) As Boolean
For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False
Next : Return True
End Function
Sub Rot(ByRef p As List(Of Integer))
For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next
End Sub
Sub Mir(ByRef p As List(Of Integer))
For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next
End Sub
End Module
| package main
import (
"fmt"
"math/rand"
"time"
)
var F = [][]int{
{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},
{1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0},
{1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1},
{1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1},
}
var I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}
var L = [][]int{
{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},
{0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},
{0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0},
}
var N = [][]int{
{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},
{0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},
{1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1},
}
var P = [][]int{
{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},
{1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},
{1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0},
}
var T = [][]int{
{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},
{1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0},
}
var U = [][]int{
{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},
{0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1},
}
var V = [][]int{
{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},
{1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2},
}
var W = [][]int{
{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},
{0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1},
}
var X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}}
var Y = [][]int{
{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},
{0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},
{1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0},
}
var Z = [][]int{
{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},
{0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2},
}
var shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z}
var symbols = []byte("FILNPTUVWXYZ-")
const (
nRows = 8
nCols = 8
blank = 12
)
var grid [nRows][nCols]int
var placed [12]bool
func tryPlaceOrientation(o []int, r, c, shapeIndex int) bool {
for i := 0; i < len(o); i += 2 {
x := c + o[i+1]
y := r + o[i]
if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 {
return false
}
}
grid[r][c] = shapeIndex
for i := 0; i < len(o); i += 2 {
grid[r+o[i]][c+o[i+1]] = shapeIndex
}
return true
}
func removeOrientation(o []int, r, c int) {
grid[r][c] = -1
for i := 0; i < len(o); i += 2 {
grid[r+o[i]][c+o[i+1]] = -1
}
}
func solve(pos, numPlaced int) bool {
if numPlaced == len(shapes) {
return true
}
row := pos / nCols
col := pos % nCols
if grid[row][col] != -1 {
return solve(pos+1, numPlaced)
}
for i := range shapes {
if !placed[i] {
for _, orientation := range shapes[i] {
if !tryPlaceOrientation(orientation, row, col, i) {
continue
}
placed[i] = true
if solve(pos+1, numPlaced+1) {
return true
}
removeOrientation(orientation, row, col)
placed[i] = false
}
}
}
return false
}
func shuffleShapes() {
rand.Shuffle(len(shapes), func(i, j int) {
shapes[i], shapes[j] = shapes[j], shapes[i]
symbols[i], symbols[j] = symbols[j], symbols[i]
})
}
func printResult() {
for _, r := range grid {
for _, i := range r {
fmt.Printf("%c ", symbols[i])
}
fmt.Println()
}
}
func main() {
rand.Seed(time.Now().UnixNano())
shuffleShapes()
for r := 0; r < nRows; r++ {
for i := range grid[r] {
grid[r][i] = -1
}
}
for i := 0; i < 4; i++ {
var randRow, randCol int
for {
randRow = rand.Intn(nRows)
randCol = rand.Intn(nCols)
if grid[randRow][randCol] != blank {
break
}
}
grid[randRow][randCol] = blank
}
if solve(0, 0) {
printResult()
} else {
fmt.Println("No solution")
}
}
|
Convert this VB block to Go, preserving its control flow and logic. | Public Sub backup(filename As String)
If Len(Dir(filename)) > 0 Then
On Error Resume Next
Name filename As filename & ".bak"
Else
If Len(Dir(filename & ".lnk")) > 0 Then
On Error Resume Next
With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk")
link = .TargetPath
.Close
End With
Name link As link & ".bak"
End If
End If
End Sub
Public Sub main()
backup "D:\test.txt"
End Sub
| package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
fn := "myth"
bx := ".backup"
var err error
if tf, err := os.Readlink(fn); err == nil {
fn = tf
}
var fi os.FileInfo
if fi, err = os.Stat(fn); err != nil {
fmt.Println(err)
return
}
if err = os.Rename(fn, fn+bx); err != nil {
fmt.Println(err)
return
}
err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm())
if err != nil {
fmt.Println(err)
}
}
|
Change the following VB code into Go without altering its purpose. | Public Sub backup(filename As String)
If Len(Dir(filename)) > 0 Then
On Error Resume Next
Name filename As filename & ".bak"
Else
If Len(Dir(filename & ".lnk")) > 0 Then
On Error Resume Next
With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk")
link = .TargetPath
.Close
End With
Name link As link & ".bak"
End If
End If
End Sub
Public Sub main()
backup "D:\test.txt"
End Sub
| package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
fn := "myth"
bx := ".backup"
var err error
if tf, err := os.Readlink(fn); err == nil {
fn = tf
}
var fi os.FileInfo
if fi, err = os.Stat(fn); err != nil {
fmt.Println(err)
return
}
if err = os.Rename(fn, fn+bx); err != nil {
fmt.Println(err)
return
}
err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm())
if err != nil {
fmt.Println(err)
}
}
|
Write the same algorithm in Go as shown in this VB implementation. | Imports System.Numerics
Public Class BigRat
Implements IComparable
Public nu, de As BigInteger
Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),
One = New BigRat(BigInteger.One, BigInteger.One)
Sub New(bRat As BigRat)
nu = bRat.nu : de = bRat.de
End Sub
Sub New(n As BigInteger, d As BigInteger)
If d = BigInteger.Zero Then _
Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d)))
Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)
If bi > BigInteger.One Then n /= bi : d /= bi
If d < BigInteger.Zero Then n = -n : d = -d
nu = n : de = d
End Sub
Shared Operator -(x As BigRat) As BigRat
Return New BigRat(-x.nu, x.de)
End Operator
Shared Operator +(x As BigRat, y As BigRat)
Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)
End Operator
Shared Operator -(x As BigRat, y As BigRat) As BigRat
Return x + (-y)
End Operator
Shared Operator *(x As BigRat, y As BigRat) As BigRat
Return New BigRat(x.nu * y.nu, x.de * y.de)
End Operator
Shared Operator /(x As BigRat, y As BigRat) As BigRat
Return New BigRat(x.nu * y.de, x.de * y.nu)
End Operator
Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Dim dif As BigRat = New BigRat(nu, de) - obj
If dif.nu < BigInteger.Zero Then Return -1
If dif.nu > BigInteger.Zero Then Return 1
Return 0
End Function
Shared Operator =(x As BigRat, y As BigRat) As Boolean
Return x.CompareTo(y) = 0
End Operator
Shared Operator <>(x As BigRat, y As BigRat) As Boolean
Return x.CompareTo(y) <> 0
End Operator
Overrides Function ToString() As String
If de = BigInteger.One Then Return nu.ToString
Return String.Format("({0}/{1})", nu, de)
End Function
Shared Function Combine(a As BigRat, b As BigRat) As BigRat
Return (a + b) / (BigRat.One - (a * b))
End Function
End Class
Public Structure Term
Dim c As Integer, br As BigRat
Sub New(cc As Integer, bigr As BigRat)
c = cc : br = bigr
End Sub
End Structure
Module Module1
Function Eval(c As Integer, x As BigRat) As BigRat
If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)
Dim hc As Integer = c \ 2
Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))
End Function
Function Sum(terms As List(Of Term)) As BigRat
If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)
Dim htc As Integer = terms.Count / 2
Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))
End Function
Function ParseLine(ByVal s As String) As List(Of Term)
ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)
While t.Contains(" ") : t = t.Replace(" ", "") : End While
p = t.IndexOf("pi/4=") : If p < 0 Then _
Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function
t = t.Substring(p + 5)
For Each item As String In t.Split(")")
If item.Length > 5 Then
If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse
item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then
Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item)
ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function
End If
x.c = 1 : x.br = New BigRat(BigRat.One)
p = item.IndexOf("/") : If p > 0 Then
x.br.de = UInt64.Parse(item.Substring(p + 1))
item = item.Substring(0, p)
p = item.IndexOf("(") : If p > 0 Then
x.br.nu = UInt64.Parse(item.Substring(p + 1))
p = item.IndexOf("a") : If p > 0 Then
Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c)
If x.c = 0 Then x.c = 1
If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c
End If
ParseLine.Add(x)
End If
End If
End If
Next
End Function
Sub Main(ByVal args As String())
Dim nl As String = vbLf
For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl &
"pi/4 = 2Atan(1/3) + ATan(1/7)" & nl &
"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl &
"pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl &
"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl &
"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl &
"PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl &
"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl &
"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl &
"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl &
"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl &
"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl &
"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl &
"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl &
"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl &
"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl &
"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl)
Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item)
Next
End Sub
End Module
| package main
import (
"fmt"
"math/big"
)
type mTerm struct {
a, n, d int64
}
var testCases = [][]mTerm{
{{1, 1, 2}, {1, 1, 3}},
{{2, 1, 3}, {1, 1, 7}},
{{4, 1, 5}, {-1, 1, 239}},
{{5, 1, 7}, {2, 3, 79}},
{{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},
{{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},
{{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},
{{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},
{{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},
{{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},
{{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},
{{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},
{{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},
{{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},
}
func main() {
for _, m := range testCases {
fmt.Printf("tan %v = %v\n", m, tans(m))
}
}
var one = big.NewRat(1, 1)
func tans(m []mTerm) *big.Rat {
if len(m) == 1 {
return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))
}
half := len(m) / 2
a := tans(m[:half])
b := tans(m[half:])
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
func tanEval(coef int64, f *big.Rat) *big.Rat {
if coef == 1 {
return f
}
if coef < 0 {
r := tanEval(-coef, f)
return r.Neg(r)
}
ca := coef / 2
cb := coef - ca
a := tanEval(ca, f)
b := tanEval(cb, f)
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
|
Change the following VB code into Go without altering its purpose. | Imports System.Numerics
Public Class BigRat
Implements IComparable
Public nu, de As BigInteger
Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),
One = New BigRat(BigInteger.One, BigInteger.One)
Sub New(bRat As BigRat)
nu = bRat.nu : de = bRat.de
End Sub
Sub New(n As BigInteger, d As BigInteger)
If d = BigInteger.Zero Then _
Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d)))
Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)
If bi > BigInteger.One Then n /= bi : d /= bi
If d < BigInteger.Zero Then n = -n : d = -d
nu = n : de = d
End Sub
Shared Operator -(x As BigRat) As BigRat
Return New BigRat(-x.nu, x.de)
End Operator
Shared Operator +(x As BigRat, y As BigRat)
Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)
End Operator
Shared Operator -(x As BigRat, y As BigRat) As BigRat
Return x + (-y)
End Operator
Shared Operator *(x As BigRat, y As BigRat) As BigRat
Return New BigRat(x.nu * y.nu, x.de * y.de)
End Operator
Shared Operator /(x As BigRat, y As BigRat) As BigRat
Return New BigRat(x.nu * y.de, x.de * y.nu)
End Operator
Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Dim dif As BigRat = New BigRat(nu, de) - obj
If dif.nu < BigInteger.Zero Then Return -1
If dif.nu > BigInteger.Zero Then Return 1
Return 0
End Function
Shared Operator =(x As BigRat, y As BigRat) As Boolean
Return x.CompareTo(y) = 0
End Operator
Shared Operator <>(x As BigRat, y As BigRat) As Boolean
Return x.CompareTo(y) <> 0
End Operator
Overrides Function ToString() As String
If de = BigInteger.One Then Return nu.ToString
Return String.Format("({0}/{1})", nu, de)
End Function
Shared Function Combine(a As BigRat, b As BigRat) As BigRat
Return (a + b) / (BigRat.One - (a * b))
End Function
End Class
Public Structure Term
Dim c As Integer, br As BigRat
Sub New(cc As Integer, bigr As BigRat)
c = cc : br = bigr
End Sub
End Structure
Module Module1
Function Eval(c As Integer, x As BigRat) As BigRat
If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)
Dim hc As Integer = c \ 2
Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))
End Function
Function Sum(terms As List(Of Term)) As BigRat
If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)
Dim htc As Integer = terms.Count / 2
Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))
End Function
Function ParseLine(ByVal s As String) As List(Of Term)
ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)
While t.Contains(" ") : t = t.Replace(" ", "") : End While
p = t.IndexOf("pi/4=") : If p < 0 Then _
Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function
t = t.Substring(p + 5)
For Each item As String In t.Split(")")
If item.Length > 5 Then
If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse
item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then
Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item)
ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function
End If
x.c = 1 : x.br = New BigRat(BigRat.One)
p = item.IndexOf("/") : If p > 0 Then
x.br.de = UInt64.Parse(item.Substring(p + 1))
item = item.Substring(0, p)
p = item.IndexOf("(") : If p > 0 Then
x.br.nu = UInt64.Parse(item.Substring(p + 1))
p = item.IndexOf("a") : If p > 0 Then
Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c)
If x.c = 0 Then x.c = 1
If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c
End If
ParseLine.Add(x)
End If
End If
End If
Next
End Function
Sub Main(ByVal args As String())
Dim nl As String = vbLf
For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl &
"pi/4 = 2Atan(1/3) + ATan(1/7)" & nl &
"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl &
"pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl &
"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl &
"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl &
"PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl &
"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl &
"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl &
"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl &
"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl &
"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl &
"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl &
"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl &
"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl &
"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl &
"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl)
Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item)
Next
End Sub
End Module
| package main
import (
"fmt"
"math/big"
)
type mTerm struct {
a, n, d int64
}
var testCases = [][]mTerm{
{{1, 1, 2}, {1, 1, 3}},
{{2, 1, 3}, {1, 1, 7}},
{{4, 1, 5}, {-1, 1, 239}},
{{5, 1, 7}, {2, 3, 79}},
{{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},
{{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},
{{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},
{{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},
{{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},
{{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},
{{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},
{{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},
{{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},
{{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},
}
func main() {
for _, m := range testCases {
fmt.Printf("tan %v = %v\n", m, tans(m))
}
}
var one = big.NewRat(1, 1)
func tans(m []mTerm) *big.Rat {
if len(m) == 1 {
return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))
}
half := len(m) / 2
a := tans(m[:half])
b := tans(m[half:])
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
func tanEval(coef int64, f *big.Rat) *big.Rat {
if coef == 1 {
return f
}
if coef < 0 {
r := tanEval(-coef, f)
return r.Neg(r)
}
ca := coef / 2
cb := coef - ca
a := tanEval(ca, f)
b := tanEval(cb, f)
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
|
Translate the given VB code snippet into Go without altering its behavior. | Imports System, Microsoft.VisualBasic.DateAndTime
Public Module Module1
Const n As Integer = 5
Dim Board As String
Dim Starting As Integer = 1
Dim Target As Integer = 13
Dim Moves As Integer()
Dim bi() As Integer
Dim ib() As Integer
Dim nl As Char = Convert.ToChar(10)
Public Function Dou(s As String) As String
Dou = "" : Dim b As Boolean = True
For Each ch As Char In s
If b Then b = ch <> " "
If b Then Dou &= ch & " " Else Dou = " " & Dou
Next : Dou = Dou.TrimEnd()
End Function
Public Function Fmt(s As String) As String
If s.Length < Board.Length Then Return s
Fmt = "" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) &
If(i = n, s.Substring(Board.Length), "") & nl
Next
End Function
Public Function Triangle(n As Integer) As Integer
Return (n * (n + 1)) / 2
End Function
Public Function Init(s As String, pos As Integer) As String
Init = s : Mid(Init, pos, 1) = "0"
End Function
Public Sub InitIndex()
ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0
For i As Integer = 0 To ib.Length - 1
If i = 0 Then
ib(i) = 0 : bi(j) = 0 : j += 1
Else
If Board(i - 1) = "1" Then ib(i) = j : bi(j) = i : j += 1
End If
Next
End Sub
Public Function solve(brd As String, pegsLeft As Integer) As String
If pegsLeft = 1 Then
If Target = 0 Then Return "Completed"
If brd(bi(Target) - 1) = "1" Then Return "Completed" Else Return "fail"
End If
For i = 1 To Board.Length
If brd(i - 1) = "1" Then
For Each mj In Moves
Dim over As Integer = i + mj
Dim land As Integer = i + 2 * mj
If land >= 1 AndAlso land <= brd.Length _
AndAlso brd(land - 1) = "0" _
AndAlso brd(over - 1) = "1" Then
setPegs(brd, "001", i, over, land)
Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1)
If Res.Length <> 4 Then _
Return brd & info(i, over, land) & nl & Res
setPegs(brd, "110", i, over, land)
End If
Next
End If
Next
Return "fail"
End Function
Function info(frm As Integer, over As Integer, dest As Integer) As String
Return " Peg from " & ib(frm).ToString() & " goes to " & ib(dest).ToString() &
", removing peg at " & ib(over).ToString()
End Function
Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer)
Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2)
End Sub
Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer)
x = Math.Max(Math.Min(x, hi), lo)
End Sub
Public Sub Main()
Dim t As Integer = Triangle(n)
LimitIt(Starting, 1, t)
LimitIt(Target, 0, t)
Dim stime As Date = Now()
Moves = {-n - 1, -n, -1, 1, n, n + 1}
Board = New String("1", n * n)
For i As Integer = 0 To n - 2
Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(" ", n - 1 - i)
Next
InitIndex()
Dim B As String = Init(Board, bi(Starting))
Console.WriteLine(Fmt(B & " Starting with peg removed from " & Starting.ToString()))
Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl)
Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & " ms."
If res(0).Length = 4 Then
If Target = 0 Then
Console.WriteLine("Unable to find a solution with last peg left anywhere.")
Else
Console.WriteLine("Unable to find a solution with last peg left at " &
Target.ToString() & ".")
End If
Console.WriteLine("Computation time: " & ts)
Else
For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next
Console.WriteLine("Computation time to first found solution: " & ts)
End If
If Diagnostics.Debugger.IsAttached Then Console.ReadLine()
End Sub
End Module
| package main
import "fmt"
type solution struct{ peg, over, land int }
type move struct{ from, to int }
var emptyStart = 1
var board [16]bool
var jumpMoves = [16][]move{
{},
{{2, 4}, {3, 6}},
{{4, 7}, {5, 9}},
{{5, 8}, {6, 10}},
{{2, 1}, {5, 6}, {7, 11}, {8, 13}},
{{8, 12}, {9, 14}},
{{3, 1}, {5, 4}, {9, 13}, {10, 15}},
{{4, 2}, {8, 9}},
{{5, 3}, {9, 10}},
{{5, 2}, {8, 7}},
{{9, 8}},
{{12, 13}},
{{8, 5}, {13, 14}},
{{8, 4}, {9, 6}, {12, 11}, {14, 15}},
{{9, 5}, {13, 12}},
{{10, 6}, {14, 13}},
}
var solutions []solution
func initBoard() {
for i := 1; i < 16; i++ {
board[i] = true
}
board[emptyStart] = false
}
func (sol solution) split() (int, int, int) {
return sol.peg, sol.over, sol.land
}
func (mv move) split() (int, int) {
return mv.from, mv.to
}
func drawBoard() {
var pegs [16]byte
for i := 1; i < 16; i++ {
if board[i] {
pegs[i] = fmt.Sprintf("%X", i)[0]
} else {
pegs[i] = '-'
}
}
fmt.Printf(" %c\n", pegs[1])
fmt.Printf(" %c %c\n", pegs[2], pegs[3])
fmt.Printf(" %c %c %c\n", pegs[4], pegs[5], pegs[6])
fmt.Printf(" %c %c %c %c\n", pegs[7], pegs[8], pegs[9], pegs[10])
fmt.Printf(" %c %c %c %c %c\n", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15])
}
func solved() bool {
count := 0
for _, b := range board {
if b {
count++
}
}
return count == 1
}
func solve() {
if solved() {
return
}
for peg := 1; peg < 16; peg++ {
if board[peg] {
for _, mv := range jumpMoves[peg] {
over, land := mv.split()
if board[over] && !board[land] {
saveBoard := board
board[peg] = false
board[over] = false
board[land] = true
solutions = append(solutions, solution{peg, over, land})
solve()
if solved() {
return
}
board = saveBoard
solutions = solutions[:len(solutions)-1]
}
}
}
}
}
func main() {
initBoard()
solve()
initBoard()
drawBoard()
fmt.Printf("Starting with peg %X removed\n\n", emptyStart)
for _, solution := range solutions {
peg, over, land := solution.split()
board[peg] = false
board[over] = false
board[land] = true
drawBoard()
fmt.Printf("Peg %X jumped over %X to land on %X\n\n", peg, over, land)
}
}
|
Generate an equivalent Go version of this VB code. | Public s As String
Public t As Integer
Function s1()
s1 = Len(s) = 12
End Function
Function s2()
t = 0
For i = 7 To 12
t = t - (Mid(s, i, 1) = "1")
Next i
s2 = t = 3
End Function
Function s3()
t = 0
For i = 2 To 12 Step 2
t = t - (Mid(s, i, 1) = "1")
Next i
s3 = t = 2
End Function
Function s4()
s4 = Mid(s, 5, 1) = "0" Or ((Mid(s, 6, 1) = "1" And Mid(s, 7, 1) = "1"))
End Function
Function s5()
s5 = Mid(s, 2, 1) = "0" And Mid(s, 3, 1) = "0" And Mid(s, 4, 1) = "0"
End Function
Function s6()
t = 0
For i = 1 To 12 Step 2
t = t - (Mid(s, i, 1) = "1")
Next i
s6 = t = 4
End Function
Function s7()
s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)
End Function
Function s8()
s8 = Mid(s, 7, 1) = "0" Or (Mid(s, 5, 1) = "1" And Mid(s, 6, 1) = "1")
End Function
Function s9()
t = 0
For i = 1 To 6
t = t - (Mid(s, i, 1) = "1")
Next i
s9 = t = 3
End Function
Function s10()
s10 = Mid(s, 11, 1) = "1" And Mid(s, 12, 1) = "1"
End Function
Function s11()
t = 0
For i = 7 To 9
t = t - (Mid(s, i, 1) = "1")
Next i
s11 = t = 1
End Function
Function s12()
t = 0
For i = 1 To 11
t = t - (Mid(s, i, 1) = "1")
Next i
s12 = t = 4
End Function
Public Sub twelve_statements()
For i = 0 To 2 ^ 12 - 1
s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \ 128)), 5) _
& Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)
For b = 1 To 12
Select Case b
Case 1: If s1 <> (Mid(s, b, 1) = "1") Then Exit For
Case 2: If s2 <> (Mid(s, b, 1) = "1") Then Exit For
Case 3: If s3 <> (Mid(s, b, 1) = "1") Then Exit For
Case 4: If s4 <> (Mid(s, b, 1) = "1") Then Exit For
Case 5: If s5 <> (Mid(s, b, 1) = "1") Then Exit For
Case 6: If s6 <> (Mid(s, b, 1) = "1") Then Exit For
Case 7: If s7 <> (Mid(s, b, 1) = "1") Then Exit For
Case 8: If s8 <> (Mid(s, b, 1) = "1") Then Exit For
Case 9: If s9 <> (Mid(s, b, 1) = "1") Then Exit For
Case 10: If s10 <> (Mid(s, b, 1) = "1") Then Exit For
Case 11: If s11 <> (Mid(s, b, 1) = "1") Then Exit For
Case 12: If s12 <> (Mid(s, b, 1) = "1") Then Exit For
End Select
If b = 12 Then Debug.Print s
Next
Next
End Sub
| package main
import "fmt"
var solution = make(chan int)
var nearMiss = make(chan int)
var done = make(chan bool)
func main() {
for i := 0; i < 4096; i++ {
go checkPerm(i)
}
var ms []int
for i := 0; i < 4096; {
select {
case <-done:
i++
case s := <-solution:
print12("solution", s)
case m := <-nearMiss:
ms = append(ms, m)
}
}
for _, m := range ms {
print12("near miss", m)
}
}
func print12(label string, bits int) {
fmt.Print(label, ":")
for i := 1; i <= 12; i++ {
if bits&1 == 1 {
fmt.Print(" ", i)
}
bits >>= 1
}
fmt.Println()
}
func checkPerm(tz int) {
ts := func(n uint) bool {
return tz>>(n-1)&1 == 1
}
ntrue := func(xs ...uint) int {
nt := 0
for _, x := range xs {
if ts(x) {
nt++
}
}
return nt
}
var con bool
test := func(statement uint, b bool) {
switch {
case ts(statement) == b:
case con:
panic("bail")
default:
con = true
}
}
defer func() {
if x := recover(); x != nil {
if msg, ok := x.(string); !ok && msg != "bail" {
panic(x)
}
}
done <- true
}()
test(1, true)
test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)
test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)
test(4, !ts(5) || ts(6) && ts(7))
test(5, !ts(4) && !ts(3) && !ts(2))
test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)
test(7, ts(2) != ts(3))
test(8, !ts(7) || ts(5) && ts(6))
test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)
test(10, ts(11) && ts(12))
test(11, ntrue(7, 8, 9) == 1)
test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)
if con {
nearMiss <- tz
} else {
solution <- tz
}
}
|
Keep all operations the same but rewrite the snippet in Go. | Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String
Dim suffix As String, parts() As String, exponent As String
Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean
flag = False
fractiondigits = Val(sfractiondigits)
suffixes = " KMGTPEZYXWVU"
number = Replace(number, ",", "", 1)
Dim c As Currency
Dim sign As Integer
If Left(number, 1) = "-" Then
number = Right(number, Len(number) - 1)
outstring = "-"
End If
If Left(number, 1) = "+" Then
number = Right(number, Len(number) - 1)
outstring = "+"
End If
parts = Split(number, "e")
number = parts(0)
If UBound(parts) > 0 Then exponent = parts(1)
parts = Split(number, ".")
number = parts(0)
If UBound(parts) > 0 Then frac = parts(1)
If base = "2" Then
Dim cnumber As Currency
cnumber = Val(number)
nsuffix = 0
Dim dnumber As Double
If cnumber > 1023 Then
cnumber = cnumber / 1024@
nsuffix = nsuffix + 1
dnumber = cnumber
Do While dnumber > 1023
dnumber = dnumber / 1024@
nsuffix = nsuffix + 1
Loop
number = CStr(dnumber)
Else
number = CStr(cnumber)
End If
leadingstring = Int(number)
number = Replace(number, ",", "")
leading = Len(leadingstring)
suffix = Mid(suffixes, nsuffix + 1, 1)
Else
nsuffix = (Len(number) + Val(exponent) - 1) \ 3
If nsuffix < 13 Then
suffix = Mid(suffixes, nsuffix + 1, 1)
leading = (Len(number) - 1) Mod 3 + 1
leadingstring = Left(number, leading)
Else
flag = True
If nsuffix > 32 Then
suffix = "googol"
leading = Len(number) + Val(exponent) - 99
leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), "0")
Else
suffix = "U"
leading = Len(number) + Val(exponent) - 35
If Val(exponent) > 36 Then
leadingstring = number & String$(Val(exponent) - 36, "0")
Else
leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))
End If
End If
End If
End If
If fractiondigits > 0 Then
If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then
fraction = Mid(number, leading + 1, fractiondigits - 1) & _
CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)
Else
fraction = Mid(number, leading + 1, fractiondigits)
End If
Else
If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> "" And sfractiondigits <> "," Then
leadingstring = Mid(number, 1, leading - 1) & _
CStr(Val(Mid(number, leading, 1)) + 1)
End If
End If
If flag Then
If sfractiondigits = "" Or sfractiondigits = "," Then
fraction = ""
End If
Else
If sfractiondigits = "" Or sfractiondigits = "," Then
fraction = Right(number, Len(number) - leading)
End If
End If
outstring = outstring & leadingstring
If Len(fraction) > 0 Then
outstring = outstring & "." & fraction
End If
If base = "2" Then
outstring = outstring & suffix & "i"
Else
outstring = outstring & suffix
End If
suffize = outstring
End Function
Sub program()
Dim s(10) As String, t As String, f As String, r As String
Dim tt() As String, temp As String
s(0) = " 87,654,321"
s(1) = " -998,877,665,544,332,211,000 3"
s(2) = " +112,233 0"
s(3) = " 16,777,216 1"
s(4) = " 456,789,100,000,000 2"
s(5) = " 456,789,100,000,000 2 10"
s(6) = " 456,789,100,000,000 5 2"
s(7) = " 456,789,100,000.000e+00 0 10"
s(8) = " +16777216 , 2"
s(9) = " 1.2e101"
For i = 0 To 9
ReDim tt(0)
t = Trim(s(i))
Do
temp = t
t = Replace(t, " ", " ")
Loop Until temp = t
tt = Split(t, " ")
If UBound(tt) > 0 Then f = tt(1) Else f = ""
If UBound(tt) > 1 Then r = tt(2) Else r = ""
Debug.Print String$(48, "-")
Debug.Print " input number = "; tt(0)
Debug.Print " fraction digs = "; f
Debug.Print " specified radix = "; r
Debug.Print " new number = "; suffize(tt(0), f, r)
Next i
End Sub
| package main
import (
"fmt"
"math/big"
"strconv"
"strings"
)
var suffixes = " KMGTPEZYXWVU"
var ggl = googol()
func googol() *big.Float {
g1 := new(big.Float).SetPrec(500)
g1.SetInt64(10000000000)
g := new(big.Float)
g.Set(g1)
for i := 2; i <= 10; i++ {
g.Mul(g, g1)
}
return g
}
func suffize(arg string) {
fields := strings.Fields(arg)
a := fields[0]
if a == "" {
a = "0"
}
var places, base int
var frac, radix string
switch len(fields) {
case 1:
places = -1
base = 10
case 2:
places, _ = strconv.Atoi(fields[1])
base = 10
frac = strconv.Itoa(places)
case 3:
if fields[1] == "," {
places = 0
frac = ","
} else {
places, _ = strconv.Atoi(fields[1])
frac = strconv.Itoa(places)
}
base, _ = strconv.Atoi(fields[2])
if base != 2 && base != 10 {
base = 10
}
radix = strconv.Itoa(base)
}
a = strings.Replace(a, ",", "", -1)
sign := ""
if a[0] == '+' || a[0] == '-' {
sign = string(a[0])
a = a[1:]
}
b := new(big.Float).SetPrec(500)
d := new(big.Float).SetPrec(500)
b.SetString(a)
g := false
if b.Cmp(ggl) >= 0 {
g = true
}
if !g && base == 2 {
d.SetUint64(1024)
} else if !g && base == 10 {
d.SetUint64(1000)
} else {
d.Set(ggl)
}
c := 0
for b.Cmp(d) >= 0 && c < 12 {
b.Quo(b, d)
c++
}
var suffix string
if !g {
suffix = string(suffixes[c])
} else {
suffix = "googol"
}
if base == 2 {
suffix += "i"
}
fmt.Println(" input number =", fields[0])
fmt.Println(" fraction digs =", frac)
fmt.Println("specified radix =", radix)
fmt.Print(" new number = ")
if places >= 0 {
fmt.Printf("%s%.*f%s\n", sign, places, b, suffix)
} else {
fmt.Printf("%s%s%s\n", sign, b.Text('g', 50), suffix)
}
fmt.Println()
}
func main() {
tests := []string{
"87,654,321",
"-998,877,665,544,332,211,000 3",
"+112,233 0",
"16,777,216 1",
"456,789,100,000,000",
"456,789,100,000,000 2 10",
"456,789,100,000,000 5 2",
"456,789,100,000.000e+00 0 10",
"+16777216 , 2",
"1.2e101",
"446,835,273,728 1",
"1e36",
"1e39",
}
for _, test := range tests {
suffize(test)
}
}
|
Rewrite the snippet below in Go so it works the same as the original VB code. | Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String
Dim suffix As String, parts() As String, exponent As String
Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean
flag = False
fractiondigits = Val(sfractiondigits)
suffixes = " KMGTPEZYXWVU"
number = Replace(number, ",", "", 1)
Dim c As Currency
Dim sign As Integer
If Left(number, 1) = "-" Then
number = Right(number, Len(number) - 1)
outstring = "-"
End If
If Left(number, 1) = "+" Then
number = Right(number, Len(number) - 1)
outstring = "+"
End If
parts = Split(number, "e")
number = parts(0)
If UBound(parts) > 0 Then exponent = parts(1)
parts = Split(number, ".")
number = parts(0)
If UBound(parts) > 0 Then frac = parts(1)
If base = "2" Then
Dim cnumber As Currency
cnumber = Val(number)
nsuffix = 0
Dim dnumber As Double
If cnumber > 1023 Then
cnumber = cnumber / 1024@
nsuffix = nsuffix + 1
dnumber = cnumber
Do While dnumber > 1023
dnumber = dnumber / 1024@
nsuffix = nsuffix + 1
Loop
number = CStr(dnumber)
Else
number = CStr(cnumber)
End If
leadingstring = Int(number)
number = Replace(number, ",", "")
leading = Len(leadingstring)
suffix = Mid(suffixes, nsuffix + 1, 1)
Else
nsuffix = (Len(number) + Val(exponent) - 1) \ 3
If nsuffix < 13 Then
suffix = Mid(suffixes, nsuffix + 1, 1)
leading = (Len(number) - 1) Mod 3 + 1
leadingstring = Left(number, leading)
Else
flag = True
If nsuffix > 32 Then
suffix = "googol"
leading = Len(number) + Val(exponent) - 99
leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), "0")
Else
suffix = "U"
leading = Len(number) + Val(exponent) - 35
If Val(exponent) > 36 Then
leadingstring = number & String$(Val(exponent) - 36, "0")
Else
leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))
End If
End If
End If
End If
If fractiondigits > 0 Then
If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then
fraction = Mid(number, leading + 1, fractiondigits - 1) & _
CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)
Else
fraction = Mid(number, leading + 1, fractiondigits)
End If
Else
If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> "" And sfractiondigits <> "," Then
leadingstring = Mid(number, 1, leading - 1) & _
CStr(Val(Mid(number, leading, 1)) + 1)
End If
End If
If flag Then
If sfractiondigits = "" Or sfractiondigits = "," Then
fraction = ""
End If
Else
If sfractiondigits = "" Or sfractiondigits = "," Then
fraction = Right(number, Len(number) - leading)
End If
End If
outstring = outstring & leadingstring
If Len(fraction) > 0 Then
outstring = outstring & "." & fraction
End If
If base = "2" Then
outstring = outstring & suffix & "i"
Else
outstring = outstring & suffix
End If
suffize = outstring
End Function
Sub program()
Dim s(10) As String, t As String, f As String, r As String
Dim tt() As String, temp As String
s(0) = " 87,654,321"
s(1) = " -998,877,665,544,332,211,000 3"
s(2) = " +112,233 0"
s(3) = " 16,777,216 1"
s(4) = " 456,789,100,000,000 2"
s(5) = " 456,789,100,000,000 2 10"
s(6) = " 456,789,100,000,000 5 2"
s(7) = " 456,789,100,000.000e+00 0 10"
s(8) = " +16777216 , 2"
s(9) = " 1.2e101"
For i = 0 To 9
ReDim tt(0)
t = Trim(s(i))
Do
temp = t
t = Replace(t, " ", " ")
Loop Until temp = t
tt = Split(t, " ")
If UBound(tt) > 0 Then f = tt(1) Else f = ""
If UBound(tt) > 1 Then r = tt(2) Else r = ""
Debug.Print String$(48, "-")
Debug.Print " input number = "; tt(0)
Debug.Print " fraction digs = "; f
Debug.Print " specified radix = "; r
Debug.Print " new number = "; suffize(tt(0), f, r)
Next i
End Sub
| package main
import (
"fmt"
"math/big"
"strconv"
"strings"
)
var suffixes = " KMGTPEZYXWVU"
var ggl = googol()
func googol() *big.Float {
g1 := new(big.Float).SetPrec(500)
g1.SetInt64(10000000000)
g := new(big.Float)
g.Set(g1)
for i := 2; i <= 10; i++ {
g.Mul(g, g1)
}
return g
}
func suffize(arg string) {
fields := strings.Fields(arg)
a := fields[0]
if a == "" {
a = "0"
}
var places, base int
var frac, radix string
switch len(fields) {
case 1:
places = -1
base = 10
case 2:
places, _ = strconv.Atoi(fields[1])
base = 10
frac = strconv.Itoa(places)
case 3:
if fields[1] == "," {
places = 0
frac = ","
} else {
places, _ = strconv.Atoi(fields[1])
frac = strconv.Itoa(places)
}
base, _ = strconv.Atoi(fields[2])
if base != 2 && base != 10 {
base = 10
}
radix = strconv.Itoa(base)
}
a = strings.Replace(a, ",", "", -1)
sign := ""
if a[0] == '+' || a[0] == '-' {
sign = string(a[0])
a = a[1:]
}
b := new(big.Float).SetPrec(500)
d := new(big.Float).SetPrec(500)
b.SetString(a)
g := false
if b.Cmp(ggl) >= 0 {
g = true
}
if !g && base == 2 {
d.SetUint64(1024)
} else if !g && base == 10 {
d.SetUint64(1000)
} else {
d.Set(ggl)
}
c := 0
for b.Cmp(d) >= 0 && c < 12 {
b.Quo(b, d)
c++
}
var suffix string
if !g {
suffix = string(suffixes[c])
} else {
suffix = "googol"
}
if base == 2 {
suffix += "i"
}
fmt.Println(" input number =", fields[0])
fmt.Println(" fraction digs =", frac)
fmt.Println("specified radix =", radix)
fmt.Print(" new number = ")
if places >= 0 {
fmt.Printf("%s%.*f%s\n", sign, places, b, suffix)
} else {
fmt.Printf("%s%s%s\n", sign, b.Text('g', 50), suffix)
}
fmt.Println()
}
func main() {
tests := []string{
"87,654,321",
"-998,877,665,544,332,211,000 3",
"+112,233 0",
"16,777,216 1",
"456,789,100,000,000",
"456,789,100,000,000 2 10",
"456,789,100,000,000 5 2",
"456,789,100,000.000e+00 0 10",
"+16777216 , 2",
"1.2e101",
"446,835,273,728 1",
"1e36",
"1e39",
}
for _, test := range tests {
suffize(test)
}
}
|
Convert this VB snippet to Go and keep its semantics consistent. | Public Sub test()
Dim t(2) As Variant
t(0) = [{1,2}]
t(1) = [{3,4,1}]
t(2) = 5
p = [{"Payload#0","Payload#1","Payload#2","Payload#3","Payload#4","Payload#5","Payload#6"}]
Dim q(6) As Boolean
For i = LBound(t) To UBound(t)
If IsArray(t(i)) Then
For j = LBound(t(i)) To UBound(t(i))
q(t(i)(j)) = True
t(i)(j) = p(t(i)(j) + 1)
Next j
Else
q(t(i)) = True
t(i) = p(t(i) + 1)
End If
Next i
For i = LBound(t) To UBound(t)
If IsArray(t(i)) Then
Debug.Print Join(t(i), ", ")
Else
Debug.Print t(i)
End If
Next i
For i = LBound(q) To UBound(q)
If Not q(i) Then Debug.Print p(i + 1); " is not used"
Next i
End Sub
| package main
import (
"fmt"
"os"
"sort"
"strings"
"text/template"
)
func main() {
const t = `[[[{{index .P 1}}, {{index .P 2}}],
[{{index .P 3}}, {{index .P 4}}, {{index .P 1}}],
{{index .P 5}}]]
`
type S struct {
P map[int]string
}
var s S
s.P = map[int]string{
0: "'Payload#0'", 1: "'Payload#1'", 2: "'Payload#2'", 3: "'Payload#3'",
4: "'Payload#4'", 5: "'Payload#5'", 6: "'Payload#6'",
}
tmpl := template.Must(template.New("").Parse(t))
tmpl.Execute(os.Stdout, s)
var unused []int
for k, _ := range s.P {
if !strings.Contains(t, fmt.Sprintf("{{index .P %d}}", k)) {
unused = append(unused, k)
}
}
sort.Ints(unused)
fmt.Println("\nThe unused payloads have indices of :", unused)
}
|
Generate an equivalent C++ version of this Go code. | package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
}
| #include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
string readFile (string path) {
string contents;
string line;
ifstream inFile(path);
while (getline (inFile, line)) {
contents.append(line);
contents.append("\n");
}
inFile.close();
return contents;
}
double entropy (string X) {
const int MAXCHAR = 127;
int N = X.length();
int count[MAXCHAR];
double count_i;
char ch;
double sum = 0.0;
for (int i = 0; i < MAXCHAR; i++) count[i] = 0;
for (int pos = 0; pos < N; pos++) {
ch = X[pos];
count[(int)ch]++;
}
for (int n_i = 0; n_i < MAXCHAR; n_i++) {
count_i = count[n_i];
if (count_i > 0) sum -= count_i / N * log2(count_i / N);
}
return sum;
}
int main () {
cout<<entropy(readFile("entropy.cpp"));
return 0;
}
|
Port the provided Go code into C++ while preserving the original functionality. | package main
import (
"fmt"
"net"
)
func main() {
if addrs, err := net.LookupHost("www.kame.net"); err == nil {
fmt.Println(addrs)
} else {
fmt.Println(err)
}
}
| #include <Rcpp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace Rcpp ;
CharacterVector getNameInfo(std::string fqdn) {
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);
if (error) { return(NA_STRING); }
int i = 0 ;
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (!error) { i++ ; }
}
CharacterVector results(i) ;
i = 0;
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (!error) { results[i++] = host ; }
}
freeaddrinfo(res0);
return(results) ;
}
|
Produce a functionally identical C++ code for the snippet given in Go. | package main
import "github.com/fogleman/gg"
var points []gg.Point
const width = 81
func peano(x, y, lg, i1, i2 int) {
if lg == 1 {
px := float64(width-x) * 10
py := float64(width-y) * 10
points = append(points, gg.Point{px, py})
return
}
lg /= 3
peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)
peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)
peano(x+lg, y+lg, lg, i1, 1-i2)
peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)
peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)
peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)
peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)
peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)
peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)
}
func main() {
peano(0, 0, width, 0, 0)
dc := gg.NewContext(820, 820)
dc.SetRGB(1, 1, 1)
dc.Clear()
for _, p := range points {
dc.LineTo(p.X, p.Y)
}
dc.SetRGB(1, 0, 1)
dc.SetLineWidth(1)
dc.Stroke()
dc.SavePNG("peano.png")
}
| #include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class peano_curve {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void peano_curve::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = length;
y_ = length;
angle_ = 90;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "L";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string peano_curve::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
switch (c) {
case 'L':
t += "LFRFL-F-RFLFR+F+LFRFL";
break;
case 'R':
t += "RFLFR+F+LFRFL-F-RFLFR";
break;
default:
t += c;
break;
}
}
return t;
}
void peano_curve::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ += length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void peano_curve::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
line(out);
break;
case '+':
angle_ = (angle_ + 90) % 360;
break;
case '-':
angle_ = (angle_ - 90) % 360;
break;
}
}
}
int main() {
std::ofstream out("peano_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
peano_curve pc;
pc.write(out, 656, 8, 4);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func dice5() int {
return rand.Intn(5) + 1
}
func dice7() (i int) {
for {
i = 5*dice5() + dice5()
if i < 27 {
break
}
}
return (i / 3) - 1
}
func distCheck(f func() int, n int,
repeats int, delta float64) (max float64, flatEnough bool) {
count := make([]int, n)
for i := 0; i < repeats; i++ {
count[f()-1]++
}
expected := float64(repeats) / float64(n)
for _, c := range count {
max = math.Max(max, math.Abs(float64(c)-expected))
}
return max, max < delta
}
func main() {
rand.Seed(time.Now().UnixNano())
const calls = 1000000
max, flatEnough := distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
max, flatEnough = distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
}
| template<typename F> class fivetoseven
{
public:
fivetoseven(F f): d5(f), rem(0), max(1) {}
int operator()();
private:
F d5;
int rem, max;
};
template<typename F>
int fivetoseven<F>::operator()()
{
while (rem/7 == max/7)
{
while (max < 7)
{
int rand5 = d5()-1;
max *= 5;
rem = 5*rem + rand5;
}
int groups = max / 7;
if (rem >= 7*groups)
{
rem -= 7*groups;
max -= 7*groups;
}
}
int result = rem % 7;
rem /= 7;
max /= 7;
return result+1;
}
int d5()
{
return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;
}
fivetoseven<int(*)()> d7(d5);
int main()
{
srand(time(0));
test_distribution(d5, 1000000, 0.001);
test_distribution(d7, 1000000, 0.001);
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"strings"
)
func main() {
p, tests, swaps := Solution()
fmt.Println(p)
fmt.Println("Tested", tests, "positions and did", swaps, "swaps.")
}
const conn = `
A B
/|\ /|\
/ | X | \
/ |/ \| \
C - D - E - F
\ |\ /| /
\ | X | /
\|/ \|/
G H`
var connections = []struct{ a, b int }{
{0, 2}, {0, 3}, {0, 4},
{1, 3}, {1, 4}, {1, 5},
{6, 2}, {6, 3}, {6, 4},
{7, 3}, {7, 4}, {7, 5},
{2, 3}, {3, 4}, {4, 5},
}
type pegs [8]int
func (p *pegs) Valid() bool {
for _, c := range connections {
if absdiff(p[c.a], p[c.b]) <= 1 {
return false
}
}
return true
}
func Solution() (p *pegs, tests, swaps int) {
var recurse func(int) bool
recurse = func(i int) bool {
if i >= len(p)-1 {
tests++
return p.Valid()
}
for j := i; j < len(p); j++ {
swaps++
p[i], p[j] = p[j], p[i]
if recurse(i + 1) {
return true
}
p[i], p[j] = p[j], p[i]
}
return false
}
p = &pegs{1, 2, 3, 4, 5, 6, 7, 8}
recurse(0)
return
}
func (p *pegs) String() string {
return strings.Map(func(r rune) rune {
if 'A' <= r && r <= 'H' {
return rune(p[r-'A'] + '0')
}
return r
}, conn)
}
func absdiff(a, b int) int {
if a > b {
return a - b
}
return b - a
}
| #include <array>
#include <iostream>
#include <vector>
std::vector<std::pair<int, int>> connections = {
{0, 2}, {0, 3}, {0, 4},
{1, 3}, {1, 4}, {1, 5},
{6, 2}, {6, 3}, {6, 4},
{7, 3}, {7, 4}, {7, 5},
{2, 3}, {3, 4}, {4, 5},
};
std::array<int, 8> pegs;
int num = 0;
void printSolution() {
std::cout << "----- " << num++ << " -----\n";
std::cout << " " << pegs[0] << ' ' << pegs[1] << '\n';
std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\n';
std::cout << " " << pegs[6] << ' ' << pegs[7] << '\n';
std::cout << '\n';
}
bool valid() {
for (size_t i = 0; i < connections.size(); i++) {
if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {
return false;
}
}
return true;
}
void solution(int le, int ri) {
if (le == ri) {
if (valid()) {
printSolution();
}
} else {
for (size_t i = le; i <= ri; i++) {
std::swap(pegs[le], pegs[i]);
solution(le + 1, ri);
std::swap(pegs[le], pegs[i]);
}
}
}
int main() {
pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };
solution(0, pegs.size() - 1);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import "fmt"
func isPrime(n uint64) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := uint64(5)
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func ord(n int) string {
m := n % 100
if m >= 4 && m <= 20 {
return fmt.Sprintf("%dth", n)
}
m %= 10
suffix := "th"
if m < 4 {
switch m {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
}
}
return fmt.Sprintf("%d%s", n, suffix)
}
func isMagnanimous(n uint64) bool {
if n < 10 {
return true
}
for p := uint64(10); ; p *= 10 {
q := n / p
r := n % p
if !isPrime(q + r) {
return false
}
if q < 10 {
break
}
}
return true
}
func listMags(from, thru, digs, perLine int) {
if from < 2 {
fmt.Println("\nFirst", thru, "magnanimous numbers:")
} else {
fmt.Printf("\n%s through %s magnanimous numbers:\n", ord(from), ord(thru))
}
for i, c := uint64(0), 0; c < thru; i++ {
if isMagnanimous(i) {
c++
if c >= from {
fmt.Printf("%*d ", digs, i)
if c%perLine == 0 {
fmt.Println()
}
}
}
}
}
func main() {
listMags(1, 45, 3, 15)
listMags(241, 250, 1, 10)
listMags(391, 400, 1, 10)
}
| #include <iomanip>
#include <iostream>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
bool is_magnanimous(unsigned int n) {
for (unsigned int p = 10; n >= p; p *= 10) {
if (!is_prime(n % p + n / p))
return false;
}
return true;
}
int main() {
unsigned int count = 0, n = 0;
std::cout << "First 45 magnanimous numbers:\n";
for (; count < 45; ++n) {
if (is_magnanimous(n)) {
if (count > 0)
std::cout << (count % 15 == 0 ? "\n" : ", ");
std::cout << std::setw(3) << n;
++count;
}
}
std::cout << "\n\n241st through 250th magnanimous numbers:\n";
for (unsigned int i = 0; count < 250; ++n) {
if (is_magnanimous(n)) {
if (count++ >= 240) {
if (i++ > 0)
std::cout << ", ";
std::cout << n;
}
}
}
std::cout << "\n\n391st through 400th magnanimous numbers:\n";
for (unsigned int i = 0; count < 400; ++n) {
if (is_magnanimous(n)) {
if (count++ >= 390) {
if (i++ > 0)
std::cout << ", ";
std::cout << n;
}
}
}
std::cout << '\n';
return 0;
}
|
Convert the following code from Go to C++, ensuring the logic remains intact. | package main
import (
"container/heap"
"fmt"
)
func main() {
p := newP()
fmt.Print("First twenty: ")
for i := 0; i < 20; i++ {
fmt.Print(p(), " ")
}
fmt.Print("\nBetween 100 and 150: ")
n := p()
for n <= 100 {
n = p()
}
for ; n < 150; n = p() {
fmt.Print(n, " ")
}
for n <= 7700 {
n = p()
}
c := 0
for ; n < 8000; n = p() {
c++
}
fmt.Println("\nNumber beween 7,700 and 8,000:", c)
p = newP()
for i := 1; i < 10000; i++ {
p()
}
fmt.Println("10,000th prime:", p())
}
func newP() func() int {
n := 1
var pq pQueue
top := &pMult{2, 4, 0}
return func() int {
for {
n++
if n < top.pMult {
heap.Push(&pq, &pMult{prime: n, pMult: n * n})
top = pq[0]
return n
}
for top.pMult == n {
top.pMult += top.prime
heap.Fix(&pq, 0)
top = pq[0]
}
}
}
}
type pMult struct {
prime int
pMult int
index int
}
type pQueue []*pMult
func (q pQueue) Len() int { return len(q) }
func (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }
func (q pQueue) Swap(i, j int) {
q[i], q[j] = q[j], q[i]
q[i].index = i
q[j].index = j
}
func (p *pQueue) Push(x interface{}) {
q := *p
e := x.(*pMult)
e.index = len(q)
*p = append(q, e)
}
func (p *pQueue) Pop() interface{} {
q := *p
last := len(q) - 1
e := q[last]
*p = q[:last]
return e
}
| #include <iostream>
#include <cstdint>
#include <queue>
#include <utility>
#include <vector>
#include <limits>
template<typename integer>
class prime_generator {
public:
integer next_prime();
integer count() const {
return count_;
}
private:
struct queue_item {
queue_item(integer prime, integer multiple, unsigned int wheel_index) :
prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}
integer prime_;
integer multiple_;
unsigned int wheel_index_;
};
struct cmp {
bool operator()(const queue_item& a, const queue_item& b) const {
return a.multiple_ > b.multiple_;
}
};
static integer wheel_next(unsigned int& index) {
integer offset = wheel_[index];
++index;
if (index == std::size(wheel_))
index = 0;
return offset;
}
typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;
integer next_ = 11;
integer count_ = 0;
queue queue_;
unsigned int wheel_index_ = 0;
static const unsigned int wheel_[];
static const integer primes_[];
};
template<typename integer>
const unsigned int prime_generator<integer>::wheel_[] = {
2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,
6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,
2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10
};
template<typename integer>
const integer prime_generator<integer>::primes_[] = {
2, 3, 5, 7
};
template<typename integer>
integer prime_generator<integer>::next_prime() {
if (count_ < std::size(primes_))
return primes_[count_++];
integer n = next_;
integer prev = 0;
while (!queue_.empty()) {
queue_item item = queue_.top();
if (prev != 0 && prev != item.multiple_)
n += wheel_next(wheel_index_);
if (item.multiple_ > n)
break;
else if (item.multiple_ == n) {
queue_.pop();
queue_item new_item(item);
new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);
queue_.push(new_item);
}
else
throw std::overflow_error("prime_generator: overflow!");
prev = item.multiple_;
}
if (std::numeric_limits<integer>::max()/n > n)
queue_.emplace(n, n * n, wheel_index_);
next_ = n + wheel_next(wheel_index_);
++count_;
return n;
}
int main() {
typedef uint32_t integer;
prime_generator<integer> pgen;
std::cout << "First 20 primes:\n";
for (int i = 0; i < 20; ++i) {
integer p = pgen.next_prime();
if (i != 0)
std::cout << ", ";
std::cout << p;
}
std::cout << "\nPrimes between 100 and 150:\n";
for (int n = 0; ; ) {
integer p = pgen.next_prime();
if (p > 150)
break;
if (p >= 100) {
if (n != 0)
std::cout << ", ";
std::cout << p;
++n;
}
}
int count = 0;
for (;;) {
integer p = pgen.next_prime();
if (p > 8000)
break;
if (p >= 7700)
++count;
}
std::cout << "\nNumber of primes between 7700 and 8000: " << count << '\n';
for (integer n = 10000; n <= 10000000; n *= 10) {
integer prime;
while (pgen.count() != n)
prime = pgen.next_prime();
std::cout << n << "th prime: " << prime << '\n';
}
return 0;
}
|
Convert this Go snippet to C++ and keep its semantics consistent. | package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or s as your play. Anything else ends the game.")
fmt.Println("Running score shown as <your wins>:<my wins>")
var pi string
var aScore, pScore int
sl := 3
pcf := make([]int, 3)
var plays int
aChoice := rand.Intn(3)
for {
fmt.Print("Play: ")
_, err := fmt.Scanln(&pi)
if err != nil || len(pi) != 1 {
break
}
pChoice := strings.Index(rps, pi)
if pChoice < 0 {
break
}
pcf[pChoice]++
plays++
fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice])
switch (aChoice - pChoice + 3) % 3 {
case 0:
fmt.Println("Tie.")
case 1:
fmt.Printf("%s. My point.\n", msg[aChoice])
aScore++
case 2:
fmt.Printf("%s. Your point.\n", msg[pChoice])
pScore++
}
sl, _ = fmt.Printf("%d:%d ", pScore, aScore)
switch rn := rand.Intn(plays); {
case rn < pcf[0]:
aChoice = 1
case rn < pcf[0]+pcf[1]:
aChoice = 2
default:
aChoice = 0
}
}
}
| #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };
enum indexes { PLAYER, COMPUTER, DRAW };
class stats
{
public:
stats() : _draw( 0 )
{
ZeroMemory( _moves, sizeof( _moves ) );
ZeroMemory( _win, sizeof( _win ) );
}
void draw() { _draw++; }
void win( int p ) { _win[p]++; }
void move( int p, int m ) { _moves[p][m]++; }
int getMove( int p, int m ) { return _moves[p][m]; }
string format( int a )
{
char t[32];
wsprintf( t, "%.3d", a );
string d( t );
return d;
}
void print()
{
string d = format( _draw ),
pw = format( _win[PLAYER] ), cw = format( _win[COMPUTER] ),
pr = format( _moves[PLAYER][ROCK] ), cr = format( _moves[COMPUTER][ROCK] ),
pp = format( _moves[PLAYER][PAPER] ), cp = format( _moves[COMPUTER][PAPER] ),
ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),
pl = format( _moves[PLAYER][LIZARD] ), cl = format( _moves[COMPUTER][LIZARD] ),
pk = format( _moves[PLAYER][SPOCK] ), ck = format( _moves[COMPUTER][SPOCK] );
system( "cls" );
cout << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |" << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << "| PLAYER | " << pw << " | | " << pr << " | " << pp << " | " << ps << " | " << pl << " | " << pk << " |" << endl;
cout << "+----------+-------+ " << d << " +--------+---------+----------+--------+---------+" << endl;
cout << "| COMPUTER | " << cw << " | | " << cr << " | " << cp << " | " << cs << " | " << cl << " | " << ck << " |" << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << endl << endl;
system( "pause" );
}
private:
int _moves[2][MX_C], _win[2], _draw;
};
class rps
{
private:
int makeMove()
{
int total = 0, r, s;
for( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );
r = rand() % total;
for( int i = ROCK; i < SCISSORS; i++ )
{
s = statistics.getMove( PLAYER, i );
if( r < s ) return ( i + 1 );
r -= s;
}
return ROCK;
}
void printMove( int p, int m )
{
if( p == COMPUTER ) cout << "My move: ";
else cout << "Your move: ";
switch( m )
{
case ROCK: cout << "ROCK\n"; break;
case PAPER: cout << "PAPER\n"; break;
case SCISSORS: cout << "SCISSORS\n"; break;
case LIZARD: cout << "LIZARD\n"; break;
case SPOCK: cout << "SPOCK\n";
}
}
public:
rps()
{
checker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;
checker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;
checker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;
checker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;
checker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;
}
void play()
{
int p, r, m;
while( true )
{
cout << "What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? ";
cin >> p;
if( !p || p < 0 ) break;
if( p > 0 && p < 6 )
{
p--;
cout << endl;
printMove( PLAYER, p );
statistics.move( PLAYER, p );
m = makeMove();
statistics.move( COMPUTER, m );
printMove( COMPUTER, m );
r = checker[p][m];
switch( r )
{
case DRAW:
cout << endl << "DRAW!" << endl << endl;
statistics.draw();
break;
case COMPUTER:
cout << endl << "I WIN!" << endl << endl;
statistics.win( COMPUTER );
break;
case PLAYER:
cout << endl << "YOU WIN!" << endl << endl;
statistics.win( PLAYER );
}
system( "pause" );
}
system( "cls" );
}
statistics.print();
}
private:
stats statistics;
int checker[MX_C][MX_C];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
rps game;
game.play();
return 0;
}
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
| #include <iostream>
int main()
{
int dim1, dim2;
std::cin >> dim1 >> dim2;
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
for (int i = 0; i < dim1; ++i)
array[i] = array_data + dim2*i;
array[0][0] = 3.5;
std::cout << array[0][0] << std::endl;
delete[] array;
delete[] array_data;
return 0;
}
|
Convert this Go snippet to C++ and keep its semantics consistent. | package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
func crt(a, n []*big.Int) (*big.Int, error) {
p := new(big.Int).Set(n[0])
for _, n1 := range n[1:] {
p.Mul(p, n1)
}
var x, q, s, z big.Int
for i, n1 := range n {
q.Div(p, n1)
z.GCD(nil, &s, n1, &q)
if z.Cmp(one) != 0 {
return nil, fmt.Errorf("%d not coprime", n1)
}
x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))
}
return x.Mod(&x, p), nil
}
func main() {
n := []*big.Int{
big.NewInt(3),
big.NewInt(5),
big.NewInt(7),
}
a := []*big.Int{
big.NewInt(2),
big.NewInt(3),
big.NewInt(2),
}
fmt.Println(crt(a, n))
}
|
#include <iostream>
#include <numeric>
#include <vector>
#include <execution>
template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {
_Ty b0 = b;
_Ty x0 = 0;
_Ty x1 = 1;
if (b == 1) {
return 1;
}
while (a > 1) {
_Ty q = a / b;
_Ty amb = a % b;
a = b;
b = amb;
_Ty xqx = x1 - q * x0;
x1 = x0;
x0 = xqx;
}
if (x1 < 0) {
x1 += b0;
}
return x1;
}
template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {
_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });
_Ty sm = 0;
for (int i = 0; i < n.size(); i++) {
_Ty p = prod / n[i];
sm += a[i] * mulInv(p, n[i]) * p;
}
return sm % prod;
}
int main() {
vector<int> n = { 3, 5, 7 };
vector<int> a = { 2, 3, 2 };
cout << chineseRemainder(n,a) << endl;
return 0;
}
|
Change the programming language of this snippet from Go to C++ without modifying what it does. | package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
func crt(a, n []*big.Int) (*big.Int, error) {
p := new(big.Int).Set(n[0])
for _, n1 := range n[1:] {
p.Mul(p, n1)
}
var x, q, s, z big.Int
for i, n1 := range n {
q.Div(p, n1)
z.GCD(nil, &s, n1, &q)
if z.Cmp(one) != 0 {
return nil, fmt.Errorf("%d not coprime", n1)
}
x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))
}
return x.Mod(&x, p), nil
}
func main() {
n := []*big.Int{
big.NewInt(3),
big.NewInt(5),
big.NewInt(7),
}
a := []*big.Int{
big.NewInt(2),
big.NewInt(3),
big.NewInt(2),
}
fmt.Println(crt(a, n))
}
|
#include <iostream>
#include <numeric>
#include <vector>
#include <execution>
template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {
_Ty b0 = b;
_Ty x0 = 0;
_Ty x1 = 1;
if (b == 1) {
return 1;
}
while (a > 1) {
_Ty q = a / b;
_Ty amb = a % b;
a = b;
b = amb;
_Ty xqx = x1 - q * x0;
x1 = x0;
x0 = xqx;
}
if (x1 < 0) {
x1 += b0;
}
return x1;
}
template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {
_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });
_Ty sm = 0;
for (int i = 0; i < n.size(); i++) {
_Ty p = prod / n[i];
sm += a[i] * mulInv(p, n[i]) * p;
}
return sm % prod;
}
int main() {
vector<int> n = { 3, 5, 7 };
vector<int> a = { 2, 3, 2 };
cout << chineseRemainder(n,a) << endl;
return 0;
}
|
Convert the following code from Go to C++, ensuring the logic remains intact. | package main
import (
"fmt"
"strings"
)
var encoded =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" +
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" +
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" +
"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" +
"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" +
"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" +
"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" +
"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" +
"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" +
"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" +
"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" +
"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" +
"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" +
"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" +
"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" +
"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" +
"FWAML ZZRXJ EKAHV FASMU LVVUT TGK"
var freq = [26]float64{
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074,
}
func sum(a []float64) (sum float64) {
for _, f := range a {
sum += f
}
return
}
func bestMatch(a []float64) int {
sum := sum(a)
bestFit, bestRotate := 1e100, 0
for rotate := 0; rotate < 26; rotate++ {
fit := 0.0
for i := 0; i < 26; i++ {
d := a[(i+rotate)%26]/sum - freq[i]
fit += d * d / freq[i]
}
if fit < bestFit {
bestFit, bestRotate = fit, rotate
}
}
return bestRotate
}
func freqEveryNth(msg []int, key []byte) float64 {
l := len(msg)
interval := len(key)
out := make([]float64, 26)
accu := make([]float64, 26)
for j := 0; j < interval; j++ {
for k := 0; k < 26; k++ {
out[k] = 0.0
}
for i := j; i < l; i += interval {
out[msg[i]]++
}
rot := bestMatch(out)
key[j] = byte(rot + 65)
for i := 0; i < 26; i++ {
accu[i] += out[(i+rot)%26]
}
}
sum := sum(accu)
ret := 0.0
for i := 0; i < 26; i++ {
d := accu[i]/sum - freq[i]
ret += d * d / freq[i]
}
return ret
}
func decrypt(text, key string) string {
var sb strings.Builder
ki := 0
for _, c := range text {
if c < 'A' || c > 'Z' {
continue
}
ci := (c - rune(key[ki]) + 26) % 26
sb.WriteRune(ci + 65)
ki = (ki + 1) % len(key)
}
return sb.String()
}
func main() {
enc := strings.Replace(encoded, " ", "", -1)
txt := make([]int, len(enc))
for i := 0; i < len(txt); i++ {
txt[i] = int(enc[i] - 'A')
}
bestFit, bestKey := 1e100, ""
fmt.Println(" Fit Length Key")
for j := 1; j <= 26; j++ {
key := make([]byte, j)
fit := freqEveryNth(txt, key)
sKey := string(key)
fmt.Printf("%f %2d %s", fit, j, sKey)
if fit < bestFit {
bestFit, bestKey = fit, sKey
fmt.Print(" <--- best so far")
}
fmt.Println()
}
fmt.Println("\nBest key :", bestKey)
fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey))
}
| #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <array>
using namespace std;
typedef array<pair<char, double>, 26> FreqArray;
class VigenereAnalyser
{
private:
array<double, 26> targets;
array<double, 26> sortedTargets;
FreqArray freq;
FreqArray& frequency(const string& input)
{
for (char c = 'A'; c <= 'Z'; ++c)
freq[c - 'A'] = make_pair(c, 0);
for (size_t i = 0; i < input.size(); ++i)
freq[input[i] - 'A'].second++;
return freq;
}
double correlation(const string& input)
{
double result = 0.0;
frequency(input);
sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool
{ return u.second < v.second; });
for (size_t i = 0; i < 26; ++i)
result += freq[i].second * sortedTargets[i];
return result;
}
public:
VigenereAnalyser(const array<double, 26>& targetFreqs)
{
targets = targetFreqs;
sortedTargets = targets;
sort(sortedTargets.begin(), sortedTargets.end());
}
pair<string, string> analyze(string input)
{
string cleaned;
for (size_t i = 0; i < input.size(); ++i)
{
if (input[i] >= 'A' && input[i] <= 'Z')
cleaned += input[i];
else if (input[i] >= 'a' && input[i] <= 'z')
cleaned += input[i] + 'A' - 'a';
}
size_t bestLength = 0;
double bestCorr = -100.0;
for (size_t i = 2; i < cleaned.size() / 20; ++i)
{
vector<string> pieces(i);
for (size_t j = 0; j < cleaned.size(); ++j)
pieces[j % i] += cleaned[j];
double corr = -0.5*i;
for (size_t j = 0; j < i; ++j)
corr += correlation(pieces[j]);
if (corr > bestCorr)
{
bestLength = i;
bestCorr = corr;
}
}
if (bestLength == 0)
return make_pair("Text is too short to analyze", "");
vector<string> pieces(bestLength);
for (size_t i = 0; i < cleaned.size(); ++i)
pieces[i % bestLength] += cleaned[i];
vector<FreqArray> freqs;
for (size_t i = 0; i < bestLength; ++i)
freqs.push_back(frequency(pieces[i]));
string key = "";
for (size_t i = 0; i < bestLength; ++i)
{
sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool
{ return u.second > v.second; });
size_t m = 0;
double mCorr = 0.0;
for (size_t j = 0; j < 26; ++j)
{
double corr = 0.0;
char c = 'A' + j;
for (size_t k = 0; k < 26; ++k)
{
int d = (freqs[i][k].first - c + 26) % 26;
corr += freqs[i][k].second * targets[d];
}
if (corr > mCorr)
{
m = j;
mCorr = corr;
}
}
key += m + 'A';
}
string result = "";
for (size_t i = 0; i < cleaned.size(); ++i)
result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';
return make_pair(result, key);
}
};
int main()
{
string input =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH"
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD"
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS"
"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG"
"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ"
"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS"
"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT"
"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST"
"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH"
"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV"
"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW"
"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO"
"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR"
"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX"
"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB"
"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA"
"FWAML ZZRXJ EKAHV FASMU LVVUT TGK";
array<double, 26> english = {
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,
0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,
0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,
0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,
0.01974, 0.00074};
VigenereAnalyser va(english);
pair<string, string> output = va.analyze(input);
cout << "Key: " << output.second << endl << endl;
cout << "Text: " << output.first << endl;
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import (
"fmt"
"math/big"
)
type lft struct {
q,r,s,t big.Int
}
func (t *lft) extr(x *big.Int) *big.Rat {
var n, d big.Int
var r big.Rat
return r.SetFrac(
n.Add(n.Mul(&t.q, x), &t.r),
d.Add(d.Mul(&t.s, x), &t.t))
}
var three = big.NewInt(3)
var four = big.NewInt(4)
func (t *lft) next() *big.Int {
r := t.extr(three)
var f big.Int
return f.Div(r.Num(), r.Denom())
}
func (t *lft) safe(n *big.Int) bool {
r := t.extr(four)
var f big.Int
if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {
return true
}
return false
}
func (t *lft) comp(u *lft) *lft {
var r lft
var a, b big.Int
r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))
r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))
r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))
r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))
return &r
}
func (t *lft) prod(n *big.Int) *lft {
var r lft
r.q.SetInt64(10)
r.r.Mul(r.r.SetInt64(-10), n)
r.t.SetInt64(1)
return r.comp(t)
}
func main() {
z := new(lft)
z.q.SetInt64(1)
z.t.SetInt64(1)
var k int64
lfts := func() *lft {
k++
r := new(lft)
r.q.SetInt64(k)
r.r.SetInt64(4*k+2)
r.t.SetInt64(2*k+1)
return r
}
for {
y := z.next()
if z.safe(y) {
fmt.Print(y)
z = z.prod(y)
} else {
z = z.comp(lfts())
}
}
}
| #include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
class Gospers
{
cpp_int q, r, t, i, n;
public:
Gospers() : q{1}, r{0}, t{1}, i{1}
{
++*this;
}
Gospers& operator++()
{
n = (q*(27*i-12)+5*r) / (5*t);
while(n != (q*(675*i-216)+125*r)/(125*t))
{
r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);
q = i*(2*i-1)*q;
t = 3*(3*i+1)*(3*i+2)*t;
i++;
n = (q*(27*i-12)+5*r) / (5*t);
}
q = 10*q;
r = 10*r-10*n*t;
return *this;
}
int operator*()
{
return (int)n;
}
};
int main()
{
Gospers g;
std::cout << *g << ".";
for(;;)
{
std::cout << *++g;
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Go version. | package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap()
for n := 1; n <= 10; n++ {
showQ(n)
}
showQ(1000)
count, p := 0, 1
for n := 2; n <= 1e5; n++ {
qn := q(n)
if qn < p {
count++
}
p = qn
}
fmt.Println("count:", count)
initMap()
showQ(1e6)
}
func showQ(n int) {
fmt.Printf("Q(%d) = %d\n", n, q(n))
}
| #include <iostream>
int main() {
const int size = 100000;
int hofstadters[size] = { 1, 1 };
for (int i = 3 ; i < size; i++)
hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +
hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];
std::cout << "The first 10 numbers are: ";
for (int i = 0; i < 10; i++)
std::cout << hofstadters[ i ] << ' ';
std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl;
int less_than_preceding = 0;
for (int i = 0; i < size - 1; i++)
if (hofstadters[ i + 1 ] < hofstadters[ i ])
less_than_preceding++;
std::cout << "In array of size: " << size << ", ";
std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.