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. | Imports System
Module Sorting_Using_a_Custom_Comparator
Function CustomComparator(ByVal x As String, ByVal y As String) As Integer
Dim result As Integer
result = y.Length - x.Length
If result = 0 Then
result = String.Compare(x, y, True)
End If
Return result
End Function
Sub Main()
Dim strings As String() = {"test", "Zoom", "strings", "a"}
Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))
End Sub
End Module
| package main
import (
"fmt"
"sort"
"strings"
)
type sortable []string
func (s sortable) Len() int { return len(s) }
func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s sortable) Less(i, j int) bool {
a, b := s[i], s[j]
if len(a) != len(b) {
return len(a) > len(b)
}
return strings.ToLower(a) < strings.ToLower(b)
}
func main() {
var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog")
fmt.Println(s, "(original)")
sort.Sort(s)
fmt.Println(s, "(sorted)")
}
|
Preserve the algorithm and functionality while converting the code from VB to Go. | VERSION 5.00
Begin VB.Form Form1
Begin VB.Timer Timer1
Interval = 250
End
Begin VB.Label Label1
AutoSize = -1
Caption = "Hello World! "
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private goRight As Boolean
Private Sub Label1_Click()
goRight = Not goRight
End Sub
Private Sub Timer1_Timer()
If goRight Then
x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)
Else
x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)
End If
Label1.Caption = x
End Sub
| package main
import (
"log"
"time"
"github.com/gdamore/tcell"
)
const (
msg = "Hello World! "
x0, y0 = 8, 3
shiftsPerSecond = 4
clicksToExit = 5
)
func main() {
s, err := tcell.NewScreen()
if err != nil {
log.Fatal(err)
}
if err = s.Init(); err != nil {
log.Fatal(err)
}
s.Clear()
s.EnableMouse()
tick := time.Tick(time.Second / shiftsPerSecond)
click := make(chan bool)
go func() {
for {
em, ok := s.PollEvent().(*tcell.EventMouse)
if !ok || em.Buttons()&0xFF == tcell.ButtonNone {
continue
}
mx, my := em.Position()
if my == y0 && mx >= x0 && mx < x0+len(msg) {
click <- true
}
}
}()
for inc, shift, clicks := 1, 0, 0; ; {
select {
case <-tick:
shift = (shift + inc) % len(msg)
for i, r := range msg {
s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)
}
s.Show()
case <-click:
clicks++
if clicks == clicksToExit {
s.Fini()
return
}
inc = len(msg) - inc
}
}
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
| package main
import "fmt"
type (
seq []int
sofs []seq
)
func newSeq(start, end int) seq {
if end < start {
end = start
}
s := make(seq, end-start+1)
for i := 0; i < len(s); i++ {
s[i] = start + i
}
return s
}
func newSofs() sofs {
return sofs{seq{}}
}
func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs {
var s2 sofs
for _, t := range expr(s, in) {
if pred(t) {
s2 = append(s2, t)
}
}
return s2
}
func (s sofs) build(t seq) sofs {
var u sofs
for _, ss := range s {
for _, tt := range t {
uu := make(seq, len(ss))
copy(uu, ss)
uu = append(uu, tt)
u = append(u, uu)
}
}
return u
}
func main() {
pt := newSofs()
in := newSeq(1, 20)
expr := func(s sofs, t seq) sofs {
return s.build(t).build(t).build(t)
}
pred := func(t seq) bool {
if len(t) != 3 {
return false
}
return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2]
}
pt = pt.listComp(in, expr, pred)
fmt.Println(pt)
}
|
Convert this VB block to Go, preserving its control flow and logic. | Function Selection_Sort(s)
arr = Split(s,",")
For i = 0 To UBound(arr)
For j = i To UBound(arr)
temp = arr(i)
If arr(j) < arr(i) Then
arr(i) = arr(j)
arr(j) = temp
End If
Next
Next
Selection_Sort = (Join(arr,","))
End Function
WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted"
WScript.StdOut.WriteLine
WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1")
WScript.StdOut.WriteLine
WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
| package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
selectionSort(a)
fmt.Println("after: ", a)
}
func selectionSort(a []int) {
last := len(a) - 1
for i := 0; i < last; i++ {
aMin := a[i]
iMin := i
for j := i + 1; j < len(a); j++ {
if a[j] < aMin {
aMin = a[j]
iMin = j
}
}
a[i], a[iMin] = aMin, a[i]
}
}
|
Write the same code in Go as shown below in VB. | Option Explicit
Sub Main()
Dim arr, i
arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next
Debug.Print Join(arr, ", ")
End Sub
Private Function Fibonacci(N) As Variant
If N <= 1 Then
Fibonacci = N
Else
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End Function
| package main
import "fmt"
func main() {
for _, i := range []int{1, 2, 3, 4, 5} {
fmt.Println(i * i)
}
}
|
Port the following code from VB to Go with equivalent syntax and logic. | Public Sub case_sensitivity()
Dim DOG As String
DOG = "Benjamin"
DOG = "Samba"
DOG = "Bernie"
Debug.Print "There is just one dog named " & DOG
End Sub
| package dogs
import "fmt"
var dog = "Salt"
var Dog = "Pepper"
var DOG = "Mustard"
func PackageSees() map[*string]int {
fmt.Println("Package sees:", dog, Dog, DOG)
return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1}
}
|
Generate an equivalent Go version of this VB code. | For i = 10 To 0 Step -1
Debug.Print i
Next i
| for i := 10; i >= 0; i-- {
fmt.Println(i)
}
|
Please provide an equivalent version of this VB code in Go. | Option Explicit
Const strName As String = "MyFileText.txt"
Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _
"The reverse of Read entire file—for when you want to update or " & vbCrLf & _
"create a file which you would read in its entirety all at once."
Sub Main()
Dim Nb As Integer
Nb = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb
Print #1, Text
Close #Nb
End Sub
| import "io/ioutil"
func main() {
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
}
|
Port the provided VB code into Go while preserving the original functionality. | Public OutConsole As Scripting.TextStream
For i = 0 To 4
For j = 0 To i
OutConsole.Write "*"
Next j
OutConsole.WriteLine
Next i
| package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("*")
}
fmt.Printf("\n")
}
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | 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
sub sier(lev,lgth)
dim i
if lev=1 then
for i=1 to 3
x.fw lgth
x.lt 2
next
else
sier lev-1,lgth\2
x.fw lgth\2
sier lev-1,lgth\2
x.bw lgth\2
x.lt 1
x.fw lgth\2
x.rt 1
sier lev-1,lgth\2
x.lt 1
x.bw lgth\2
x.rt 1
end if
end sub
dim x
set x=new turtle
x.iangle=60
x.orient=0
x.incr=10
x.x=100:x.y=100
sier 7,64
set x=nothing
| package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
func main() {
const order = 8
const width = 1 << order
const margin = 10
bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)
im := image.NewGray(bounds)
gBlack := color.Gray{0}
gWhite := color.Gray{255}
draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)
for y := 0; y < width; y++ {
for x := 0; x < width; x++ {
if x&y == 0 {
im.SetGray(x, y, gBlack)
}
}
}
f, err := os.Create("sierpinski.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, im); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Write the same algorithm in Go as shown in this VB implementation. | 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
sub sier(lev,lgth)
dim i
if lev=1 then
for i=1 to 3
x.fw lgth
x.lt 2
next
else
sier lev-1,lgth\2
x.fw lgth\2
sier lev-1,lgth\2
x.bw lgth\2
x.lt 1
x.fw lgth\2
x.rt 1
sier lev-1,lgth\2
x.lt 1
x.bw lgth\2
x.rt 1
end if
end sub
dim x
set x=new turtle
x.iangle=60
x.orient=0
x.incr=10
x.x=100:x.y=100
sier 7,64
set x=nothing
| package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
func main() {
const order = 8
const width = 1 << order
const margin = 10
bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin)
im := image.NewGray(bounds)
gBlack := color.Gray{0}
gWhite := color.Gray{255}
draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src)
for y := 0; y < width; y++ {
for x := 0; x < width; x++ {
if x&y == 0 {
im.SetGray(x, y, gBlack)
}
}
}
f, err := os.Create("sierpinski.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, im); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the VB version. |
Function noncontsubseq(l)
Dim i, j, g, n, r, s, w, m
Dim a, b, c
n = Ubound(l)
For s = 0 To n-2
For g = s+1 To n-1
a = "["
For i = s To g-1
a = a & l(i) & ", "
Next
For w = 1 To n-g
r = n+1-g-w
For i = 1 To 2^r-1 Step 2
b = a
For j = 0 To r-1
If i And 2^j Then b=b & l(g+w+j) & ", "
Next
c = (Left(b, Len(b)-1))
WScript.Echo Left(c, Len(c)-1) & "]"
m = m+1
Next
Next
Next
Next
noncontsubseq = m
End Function
list = Array("1", "2", "3", "4")
WScript.Echo "List: [" & Join(list, ", ") & "]"
nn = noncontsubseq(list)
WScript.Echo nn & " non-continuous subsequences"
| package main
import "fmt"
const (
m = iota
c
cm
cmc
)
func ncs(s []int) [][]int {
if len(s) < 3 {
return nil
}
return append(n2(nil, s[1:], m), n2([]int{s[0]}, s[1:], c)...)
}
var skip = []int{m, cm, cm, cmc}
var incl = []int{c, c, cmc, cmc}
func n2(ss, tail []int, seq int) [][]int {
if len(tail) == 0 {
if seq != cmc {
return nil
}
return [][]int{ss}
}
return append(n2(append([]int{}, ss...), tail[1:], skip[seq]),
n2(append(ss, tail[0]), tail[1:], incl[seq])...)
}
func main() {
ss := ncs([]int{1, 2, 3, 4})
fmt.Println(len(ss), "non-continuous subsequences:")
for _, s := range ss {
fmt.Println(" ", s)
}
}
|
Port the following code from VB to Go with equivalent syntax and logic. | Function IsPrime(x As Long) As Boolean
Dim i As Long
If x Mod 2 = 0 Then
Exit Function
Else
For i = 3 To Int(Sqr(x)) Step 2
If x Mod i = 0 Then Exit Function
Next i
End If
IsPrime = True
End Function
Function TwinPrimePairs(max As Long) As Long
Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long
p2 = True
For i = 5 To max Step 2
p1 = p2
p2 = IsPrime(i)
If p1 And p2 Then count = count + 1
Next i
TwinPrimePairs = count
End Function
Sub Test(x As Long)
Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x))
End Sub
Sub Main()
Test 10
Test 100
Test 1000
Test 10000
Test 100000
Test 1000000
Test 10000000
End Sub
| package main
import "fmt"
func sieve(limit uint64) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
p := uint64(3)
for {
p2 := p * p
if p2 >= limit {
break
}
for i := p2; i < limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
return c
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
c := sieve(1e10 - 1)
limit := 10
start := 3
twins := 0
for i := 1; i < 11; i++ {
for i := start; i < limit; i += 2 {
if !c[i] && !c[i-2] {
twins++
}
}
fmt.Printf("Under %14s there are %10s pairs of twin primes.\n", commatize(limit), commatize(twins))
start = limit + 1
limit *= 10
}
}
|
Please provide an equivalent version of this VB code in Go. | Public Sub roots_of_unity()
For n = 2 To 9
Debug.Print n; "th roots of 1:"
For r00t = 0 To n - 1
Debug.Print " Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _
Sin(2 * WorksheetFunction.Pi() * r00t / n))
Next r00t
Debug.Print
Next n
End Sub
| package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
for n := 2; n <= 5; n++ {
fmt.Printf("%d roots of 1:\n", n)
for _, r := range roots(n) {
fmt.Printf(" %18.15f\n", r)
}
}
}
func roots(n int) []complex128 {
r := make([]complex128, n)
for i := 0; i < n; i++ {
r[i] = cmplx.Rect(1, 2*math.Pi*float64(i)/float64(n))
}
return r
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Imports System
Imports System.Console
Imports BI = System.Numerics.BigInteger
Module Module1
Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D
Structure bd
Public hi, lo As Decimal
End Structure
Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String
Dim r As String = If(a.hi = 0, String.Format("{0:0}", a.lo),
String.Format("{0:0}{1:" & New String("0"c, 28) & "}", a.hi, a.lo))
If Not comma Then Return r
Dim rc As String = ""
For i As Integer = r.Length - 3 To 0 Step -3
rc = "," & r.Substring(i, 3) & rc : Next
toStr = r.Substring(0, r.Length Mod 3) & rc
toStr = toStr.Substring(If(toStr.Chars(0) = "," , 1, 0))
End Function
Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal
If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _
Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas
End Function
Sub Main(ByVal args As String())
For p As UInteger = 64 To 95 - 1 Step 30
Dim y As bd, x As bd : a = Pow_dec(2D, p)
WriteLine("The square of (2^{0}): {1,38:n0}", p, a)
x.hi = Math.Floor(a / hm) : x.lo = a Mod hm
Dim BS As BI = BI.Pow(CType(a, BI), 2)
y.lo = x.lo * x.lo : y.hi = x.hi * x.hi
a = x.hi * x.lo * 2D
y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm
While y.lo > mx : y.lo -= mx : y.hi += 1 : End While
WriteLine(" is {0,75} (which {1} match the BigInteger computation)" & vbLf,
toStr(y, True), If(BS.ToString() = toStr(y), "does", "fails to"))
Next
End Sub
End Module
|
package main
import "fmt"
func d(b byte) byte {
if b < '0' || b > '9' {
panic("digit 0-9 expected")
}
return b - '0'
}
func add(x, y string) string {
if len(y) > len(x) {
x, y = y, x
}
b := make([]byte, len(x)+1)
var c byte
for i := 1; i <= len(x); i++ {
if i <= len(y) {
c += d(y[len(y)-i])
}
s := d(x[len(x)-i]) + c
c = s / 10
b[len(b)-i] = (s % 10) + '0'
}
if c == 0 {
return string(b[1:])
}
b[0] = c + '0'
return string(b)
}
func mulDigit(x string, y byte) string {
if y == '0' {
return "0"
}
y = d(y)
b := make([]byte, len(x)+1)
var c byte
for i := 1; i <= len(x); i++ {
s := d(x[len(x)-i])*y + c
c = s / 10
b[len(b)-i] = (s % 10) + '0'
}
if c == 0 {
return string(b[1:])
}
b[0] = c + '0'
return string(b)
}
func mul(x, y string) string {
result := mulDigit(x, y[len(y)-1])
for i, zeros := 2, ""; i <= len(y); i++ {
zeros += "0"
result = add(result, mulDigit(x, y[len(y)-i])+zeros)
}
return result
}
const n = "18446744073709551616"
func main() {
fmt.Println(mul(n, n))
}
|
Rewrite the snippet below in Go so it works the same as the original VB code. | Imports System.Numerics
Module Module1
Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)
Dim t As BigInteger = a : a = b : b = b * c + t
End Sub
Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)
Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,
e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1
While True
y = r * z - y : z = (n - y * y) / z : r = (x + y) / z
Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)
If a * a - n * b * b = 1 Then Exit Sub
End While
End Sub
Sub Main()
Dim x As BigInteger, y As BigInteger
For Each n As Integer In {61, 109, 181, 277}
SolvePell(n, x, y)
Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y)
Next
End Sub
End Module
| package main
import (
"fmt"
"math/big"
)
var big1 = new(big.Int).SetUint64(1)
func solvePell(nn uint64) (*big.Int, *big.Int) {
n := new(big.Int).SetUint64(nn)
x := new(big.Int).Set(n)
x.Sqrt(x)
y := new(big.Int).Set(x)
z := new(big.Int).SetUint64(1)
r := new(big.Int).Lsh(x, 1)
e1 := new(big.Int).SetUint64(1)
e2 := new(big.Int)
f1 := new(big.Int)
f2 := new(big.Int).SetUint64(1)
t := new(big.Int)
u := new(big.Int)
a := new(big.Int)
b := new(big.Int)
for {
t.Mul(r, z)
y.Sub(t, y)
t.Mul(y, y)
t.Sub(n, t)
z.Quo(t, z)
t.Add(x, y)
r.Quo(t, z)
u.Set(e1)
e1.Set(e2)
t.Mul(r, e2)
e2.Add(t, u)
u.Set(f1)
f1.Set(f2)
t.Mul(r, f2)
f2.Add(t, u)
t.Mul(x, f2)
a.Add(e2, t)
b.Set(f2)
t.Mul(a, a)
u.Mul(n, b)
u.Mul(u, b)
t.Sub(t, u)
if t.Cmp(big1) == 0 {
return a, b
}
}
}
func main() {
ns := []uint64{61, 109, 181, 277}
for _, n := range ns {
x, y := solvePell(n)
fmt.Printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y)
}
}
|
Please provide an equivalent version of this VB code in Go. | Option Explicit
Sub Main_Bulls_and_cows()
Dim strNumber As String, strInput As String, strMsg As String, strTemp As String
Dim boolEnd As Boolean
Dim lngCpt As Long
Dim i As Byte, bytCow As Byte, bytBull As Byte
Const NUMBER_OF_DIGITS As Byte = 4
Const MAX_LOOPS As Byte = 25
strNumber = Create_Number(NUMBER_OF_DIGITS)
Do
bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1
If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do
strInput = AskToUser(NUMBER_OF_DIGITS)
If strInput = "Exit Game" Then strMsg = "User abort": Exit Do
For i = 1 To Len(strNumber)
If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then
bytBull = bytBull + 1
ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then
bytCow = bytCow + 1
End If
Next i
If bytBull = Len(strNumber) Then
boolEnd = True: strMsg = "You win in " & lngCpt & " loops!"
Else
strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows."
MsgBox strTemp
End If
Loop While Not boolEnd
MsgBox strMsg
End Sub
Function Create_Number(NbDigits As Byte) As String
Dim myColl As New Collection
Dim strTemp As String
Dim bytAlea As Byte
Randomize
Do
bytAlea = Int((Rnd * 9) + 1)
On Error Resume Next
myColl.Add CStr(bytAlea), CStr(bytAlea)
If Err <> 0 Then
On Error GoTo 0
Else
strTemp = strTemp & CStr(bytAlea)
End If
Loop While Len(strTemp) < NbDigits
Create_Number = strTemp
End Function
Function AskToUser(NbDigits As Byte) As String
Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte
Do While Not boolGood
strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number")
If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do
If strIn <> "" Then
If Len(strIn) = NbDigits Then
NbDiff = 0
For i = 1 To Len(strIn)
If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then
NbDiff = 1
Exit For
End If
Next i
If NbDiff = 0 Then boolGood = True
End If
End If
Loop
AskToUser = strIn
End Function
| package main
import (
"bufio"
"bytes"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
func main() {
fmt.Println(`Cows and Bulls
Guess four digit number of unique digits in the range 1 to 9.
A correct digit but not in the correct place is a cow.
A correct digit in the correct place is a bull.`)
pat := make([]byte, 4)
rand.Seed(time.Now().Unix())
r := rand.Perm(9)
for i := range pat {
pat[i] = '1' + byte(r[i])
}
valid := []byte("123456789")
guess:
for in := bufio.NewReader(os.Stdin); ; {
fmt.Print("Guess: ")
guess, err := in.ReadString('\n')
if err != nil {
fmt.Println("\nSo, bye.")
return
}
guess = strings.TrimSpace(guess)
if len(guess) != 4 {
fmt.Println("Please guess a four digit number.")
continue
}
var cows, bulls int
for ig, cg := range guess {
if strings.IndexRune(guess[:ig], cg) >= 0 {
fmt.Printf("Repeated digit: %c\n", cg)
continue guess
}
switch bytes.IndexByte(pat, byte(cg)) {
case -1:
if bytes.IndexByte(valid, byte(cg)) == -1 {
fmt.Printf("Invalid digit: %c\n", cg)
continue guess
}
default:
cows++
case ig:
bulls++
}
}
fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls)
if bulls == 4 {
fmt.Println("You got it.")
return
}
}
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sortable.Shuffle()
Dim swapped As Boolean
Do
Dim index, bound As Integer
bound = sortable.Ubound
While index < bound
If sortable(index) > sortable(index + 1) Then
Dim s As Integer = sortable(index)
sortable.Remove(index)
sortable.Insert(index + 1, s)
swapped = True
End If
index = index + 1
Wend
Loop Until Not swapped
| package main
import "fmt"
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
fmt.Println("unsorted:", list)
bubblesort(list)
fmt.Println("sorted! ", list)
}
func bubblesort(a []int) {
for itemCount := len(a) - 1; ; itemCount-- {
hasChanged := false
for index := 0; index < itemCount; index++ {
if a[index] > a[index+1] {
a[index], a[index+1] = a[index+1], a[index]
hasChanged = true
}
}
if hasChanged == false {
break
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Dim tos As TextOutputStream
tis = tis.Open(input)
tos = tos.Create(output)
While Not tis.EOF
tos.WriteLine(tis.ReadLine)
Wend
tis.Close
tos.Close
End Sub
| package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("input.txt")
if err != nil {
fmt.Println(err)
return
}
if err = ioutil.WriteFile("output.txt", b, 0666); err != nil {
fmt.Println(err)
}
}
|
Port the following code from VB to Go with equivalent syntax and logic. | Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Dim tos As TextOutputStream
tis = tis.Open(input)
tos = tos.Create(output)
While Not tis.EOF
tos.WriteLine(tis.ReadLine)
Wend
tis.Close
tos.Close
End Sub
| package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("input.txt")
if err != nil {
fmt.Println(err)
return
}
if err = ioutil.WriteFile("output.txt", b, 0666); err != nil {
fmt.Println(err)
}
}
|
Translate this program into Go but keep the logic exactly as in VB. | START:
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
IF b = 0 THEN
PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder."
GOTO START
END IF
PRINT
PRINT " Sum = "; a + b
PRINT " Difference = "; a - b
PRINT " Product = "; a * b
PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0."
PRINT " Remainder = "; a MOD b, , "* Sign matches first operand."
PRINT " Exponentiation = "; a ^ b
PRINT
INPUT "Again? (y/N)"; a$
IF UCASE$(a$) = "Y" THEN CLS: GOTO START
CLS
END
| package main
import "fmt"
func main() {
var a, b int
fmt.Print("enter two integers: ")
fmt.Scanln(&a, &b)
fmt.Printf("%d + %d = %d\n", a, b, a+b)
fmt.Printf("%d - %d = %d\n", a, b, a-b)
fmt.Printf("%d * %d = %d\n", a, b, a*b)
fmt.Printf("%d / %d = %d\n", a, b, a/b)
fmt.Printf("%d %% %d = %d\n", a, b, a%b)
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Function transpose(m As Variant) As Variant
transpose = WorksheetFunction.transpose(m)
End Function
| package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func main() {
m := mat.NewDense(2, 3, []float64{
1, 2, 3,
4, 5, 6,
})
fmt.Println(mat.Formatted(m))
fmt.Println()
fmt.Println(mat.Formatted(m.T()))
}
|
Produce a functionally identical Go code for the snippet given in VB. | Private Function a(i As Variant) As Boolean
Debug.Print "a: "; i = 1,
a = i
End Function
Private Function b(j As Variant) As Boolean
Debug.Print "b: "; j = 1;
b = j
End Function
Public Sub short_circuit()
Dim x As Boolean, y As Boolean
Debug.Print "=====AND=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print "======OR=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If Not a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print
End Sub
| package main
import "fmt"
func a(v bool) bool {
fmt.Print("a")
return v
}
func b(v bool) bool {
fmt.Print("b")
return v
}
func test(i, j bool) {
fmt.Printf("Testing a(%t) && b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) && b(j))
fmt.Printf("Testing a(%t) || b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) || b(j))
fmt.Println("")
}
func main() {
test(false, false)
test(false, true)
test(true, false)
test(true, true)
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | Option Explicit
Sub Main()
Debug.Print "The limit is : " & Limite_Recursivite(0)
End Sub
Function Limite_Recursivite(Cpt As Long) As Long
Cpt = Cpt + 1
On Error Resume Next
Limite_Recursivite Cpt
On Error GoTo 0
Limite_Recursivite = Cpt
End Function
| package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | Option Explicit
Sub Main()
Debug.Print "The limit is : " & Limite_Recursivite(0)
End Sub
Function Limite_Recursivite(Cpt As Long) As Long
Cpt = Cpt + 1
On Error Resume Next
Limite_Recursivite Cpt
On Error GoTo 0
Limite_Recursivite = Cpt
End Function
| package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
|
Write a version of this VB function in Go with identical behavior. | Option Explicit
Sub Main()
Debug.Print "The limit is : " & Limite_Recursivite(0)
End Sub
Function Limite_Recursivite(Cpt As Long) As Long
Cpt = Cpt + 1
On Error Resume Next
Limite_Recursivite Cpt
On Error GoTo 0
Limite_Recursivite = Cpt
End Function
| package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
}
|
Change the following VB code into Go without altering its purpose. |
function isarit_compo(i)
cnt=0
sum=0
for j=1 to sqr(i)
if (i mod j)=0 then
k=i\j
if k=j then
cnt=cnt+1:sum=sum+j
else
cnt=cnt+2:sum=sum+j+k
end if
end if
next
avg= sum/cnt
isarit_compo= array((fix(avg)=avg),-(cnt>2))
end function
function rpad(a,n) rpad=right(space(n)&a,n) :end function
dim s1
sub print(s)
s1=s1& rpad(s,4)
if len(s1)=40 then wscript.stdout.writeline s1:s1=""
end sub
cntr=0
cntcompo=0
i=1
wscript.stdout.writeline "the first 100 arithmetic numbers are:"
do
a=isarit_compo(i)
if a(0) then
cntcompo=cntcompo+a(1)
cntr=cntr+1
if cntr<=100 then print i
if cntr=1000 then wscript.stdout.writeline vbcrlf&"1000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6)
if cntr=10000 then wscript.stdout.writeline vbcrlf& "10000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6)
if cntr=100000 then wscript.stdout.writeline vbcrlf &"100000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6):exit do
end if
i=i+1
loop
| package main
import (
"fmt"
"math"
"rcu"
"sort"
)
func main() {
arithmetic := []int{1}
primes := []int{}
limit := int(1e6)
for n := 3; len(arithmetic) < limit; n++ {
divs := rcu.Divisors(n)
if len(divs) == 2 {
primes = append(primes, n)
arithmetic = append(arithmetic, n)
} else {
mean := float64(rcu.SumInts(divs)) / float64(len(divs))
if mean == math.Trunc(mean) {
arithmetic = append(arithmetic, n)
}
}
}
fmt.Println("The first 100 arithmetic numbers are:")
rcu.PrintTable(arithmetic[0:100], 10, 3, false)
for _, x := range []int{1e3, 1e4, 1e5, 1e6} {
last := arithmetic[x-1]
lastc := rcu.Commatize(last)
fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc)
pcount := sort.SearchInts(primes, last) + 1
if !rcu.IsPrime(last) {
pcount--
}
comp := x - pcount - 1
compc := rcu.Commatize(comp)
fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc)
}
}
|
Port the provided VB code into Go while preserving the original functionality. |
function isarit_compo(i)
cnt=0
sum=0
for j=1 to sqr(i)
if (i mod j)=0 then
k=i\j
if k=j then
cnt=cnt+1:sum=sum+j
else
cnt=cnt+2:sum=sum+j+k
end if
end if
next
avg= sum/cnt
isarit_compo= array((fix(avg)=avg),-(cnt>2))
end function
function rpad(a,n) rpad=right(space(n)&a,n) :end function
dim s1
sub print(s)
s1=s1& rpad(s,4)
if len(s1)=40 then wscript.stdout.writeline s1:s1=""
end sub
cntr=0
cntcompo=0
i=1
wscript.stdout.writeline "the first 100 arithmetic numbers are:"
do
a=isarit_compo(i)
if a(0) then
cntcompo=cntcompo+a(1)
cntr=cntr+1
if cntr<=100 then print i
if cntr=1000 then wscript.stdout.writeline vbcrlf&"1000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6)
if cntr=10000 then wscript.stdout.writeline vbcrlf& "10000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6)
if cntr=100000 then wscript.stdout.writeline vbcrlf &"100000th : "&rpad(i,6) & " nr composites " &rpad(cntcompo,6):exit do
end if
i=i+1
loop
| package main
import (
"fmt"
"math"
"rcu"
"sort"
)
func main() {
arithmetic := []int{1}
primes := []int{}
limit := int(1e6)
for n := 3; len(arithmetic) < limit; n++ {
divs := rcu.Divisors(n)
if len(divs) == 2 {
primes = append(primes, n)
arithmetic = append(arithmetic, n)
} else {
mean := float64(rcu.SumInts(divs)) / float64(len(divs))
if mean == math.Trunc(mean) {
arithmetic = append(arithmetic, n)
}
}
}
fmt.Println("The first 100 arithmetic numbers are:")
rcu.PrintTable(arithmetic[0:100], 10, 3, false)
for _, x := range []int{1e3, 1e4, 1e5, 1e6} {
last := arithmetic[x-1]
lastc := rcu.Commatize(last)
fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc)
pcount := sort.SearchInts(primes, last) + 1
if !rcu.IsPrime(last) {
pcount--
}
comp := x - pcount - 1
compc := rcu.Commatize(comp)
fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc)
}
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Imports System.Drawing.Imaging
Public Class frmSnowExercise
Dim bRunning As Boolean = True
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _
Or ControlStyles.OptimizedDoubleBuffer, True)
UpdateStyles()
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
MaximizeBox = False
Width = 320 + Size.Width - ClientSize.Width
Height = 240 + Size.Height - ClientSize.Height
Show()
Activate()
Application.DoEvents()
RenderLoop()
Close()
End Sub
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _
System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
e.Cancel = bRunning
bRunning = False
End Sub
Private Sub RenderLoop()
Const cfPadding As Single = 5.0F
Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,
PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(b)
Dim r As New Random(Now.Millisecond)
Dim oBMPData As BitmapData = Nothing
Dim oPixels() As Integer = Nothing
Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}
Dim oStopwatch As New Stopwatch
Dim fElapsed As Single = 0.0F
Dim iLoops As Integer = 0
Dim sFPS As String = "0.0 FPS"
Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)
Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
g.Clear(Color.Black)
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
Array.Resize(oPixels, b.Width * b.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,
oPixels, 0, oPixels.Length)
b.UnlockBits(oBMPData)
Do
fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F
oStopwatch.Reset() : oStopwatch.Start()
iLoops += 1
If fElapsed >= 1.0F Then
sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS"
oFPSSize = g.MeasureString(sFPS, Font)
oFPSBG = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
fElapsed -= 1.0F
iLoops = 0
End If
For i As Integer = 0 To oPixels.GetUpperBound(0)
oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))
Next
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,
oPixels.Length)
b.UnlockBits(oBMPData)
g.FillRectangle(Brushes.Black, oFPSBG)
g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)
BackgroundImage = b
Invalidate(ClientRectangle)
Application.DoEvents()
Loop While bRunning
End Sub
End Class
| package main
import (
"code.google.com/p/x-go-binding/ui/x11"
"fmt"
"image"
"image/color"
"image/draw"
"log"
"os"
"time"
)
var randcol = genrandcol()
func genrandcol() <-chan color.Color {
c := make(chan color.Color)
go func() {
for {
select {
case c <- image.Black:
case c <- image.White:
}
}
}()
return c
}
func gennoise(screen draw.Image) {
for y := 0; y < 240; y++ {
for x := 0; x < 320; x++ {
screen.Set(x, y, <-randcol)
}
}
}
func fps() chan<- bool {
up := make(chan bool)
go func() {
var frames int64
var lasttime time.Time
var totaltime time.Duration
for {
<-up
frames++
now := time.Now()
totaltime += now.Sub(lasttime)
if totaltime > time.Second {
fmt.Printf("FPS: %v\n", float64(frames)/totaltime.Seconds())
frames = 0
totaltime = 0
}
lasttime = now
}
}()
return up
}
func main() {
win, err := x11.NewWindow()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer win.Close()
go func() {
upfps := fps()
screen := win.Screen()
for {
gennoise(screen)
win.FlushImage()
upfps <- true
}
}()
for _ = range win.EventChan() {
}
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. |
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
| package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
s.MovePrint(20, 0, "Press y/n ")
s.Refresh()
switch k = s.GetChar(); k {
default:
continue
case 'y', 'Y', 'n', 'N':
}
break
}
s.Printf("\nThanks for the %c!\n", k)
s.Refresh()
s.GetChar()
}
|
Write a version of this VB function in Go with identical behavior. |
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
| package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
s.MovePrint(20, 0, "Press y/n ")
s.Refresh()
switch k = s.GetChar(); k {
default:
continue
case 'y', 'Y', 'n', 'N':
}
break
}
s.Printf("\nThanks for the %c!\n", k)
s.Refresh()
s.GetChar()
}
|
Preserve the algorithm and functionality while converting the code from VB to Go. | Private Function Factors(x As Long) As String
Application.Volatile
Dim i As Long
Dim cooresponding_factors As String
Factors = 1
corresponding_factors = x
For i = 2 To Sqr(x)
If x Mod i = 0 Then
Factors = Factors & ", " & i
If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors
End If
Next i
If x <> 1 Then Factors = Factors & ", " & corresponding_factors
End Function
Private Function is_perfect(n As Long)
fs = Split(Factors(n), ", ")
Dim f() As Long
ReDim f(UBound(fs))
For i = 0 To UBound(fs)
f(i) = Val(fs(i))
Next i
is_perfect = WorksheetFunction.Sum(f) - n = n
End Function
Public Sub main()
Dim i As Long
For i = 2 To 100000
If is_perfect(i) Then Debug.Print i
Next i
End Sub
| package main
import "fmt"
func computePerfect(n int64) bool {
var sum int64
for i := int64(1); i < n; i++ {
if n%i == 0 {
sum += i
}
}
return sum == n
}
func isPerfect(n int64) bool {
switch n {
case 6, 28, 496, 8128, 33550336, 8589869056,
137438691328, 2305843008139952128:
return true
}
return false
}
func main() {
for n := int64(1); ; n++ {
if isPerfect(n) != computePerfect(n) {
panic("bug")
}
if n%1e3 == 0 {
fmt.Println("tested", n)
}
}
}
|
Write the same code in Go as shown below in VB. | Option Base 1
Private Function sq_add(arr As Variant, x As Double) As Variant
Dim res() As Variant
ReDim res(UBound(arr))
For i = 1 To UBound(arr)
res(i) = arr(i) + x
Next i
sq_add = res
End Function
Private Function beadsort(ByVal a As Variant) As Variant
Dim poles() As Variant
ReDim poles(WorksheetFunction.Max(a))
For i = 1 To UBound(a)
For j = 1 To a(i)
poles(j) = poles(j) + 1
Next j
Next i
For j = 1 To UBound(a)
a(j) = 0
Next j
For i = 1 To UBound(poles)
For j = 1 To poles(i)
a(j) = a(j) + 1
Next j
Next i
beadsort = a
End Function
Public Sub main()
Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ")
End Sub
| package main
import (
"fmt"
"sync"
)
var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000
const bead = 'o'
func main() {
fmt.Println("before:", a)
beadSort()
fmt.Println("after: ", a)
}
func beadSort() {
all := make([]byte, aMax*len(a))
abacus := make([][]byte, aMax)
for pole, space := 0, all; pole < aMax; pole++ {
abacus[pole] = space[:len(a)]
space = space[len(a):]
}
var wg sync.WaitGroup
wg.Add(len(a))
for row, n := range a {
go func(row, n int) {
for pole := 0; pole < n; pole++ {
abacus[pole][row] = bead
}
wg.Done()
}(row, n)
}
wg.Wait()
wg.Add(aMax)
for _, pole := range abacus {
go func(pole []byte) {
top := 0
for row, space := range pole {
if space == bead {
pole[row] = 0
pole[top] = bead
top++
}
}
wg.Done()
}(pole)
}
wg.Wait()
for row := range a {
x := 0
for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {
x++
}
a[len(a)-1-row] = x
}
}
|
Translate this program into Go but keep the logic exactly as in VB. | Imports System.Console
Imports BI = System.Numerics.BigInteger
Module Module1
Dim Implems() As String = {"Built-In", "Recursive", "Iterative"},
powers() As Integer = {5, 4, 3, 2}
Function intPowR(val As BI, exp As BI) As BI
If exp = 0 Then Return 1
Dim ne As BI, vs As BI = val * val
If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)
ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val
End Function
Function intPowI(val As BI, exp As BI) As BI
intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val
val *= val : exp >>= 1 : End While
End Function
Sub DoOne(title As String, p() As Integer)
Dim st As DateTime = DateTime.Now, res As BI, resStr As String
Select Case (Array.IndexOf(Implems, title))
Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))
Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))
Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))
End Select : resStr = res.ToString()
Dim et As TimeSpan = DateTime.Now - st
Debug.Assert(resStr.Length = 183231)
Debug.Assert(resStr.StartsWith("62060698786608744707"))
Debug.Assert(resStr.EndsWith("92256259918212890625"))
WriteLine("n = {0}", String.Join("^", powers))
WriteLine("n = {0}...{1}", resStr.Substring(0, 20), resStr.Substring(resStr.Length - 20, 20))
WriteLine("n digits = {0}", resStr.Length)
WriteLine("{0} elasped: {1} milliseconds." & vblf, title, et.TotalMilliseconds)
End Sub
Sub Main()
For Each itm As String in Implems : DoOne(itm, powers) : Next
If Debugger.IsAttached Then Console.ReadKey()
End Sub
End Module
| package main
import (
"fmt"
"math/big"
)
func main() {
x := big.NewInt(2)
x = x.Exp(big.NewInt(3), x, nil)
x = x.Exp(big.NewInt(4), x, nil)
x = x.Exp(big.NewInt(5), x, nil)
str := x.String()
fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
len(str),
str[:20],
str[len(str)-20:],
)
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
Sub Normalize(v)
length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub
Function Dot(x, y)
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
If d < 0 Then Dot = -d Else Dot = 0 End If
End Function
Function Ceil(x)
Ceil = Int(x)
If Ceil <> x Then Ceil = Ceil + 1 End if
End Function
Sub DrawSphere(R, k, ambient)
Dim i, j, intensity, inten, b, x, y
Dim vec(3)
For i = Int(-R) to Ceil(R)
x = i + 0.5
line = ""
For j = Int(-2*R) to Ceil(2*R)
y = j / 2 + 0.5
If x * x + y * y <= R*R Then
vec(0) = x
vec(1) = y
vec(2) = Sqr(R * R - x * x - y * y)
Normalize vec
b = dot(light, vec)^k + ambient
intensity = Int((1 - b) * UBound(shades))
If intensity < 0 Then intensity = 0 End If
If intensity >= UBound(shades) Then
intensity = UBound(shades)
End If
line = line & shades(intensity)
Else
line = line & " "
End If
Next
WScript.StdOut.WriteLine line
Next
End Sub
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4
| package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Convert the following code from VB to Go, ensuring the logic remains intact. | shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
Sub Normalize(v)
length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub
Function Dot(x, y)
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
If d < 0 Then Dot = -d Else Dot = 0 End If
End Function
Function Ceil(x)
Ceil = Int(x)
If Ceil <> x Then Ceil = Ceil + 1 End if
End Function
Sub DrawSphere(R, k, ambient)
Dim i, j, intensity, inten, b, x, y
Dim vec(3)
For i = Int(-R) to Ceil(R)
x = i + 0.5
line = ""
For j = Int(-2*R) to Ceil(2*R)
y = j / 2 + 0.5
If x * x + y * y <= R*R Then
vec(0) = x
vec(1) = y
vec(2) = Sqr(R * R - x * x - y * y)
Normalize vec
b = dot(light, vec)^k + ambient
intensity = Int((1 - b) * UBound(shades))
If intensity < 0 Then intensity = 0 End If
If intensity >= UBound(shades) Then
intensity = UBound(shades)
End If
line = line & shades(intensity)
Else
line = line & " "
End If
Next
WScript.StdOut.WriteLine line
Next
End Sub
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4
| package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function
| package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
|
Preserve the algorithm and functionality while converting the code from VB to Go. | Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function
| package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}
|
Convert the following code from VB to Go, ensuring the logic remains intact. | Public Sub LoopsBreak()
Dim value As Integer
Randomize
Do While True
value = Int(20 * Rnd)
Debug.Print value
If value = 10 Then Exit Do
Debug.Print Int(20 * Rnd)
Loop
End Sub
| package main
import "fmt"
import "math/rand"
import "time"
func main() {
rand.Seed(time.Now().UnixNano())
for {
a := rand.Intn(20)
fmt.Println(a)
if a == 10 {
break
}
b := rand.Intn(20)
fmt.Println(b)
}
}
|
Write a version of this VB function in Go with identical behavior. |
Module Module1
Sub Main(Args() As String)
Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1
Dim wta As Integer()() = {
New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},
New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}
Dim blk As String,
lf As String = vbLf,
tb = "██", wr = "≈≈", mt = " "
For i As Integer = 0 To wta.Length - 1
Dim bpf As Integer
blk = ""
Do
bpf = 0 : Dim floor As String = ""
For j As Integer = 0 To wta(i).Length - 1
If wta(i)(j) > 0 Then
floor &= tb : wta(i)(j) -= 1 : bpf += 1
Else
floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)
End If
Next
If bpf > 0 Then blk = floor & lf & blk
Loop Until bpf = 0
While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While
While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While
If shoTow Then Console.Write("{0}{1}", lf, blk)
Console.Write("Block {0} retains {1,2} water units.{2}", i + 1,
(blk.Length - blk.Replace(wr, "").Length) \ 2, lf)
Next
End Sub
End Module
| package main
import "fmt"
func maxl(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := 0; i < len(hm);i++{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func maxr(hm []int ) []int{
res := make([]int,len(hm))
max := 1
for i := len(hm) - 1 ; i >= 0;i--{
if(hm[i] > max){
max = hm[i]
}
res[i] = max;
}
return res
}
func min(a,b []int) []int {
res := make([]int,len(a))
for i := 0; i < len(a);i++{
if a[i] >= b[i]{
res[i] = b[i]
}else {
res[i] = a[i]
}
}
return res
}
func diff(hm, min []int) []int {
res := make([]int,len(hm))
for i := 0; i < len(hm);i++{
if min[i] > hm[i]{
res[i] = min[i] - hm[i]
}
}
return res
}
func sum(a []int) int {
res := 0
for i := 0; i < len(a);i++{
res += a[i]
}
return res
}
func waterCollected(hm []int) int {
maxr := maxr(hm)
maxl := maxl(hm)
min := min(maxr,maxl)
diff := diff(hm,min)
sum := sum(diff)
return sum
}
func main() {
fmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))
fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))
fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))
fmt.Println(waterCollected([]int{5, 5, 5, 5}))
fmt.Println(waterCollected([]int{5, 6, 7, 8}))
fmt.Println(waterCollected([]int{8, 7, 7, 6}))
fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}
|
Generate an equivalent Go version of this VB code. | Module Module1
Function Sieve(limit As Long) As List(Of Long)
Dim primes As New List(Of Long) From {2}
Dim c(limit + 1) As Boolean
Dim p = 3L
While True
Dim p2 = p * p
If p2 > limit Then
Exit While
End If
For i = p2 To limit Step 2 * p
c(i) = True
Next
While True
p += 2
If Not c(p) Then
Exit While
End If
End While
End While
For i = 3 To limit Step 2
If Not c(i) Then
primes.Add(i)
End If
Next
Return primes
End Function
Function SquareFree(from As Long, to_ As Long) As List(Of Long)
Dim limit = CType(Math.Sqrt(to_), Long)
Dim primes = Sieve(limit)
Dim results As New List(Of Long)
Dim i = from
While i <= to_
For Each p In primes
Dim p2 = p * p
If p2 > i Then
Exit For
End If
If (i Mod p2) = 0 Then
i += 1
Continue While
End If
Next
results.Add(i)
i += 1
End While
Return results
End Function
ReadOnly TRILLION As Long = 1_000_000_000_000
Sub Main()
Console.WriteLine("Square-free integers from 1 to 145:")
Dim sf = SquareFree(1, 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 20) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,4}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145)
sf = SquareFree(TRILLION, TRILLION + 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 5) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,14}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Number of square-free integers:")
For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}
Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count)
Next
End Sub
End Module
| package main
import (
"fmt"
"math"
)
func sieve(limit uint64) []uint64 {
primes := []uint64{2}
c := make([]bool, limit+1)
p := uint64(3)
for {
p2 := p * p
if p2 > limit {
break
}
for i := p2; i <= limit; i += 2 * p {
c[i] = true
}
for {
p += 2
if !c[p] {
break
}
}
}
for i := uint64(3); i <= limit; i += 2 {
if !c[i] {
primes = append(primes, i)
}
}
return primes
}
func squareFree(from, to uint64) (results []uint64) {
limit := uint64(math.Sqrt(float64(to)))
primes := sieve(limit)
outer:
for i := from; i <= to; i++ {
for _, p := range primes {
p2 := p * p
if p2 > i {
break
}
if i%p2 == 0 {
continue outer
}
}
results = append(results, i)
}
return
}
const trillion uint64 = 1000000000000
func main() {
fmt.Println("Square-free integers from 1 to 145:")
sf := squareFree(1, 145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%20 == 0 {
fmt.Println()
}
fmt.Printf("%4d", sf[i])
}
fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145)
sf = squareFree(trillion, trillion+145)
for i := 0; i < len(sf); i++ {
if i > 0 && i%5 == 0 {
fmt.Println()
}
fmt.Printf("%14d", sf[i])
}
fmt.Println("\n\nNumber of square-free integers:\n")
a := [...]uint64{100, 1000, 10000, 100000, 1000000}
for _, n := range a {
fmt.Printf(" from %d to %d = %d\n", 1, n, len(squareFree(1, n)))
}
}
|
Preserve the algorithm and functionality while converting the code from VB to Go. | Option Explicit
Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double
Dim dummyChar, match1, match2 As String
Dim i, f, t, j, m, l, s1, s2, limit As Integer
i = 1
Do
dummyChar = Chr(i)
i = i + 1
Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0
s1 = Len(text1)
s2 = Len(text2)
limit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)
match1 = String(s1, dummyChar)
match2 = String(s2, dummyChar)
For l = 1 To WorksheetFunction.Min(4, s1, s2)
If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For
Next l
l = l - 1
For i = 1 To s1
f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)
t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)
j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)
If j > 0 Then
m = m + 1
text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)
match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)
match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)
End If
Next i
match1 = Replace(match1, dummyChar, "", 1, -1, vbTextCompare)
match2 = Replace(match2, dummyChar, "", 1, -1, vbTextCompare)
t = 0
For i = 1 To m
If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1
Next i
JaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3
JaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)
End Function
| package main
import "fmt"
func jaro(str1, str2 string) float64 {
if len(str1) == 0 && len(str2) == 0 {
return 1
}
if len(str1) == 0 || len(str2) == 0 {
return 0
}
match_distance := len(str1)
if len(str2) > match_distance {
match_distance = len(str2)
}
match_distance = match_distance/2 - 1
str1_matches := make([]bool, len(str1))
str2_matches := make([]bool, len(str2))
matches := 0.
transpositions := 0.
for i := range str1 {
start := i - match_distance
if start < 0 {
start = 0
}
end := i + match_distance + 1
if end > len(str2) {
end = len(str2)
}
for k := start; k < end; k++ {
if str2_matches[k] {
continue
}
if str1[i] != str2[k] {
continue
}
str1_matches[i] = true
str2_matches[k] = true
matches++
break
}
}
if matches == 0 {
return 0
}
k := 0
for i := range str1 {
if !str1_matches[i] {
continue
}
for !str2_matches[k] {
k++
}
if str1[i] != str2[k] {
transpositions++
}
k++
}
transpositions /= 2
return (matches/float64(len(str1)) +
matches/float64(len(str2)) +
(matches-transpositions)/matches) / 3
}
func main() {
fmt.Printf("%f\n", jaro("MARTHA", "MARHTA"))
fmt.Printf("%f\n", jaro("DIXON", "DICKSONX"))
fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"))
}
|
Please provide an equivalent version of this VB code in Go. | Module Module1
Function Turn(base As Integer, n As Integer) As Integer
Dim sum = 0
While n <> 0
Dim re = n Mod base
n \= base
sum += re
End While
Return sum Mod base
End Function
Sub Fairshare(base As Integer, count As Integer)
Console.Write("Base {0,2}:", base)
For i = 1 To count
Dim t = Turn(base, i - 1)
Console.Write(" {0,2}", t)
Next
Console.WriteLine()
End Sub
Sub TurnCount(base As Integer, count As Integer)
Dim cnt(base) As Integer
For i = 1 To base
cnt(i - 1) = 0
Next
For i = 1 To count
Dim t = Turn(base, i - 1)
cnt(t) += 1
Next
Dim minTurn = Integer.MaxValue
Dim maxTurn = Integer.MinValue
Dim portion = 0
For i = 1 To base
Dim num = cnt(i - 1)
If num > 0 Then
portion += 1
End If
If num < minTurn Then
minTurn = num
End If
If num > maxTurn Then
maxTurn = num
End If
Next
Console.Write(" With {0} people: ", base)
If 0 = minTurn Then
Console.WriteLine("Only {0} have a turn", portion)
ElseIf minTurn = maxTurn Then
Console.WriteLine(minTurn)
Else
Console.WriteLine("{0} or {1}", minTurn, maxTurn)
End If
End Sub
Sub Main()
Fairshare(2, 25)
Fairshare(3, 25)
Fairshare(5, 25)
Fairshare(11, 25)
Console.WriteLine("How many times does each get a turn in 50000 iterations?")
TurnCount(191, 50000)
TurnCount(1377, 50000)
TurnCount(49999, 50000)
TurnCount(50000, 50000)
TurnCount(50001, 50000)
End Sub
End Module
| package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
func fairshare(n, base int) []int {
res := make([]int, n)
for i := 0; i < n; i++ {
j := i
sum := 0
for j > 0 {
sum += j % base
j /= base
}
res[i] = sum % base
}
return res
}
func turns(n int, fss []int) string {
m := make(map[int]int)
for _, fs := range fss {
m[fs]++
}
m2 := make(map[int]int)
for _, v := range m {
m2[v]++
}
res := []int{}
sum := 0
for k, v := range m2 {
sum += v
res = append(res, k)
}
if sum != n {
return fmt.Sprintf("only %d have a turn", sum)
}
sort.Ints(res)
res2 := make([]string, len(res))
for i := range res {
res2[i] = strconv.Itoa(res[i])
}
return strings.Join(res2, " or ")
}
func main() {
for _, base := range []int{2, 3, 5, 11} {
fmt.Printf("%2d : %2d\n", base, fairshare(25, base))
}
fmt.Println("\nHow many times does each get a turn in 50000 iterations?")
for _, base := range []int{191, 1377, 49999, 50000, 50001} {
t := turns(base, fairshare(50000, base))
fmt.Printf(" With %d people: %s\n", base, t)
}
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Module Module1
Class SymbolType
Public ReadOnly symbol As String
Public ReadOnly precedence As Integer
Public ReadOnly rightAssociative As Boolean
Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)
Me.symbol = symbol
Me.precedence = precedence
Me.rightAssociative = rightAssociative
End Sub
End Class
ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From
{
{"^", New SymbolType("^", 4, True)},
{"*", New SymbolType("*", 3, False)},
{"/", New SymbolType("/", 3, False)},
{"+", New SymbolType("+", 2, False)},
{"-", New SymbolType("-", 2, False)}
}
Function ToPostfix(infix As String) As String
Dim tokens = infix.Split(" ")
Dim stack As New Stack(Of String)
Dim output As New List(Of String)
Dim Print = Sub(action As String) Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {String.Join(" ", stack.Reverse())} ]", $"out[ {String.Join(" ", output)} ]")
For Each token In tokens
Dim iv As Integer
Dim op1 As SymbolType
Dim op2 As SymbolType
If Integer.TryParse(token, iv) Then
output.Add(token)
Print(token)
ElseIf Operators.TryGetValue(token, op1) Then
While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)
Dim c = op1.precedence.CompareTo(op2.precedence)
If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then
output.Add(stack.Pop())
Else
Exit While
End If
End While
stack.Push(token)
Print(token)
ElseIf token = "(" Then
stack.Push(token)
Print(token)
ElseIf token = ")" Then
Dim top = ""
While stack.Count > 0
top = stack.Pop()
If top <> "(" Then
output.Add(top)
Else
Exit While
End If
End While
If top <> "(" Then
Throw New ArgumentException("No matching left parenthesis.")
End If
Print(token)
End If
Next
While stack.Count > 0
Dim top = stack.Pop()
If Not Operators.ContainsKey(top) Then
Throw New ArgumentException("No matching right parenthesis.")
End If
output.Add(top)
End While
Print("pop")
Return String.Join(" ", output)
End Function
Sub Main()
Dim infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
Console.WriteLine(ToPostfix(infix))
End Sub
End Module
| package main
import (
"fmt"
"strings"
)
var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
var opa = map[string]struct {
prec int
rAssoc bool
}{
"^": {4, true},
"*": {3, false},
"/": {3, false},
"+": {2, false},
"-": {2, false},
}
func main() {
fmt.Println("infix: ", input)
fmt.Println("postfix:", parseInfix(input))
}
func parseInfix(e string) (rpn string) {
var stack []string
for _, tok := range strings.Fields(e) {
switch tok {
case "(":
stack = append(stack, tok)
case ")":
var op string
for {
op, stack = stack[len(stack)-1], stack[:len(stack)-1]
if op == "(" {
break
}
rpn += " " + op
}
default:
if o1, isOp := opa[tok]; isOp {
for len(stack) > 0 {
op := stack[len(stack)-1]
if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||
o1.prec == o2.prec && o1.rAssoc {
break
}
stack = stack[:len(stack)-1]
rpn += " " + op
}
stack = append(stack, tok)
} else {
if rpn > "" {
rpn += " "
}
rpn += tok
}
}
}
for len(stack) > 0 {
rpn += " " + stack[len(stack)-1]
stack = stack[:len(stack)-1]
}
return
}
|
Preserve the algorithm and functionality while converting the code from VB to Go. | Module Module1
Class SymbolType
Public ReadOnly symbol As String
Public ReadOnly precedence As Integer
Public ReadOnly rightAssociative As Boolean
Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)
Me.symbol = symbol
Me.precedence = precedence
Me.rightAssociative = rightAssociative
End Sub
End Class
ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From
{
{"^", New SymbolType("^", 4, True)},
{"*", New SymbolType("*", 3, False)},
{"/", New SymbolType("/", 3, False)},
{"+", New SymbolType("+", 2, False)},
{"-", New SymbolType("-", 2, False)}
}
Function ToPostfix(infix As String) As String
Dim tokens = infix.Split(" ")
Dim stack As New Stack(Of String)
Dim output As New List(Of String)
Dim Print = Sub(action As String) Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {String.Join(" ", stack.Reverse())} ]", $"out[ {String.Join(" ", output)} ]")
For Each token In tokens
Dim iv As Integer
Dim op1 As SymbolType
Dim op2 As SymbolType
If Integer.TryParse(token, iv) Then
output.Add(token)
Print(token)
ElseIf Operators.TryGetValue(token, op1) Then
While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)
Dim c = op1.precedence.CompareTo(op2.precedence)
If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then
output.Add(stack.Pop())
Else
Exit While
End If
End While
stack.Push(token)
Print(token)
ElseIf token = "(" Then
stack.Push(token)
Print(token)
ElseIf token = ")" Then
Dim top = ""
While stack.Count > 0
top = stack.Pop()
If top <> "(" Then
output.Add(top)
Else
Exit While
End If
End While
If top <> "(" Then
Throw New ArgumentException("No matching left parenthesis.")
End If
Print(token)
End If
Next
While stack.Count > 0
Dim top = stack.Pop()
If Not Operators.ContainsKey(top) Then
Throw New ArgumentException("No matching right parenthesis.")
End If
output.Add(top)
End While
Print("pop")
Return String.Join(" ", output)
End Function
Sub Main()
Dim infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
Console.WriteLine(ToPostfix(infix))
End Sub
End Module
| package main
import (
"fmt"
"strings"
)
var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
var opa = map[string]struct {
prec int
rAssoc bool
}{
"^": {4, true},
"*": {3, false},
"/": {3, false},
"+": {2, false},
"-": {2, false},
}
func main() {
fmt.Println("infix: ", input)
fmt.Println("postfix:", parseInfix(input))
}
func parseInfix(e string) (rpn string) {
var stack []string
for _, tok := range strings.Fields(e) {
switch tok {
case "(":
stack = append(stack, tok)
case ")":
var op string
for {
op, stack = stack[len(stack)-1], stack[:len(stack)-1]
if op == "(" {
break
}
rpn += " " + op
}
default:
if o1, isOp := opa[tok]; isOp {
for len(stack) > 0 {
op := stack[len(stack)-1]
if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||
o1.prec == o2.prec && o1.rAssoc {
break
}
stack = stack[:len(stack)-1]
rpn += " " + op
}
stack = append(stack, tok)
} else {
if rpn > "" {
rpn += " "
}
rpn += tok
}
}
}
for len(stack) > 0 {
rpn += " " + stack[len(stack)-1]
stack = stack[:len(stack)-1]
}
return
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. | Option Strict On
Option Explicit On
Imports System.IO
Module vMain
Public Const maxNumber As Integer = 20
Dim prime(2 * maxNumber) As Boolean
Public Function countArrangements(ByVal n As Integer) As Integer
If n < 2 Then
Return 0
ElseIf n < 4 Then
For i As Integer = 1 To n
Console.Out.Write(i.ToString.PadLeft(3))
Next i
Console.Out.WriteLine()
Return 1
Else
Dim printSolution As Boolean = true
Dim used(n) As Boolean
Dim number(n) As Integer
For i As Integer = 0 To n - 1
number(i) = i Mod 2
Next i
used(1) = True
number(n) = n
used(n) = True
Dim count As Integer = 0
Dim p As Integer = 2
Do While p > 0
Dim p1 As Integer = number(p - 1)
Dim current As Integer = number(p)
Dim [next] As Integer = current + 2
Do While [next] < n AndAlso (Not prime(p1 + [next]) Or used([next]))
[next] += 2
Loop
If [next] >= n Then
[next] = 0
End If
If p = n - 1 Then
If [next] <> 0 Then
If prime([next] + n) Then
count += 1
If printSolution Then
For i As Integer = 1 To n - 2
Console.Out.Write(number(i).ToString.PadLeft(3))
Next i
Console.Out.WriteLine([next].ToString.PadLeft(3) & n.ToString.PadLeft(3))
printSolution = False
End If
End If
[next] = 0
End If
p -= 1
End If
If [next] <> 0 Then
used(current) = False
used([next]) = True
number(p) = [next]
p += 1
ElseIf p <= 2 Then
p = 0
Else
used(number(p)) = False
number(p) = p Mod 2
p -= 1
End If
Loop
Return count
End If
End Function
Public Sub Main
prime(2) = True
For i As Integer = 3 To UBound(prime) Step 2
prime(i) = True
Next i
For i As Integer = 3 To Convert.ToInt32(Math.Floor(Math.Sqrt(Ubound(prime)))) Step 2
If prime(i) Then
For s As Integer = i * i To Ubound(prime) Step i + i
prime(s) = False
Next s
End If
Next i
Dim arrangements(maxNumber) As Integer
For n As Integer = 2 To UBound(arrangements)
arrangements(n) = countArrangements(n)
Next n
For n As Integer = 2 To UBound(arrangements)
Console.Out.Write(" " & arrangements(n))
Next n
Console.Out.WriteLine()
End Sub
End Module
| package main
import "fmt"
var canFollow [][]bool
var arrang []int
var bFirst = true
var pmap = make(map[int]bool)
func init() {
for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} {
pmap[i] = true
}
}
func ptrs(res, n, done int) int {
ad := arrang[done-1]
if n-done <= 1 {
if canFollow[ad-1][n-1] {
if bFirst {
for _, e := range arrang {
fmt.Printf("%2d ", e)
}
fmt.Println()
bFirst = false
}
res++
}
} else {
done++
for i := done - 1; i <= n-2; i += 2 {
ai := arrang[i]
if canFollow[ad-1][ai-1] {
arrang[i], arrang[done-1] = arrang[done-1], arrang[i]
res = ptrs(res, n, done)
arrang[i], arrang[done-1] = arrang[done-1], arrang[i]
}
}
}
return res
}
func primeTriangle(n int) int {
canFollow = make([][]bool, n)
for i := 0; i < n; i++ {
canFollow[i] = make([]bool, n)
for j := 0; j < n; j++ {
_, ok := pmap[i+j+2]
canFollow[i][j] = ok
}
}
bFirst = true
arrang = make([]int, n)
for i := 0; i < n; i++ {
arrang[i] = i + 1
}
return ptrs(0, n, 1)
}
func main() {
counts := make([]int, 19)
for i := 2; i <= 20; i++ {
counts[i-2] = primeTriangle(i)
}
fmt.Println()
for i := 0; i < 19; i++ {
fmt.Printf("%d ", counts[i])
}
fmt.Println()
}
|
Convert the following code from VB to Go, ensuring the logic remains intact. | Function tpk(s)
arr = Split(s," ")
For i = UBound(arr) To 0 Step -1
n = fx(CDbl(arr(i)))
If n > 400 Then
WScript.StdOut.WriteLine arr(i) & " = OVERFLOW"
Else
WScript.StdOut.WriteLine arr(i) & " = " & n
End If
Next
End Function
Function fx(x)
fx = Sqr(Abs(x))+5*x^3
End Function
WScript.StdOut.Write "Please enter a series of numbers:"
list = WScript.StdIn.ReadLine
tpk(list)
| package main
import (
"fmt"
"log"
"math"
)
func main() {
fmt.Print("Enter 11 numbers: ")
var s [11]float64
for i := 0; i < 11; {
if n, _ := fmt.Scan(&s[i]); n > 0 {
i++
}
}
for i, item := range s[:5] {
s[i], s[10-i] = s[10-i], item
}
for _, item := range s {
if result, overflow := f(item); overflow {
log.Printf("f(%g) overflow", item)
} else {
fmt.Printf("f(%g) = %g\n", item, result)
}
}
}
func f(x float64) (float64, bool) {
result := math.Sqrt(math.Abs(x)) + 5*x*x*x
return result, result > 400
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Option Explicit
Sub Main_Middle_three_digits()
Dim Numbers, i&
Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _
100, -12345, 1, 2, -1, -10, 2002, -2002, 0)
For i = 0 To 16
Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i)))
Next
End Sub
Function Middle3digits(strNb As String) As String
If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1)
If Len(strNb) < 3 Then
Middle3digits = "Error ! Number of digits must be >= 3"
ElseIf Len(strNb) Mod 2 = 0 Then
Middle3digits = "Error ! Number of digits must be odd"
Else
Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)
End If
End Function
| package m3
import (
"errors"
"strconv"
)
var (
ErrorLT3 = errors.New("N of at least three digits required.")
ErrorEven = errors.New("N with odd number of digits required.")
)
func Digits(i int) (string, error) {
if i < 0 {
i = -i
}
if i < 100 {
return "", ErrorLT3
}
s := strconv.Itoa(i)
if len(s)%2 == 0 {
return "", ErrorEven
}
m := len(s) / 2
return s[m-1 : m+2], nil
}
|
Port the provided VB code into Go while preserving the original functionality. | Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Do
flag = Not flag
l = FindNextPunct(i, W) - count + 1
If flag Then
temp = temp & ExtractWord(W, count, l)
Else
temp = temp & ReverseWord(W, count, l)
End If
Loop While count < Len(W)
OddWordFirst = temp
End Function
Private Function FindNextPunct(d As Integer, W As String) As Integer
Const PUNCT As String = ",;:."
Do
d = d + 1
Loop While InStr(PUNCT, Mid(W, d, 1)) = 0
FindNextPunct = d
End Function
Private Function ExtractWord(W As String, c As Integer, i As Integer) As String
ExtractWord = Mid(W, c, i)
c = c + Len(ExtractWord)
End Function
Private Function ReverseWord(W As String, c As Integer, i As Integer) As String
Dim temp As String, sep As String
temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)
sep = Right(Mid(W, c, i), 1)
ReverseWord = StrReverse(temp) & sep
c = c + Len(ReverseWord)
End Function
| package main
import (
"bytes"
"fmt"
"io"
"os"
"unicode"
)
func main() {
owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life."))
fmt.Println()
owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more."))
fmt.Println()
}
func owp(dst io.Writer, src io.Reader) {
byte_in := func () byte {
bs := make([]byte, 1)
src.Read(bs)
return bs[0]
}
byte_out := func (b byte) { dst.Write([]byte{b}) }
var odd func() byte
odd = func() byte {
s := byte_in()
if unicode.IsPunct(rune(s)) {
return s
}
b := odd()
byte_out(s)
return b
}
for {
for {
b := byte_in()
byte_out(b)
if b == '.' {
return
}
if unicode.IsPunct(rune(b)) {
break
}
}
b := odd()
byte_out(b)
if b == '.' {
return
}
}
}
|
Generate an equivalent Go version of this VB code. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = DaysBetween Mod 28
positionM = DaysBetween Mod 33
Biorhythm = CStr(positionP) & "/" & CStr(positionE) & "/" & CStr(positionM)
quadrantP = Int(4 * positionP / 23)
quadrantE = Int(4 * positionE / 28)
quadrantM = Int(4 * positionM / 33)
percentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)
percentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)
percentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)
transitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP
transitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE
transitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM
Select Case True
Case percentageP > 95
textP = "Physical day " & positionP & " : " & "peak"
Case percentageP < -95
textP = "Physical day " & positionP & " : " & "valley"
Case percentageP < 5 And percentageP > -5
textP = "Physical day " & positionP & " : " & "critical transition"
Case Else
textP = "Physical day " & positionP & " : " & percentageP & "% (" & TextArray(quadrantP)(0) & ", next " & TextArray(quadrantP)(1) & " " & transitionP & ")"
End Select
Select Case True
Case percentageE > 95
textE = "Emotional day " & positionE & " : " & "peak"
Case percentageE < -95
textE = "Emotional day " & positionE & " : " & "valley"
Case percentageE < 5 And percentageE > -5
textE = "Emotional day " & positionE & " : " & "critical transition"
Case Else
textE = "Emotional day " & positionE & " : " & percentageE & "% (" & TextArray(quadrantE)(0) & ", next " & TextArray(quadrantE)(1) & " " & transitionE & ")"
End Select
Select Case True
Case percentageM > 95
textM = "Mental day " & positionM & " : " & "peak"
Case percentageM < -95
textM = "Mental day " & positionM & " : " & "valley"
Case percentageM < 5 And percentageM > -5
textM = "Mental day " & positionM & " : " & "critical transition"
Case Else
textM = "Mental day " & positionM & " : " & percentageM & "% (" & TextArray(quadrantM)(0) & ", next " & TextArray(quadrantM)(1) & " " & transitionM & ")"
End Select
Header1Text = "Born " & Birthdate & ", Target " & Targetdate
Header2Text = "Day " & DaysBetween
Debug.Print Header1Text
Debug.Print Header2Text
Debug.Print textP
Debug.Print textE
Debug.Print textM
Debug.Print ""
End Function
| package main
import (
"fmt"
"log"
"math"
"time"
)
const layout = "2006-01-02"
var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "}
var lengths = [3]int{23, 28, 33}
var quadrants = [4][2]string{
{"up and rising", "peak"},
{"up but falling", "transition"},
{"down and falling", "valley"},
{"down but rising", "transition"},
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func biorhythms(birthDate, targetDate string) {
bd, err := time.Parse(layout, birthDate)
check(err)
td, err := time.Parse(layout, targetDate)
check(err)
days := int(td.Sub(bd).Hours() / 24)
fmt.Printf("Born %s, Target %s\n", birthDate, targetDate)
fmt.Println("Day", days)
for i := 0; i < 3; i++ {
length := lengths[i]
cycle := cycles[i]
position := days % length
quadrant := position * 4 / length
percent := math.Sin(2 * math.Pi * float64(position) / float64(length))
percent = math.Floor(percent*1000) / 10
descript := ""
if percent > 95 {
descript = " peak"
} else if percent < -95 {
descript = " valley"
} else if math.Abs(percent) < 5 {
descript = " critical transition"
} else {
daysToAdd := (quadrant+1)*length/4 - position
transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))
trend := quadrants[quadrant][0]
next := quadrants[quadrant][1]
transStr := transition.Format(layout)
descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr)
}
fmt.Printf("%s %2d : %s\n", cycle, position, descript)
}
fmt.Println()
}
func main() {
datePairs := [][2]string{
{"1943-03-09", "1972-07-11"},
{"1809-01-12", "1863-11-19"},
{"1809-02-12", "1863-11-19"},
}
for _, datePair := range datePairs {
biorhythms(datePair[0], datePair[1])
}
}
|
Generate a Go translation of this VB snippet without changing its computational steps. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = DaysBetween Mod 28
positionM = DaysBetween Mod 33
Biorhythm = CStr(positionP) & "/" & CStr(positionE) & "/" & CStr(positionM)
quadrantP = Int(4 * positionP / 23)
quadrantE = Int(4 * positionE / 28)
quadrantM = Int(4 * positionM / 33)
percentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)
percentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)
percentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)
transitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP
transitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE
transitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM
Select Case True
Case percentageP > 95
textP = "Physical day " & positionP & " : " & "peak"
Case percentageP < -95
textP = "Physical day " & positionP & " : " & "valley"
Case percentageP < 5 And percentageP > -5
textP = "Physical day " & positionP & " : " & "critical transition"
Case Else
textP = "Physical day " & positionP & " : " & percentageP & "% (" & TextArray(quadrantP)(0) & ", next " & TextArray(quadrantP)(1) & " " & transitionP & ")"
End Select
Select Case True
Case percentageE > 95
textE = "Emotional day " & positionE & " : " & "peak"
Case percentageE < -95
textE = "Emotional day " & positionE & " : " & "valley"
Case percentageE < 5 And percentageE > -5
textE = "Emotional day " & positionE & " : " & "critical transition"
Case Else
textE = "Emotional day " & positionE & " : " & percentageE & "% (" & TextArray(quadrantE)(0) & ", next " & TextArray(quadrantE)(1) & " " & transitionE & ")"
End Select
Select Case True
Case percentageM > 95
textM = "Mental day " & positionM & " : " & "peak"
Case percentageM < -95
textM = "Mental day " & positionM & " : " & "valley"
Case percentageM < 5 And percentageM > -5
textM = "Mental day " & positionM & " : " & "critical transition"
Case Else
textM = "Mental day " & positionM & " : " & percentageM & "% (" & TextArray(quadrantM)(0) & ", next " & TextArray(quadrantM)(1) & " " & transitionM & ")"
End Select
Header1Text = "Born " & Birthdate & ", Target " & Targetdate
Header2Text = "Day " & DaysBetween
Debug.Print Header1Text
Debug.Print Header2Text
Debug.Print textP
Debug.Print textE
Debug.Print textM
Debug.Print ""
End Function
| package main
import (
"fmt"
"log"
"math"
"time"
)
const layout = "2006-01-02"
var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "}
var lengths = [3]int{23, 28, 33}
var quadrants = [4][2]string{
{"up and rising", "peak"},
{"up but falling", "transition"},
{"down and falling", "valley"},
{"down but rising", "transition"},
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func biorhythms(birthDate, targetDate string) {
bd, err := time.Parse(layout, birthDate)
check(err)
td, err := time.Parse(layout, targetDate)
check(err)
days := int(td.Sub(bd).Hours() / 24)
fmt.Printf("Born %s, Target %s\n", birthDate, targetDate)
fmt.Println("Day", days)
for i := 0; i < 3; i++ {
length := lengths[i]
cycle := cycles[i]
position := days % length
quadrant := position * 4 / length
percent := math.Sin(2 * math.Pi * float64(position) / float64(length))
percent = math.Floor(percent*1000) / 10
descript := ""
if percent > 95 {
descript = " peak"
} else if percent < -95 {
descript = " valley"
} else if math.Abs(percent) < 5 {
descript = " critical transition"
} else {
daysToAdd := (quadrant+1)*length/4 - position
transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))
trend := quadrants[quadrant][0]
next := quadrants[quadrant][1]
transStr := transition.Format(layout)
descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr)
}
fmt.Printf("%s %2d : %s\n", cycle, position, descript)
}
fmt.Println()
}
func main() {
datePairs := [][2]string{
{"1943-03-09", "1972-07-11"},
{"1809-01-12", "1863-11-19"},
{"1809-02-12", "1863-11-19"},
}
for _, datePair := range datePairs {
biorhythms(datePair[0], datePair[1])
}
}
|
Write the same code in Go as shown below in VB. | Option Explicit
Dim objFSO, DBSource
Set objFSO = CreateObject("Scripting.FileSystemObject")
DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb"
With CreateObject("ADODB.Connection")
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource
.Execute "CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL," &_
"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)"
.Close
End With
| package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "rc.db")
if err != nil {
log.Print(err)
return
}
defer db.Close()
_, err = db.Exec(`create table addr (
id int unique,
street text,
city text,
state text,
zip text
)`)
if err != nil {
log.Print(err)
return
}
rows, err := db.Query(`pragma table_info(addr)`)
if err != nil {
log.Print(err)
return
}
var field, storage string
var ignore sql.RawBytes
for rows.Next() {
err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)
if err != nil {
log.Print(err)
return
}
fmt.Println(field, storage)
}
}
|
Convert this VB snippet to Go and keep its semantics consistent. |
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
| |
Maintain the same structure and functionality when rewriting this code in Go. |
package main
import "fmt"
func hello() {
fmt.Println("Hello from main.go")
}
func main() {
hello()
hello2()
}
| |
Change the programming language of this snippet from VB to Go without modifying what it does. | Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Dim l As List(Of Integer) = {1, 1}.ToList()
Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer
Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)
End Function
Sub Main(ByVal args As String())
Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,
selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}
Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1
Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take)
Console.WriteLine("{0}" & vbLf, String.Join(", ", l.Take(take)))
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:")
For Each ii As Integer In selection
Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1
Console.WriteLine("{0,3}: {1:n0}", ii, j)
Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max
If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For
Next
Console.WriteLine("The greatest common divisor of all the two consecutive items of the" &
" series up to the {0}th item is {1}always one.", max, If(good, "", "not "))
End Sub
End Module
| package main
import (
"fmt"
"sternbrocot"
)
func main() {
g := sb.Generator()
fmt.Println("First 15:")
for i := 1; i <= 15; i++ {
fmt.Printf("%2d: %d\n", i, g())
}
s := sb.New()
fmt.Println("First 15:", s.FirstN(15))
for _, x := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100} {
fmt.Printf("%3d at 1-based index %d\n", x, 1+s.Find(x))
}
fmt.Println("1-based indexes: gcd")
for n, f := range s.FirstN(1000)[:999] {
g := gcd(f, (*s)[n+1])
fmt.Printf("%d,%d: gcd(%d, %d) = %d\n", n+1, n+2, f, (*s)[n+1], g)
if g != 1 {
panic("oh no!")
return
}
}
}
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? |
tt=array( _
"Ashcraft","Ashcroft","Gauss","Ghosh","Hilbert","Heilbronn","Lee","Lloyd", _
"Moses","Pfister","Robert","Rupert","Rubin","Tymczak","Soundex","Example")
tv=array( _
"A261","A261","G200","G200","H416","H416","L000","L300", _
"M220","P236","R163","R163","R150","T522","S532","E251")
For i=lbound(tt) To ubound(tt)
ts=soundex(tt(i))
If ts<>tv(i) Then ok=" KO "& tv(i) Else ok=""
Wscript.echo right(" "& i ,2) & " " & left( tt(i) &space(12),12) & " " & ts & ok
Next
Function getCode(c)
Select Case c
Case "B", "F", "P", "V"
getCode = "1"
Case "C", "G", "J", "K", "Q", "S", "X", "Z"
getCode = "2"
Case "D", "T"
getCode = "3"
Case "L"
getCode = "4"
Case "M", "N"
getCode = "5"
Case "R"
getCode = "6"
Case "W","H"
getCode = "-"
End Select
End Function
Function soundex(s)
Dim code, previous, i
code = UCase(Mid(s, 1, 1))
previous = getCode(UCase(Mid(s, 1, 1)))
For i = 2 To Len(s)
current = getCode(UCase(Mid(s, i, 1)))
If current <> "" And current <> "-" And current <> previous Then code = code & current
If current <> "-" Then previous = current
Next
soundex = Mid(code & "000", 1, 4)
End Function
| package main
import (
"errors"
"fmt"
"unicode"
)
var code = []byte("01230127022455012623017202")
func soundex(s string) (string, error) {
var sx [4]byte
var sxi int
var cx, lastCode byte
for i, c := range s {
switch {
case !unicode.IsLetter(c):
if c < ' ' || c == 127 {
return "", errors.New("ASCII control characters disallowed")
}
if i == 0 {
return "", errors.New("initial character must be a letter")
}
lastCode = '0'
continue
case c >= 'A' && c <= 'Z':
cx = byte(c - 'A')
case c >= 'a' && c <= 'z':
cx = byte(c - 'a')
default:
return "", errors.New("non-ASCII letters unsupported")
}
if i == 0 {
sx[0] = cx + 'A'
sxi = 1
continue
}
switch x := code[cx]; x {
case '7', lastCode:
case '0':
lastCode = '0'
default:
sx[sxi] = x
if sxi == 3 {
return string(sx[:]), nil
}
sxi++
lastCode = x
}
}
if sxi == 0 {
return "", errors.New("no letters present")
}
for ; sxi < 4; sxi++ {
sx[sxi] = '0'
}
return string(sx[:]), nil
}
func main() {
for _, s := range []string{
"Robert",
"Rupert",
"Rubin",
"ashcroft",
"ashcraft",
"moses",
"O'Mally",
"d jay",
"R2-D2",
"12p2",
"naïve",
"",
"bump\t",
} {
if x, err := soundex(s); err == nil {
fmt.Println("soundex", s, "=", x)
} else {
fmt.Printf("\"%s\" fail. %s\n", s, err)
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Module Module1
Class State
Private ReadOnly client As TcpClient
Private ReadOnly sb As New StringBuilder
Public Sub New(name As String, client As TcpClient)
Me.Name = name
Me.client = client
End Sub
Public ReadOnly Property Name As String
Public Sub Send(text As String)
Dim bytes = Encoding.ASCII.GetBytes(String.Format("{0}" & vbCrLf, text))
client.GetStream().Write(bytes, 0, bytes.Length)
End Sub
End Class
ReadOnly connections As New Dictionary(Of Integer, State)
Dim listen As TcpListener
Dim serverThread As Thread
Sub Main()
listen = New TcpListener(Net.IPAddress.Parse("127.0.0.1"), 4004)
serverThread = New Thread(New ThreadStart(AddressOf DoListen))
serverThread.Start()
End Sub
Private Sub DoListen()
listen.Start()
Console.WriteLine("Server: Started server")
Do
Console.Write("Server: Waiting...")
Dim client = listen.AcceptTcpClient()
Console.WriteLine(" Connected")
Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))
clientThread.Start(client)
Loop
End Sub
Private Sub DoClient(client As TcpClient)
Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId)
Dim bytes = Encoding.ASCII.GetBytes("Enter name: ")
client.GetStream().Write(bytes, 0, bytes.Length)
Dim done As Boolean
Dim name As String
Do
If Not client.Connected Then
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
client.Close()
Thread.CurrentThread.Abort()
End If
name = Receive(client)
done = True
For Each cl In connections
Dim state = cl.Value
If state.Name = name Then
bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ")
client.GetStream().Write(bytes, 0, bytes.Length)
done = False
End If
Next
Loop While Not done
connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))
Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
Broadcast(String.Format("+++ {0} arrived +++", name))
Do
Dim text = Receive(client)
If text = "/quit" Then
Broadcast(String.Format("Connection from {0} closed.", name))
connections.Remove(Thread.CurrentThread.ManagedThreadId)
Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
Exit Do
End If
If Not client.Connected Then
Exit Do
End If
Broadcast(String.Format("{0}> {1}", name, text))
Loop
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
client.Close()
Thread.CurrentThread.Abort()
End Sub
Private Function Receive(client As TcpClient) As String
Dim sb As New StringBuilder
Do
If client.Available > 0 Then
While client.Available > 0
Dim ch = Chr(client.GetStream.ReadByte())
If ch = vbCr Then
Continue While
End If
If ch = vbLf Then
Return sb.ToString()
End If
sb.Append(ch)
End While
Thread.Sleep(100)
End If
Loop
End Function
Private Sub Broadcast(text As String)
Console.WriteLine(text)
For Each client In connections
If client.Key <> Thread.CurrentThread.ManagedThreadId Then
Dim state = client.Value
state.Send(text)
End If
Next
End Sub
End Module
| package main
import (
"bufio"
"flag"
"fmt"
"log"
"net"
"strings"
"time"
)
func main() {
log.SetPrefix("chat: ")
addr := flag.String("addr", "localhost:4000", "listen address")
flag.Parse()
log.Fatal(ListenAndServe(*addr))
}
type Server struct {
add chan *conn
rem chan string
msg chan string
stop chan bool
}
func ListenAndServe(addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
log.Println("Listening for connections on", addr)
defer ln.Close()
s := &Server{
add: make(chan *conn),
rem: make(chan string),
msg: make(chan string),
stop: make(chan bool),
}
go s.handleConns()
for {
rwc, err := ln.Accept()
if err != nil {
close(s.stop)
return err
}
log.Println("New connection from", rwc.RemoteAddr())
go newConn(s, rwc).welcome()
}
}
func (s *Server) handleConns() {
conns := make(map[string]*conn)
var dropConn func(string)
writeAll := func(str string) {
log.Printf("Broadcast: %q", str)
for name, c := range conns {
c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond))
_, err := c.Write([]byte(str))
if err != nil {
log.Printf("Error writing to %q: %v", name, err)
c.Close()
delete(conns, name)
defer dropConn(name)
}
}
}
dropConn = func(name string) {
if c, ok := conns[name]; ok {
log.Printf("Closing connection with %q from %v",
name, c.RemoteAddr())
c.Close()
delete(conns, name)
} else {
log.Printf("Dropped connection with %q", name)
}
str := fmt.Sprintf("--- %q disconnected ---\n", name)
writeAll(str)
}
defer func() {
writeAll("Server stopping!\n")
for _, c := range conns {
c.Close()
}
}()
for {
select {
case c := <-s.add:
if _, exists := conns[c.name]; exists {
fmt.Fprintf(c, "Name %q is not available\n", c.name)
go c.welcome()
continue
}
str := fmt.Sprintf("+++ %q connected +++\n", c.name)
writeAll(str)
conns[c.name] = c
go c.readloop()
case str := <-s.msg:
writeAll(str)
case name := <-s.rem:
dropConn(name)
case <-s.stop:
return
}
}
}
type conn struct {
*bufio.Reader
net.Conn
server *Server
name string
}
func newConn(s *Server, rwc net.Conn) *conn {
return &conn{
Reader: bufio.NewReader(rwc),
Conn: rwc,
server: s,
}
}
func (c *conn) welcome() {
var err error
for c.name = ""; c.name == ""; {
fmt.Fprint(c, "Enter your name: ")
c.name, err = c.ReadString('\n')
if err != nil {
log.Printf("Reading name from %v: %v", c.RemoteAddr(), err)
c.Close()
return
}
c.name = strings.TrimSpace(c.name)
}
c.server.add <- c
}
func (c *conn) readloop() {
for {
msg, err := c.ReadString('\n')
if err != nil {
break
}
c.server.msg <- c.name + "> " + msg
}
c.server.rem <- c.name
}
|
Write the same code in Go as shown below in VB. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
| import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
|
Write the same code in Go as shown below in VB. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
| import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
| import (
"fmt"
"os"
)
if err := os.Truncate("filename", newSize); err != nil {
fmt.Println(err)
}
|
Keep all operations the same but rewrite the snippet in Go. | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
| package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("Decimal :", n)
fmt.Println("Binary :", strconv.FormatUint(n, 2))
fmt.Println("Ternary :", strconv.FormatUint(n, 3))
fmt.Println("Time :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
|
Write a version of this VB function in Go with identical behavior. | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
| package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("Decimal :", n)
fmt.Println("Binary :", strconv.FormatUint(n, 2))
fmt.Println("Ternary :", strconv.FormatUint(n, 3))
fmt.Println("Time :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
|
Generate a Go translation of this VB snippet without changing its computational steps. | Module Module1
Sub Main()
Dim bufferHeight = Console.BufferHeight
Dim bufferWidth = Console.BufferWidth
Dim windowHeight = Console.WindowHeight
Dim windowWidth = Console.WindowWidth
Console.Write("Buffer Height: ")
Console.WriteLine(bufferHeight)
Console.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
End Sub
End Module
| package main
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(h, w)
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Module Module1
Sub Main()
Dim bufferHeight = Console.BufferHeight
Dim bufferWidth = Console.BufferWidth
Dim windowHeight = Console.WindowHeight
Dim windowWidth = Console.WindowWidth
Console.Write("Buffer Height: ")
Console.WriteLine(bufferHeight)
Console.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
End Sub
End Module
| package main
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(h, w)
}
|
Write the same algorithm in Go as shown in this VB implementation. | Enum states
READY
WAITING
DISPENSE
REFUND
QU1T
End Enum
Public Sub finite_state_machine()
Dim state As Integer: state = READY: ch = " "
Do While True
Debug.Print ch
Select Case state
Case READY: Debug.Print "Machine is READY. (D)eposit or (Q)uit :"
Do While True
If ch = "D" Then
state = WAITING
Exit Do
End If
If ch = "Q" Then
state = QU1T
Exit Do
End If
ch = InputBox("Machine is READY. (D)eposit or (Q)uit :")
Loop
Case WAITING: Debug.Print "(S)elect product or choose to (R)efund :"
Do While True
If ch = "S" Then
state = DISPENSE
Exit Do
End If
If ch = "R" Then
state = REFUND
Exit Do
End If
ch = InputBox("(S)elect product or choose to (R)efund :")
Loop
Case DISPENSE: Debug.Print "Dispensing product..."
Do While True
If ch = "C" Then
state = READY
Exit Do
End If
ch = InputBox("Please (C)ollect product. :")
Loop
Case REFUND: Debug.Print "Please collect refund."
state = READY
ch = " "
Case QU1T: Debug.Print "Thank you, shutting down now."
Exit Sub
End Select
Loop
End Sub
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
type state int
const (
ready state = iota
waiting
exit
dispense
refunding
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func fsm() {
fmt.Println("Please enter your option when prompted")
fmt.Println("(any characters after the first will be ignored)")
state := ready
var trans string
scanner := bufio.NewScanner(os.Stdin)
for {
switch state {
case ready:
for {
fmt.Print("\n(D)ispense or (Q)uit : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 'd' {
state = waiting
break
} else if option == 'q' {
state = exit
break
}
}
case waiting:
fmt.Println("OK, put your money in the slot")
for {
fmt.Print("(S)elect product or choose a (R)efund : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 's' {
state = dispense
break
} else if option == 'r' {
state = refunding
break
}
}
case dispense:
for {
fmt.Print("(R)emove product : ")
scanner.Scan()
trans = scanner.Text()
check(scanner.Err())
if len(trans) == 0 {
continue
}
option := strings.ToLower(trans)[0]
if option == 'r' {
state = ready
break
}
}
case refunding:
fmt.Println("OK, refunding your money")
state = ready
case exit:
fmt.Println("OK, quitting")
return
}
}
}
func main() {
fsm()
}
|
Generate a Go translation of this VB snippet without changing its computational steps. | Imports System.Numerics
Module Module1
ReadOnly BIG = BigInteger.Pow(10, 50) + 151
Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)
Dim n = BigInteger.Parse(ns)
Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)
Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)
If ls(n) <> 1 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Dim a = BigInteger.Zero
Dim omega2 As BigInteger
Do
omega2 = (a * a + p - n) Mod p
If ls(omega2) = p - 1 Then
Exit Do
End If
a += 1
Loop
Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))
Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)
End Function
Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)
Dim s = Tuple.Create(a, BigInteger.One)
Dim nn = ((p + 1) >> 1) Mod p
While nn > 0
If nn Mod 2 = 1 Then
r = mul(r, s)
End If
s = mul(s, s)
nn >>= 1
End While
If r.Item2 <> 0 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
If r.Item1 * r.Item1 Mod p <> n Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Return Tuple.Create(r.Item1, p - r.Item1, True)
End Function
Sub Main()
Console.WriteLine(C("10", "13"))
Console.WriteLine(C("56", "101"))
Console.WriteLine(C("8218", "10007"))
Console.WriteLine(C("8219", "10007"))
Console.WriteLine(C("331575", "1000003"))
Console.WriteLine(C("665165880", "1000000007"))
Console.WriteLine(C("881398088036", "1000000000039"))
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""))
End Sub
End Module
| package main
import "fmt"
func c(n, p int) (R1, R2 int, ok bool) {
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
if ls(n) != 1 {
return
}
var a, ω2 int
for a = 0; ; a++ {
ω2 = (a*a + p - n) % p
if ls(ω2) == p-1 {
break
}
}
type point struct{ x, y int }
mul := func(a, b point) point {
return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}
}
r := point{1, 0}
s := point{a, 1}
for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
if n&1 == 1 {
r = mul(r, s)
}
s = mul(s, s)
}
if r.y != 0 {
return
}
if r.x*r.x%p != n {
return
}
return r.x, p - r.x, true
}
func main() {
fmt.Println(c(10, 13))
fmt.Println(c(56, 101))
fmt.Println(c(8218, 10007))
fmt.Println(c(8219, 10007))
fmt.Println(c(331575, 1000003))
}
|
Translate the given VB code snippet into Go without altering its behavior. | Imports System.Numerics
Module Module1
ReadOnly BIG = BigInteger.Pow(10, 50) + 151
Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)
Dim n = BigInteger.Parse(ns)
Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)
Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)
If ls(n) <> 1 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Dim a = BigInteger.Zero
Dim omega2 As BigInteger
Do
omega2 = (a * a + p - n) Mod p
If ls(omega2) = p - 1 Then
Exit Do
End If
a += 1
Loop
Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))
Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)
End Function
Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)
Dim s = Tuple.Create(a, BigInteger.One)
Dim nn = ((p + 1) >> 1) Mod p
While nn > 0
If nn Mod 2 = 1 Then
r = mul(r, s)
End If
s = mul(s, s)
nn >>= 1
End While
If r.Item2 <> 0 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
If r.Item1 * r.Item1 Mod p <> n Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Return Tuple.Create(r.Item1, p - r.Item1, True)
End Function
Sub Main()
Console.WriteLine(C("10", "13"))
Console.WriteLine(C("56", "101"))
Console.WriteLine(C("8218", "10007"))
Console.WriteLine(C("8219", "10007"))
Console.WriteLine(C("331575", "1000003"))
Console.WriteLine(C("665165880", "1000000007"))
Console.WriteLine(C("881398088036", "1000000000039"))
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""))
End Sub
End Module
| package main
import "fmt"
func c(n, p int) (R1, R2 int, ok bool) {
powModP := func(a, e int) int {
s := 1
for ; e > 0; e-- {
s = s * a % p
}
return s
}
ls := func(a int) int {
return powModP(a, (p-1)/2)
}
if ls(n) != 1 {
return
}
var a, ω2 int
for a = 0; ; a++ {
ω2 = (a*a + p - n) % p
if ls(ω2) == p-1 {
break
}
}
type point struct{ x, y int }
mul := func(a, b point) point {
return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}
}
r := point{1, 0}
s := point{a, 1}
for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
if n&1 == 1 {
r = mul(r, s)
}
s = mul(s, s)
}
if r.y != 0 {
return
}
if r.x*r.x%p != n {
return
}
return r.x, p - r.x, true
}
func main() {
fmt.Println(c(10, 13))
fmt.Println(c(56, 101))
fmt.Println(c(8218, 10007))
fmt.Println(c(8219, 10007))
fmt.Println(c(331575, 1000003))
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. | Private Sub sierpinski(Order_ As Integer, Side As Double)
Dim Circumradius As Double, Inradius As Double
Dim Height As Double, Diagonal As Double, HeightDiagonal As Double
Dim Pi As Double, p(5) As String, Shp As Shape
Circumradius = Sqr(50 + 10 * Sqr(5)) / 10
Inradius = Sqr(25 + 10 * Sqr(5)) / 10
Height = Circumradius + Inradius
Diagonal = (1 + Sqr(5)) / 2
HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4
Pi = WorksheetFunction.Pi
Ratio = Height / (2 * Height + HeightDiagonal)
Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _
2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)
p(0) = Shp.Name
Shp.Rotation = 180
Shp.Line.Weight = 0
For j = 1 To Order_
For i = 0 To 4
Set Shp = Shp.Duplicate
p(i + 1) = Shp.Name
If i = 0 Then Shp.Rotation = 0
Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)
Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)
Shp.Visible = msoTrue
Next i
Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group
p(0) = Shp.Name
If j < Order_ Then
Shp.ScaleHeight Ratio, False
Shp.ScaleWidth Ratio, False
Shp.Rotation = 180
Shp.Left = 2 * Side
Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side
End If
Next j
End Sub
Public Sub main()
sierpinski Order_:=5, Side:=200
End Sub
| package main
import (
"github.com/fogleman/gg"
"image/color"
"math"
)
var (
red = color.RGBA{255, 0, 0, 255}
green = color.RGBA{0, 255, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
magenta = color.RGBA{255, 0, 255, 255}
cyan = color.RGBA{0, 255, 255, 255}
)
var (
w, h = 640, 640
dc = gg.NewContext(w, h)
deg72 = gg.Radians(72)
scaleFactor = 1 / (2 + math.Cos(deg72)*2)
palette = [5]color.Color{red, green, blue, magenta, cyan}
colorIndex = 0
)
func drawPentagon(x, y, side float64, depth int) {
angle := 3 * deg72
if depth == 0 {
dc.MoveTo(x, y)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * side
y -= math.Sin(angle) * side
dc.LineTo(x, y)
angle += deg72
}
dc.SetColor(palette[colorIndex])
dc.Fill()
colorIndex = (colorIndex + 1) % 5
} else {
side *= scaleFactor
dist := side * (1 + math.Cos(deg72)*2)
for i := 0; i < 5; i++ {
x += math.Cos(angle) * dist
y -= math.Sin(angle) * dist
drawPentagon(x, y, side, depth-1)
angle += deg72
}
}
}
func main() {
dc.SetRGB(1, 1, 1)
dc.Clear()
order := 5
hw := float64(w / 2)
margin := 20.0
radius := hw - 2*margin
side := radius * math.Sin(math.Pi/5) * 2
drawPentagon(hw, 3*margin, side, order-1)
dc.SavePNG("sierpinski_pentagon.png")
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Function rep_string(s)
max_len = Int(Len(s)/2)
tmp = ""
If max_len = 0 Then
rep_string = "No Repeating String"
Exit Function
End If
For i = 1 To max_len
If InStr(i+1,s,tmp & Mid(s,i,1))Then
tmp = tmp & Mid(s,i,1)
Else
Exit For
End If
Next
Do While Len(tmp) > 0
If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then
rep_string = tmp
Exit Do
Else
tmp = Mid(tmp,1,Len(tmp)-1)
End If
Loop
If Len(tmp) > 0 Then
rep_string = tmp
Else
rep_string = "No Repeating String"
End If
End Function
arr = Array("1001110011","1110111011","0010010010","1010101010",_
"1111111111","0100101101","0100100","101","11","00","1")
For n = 0 To UBound(arr)
WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n))
WScript.StdOut.WriteLine
Next
| package main
import (
"fmt"
"strings"
)
func rep(s string) int {
for x := len(s) / 2; x > 0; x-- {
if strings.HasPrefix(s, s[x:]) {
return x
}
}
return 0
}
const m = `
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1`
func main() {
for _, s := range strings.Fields(m) {
if n := rep(s); n > 0 {
fmt.Printf("%q %d rep-string %q\n", s, n, s[:n])
} else {
fmt.Printf("%q not a rep-string\n", s)
}
}
}
|
Port the provided VB code into Go while preserving the original functionality. | Debug.Print "Tom said, ""The fox ran away."""
Debug.Print "Tom said,
| ch := 'z'
ch = 122
ch = '\x7a'
ch = '\u007a'
ch = '\U0000007a'
ch = '\172'
|
Keep all operations the same but rewrite the snippet in Go. | TYPE syswindowstru
screenheight AS INTEGER
screenwidth AS INTEGER
maxheight AS INTEGER
maxwidth AS INTEGER
END TYPE
DIM syswindow AS syswindowstru
syswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX
syswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY
| package main
import (
"fmt"
"github.com/go-vgo/robotgo"
)
func main() {
w, h := robotgo.GetScreenSize()
fmt.Printf("Screen size: %d x %d\n", w, h)
fpid, err := robotgo.FindIds("firefox")
if err == nil && len(fpid) > 0 {
pid := fpid[0]
robotgo.ActivePID(pid)
robotgo.MaxWindow(pid)
_, _, w, h = robotgo.GetBounds(pid)
fmt.Printf("Max usable : %d x %d\n", w, h)
}
}
|
Produce a functionally identical Go code for the snippet given in VB. | TYPE syswindowstru
screenheight AS INTEGER
screenwidth AS INTEGER
maxheight AS INTEGER
maxwidth AS INTEGER
END TYPE
DIM syswindow AS syswindowstru
syswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX
syswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY
| package main
import (
"fmt"
"github.com/go-vgo/robotgo"
)
func main() {
w, h := robotgo.GetScreenSize()
fmt.Printf("Screen size: %d x %d\n", w, h)
fpid, err := robotgo.FindIds("firefox")
if err == nil && len(fpid) > 0 {
pid := fpid[0]
robotgo.ActivePID(pid)
robotgo.MaxWindow(pid)
_, _, w, h = robotgo.GetBounds(pid)
fmt.Printf("Max usable : %d x %d\n", w, h)
}
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? |
Enum fruits
apple
banana
cherry
End Enum
Enum fruits2
pear = 5
mango = 10
kiwi = 20
pineapple = 20
End Enum
Sub test()
Dim f As fruits
f = apple
Debug.Print "apple equals "; f
Debug.Print "kiwi equals "; kiwi
Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple
End Sub
| const (
apple = iota
banana
cherry
)
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Sub pentagram()
With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Line.Weight = 3
.Line.ForeColor.RGB = RGB(0, 0, 255)
End With
End Sub
| package main
import (
"github.com/fogleman/gg"
"math"
)
func Pentagram(x, y, r float64) []gg.Point {
points := make([]gg.Point, 5)
for i := 0; i < 5; i++ {
fi := float64(i)
angle := 2*math.Pi*fi/5 - math.Pi/2
points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
}
return points
}
func main() {
points := Pentagram(320, 320, 250)
dc := gg.NewContext(640, 640)
dc.SetRGB(1, 1, 1)
dc.Clear()
for i := 0; i <= 5; i++ {
index := (i * 2) % 5
p := points[index]
dc.LineTo(p.X, p.Y)
}
dc.SetHexColor("#6495ED")
dc.SetFillRule(gg.FillRuleWinding)
dc.FillPreserve()
dc.SetRGB(0, 0, 0)
dc.SetLineWidth(5)
dc.Stroke()
dc.SavePNG("pentagram.png")
}
|
Rewrite the snippet below in Go so it works the same as the original VB code. | Sub pentagram()
With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Line.Weight = 3
.Line.ForeColor.RGB = RGB(0, 0, 255)
End With
End Sub
| package main
import (
"github.com/fogleman/gg"
"math"
)
func Pentagram(x, y, r float64) []gg.Point {
points := make([]gg.Point, 5)
for i := 0; i < 5; i++ {
fi := float64(i)
angle := 2*math.Pi*fi/5 - math.Pi/2
points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
}
return points
}
func main() {
points := Pentagram(320, 320, 250)
dc := gg.NewContext(640, 640)
dc.SetRGB(1, 1, 1)
dc.Clear()
for i := 0; i <= 5; i++ {
index := (i * 2) % 5
p := points[index]
dc.LineTo(p.X, p.Y)
}
dc.SetHexColor("#6495ED")
dc.SetFillRule(gg.FillRuleWinding)
dc.FillPreserve()
dc.SetRGB(0, 0, 0)
dc.SetLineWidth(5)
dc.Stroke()
dc.SavePNG("pentagram.png")
}
|
Please provide an equivalent version of this VB code in Go. | Function parse_ip(addr)
Set ipv4_pattern = New RegExp
ipv4_pattern.Global = True
ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}"
Set ipv6_pattern = New RegExp
ipv6_pattern.Global = True
ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}"
If ipv4_pattern.Test(addr) Then
port = Split(addr,":")
octet = Split(port(0),".")
ipv4_hex = ""
For i = 0 To UBound(octet)
If octet(i) <= 255 And octet(i) >= 0 Then
ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2)
Else
ipv4_hex = "Erroneous Address"
Exit For
End If
Next
parse_ip = "Test Case: " & addr & vbCrLf &_
"Address: " & ipv4_hex & vbCrLf
If UBound(port) = 1 Then
If port(1) <= 65535 And port(1) >= 0 Then
parse_ip = parse_ip & "Port: " & port(1) & vbCrLf
Else
parse_ip = parse_ip & "Port: Invalid" & vbCrLf
End If
End If
End If
If ipv6_pattern.Test(addr) Then
parse_ip = "Test Case: " & addr & vbCrLf
port_v6 = "Port: "
ipv6_hex = ""
If InStr(1,addr,"[") Then
port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1)))
addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1))
End If
word = Split(addr,":")
word_count = 0
For i = 0 To UBound(word)
If word(i) = "" Then
If i < UBound(word) Then
If Int((7-(i+1))/2) = 1 Then
k = 1
ElseIf UBound(word) < 6 Then
k = Int((7-(i+1))/2)
ElseIf UBound(word) >= 6 Then
k = Int((7-(i+1))/2)-1
End If
For j = 0 To k
ipv6_hex = ipv6_hex & "0000"
word_count = word_count + 1
Next
Else
For j = 0 To (7-word_count)
ipv6_hex = ipv6_hex & "0000"
Next
End If
Else
ipv6_hex = ipv6_hex & Right("0000" & word(i),4)
word_count = word_count + 1
End If
Next
parse_ip = parse_ip & "Address: " & ipv6_hex &_
vbCrLf & port_v6 & vbCrLf
End If
If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then
parse_ip = "Test Case: " & addr & vbCrLf &_
"Address: Invalid Address" & vbCrLf
End If
End Function
ip_arr = Array("127.0.0.1","127.0.0.1:80","::1",_
"[::1]:80","2605:2700:0:3::4713:93e3","[2605:2700:0:3::4713:93e3]:80","RosettaCode")
For n = 0 To UBound(ip_arr)
WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf
Next
| package main
import (
"encoding/hex"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func parseIPPort(address string) (net.IP, *uint64, error) {
ip := net.ParseIP(address)
if ip != nil {
return ip, nil, nil
}
host, portStr, err := net.SplitHostPort(address)
if err != nil {
return nil, nil, fmt.Errorf("splithostport failed: %w", err)
}
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse port: %w", err)
}
ip = net.ParseIP(host)
if ip == nil {
return nil, nil, fmt.Errorf("failed to parse ip address")
}
return ip, &port, nil
}
func ipVersion(ip net.IP) int {
if ip.To4() == nil {
return 6
}
return 4
}
func main() {
testCases := []string{
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:443",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80",
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
writeTSV := func(w io.Writer, args ...interface{}) {
fmt.Fprintf(w, strings.Repeat("%s\t", len(args)), args...)
fmt.Fprintf(w, "\n")
}
writeTSV(w, "Input", "Address", "Space", "Port")
for _, addr := range testCases {
ip, port, err := parseIPPort(addr)
if err != nil {
panic(err)
}
portStr := "n/a"
if port != nil {
portStr = fmt.Sprint(*port)
}
ipVersion := fmt.Sprintf("IPv%d", ipVersion(ip))
writeTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)
}
w.Flush()
}
|
Convert this VB block to Go, preserving its control flow and logic. | Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function
Sub Main()
Const Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5
Dim P&, I&, G&, A&, M, Cur(Value To Volume)
Dim S As New Collection: S.Add Array(0)
Const SackW = 25, SackV = 0.25
Dim Panacea: Panacea = Array(3000, 0.3, 0.025)
Dim Ichor: Ichor = Array(1800, 0.2, 0.015)
Dim Gold: Gold = Array(2500, 2, 0.002)
For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))
For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))
For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))
For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next
If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _
S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1
Next G, I, P
Debug.Print "Value", "Weight", "Volume", "PanaceaCount", "IchorCount", "GoldCount"
For Each M In S
If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)
Next
End Sub
| package main
import "fmt"
type Item struct {
Name string
Value int
Weight, Volume float64
}
type Result struct {
Counts []int
Sum int
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func Knapsack(items []Item, weight, volume float64) (best Result) {
if len(items) == 0 {
return
}
n := len(items) - 1
maxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))
for count := 0; count <= maxCount; count++ {
sol := Knapsack(items[:n],
weight-float64(count)*items[n].Weight,
volume-float64(count)*items[n].Volume)
sol.Sum += items[n].Value * count
if sol.Sum > best.Sum {
sol.Counts = append(sol.Counts, count)
best = sol
}
}
return
}
func main() {
items := []Item{
{"Panacea", 3000, 0.3, 0.025},
{"Ichor", 1800, 0.2, 0.015},
{"Gold", 2500, 2.0, 0.002},
}
var sumCount, sumValue int
var sumWeight, sumVolume float64
result := Knapsack(items, 25, 0.25)
for i := range result.Counts {
fmt.Printf("%-8s x%3d -> Weight: %4.1f Volume: %5.3f Value: %6d\n",
items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),
items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])
sumCount += result.Counts[i]
sumValue += items[i].Value * result.Counts[i]
sumWeight += items[i].Weight * float64(result.Counts[i])
sumVolume += items[i].Volume * float64(result.Counts[i])
}
fmt.Printf("TOTAL (%3d items) Weight: %4.1f Volume: %5.3f Value: %6d\n",
sumCount, sumWeight, sumVolume, sumValue)
}
|
Maintain the same structure and functionality when rewriting this code in Go. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1)
Set objKeyMap = CreateObject("Scripting.Dictionary")
With objKeyMap
.Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5"
.Add "MNO", "6" : .Add "PQRS", "7" : .Add "TUV", "8" : .Add "WXYZ", "9"
End With
TotalWords = 0
UniqueCombinations = 0
Set objUniqueWords = CreateObject("Scripting.Dictionary")
Set objMoreThanOneWord = CreateObject("Scripting.Dictionary")
Do Until objInFile.AtEndOfStream
Word = objInFile.ReadLine
c = 0
Num = ""
If Word <> "" Then
For i = 1 To Len(Word)
For Each Key In objKeyMap.Keys
If InStr(1,Key,Mid(Word,i,1),1) > 0 Then
Num = Num & objKeyMap.Item(Key)
c = c + 1
End If
Next
Next
If c = Len(Word) Then
TotalWords = TotalWords + 1
If objUniqueWords.Exists(Num) = False Then
objUniqueWords.Add Num, ""
UniqueCombinations = UniqueCombinations + 1
Else
If objMoreThanOneWord.Exists(Num) = False Then
objMoreThanOneWord.Add Num, ""
End If
End If
End If
End If
Loop
WScript.Echo "There are " & TotalWords & " words in ""unixdict.txt"" which can be represented by the digit key mapping." & vbCrLf &_
"They require " & UniqueCombinations & " digit combinations to represent them." & vbCrLf &_
objMoreThanOneWord.Count & " digit combinations represent Textonyms."
objInFile.Close
| package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
func main() {
log.SetFlags(0)
log.SetPrefix("textonyms: ")
wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
t := NewTextonym(phoneMap)
_, err := ReadFromFile(t, *wordlist)
if err != nil {
log.Fatal(err)
}
t.Report(os.Stdout, *wordlist)
}
var phoneMap = map[byte][]rune{
'2': []rune("ABC"),
'3': []rune("DEF"),
'4': []rune("GHI"),
'5': []rune("JKL"),
'6': []rune("MNO"),
'7': []rune("PQRS"),
'8': []rune("TUV"),
'9': []rune("WXYZ"),
}
func ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
n, err := r.ReadFrom(f)
if cerr := f.Close(); err == nil && cerr != nil {
err = cerr
}
return n, err
}
type Textonym struct {
numberMap map[string][]string
letterMap map[rune]byte
count int
textonyms int
}
func NewTextonym(dm map[byte][]rune) *Textonym {
lm := make(map[rune]byte, 26)
for d, ll := range dm {
for _, l := range ll {
lm[l] = d
}
}
return &Textonym{letterMap: lm}
}
func (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {
t.numberMap = make(map[string][]string)
buf := make([]byte, 0, 32)
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
scan:
for sc.Scan() {
buf = buf[:0]
word := sc.Text()
n += int64(len(word)) + 1
for _, r := range word {
d, ok := t.letterMap[unicode.ToUpper(r)]
if !ok {
continue scan
}
buf = append(buf, d)
}
num := string(buf)
t.numberMap[num] = append(t.numberMap[num], word)
t.count++
if len(t.numberMap[num]) == 2 {
t.textonyms++
}
}
return n, sc.Err()
}
func (t *Textonym) Most() (most int, subset map[string][]string) {
for k, v := range t.numberMap {
switch {
case len(v) > most:
subset = make(map[string][]string)
most = len(v)
fallthrough
case len(v) == most:
subset[k] = v
}
}
return most, subset
}
func (t *Textonym) Report(w io.Writer, name string) {
fmt.Fprintf(w, `
There are %v words in %q which can be represented by the digit key mapping.
They require %v digit combinations to represent them.
%v digit combinations represent Textonyms.
`,
t.count, name, len(t.numberMap), t.textonyms)
n, sub := t.Most()
fmt.Fprintln(w, "\nThe numbers mapping to the most words map to",
n, "words each:")
for k, v := range sub {
fmt.Fprintln(w, "\t", k, "maps to:", strings.Join(v, ", "))
}
}
|
Convert this VB snippet to Go and keep its semantics consistent. | Public Function RangeExtraction(AList) As String
Const RangeDelim = "-"
Dim result As String
Dim InRange As Boolean
Dim Posn, ub, lb, rangestart, rangelen As Integer
result = ""
ub = UBound(AList)
lb = LBound(AList)
Posn = lb
While Posn < ub
rangestart = Posn
rangelen = 0
InRange = True
While InRange
rangelen = rangelen + 1
If Posn = ub Then
InRange = False
Else
InRange = (AList(Posn + 1) = AList(Posn) + 1)
Posn = Posn + 1
End If
Wend
If rangelen > 2 Then
result = result & "," & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))
Else
For i = rangestart To rangestart + rangelen - 1
result = result & "," & Format$(AList(i))
Next
End If
Posn = rangestart + rangelen
Wend
RangeExtraction = Mid$(result, 2)
End Function
Public Sub RangeTest()
Dim MyList As Variant
MyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)
Debug.Print "a) "; RangeExtraction(MyList)
Dim MyOtherList(1 To 20) As Integer
MyOtherList(1) = -6
MyOtherList(2) = -3
MyOtherList(3) = -2
MyOtherList(4) = -1
MyOtherList(5) = 0
MyOtherList(6) = 1
MyOtherList(7) = 3
MyOtherList(8) = 4
MyOtherList(9) = 5
MyOtherList(10) = 7
MyOtherList(11) = 8
MyOtherList(12) = 9
MyOtherList(13) = 10
MyOtherList(14) = 11
MyOtherList(15) = 14
MyOtherList(16) = 15
MyOtherList(17) = 17
MyOtherList(18) = 18
MyOtherList(19) = 19
MyOtherList(20) = 20
Debug.Print "b) "; RangeExtraction(MyOtherList)
End Sub
| package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
func main() {
rf, err := rangeFormat([]int{
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39,
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println("range format:", rf)
}
func rangeFormat(a []int) (string, error) {
if len(a) == 0 {
return "", nil
}
var parts []string
for n1 := 0; ; {
n2 := n1 + 1
for n2 < len(a) && a[n2] == a[n2-1]+1 {
n2++
}
s := strconv.Itoa(a[n1])
if n2 == n1+2 {
s += "," + strconv.Itoa(a[n2-1])
} else if n2 > n1+2 {
s += "-" + strconv.Itoa(a[n2-1])
}
parts = append(parts, s)
if n2 == len(a) {
break
}
if a[n2] == a[n2-1] {
return "", errors.New(fmt.Sprintf(
"sequence repeats value %d", a[n2]))
}
if a[n2] < a[n2-1] {
return "", errors.New(fmt.Sprintf(
"sequence not ordered: %d < %d", a[n2], a[n2-1]))
}
n1 = n2
}
return strings.Join(parts, ","), nil
}
|
Maintain the same structure and functionality when rewriting this code in Go. | Public Sub main()
Dim c(1) As Currency
Dim d(1) As Double
Dim dt(1) As Date
Dim a(1) As Integer
Dim l(1) As Long
Dim s(1) As Single
Dim e As Variant
Dim o As Object
Set o = New Application
Debug.Print TypeName(o)
Debug.Print TypeName(1 = 1)
Debug.Print TypeName(CByte(1))
Set o = New Collection
Debug.Print TypeName(o)
Debug.Print TypeName(1@)
Debug.Print TypeName(c)
Debug.Print TypeName(CDate(1))
Debug.Print TypeName(dt)
Debug.Print TypeName(CDec(1))
Debug.Print TypeName(1#)
Debug.Print TypeName(d)
Debug.Print TypeName(e)
Debug.Print TypeName(CVErr(1))
Debug.Print TypeName(1)
Debug.Print TypeName(a)
Debug.Print TypeName(1&)
Debug.Print TypeName(l)
Set o = Nothing
Debug.Print TypeName(o)
Debug.Print TypeName([A1])
Debug.Print TypeName(1!)
Debug.Print TypeName(s)
Debug.Print TypeName(CStr(1))
Debug.Print TypeName(Worksheets(1))
End Sub
| package main
import "fmt"
type any = interface{}
func showType(a any) {
switch a.(type) {
case rune:
fmt.Printf("The type of '%c' is %T\n", a, a)
default:
fmt.Printf("The type of '%v' is %T\n", a, a)
}
}
func main() {
values := []any{5, 7.5, 2 + 3i, 'd', true, "Rosetta"}
for _, value := range values {
showType(value)
}
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. |
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_
"\triangle.txt",1,False)
row = Split(objinfile.ReadAll,vbCrLf)
For i = UBound(row) To 0 Step -1
row(i) = Split(row(i)," ")
If i < UBound(row) Then
For j = 0 To UBound(row(i))
If (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then
row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))
Else
row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))
End If
Next
End If
Next
WScript.Echo row(0)(0)
objinfile.Close
Set objfso = Nothing
| package main
import (
"fmt"
"strconv"
"strings"
)
const t = ` 55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93`
func main() {
lines := strings.Split(t, "\n")
f := strings.Fields(lines[len(lines)-1])
d := make([]int, len(f))
var err error
for i, s := range f {
if d[i], err = strconv.Atoi(s); err != nil {
panic(err)
}
}
d1 := d[1:]
var l, r, u int
for row := len(lines) - 2; row >= 0; row-- {
l = d[0]
for i, s := range strings.Fields(lines[row]) {
if u, err = strconv.Atoi(s); err != nil {
panic(err)
}
if r = d1[i]; l > r {
d[i] = u + l
} else {
d[i] = u + r
}
l = r
}
}
fmt.Println(d[0])
}
|
Change the following VB code into Go without altering its purpose. | Public n As Variant
Private Sub init()
n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]
End Sub
Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant
Dim wtb As Integer
Dim bn As Integer
Dim prev As String: prev = "#"
Dim next_ As String
Dim p2468 As String
For i = 1 To UBound(n)
next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)
wtb = wtb - (prev = "." And next_ <= "#")
bn = bn - (i > 1 And next_ <= "#")
If (i And 1) = 0 Then p2468 = p2468 & prev
prev = next_
Next i
If step = 2 Then
p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)
End If
Dim ret(2) As Variant
ret(0) = wtb
ret(1) = bn
ret(2) = p2468
AB = ret
End Function
Private Sub Zhang_Suen(text As Variant)
Dim wtb As Integer
Dim bn As Integer
Dim changed As Boolean, changes As Boolean
Dim p2468 As String
Dim x As Integer, y As Integer, step As Integer
Do While True
changed = False
For step = 1 To 2
changes = False
For y = 1 To UBound(text) - 1
For x = 2 To Len(text(y)) - 1
If Mid(text(y), x, 1) = "#" Then
ret = AB(text, y, x, step)
wtb = ret(0)
bn = ret(1)
p2468 = ret(2)
If wtb = 1 _
And bn >= 2 And bn <= 6 _
And InStr(1, Mid(p2468, 1, 3), ".") _
And InStr(1, Mid(p2468, 2, 3), ".") Then
changes = True
text(y) = Left(text(y), x - 1) & "!" & Right(text(y), Len(text(y)) - x)
End If
End If
Next x
Next y
If changes Then
For y = 1 To UBound(text) - 1
text(y) = Replace(text(y), "!", ".")
Next y
changed = True
End If
Next step
If Not changed Then Exit Do
Loop
Debug.Print Join(text, vbCrLf)
End Sub
Public Sub main()
init
Dim Small_rc(9) As String
Small_rc(0) = "................................"
Small_rc(1) = ".#########.......########......."
Small_rc(2) = ".###...####.....####..####......"
Small_rc(3) = ".###....###.....###....###......"
Small_rc(4) = ".###...####.....###............."
Small_rc(5) = ".#########......###............."
Small_rc(6) = ".###.####.......###....###......"
Small_rc(7) = ".###..####..###.####..####.###.."
Small_rc(8) = ".###...####.###..########..###.."
Small_rc(9) = "................................"
Zhang_Suen (Small_rc)
End Sub
| package main
import (
"bytes"
"fmt"
"strings"
)
var in = `
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000`
func main() {
b := wbFromString(in, '1')
b.zhangSuen()
fmt.Println(b)
}
const (
white = 0
black = 1
)
type wbArray [][]byte
func wbFromString(s string, blk byte) wbArray {
lines := strings.Split(s, "\n")[1:]
b := make(wbArray, len(lines))
for i, sl := range lines {
bl := make([]byte, len(sl))
for j := 0; j < len(sl); j++ {
bl[j] = sl[j] & 1
}
b[i] = bl
}
return b
}
var sym = [2]byte{
white: ' ',
black: '#',
}
func (b wbArray) String() string {
b2 := bytes.Join(b, []byte{'\n'})
for i, b1 := range b2 {
if b1 > 1 {
continue
}
b2[i] = sym[b1]
}
return string(b2)
}
var nb = [...][2]int{
2: {-1, 0},
3: {-1, 1},
4: {0, 1},
5: {1, 1},
6: {1, 0},
7: {1, -1},
8: {0, -1},
9: {-1, -1},
}
func (b wbArray) reset(en []int) (rs bool) {
var r, c int
var p [10]byte
readP := func() {
for nx := 1; nx <= 9; nx++ {
n := nb[nx]
p[nx] = b[r+n[0]][c+n[1]]
}
}
shiftRead := func() {
n := nb[3]
p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]
n = nb[4]
p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]
n = nb[5]
p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]
}
countA := func() (ct byte) {
bit := p[9]
for nx := 2; nx <= 9; nx++ {
last := bit
bit = p[nx]
if last == white {
ct += bit
}
}
return ct
}
countB := func() (ct byte) {
for nx := 2; nx <= 9; nx++ {
ct += p[nx]
}
return ct
}
lastRow := len(b) - 1
lastCol := len(b[0]) - 1
mark := make([][]bool, lastRow)
for r = range mark {
mark[r] = make([]bool, lastCol)
}
for r = 1; r < lastRow; r++ {
c = 1
readP()
for {
m := false
if !(p[1] == black) {
goto markDone
}
if b1 := countB(); !(2 <= b1 && b1 <= 6) {
goto markDone
}
if !(countA() == 1) {
goto markDone
}
{
e1, e2 := p[en[1]], p[en[2]]
if !(p[en[0]]&e1&e2 == 0) {
goto markDone
}
if !(e1&e2&p[en[3]] == 0) {
goto markDone
}
}
m = true
rs = true
markDone:
mark[r][c] = m
c++
if c == lastCol {
break
}
shiftRead()
}
}
if rs {
for r = 1; r < lastRow; r++ {
for c = 1; c < lastCol; c++ {
if mark[r][c] {
b[r][c] = white
}
}
}
}
return rs
}
var step1 = []int{2, 4, 6, 8}
var step2 = []int{4, 2, 8, 6}
func (b wbArray) zhangSuen() {
for {
rs1 := b.reset(step1)
rs2 := b.reset(step2)
if !rs1 && !rs2 {
break
}
}
}
|
Convert the following code from VB to Go, ensuring the logic remains intact. | Option Strict On
Option Explicit On
Imports System.IO
Module vMain
Public Sub Main
Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}
For i As Integer = 0 To Ubound(s)
Dim curr As Integer = s(i)
Dim prev As Integer
If i > 1 AndAlso curr = prev Then
Console.Out.WriteLine(i)
End If
prev = curr
Next i
End Sub
End Module
| package main
import "fmt"
func main() {
s := []int{1, 2, 2, 3, 4, 4, 5}
for i := 0; i < len(s); i++ {
curr := s[i]
var prev int
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
var prev int
for i := 0; i < len(s); i++ {
curr := s[i]
if i > 0 && curr == prev {
fmt.Println(i)
}
prev = curr
}
}
|
Please provide an equivalent version of this VB code in Go. | SUB Main()
END
| package main
import "fmt"
var count = 0
func foo() {
fmt.Println("foo called")
}
func init() {
fmt.Println("first init called")
foo()
}
func init() {
fmt.Println("second init called")
main()
}
func main() {
count++
fmt.Println("main called when count is", count)
}
|
Change the programming language of this snippet from VB to Go without modifying what it does. | SUB Main()
END
| package main
import "fmt"
var count = 0
func foo() {
fmt.Println("foo called")
}
func init() {
fmt.Println("first init called")
foo()
}
func init() {
fmt.Println("second init called")
main()
}
func main() {
count++
fmt.Println("main called when count is", count)
}
|
Convert this VB block to Go, preserving its control flow and logic. | SUB Main()
END
| package main
import "fmt"
var count = 0
func foo() {
fmt.Println("foo called")
}
func init() {
fmt.Println("first init called")
foo()
}
func init() {
fmt.Println("second init called")
main()
}
func main() {
count++
fmt.Println("main called when count is", count)
}
|
Change the following VB code into Go without altering its purpose. | 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:
if ori<0 then ori = ori+pi*2
end sub
public sub lt(i):
ori=(ori + i*iang)
if ori>(pi*2) then ori=ori-pi*2
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
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
sub koch (n,le)
if n=0 then x.fw le :exit sub
koch n-1, le/3
x.lt 1
koch n-1, le/3
x.rt 2
koch n-1, le/3
x.lt 1
koch n-1, le/3
end sub
dim x,i
set x=new turtle
x.iangle=60
x.orient=0
x.incr=3
x.x=100:x.y=300
for i=0 to 3
koch 7,100
x.rt 2
next
set x=nothing
| package main
import (
"github.com/fogleman/gg"
"math"
)
var dc = gg.NewContext(512, 512)
func koch(x1, y1, x2, y2 float64, iter int) {
angle := math.Pi / 3
x3 := (x1*2 + x2) / 3
y3 := (y1*2 + y2) / 3
x4 := (x1 + x2*2) / 3
y4 := (y1 + y2*2) / 3
x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle)
y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle)
if iter > 0 {
iter--
koch(x1, y1, x3, y3, iter)
koch(x3, y3, x5, y5, iter)
koch(x5, y5, x4, y4, iter)
koch(x4, y4, x2, y2, iter)
} else {
dc.LineTo(x1, y1)
dc.LineTo(x3, y3)
dc.LineTo(x5, y5)
dc.LineTo(x4, y4)
dc.LineTo(x2, y2)
}
}
func main() {
dc.SetRGB(1, 1, 1)
dc.Clear()
koch(100, 100, 400, 400, 4)
dc.SetRGB(0, 0, 1)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("koch.png")
}
|
Translate the given VB code snippet into Go without altering its behavior. | Sub draw()
Dim sh As Shape, sl As Shape
Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)
Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)
sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)
End Sub
| package main
import (
"fmt"
"image"
"image/color"
"image/draw"
)
func main() {
rect := image.Rect(0, 0, 320, 240)
img := image.NewRGBA(rect)
green := color.RGBA{0, 255, 0, 255}
draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)
red := color.RGBA{255, 0, 0, 255}
img.Set(100, 100, red)
cmap := map[color.Color]string{green: "green", red: "red"}
c1 := img.At(0, 0)
c2 := img.At(100, 100)
fmt.Println("The color of the pixel at ( 0, 0) is", cmap[c1], "\b.")
fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.")
}
|
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")
redim b(ubound(a))
i=0
for each x in a
s=trim(x)
if len(s)>=9 then
if len(s)= 9 then d.add s,""
b(i)=s
i=i+1
end if
next
redim preserve b(i-1)
wscript.echo i
j=1
for i=0 to ubound(b)-9
s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_
mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)
if d.exists(s9) then
wscript.echo j,s9
d.remove(s9)
j=j+1
end if
next
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
"unicode/utf8"
)
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) >= 9 {
words = append(words, s)
}
}
count := 0
var alreadyFound []string
le := len(words)
var sb strings.Builder
for i := 0; i < le-9; i++ {
sb.Reset()
for j := i; j < i+9; j++ {
sb.WriteByte(words[j][j-i])
}
word := sb.String()
ix := sort.SearchStrings(words, word)
if ix < le && word == words[ix] {
ix2 := sort.SearchStrings(alreadyFound, word)
if ix2 == len(alreadyFound) {
count++
fmt.Printf("%2d: %s\n", count, word)
alreadyFound = append(alreadyFound, word)
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Go. |
Function BFInpt(s, sp, d, dp, i, ip, o)
While sp < Len(s)
Select Case Mid(s, sp + 1, 1)
Case "+"
newd = Asc(d(dp)) + 1
If newd > 255 Then newd = newd Mod 256
d(dp) = Chr(newd)
Case "-"
newd = Asc(d(dp)) - 1
If newd < 0 Then newd = (newd Mod 256) + 256
d(dp) = Chr(newd)
Case ">"
dp = dp + 1
If dp > UBound(d) Then
ReDim Preserve d(UBound(d) + 1)
d(dp) = Chr(0)
End If
Case "<"
dp = dp - 1
Case "."
o = o & d(dp)
Case ","
If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)
Case "["
If Asc(d(dp)) = 0 Then
bracket = 1
While bracket And sp < Len(s)
sp = sp + 1
If Mid(s, sp + 1, 1) = "[" Then
bracket = bracket + 1
ElseIf Mid(s, sp + 1, 1) = "]" Then
bracket = bracket - 1
End If
WEnd
Else
pos = sp - 1
sp = sp + 1
If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos
End If
Case "]"
BFInpt = Asc(d(dp)) <> 0
Exit Function
End Select
sp = sp + 1
WEnd
End Function
Function BFuck(source, input)
Dim data() : ReDim data(0)
data(0) = Chr(0)
DataPtr = 0
SrcPtr = 0
InputPtr = 0
output = ""
BFInpt source , SrcPtr , _
data , DataPtr , _
input , InputPtr , _
output
BFuck = output
End Function
code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _
">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++."
inpstr = ""
WScript.StdOut.Write BFuck(code, inpstr)
| package main
import "fmt"
func main() {
bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}
func bf(dLen int, is string) {
ds := make([]byte, dLen)
var dp int
for ip := 0; ip < len(is); ip++ {
switch is[ip] {
case '>':
dp++
case '<':
dp--
case '+':
ds[dp]++
case '-':
ds[dp]--
case '.':
fmt.Printf("%c", ds[dp])
case ',':
fmt.Scanf("%c", &ds[dp])
case '[':
if ds[dp] == 0 {
for nc := 1; nc > 0; {
ip++
if is[ip] == '[' {
nc++
} else if is[ip] == ']' {
nc--
}
}
}
case ']':
if ds[dp] != 0 {
for nc := 1; nc > 0; {
ip--
if is[ip] == ']' {
nc++
} else if is[ip] == '[' {
nc--
}
}
}
}
}
}
|
Write a version of this VB function in Go with identical behavior. |
Function BFInpt(s, sp, d, dp, i, ip, o)
While sp < Len(s)
Select Case Mid(s, sp + 1, 1)
Case "+"
newd = Asc(d(dp)) + 1
If newd > 255 Then newd = newd Mod 256
d(dp) = Chr(newd)
Case "-"
newd = Asc(d(dp)) - 1
If newd < 0 Then newd = (newd Mod 256) + 256
d(dp) = Chr(newd)
Case ">"
dp = dp + 1
If dp > UBound(d) Then
ReDim Preserve d(UBound(d) + 1)
d(dp) = Chr(0)
End If
Case "<"
dp = dp - 1
Case "."
o = o & d(dp)
Case ","
If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1)
Case "["
If Asc(d(dp)) = 0 Then
bracket = 1
While bracket And sp < Len(s)
sp = sp + 1
If Mid(s, sp + 1, 1) = "[" Then
bracket = bracket + 1
ElseIf Mid(s, sp + 1, 1) = "]" Then
bracket = bracket - 1
End If
WEnd
Else
pos = sp - 1
sp = sp + 1
If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos
End If
Case "]"
BFInpt = Asc(d(dp)) <> 0
Exit Function
End Select
sp = sp + 1
WEnd
End Function
Function BFuck(source, input)
Dim data() : ReDim data(0)
data(0) = Chr(0)
DataPtr = 0
SrcPtr = 0
InputPtr = 0
output = ""
BFInpt source , SrcPtr , _
data , DataPtr , _
input , InputPtr , _
output
BFuck = output
End Function
code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _
">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++."
inpstr = ""
WScript.StdOut.Write BFuck(code, inpstr)
| package main
import "fmt"
func main() {
bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}
func bf(dLen int, is string) {
ds := make([]byte, dLen)
var dp int
for ip := 0; ip < len(is); ip++ {
switch is[ip] {
case '>':
dp++
case '<':
dp--
case '+':
ds[dp]++
case '-':
ds[dp]--
case '.':
fmt.Printf("%c", ds[dp])
case ',':
fmt.Scanf("%c", &ds[dp])
case '[':
if ds[dp] == 0 {
for nc := 1; nc > 0; {
ip++
if is[ip] == '[' {
nc++
} else if is[ip] == ']' {
nc--
}
}
}
case ']':
if ds[dp] != 0 {
for nc := 1; nc > 0; {
ip--
if is[ip] == ']' {
nc++
} else if is[ip] == '[' {
nc--
}
}
}
}
}
}
|
Preserve the algorithm and functionality while converting the code from VB to Go. | Private Function unicode_2_utf8(x As Long) As Byte()
Dim y() As Byte
Dim r As Long
Select Case x
Case 0 To &H7F
ReDim y(0)
y(0) = x
Case &H80 To &H7FF
ReDim y(1)
y(0) = 192 + x \ 64
y(1) = 128 + x Mod 64
Case &H800 To &H7FFF
ReDim y(2)
y(2) = 128 + x Mod 64
r = x \ 64
y(1) = 128 + r Mod 64
y(0) = 224 + r \ 64
Case 32768 To 65535
ReDim y(2)
y(2) = 128 + x Mod 64
r = x \ 64
y(1) = 128 + r Mod 64
y(0) = 224 + r \ 64
Case &H10000 To &H10FFFF
ReDim y(3)
y(3) = 128 + x Mod 64
r = x \ 64
y(2) = 128 + r Mod 64
r = r \ 64
y(1) = 128 + r Mod 64
y(0) = 240 + r \ 64
Case Else
MsgBox "what else?" & x & " " & Hex(x)
End Select
unicode_2_utf8 = y
End Function
Private Function utf8_2_unicode(x() As Byte) As Long
Dim first As Long, second As Long, third As Long, fourth As Long
Dim total As Long
Select Case UBound(x) - LBound(x)
Case 0
If x(0) < 128 Then
total = x(0)
Else
MsgBox "highest bit set error"
End If
Case 1
If x(0) \ 32 = 6 Then
first = x(0) Mod 32
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
Else
MsgBox "mask error"
End If
Else
MsgBox "leading byte error"
End If
total = 64 * first + second
Case 2
If x(0) \ 16 = 14 Then
first = x(0) Mod 16
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
If x(2) \ 64 = 2 Then
third = x(2) Mod 64
Else
MsgBox "mask error last byte"
End If
Else
MsgBox "mask error middle byte"
End If
Else
MsgBox "leading byte error"
End If
total = 4096 * first + 64 * second + third
Case 3
If x(0) \ 8 = 30 Then
first = x(0) Mod 8
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
If x(2) \ 64 = 2 Then
third = x(2) Mod 64
If x(3) \ 64 = 2 Then
fourth = x(3) Mod 64
Else
MsgBox "mask error last byte"
End If
Else
MsgBox "mask error third byte"
End If
Else
MsgBox "mask error second byte"
End If
Else
MsgBox "mask error leading byte"
End If
total = CLng(262144 * first + 4096 * second + 64 * third + fourth)
Case Else
MsgBox "more bytes than expected"
End Select
utf8_2_unicode = total
End Function
Public Sub program()
Dim cp As Variant
Dim r() As Byte, s As String
cp = [{65, 246, 1046, 8364, 119070}]
Debug.Print "ch unicode UTF-8 encoded decoded"
For Each cpi In cp
r = unicode_2_utf8(CLng(cpi))
On Error Resume Next
s = CStr(Hex(cpi))
Debug.Print ChrW(cpi); String$(10 - Len(s), " "); s,
If Err.Number = 5 Then Debug.Print "?"; String$(10 - Len(s), " "); s,
s = ""
For Each yz In r
s = s & CStr(Hex(yz)) & " "
Next yz
Debug.Print String$(13 - Len(s), " "); s;
s = CStr(Hex(utf8_2_unicode(r)))
Debug.Print String$(8 - Len(s), " "); s
Next cpi
End Sub
| package main
import (
"bytes"
"encoding/hex"
"fmt"
"log"
"strings"
)
var testCases = []struct {
rune
string
}{
{'A', "41"},
{'ö', "C3 B6"},
{'Ж', "D0 96"},
{'€', "E2 82 AC"},
{'𝄞', "F0 9D 84 9E"},
}
func main() {
for _, tc := range testCases {
u := fmt.Sprintf("U+%04X", tc.rune)
b, err := hex.DecodeString(strings.Replace(tc.string, " ", "", -1))
if err != nil {
log.Fatal("bad test data")
}
e := encodeUTF8(tc.rune)
d := decodeUTF8(b)
fmt.Printf("%c %-7s %X\n", d, u, e)
if !bytes.Equal(e, b) {
log.Fatal("encodeUTF8 wrong")
}
if d != tc.rune {
log.Fatal("decodeUTF8 wrong")
}
}
}
const (
b2Lead = 0xC0
b2Mask = 0x1F
b3Lead = 0xE0
b3Mask = 0x0F
b4Lead = 0xF0
b4Mask = 0x07
mbLead = 0x80
mbMask = 0x3F
)
func encodeUTF8(r rune) []byte {
switch i := uint32(r); {
case i <= 1<<7-1:
return []byte{byte(r)}
case i <= 1<<11-1:
return []byte{
b2Lead | byte(r>>6),
mbLead | byte(r)&mbMask}
case i <= 1<<16-1:
return []byte{
b3Lead | byte(r>>12),
mbLead | byte(r>>6)&mbMask,
mbLead | byte(r)&mbMask}
default:
return []byte{
b4Lead | byte(r>>18),
mbLead | byte(r>>12)&mbMask,
mbLead | byte(r>>6)&mbMask,
mbLead | byte(r)&mbMask}
}
}
func decodeUTF8(b []byte) rune {
switch b0 := b[0]; {
case b0 < 0x80:
return rune(b0)
case b0 < 0xE0:
return rune(b0&b2Mask)<<6 |
rune(b[1]&mbMask)
case b0 < 0xF0:
return rune(b0&b3Mask)<<12 |
rune(b[1]&mbMask)<<6 |
rune(b[2]&mbMask)
default:
return rune(b0&b4Mask)<<18 |
rune(b[1]&mbMask)<<12 |
rune(b[2]&mbMask)<<6 |
rune(b[3]&mbMask)
}
}
|
Change the programming language of this snippet from VB to Go without modifying what it does. |
n=8
pattern="1001011001101001"
size=n*n: w=len(size)
mult=n\4
wscript.echo "Magic square : " & n & " x " & n
i=0
For r=0 To n-1
l=""
For c=0 To n-1
bit=Mid(pattern, c\mult+(r\mult)*4+1, 1)
If bit="1" Then t=i+1 Else t=size-i
l=l & Right(Space(w) & t, w) & " "
i=i+1
Next
wscript.echo l
Next
wscript.echo "Magic constant=" & (n*n+1)*n/2
| package main
import (
"fmt"
"log"
"strings"
)
const dimensions int = 8
func setupMagicSquareData(d int) ([][]int, error) {
var output [][]int
if d < 4 || d%4 != 0 {
return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4")
}
var bits uint = 0x9669
size := d * d
mult := d / 4
for i, r := 0, 0; r < d; r++ {
output = append(output, []int{})
for c := 0; c < d; i, c = i+1, c+1 {
bitPos := c/mult + (r/mult)*4
if (bits & (1 << uint(bitPos))) != 0 {
output[r] = append(output[r], i+1)
} else {
output[r] = append(output[r], size-i)
}
}
}
return output, nil
}
func arrayItoa(input []int) []string {
var output []string
for _, i := range input {
output = append(output, fmt.Sprintf("%4d", i))
}
return output
}
func main() {
data, err := setupMagicSquareData(dimensions)
if err != nil {
log.Fatal(err)
}
magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2
for _, row := range data {
fmt.Println(strings.Join(arrayItoa(row), " "))
}
fmt.Printf("\nMagic Constant: %d\n", magicConstant)
}
|
Change the programming language of this snippet from VB to Go without modifying what it does. | OPTION COMPARE BINARY
OPTION EXPLICIT ON
OPTION INFER ON
OPTION STRICT ON
IMPORTS SYSTEM.GLOBALIZATION
IMPORTS SYSTEM.TEXT
IMPORTS SYSTEM.RUNTIME.INTEROPSERVICES
IMPORTS SYSTEM.RUNTIME.COMPILERSERVICES
MODULE ARGHELPER
READONLY _ARGDICT AS NEW DICTIONARY(OF STRING, STRING)()
DELEGATE FUNCTION TRYPARSE(OF T, TRESULT)(VALUE AS T, <OUT> BYREF RESULT AS TRESULT) AS BOOLEAN
SUB INITIALIZEARGUMENTS(ARGS AS STRING())
FOR EACH ITEM IN ARGS
ITEM = ITEM.TOUPPERINVARIANT()
IF ITEM.LENGTH > 0 ANDALSO ITEM(0) <> """"C THEN
DIM COLONPOS = ITEM.INDEXOF(":"C, STRINGCOMPARISON.ORDINAL)
IF COLONPOS <> -1 THEN
_ARGDICT.ADD(ITEM.SUBSTRING(0, COLONPOS), ITEM.SUBSTRING(COLONPOS + 1, ITEM.LENGTH - COLONPOS - 1))
END IF
END IF
NEXT
END SUB
SUB FROMARGUMENT(OF T)(
KEY AS STRING,
<OUT> BYREF VAR AS T,
GETDEFAULT AS FUNC(OF T),
TRYPARSE AS TRYPARSE(OF STRING, T),
OPTIONAL VALIDATE AS PREDICATE(OF T) = NOTHING)
DIM VALUE AS STRING = NOTHING
IF _ARGDICT.TRYGETVALUE(KEY.TOUPPERINVARIANT(), VALUE) THEN
IF NOT (TRYPARSE(VALUE, VAR) ANDALSO (VALIDATE IS NOTHING ORELSE VALIDATE(VAR))) THEN
CONSOLE.WRITELINE($"INVALID VALUE FOR {KEY}: {VALUE}")
ENVIRONMENT.EXIT(-1)
END IF
ELSE
VAR = GETDEFAULT()
END IF
END SUB
END MODULE
MODULE PROGRAM
SUB MAIN(ARGS AS STRING())
DIM DT AS DATE
DIM COLUMNS, ROWS, MONTHSPERROW AS INTEGER
DIM VERTSTRETCH, HORIZSTRETCH, RESIZEWINDOW AS BOOLEAN
INITIALIZEARGUMENTS(ARGS)
FROMARGUMENT("DATE", DT, FUNCTION() NEW DATE(1969, 1, 1), ADDRESSOF DATE.TRYPARSE)
FROMARGUMENT("COLS", COLUMNS, FUNCTION() 80, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 20)
FROMARGUMENT("ROWS", ROWS, FUNCTION() 43, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 0)
FROMARGUMENT("MS/ROW", MONTHSPERROW, FUNCTION() 0, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V <= 12 ANDALSO V <= COLUMNS \ 20)
FROMARGUMENT("VSTRETCH", VERTSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)
FROMARGUMENT("HSTRETCH", HORIZSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)
FROMARGUMENT("WSIZE", RESIZEWINDOW, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)
IF RESIZEWINDOW THEN
CONSOLE.WINDOWWIDTH = COLUMNS + 1
CONSOLE.WINDOWHEIGHT = ROWS
END IF
IF MONTHSPERROW < 1 THEN MONTHSPERROW = MATH.MAX(COLUMNS \ 22, 1)
FOR EACH ROW IN GETCALENDARROWS(DT:=DT, WIDTH:=COLUMNS, HEIGHT:=ROWS, MONTHSPERROW:=MONTHSPERROW, VERTSTRETCH:=VERTSTRETCH, HORIZSTRETCH:=HORIZSTRETCH)
CONSOLE.WRITE(ROW)
NEXT
END SUB
ITERATOR FUNCTION GETCALENDARROWS(
DT AS DATE,
WIDTH AS INTEGER,
HEIGHT AS INTEGER,
MONTHSPERROW AS INTEGER,
VERTSTRETCH AS BOOLEAN,
HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)
DIM YEAR = DT.YEAR
DIM CALENDARROWCOUNT AS INTEGER = CINT(MATH.CEILING(12 / MONTHSPERROW))
DIM MONTHGRIDHEIGHT AS INTEGER = HEIGHT - 3
YIELD "[SNOOPY]".PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE
YIELD YEAR.TOSTRING(CULTUREINFO.INVARIANTCULTURE).PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE
YIELD ENVIRONMENT.NEWLINE
DIM MONTH = 0
DO WHILE MONTH < 12
DIM ROWHIGHESTMONTH = MATH.MIN(MONTH + MONTHSPERROW, 12)
DIM CELLWIDTH = WIDTH \ MONTHSPERROW
DIM CELLCONTENTWIDTH = IF(MONTHSPERROW = 1, CELLWIDTH, (CELLWIDTH * 19) \ 20)
DIM CELLHEIGHT = MONTHGRIDHEIGHT \ CALENDARROWCOUNT
DIM CELLCONTENTHEIGHT = (CELLHEIGHT * 19) \ 20
DIM GETMONTHFROM =
FUNCTION(M AS INTEGER) BUILDMONTH(
DT:=NEW DATE(DT.YEAR, M, 1),
WIDTH:=CELLCONTENTWIDTH,
HEIGHT:=CELLCONTENTHEIGHT,
VERTSTRETCH:=VERTSTRETCH,
HORIZSTRETCH:=HORIZSTRETCH).SELECT(FUNCTION(X) X.PADCENTER(CELLWIDTH))
DIM MONTHSTHISROW AS IENUMERABLE(OF IENUMERABLE(OF STRING)) =
ENUMERABLE.SELECT(ENUMERABLE.RANGE(MONTH + 1, ROWHIGHESTMONTH - MONTH), GETMONTHFROM)
DIM CALENDARROW AS IENUMERABLE(OF STRING) =
INTERLEAVED(
MONTHSTHISROW,
USEINNERSEPARATOR:=FALSE,
USEOUTERSEPARATOR:=TRUE,
OUTERSEPARATOR:=ENVIRONMENT.NEWLINE)
DIM EN = CALENDARROW.GETENUMERATOR()
DIM HASNEXT = EN.MOVENEXT()
DO WHILE HASNEXT
DIM CURRENT AS STRING = EN.CURRENT
HASNEXT = EN.MOVENEXT()
YIELD IF(HASNEXT, CURRENT, CURRENT & ENVIRONMENT.NEWLINE)
LOOP
MONTH += MONTHSPERROW
LOOP
END FUNCTION
ITERATOR FUNCTION INTERLEAVED(OF T)(
SOURCES AS IENUMERABLE(OF IENUMERABLE(OF T)),
OPTIONAL USEINNERSEPARATOR AS BOOLEAN = FALSE,
OPTIONAL INNERSEPARATOR AS T = NOTHING,
OPTIONAL USEOUTERSEPARATOR AS BOOLEAN = FALSE,
OPTIONAL OUTERSEPARATOR AS T = NOTHING,
OPTIONAL WHILEANY AS BOOLEAN = TRUE) AS IENUMERABLE(OF T)
DIM SOURCEENUMERATORS AS IENUMERATOR(OF T)() = NOTHING
TRY
SOURCEENUMERATORS = SOURCES.SELECT(FUNCTION(X) X.GETENUMERATOR()).TOARRAY()
DIM NUMSOURCES = SOURCEENUMERATORS.LENGTH
DIM ENUMERATORSTATES(NUMSOURCES - 1) AS BOOLEAN
DIM ANYPREVITERS AS BOOLEAN = FALSE
DO
DIM FIRSTACTIVE = -1, LASTACTIVE = -1
FOR I = 0 TO NUMSOURCES - 1
ENUMERATORSTATES(I) = SOURCEENUMERATORS(I).MOVENEXT()
IF ENUMERATORSTATES(I) THEN
IF FIRSTACTIVE = -1 THEN FIRSTACTIVE = I
LASTACTIVE = I
END IF
NEXT
DIM THISITERHASRESULTS AS BOOLEAN = IF(WHILEANY, FIRSTACTIVE <> -1, FIRSTACTIVE = 0 ANDALSO LASTACTIVE = NUMSOURCES - 1)
IF NOT THISITERHASRESULTS THEN EXIT DO
IF ANYPREVITERS THEN
IF USEOUTERSEPARATOR THEN YIELD OUTERSEPARATOR
ELSE
ANYPREVITERS = TRUE
END IF
FOR I = 0 TO NUMSOURCES - 1
IF ENUMERATORSTATES(I) THEN
IF I > FIRSTACTIVE ANDALSO USEINNERSEPARATOR THEN YIELD INNERSEPARATOR
YIELD SOURCEENUMERATORS(I).CURRENT
END IF
NEXT
LOOP
FINALLY
IF SOURCEENUMERATORS ISNOT NOTHING THEN
FOR EACH EN IN SOURCEENUMERATORS
EN.DISPOSE()
NEXT
END IF
END TRY
END FUNCTION
ITERATOR FUNCTION BUILDMONTH(DT AS DATE, WIDTH AS INTEGER, HEIGHT AS INTEGER, VERTSTRETCH AS BOOLEAN, HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)
CONST DAY_WDT = 2
CONST ALLDAYS_WDT = DAY_WDT * 7
DT = NEW DATE(DT.YEAR, DT.MONTH, 1)
DIM DAYSEP AS NEW STRING(" "C, MATH.MIN((WIDTH - ALLDAYS_WDT) \ 6, IF(HORIZSTRETCH, INTEGER.MAXVALUE, 1)))
DIM VERTBLANKCOUNT = IF(NOT VERTSTRETCH, 0, (HEIGHT - 8) \ 7)
DIM BLOCKWIDTH = ALLDAYS_WDT + DAYSEP.LENGTH * 6
DIM LEFTPAD AS NEW STRING(" "C, (WIDTH - BLOCKWIDTH) \ 2)
DIM FULLPAD AS NEW STRING(" "C, WIDTH)
DIM SB AS NEW STRINGBUILDER(LEFTPAD)
DIM NUMLINES = 0
DIM ENDLINE =
FUNCTION() AS IENUMERABLE(OF STRING)
DIM FINISHEDLINE AS STRING = SB.TOSTRING().PADRIGHT(WIDTH)
SB.CLEAR()
SB.APPEND(LEFTPAD)
RETURN IF(NUMLINES >= HEIGHT,
ENUMERABLE.EMPTY(OF STRING)(),
ITERATOR FUNCTION() AS IENUMERABLE(OF STRING)
YIELD FINISHEDLINE
NUMLINES += 1
FOR I = 1 TO VERTBLANKCOUNT
IF NUMLINES >= HEIGHT THEN RETURN
YIELD FULLPAD
NUMLINES += 1
NEXT
END FUNCTION())
END FUNCTION
SB.APPEND(PADCENTER(DT.TOSTRING("MMMM", CULTUREINFO.INVARIANTCULTURE), BLOCKWIDTH).TOUPPER())
FOR EACH L IN ENDLINE()
YIELD L
NEXT
DIM WEEKNMABBREVS = [ENUM].GETNAMES(GETTYPE(DAYOFWEEK)).SELECT(FUNCTION(X) X.SUBSTRING(0, 2).TOUPPER())
SB.APPEND(STRING.JOIN(DAYSEP, WEEKNMABBREVS))
FOR EACH L IN ENDLINE()
YIELD L
NEXT
DIM STARTWKDY = CINT(DT.DAYOFWEEK)
DIM FIRSTPAD AS NEW STRING(" "C, (DAY_WDT + DAYSEP.LENGTH) * STARTWKDY)
SB.APPEND(FIRSTPAD)
DIM D = DT
DO WHILE D.MONTH = DT.MONTH
SB.APPENDFORMAT(CULTUREINFO.INVARIANTCULTURE, $"{{0,{DAY_WDT}}}", D.DAY)
IF D.DAYOFWEEK = DAYOFWEEK.SATURDAY THEN
FOR EACH L IN ENDLINE()
YIELD L
NEXT
ELSE
SB.APPEND(DAYSEP)
END IF
D = D.ADDDAYS(1)
LOOP
DIM NEXTLINES AS IENUMERABLE(OF STRING)
DO
NEXTLINES = ENDLINE()
FOR EACH L IN NEXTLINES
YIELD L
NEXT
LOOP WHILE NEXTLINES.ANY()
END FUNCTION
<EXTENSION()>
PRIVATE FUNCTION PADCENTER(S AS STRING, TOTALWIDTH AS INTEGER, OPTIONAL PADDINGCHAR AS CHAR = " "C) AS STRING
RETURN S.PADLEFT(((TOTALWIDTH - S.LENGTH) \ 2) + S.LENGTH, PADDINGCHAR).PADRIGHT(TOTALWIDTH, PADDINGCHAR)
END FUNCTION
END MODULE
| PACKAGE MAIN
IMPORT (
"FMT"
"TIME"
)
CONST PAGEWIDTH = 80
FUNC MAIN() {
PRINTCAL(1969)
}
FUNC PRINTCAL(YEAR INT) {
THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)
VAR (
DAYARR [12][7][6]INT
MONTH, LASTMONTH TIME.MONTH
WEEKINMONTH, DAYINMONTH INT
)
FOR THISDATE.YEAR() == YEAR {
IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {
WEEKINMONTH = 0
DAYINMONTH = 1
}
WEEKDAY := THISDATE.WEEKDAY()
IF WEEKDAY == 0 && DAYINMONTH > 1 {
WEEKINMONTH++
}
DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()
LASTMONTH = MONTH
DAYINMONTH++
THISDATE = THISDATE.ADD(TIME.HOUR * 24)
}
CENTRE := FMT.SPRINTF("%D", PAGEWIDTH/2)
FMT.PRINTF("%"+CENTRE+"S\N\N", "[SNOOPY]")
CENTRE = FMT.SPRINTF("%D", PAGEWIDTH/2-2)
FMT.PRINTF("%"+CENTRE+"D\N\N", YEAR)
MONTHS := [12]STRING{
" JANUARY ", " FEBRUARY", " MARCH ", " APRIL ",
" MAY ", " JUNE ", " JULY ", " AUGUST ",
"SEPTEMBER", " OCTOBER ", " NOVEMBER", " DECEMBER"}
DAYS := [7]STRING{"SU", "MO", "TU", "WE", "TH", "FR", "SA"}
FOR QTR := 0; QTR < 4; QTR++ {
FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {
FMT.PRINTF(" %S ", MONTHS[QTR*3+MONTHINQTR])
}
FMT.PRINTLN()
FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {
FOR DAY := 0; DAY < 7; DAY++ {
FMT.PRINTF(" %S", DAYS[DAY])
}
FMT.PRINTF(" ")
}
FMT.PRINTLN()
FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {
FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {
FOR DAY := 0; DAY < 7; DAY++ {
IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {
FMT.PRINTF(" ")
} ELSE {
FMT.PRINTF("%3D", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])
}
}
FMT.PRINTF(" ")
}
FMT.PRINTLN()
}
FMT.PRINTLN()
}
}
|
Change the programming language of this snippet from VB to Go without modifying what it does. | Do
Debug.Print "SPAM"
Loop
| package main
import "fmt"
func main() {
for {
fmt.Printf("SPAM\n")
}
}
|
Translate the given VB code snippet into Go without altering its behavior. | Function mtf_encode(s)
Set symbol_table = CreateObject("System.Collections.ArrayList")
For j = 97 To 122
symbol_table.Add Chr(j)
Next
output = ""
For i = 1 To Len(s)
char = Mid(s,i,1)
If i = Len(s) Then
output = output & symbol_table.IndexOf(char,0)
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
Else
output = output & symbol_table.IndexOf(char,0) & " "
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
End If
Next
mtf_encode = output
End Function
Function mtf_decode(s)
code = Split(s," ")
Set symbol_table = CreateObject("System.Collections.ArrayList")
For j = 97 To 122
symbol_table.Add Chr(j)
Next
output = ""
For i = 0 To UBound(code)
char = symbol_table(code(i))
output = output & char
If code(i) <> 0 Then
symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
symbol_table.Insert 0,char
End If
Next
mtf_decode = output
End Function
wordlist = Array("broood","bananaaa","hiphophiphop")
For Each word In wordlist
WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_
mtf_decode(mtf_encode(word)) & "."
WScript.StdOut.WriteBlankLines(1)
Next
| package main
import (
"bytes"
"fmt"
)
type symbolTable string
func (symbols symbolTable) encode(s string) []byte {
seq := make([]byte, len(s))
pad := []byte(symbols)
for i, c := range []byte(s) {
x := bytes.IndexByte(pad, c)
seq[i] = byte(x)
copy(pad[1:], pad[:x])
pad[0] = c
}
return seq
}
func (symbols symbolTable) decode(seq []byte) string {
chars := make([]byte, len(seq))
pad := []byte(symbols)
for i, x := range seq {
c := pad[x]
chars[i] = c
copy(pad[1:], pad[:x])
pad[0] = c
}
return string(chars)
}
func main() {
m := symbolTable("abcdefghijklmnopqrstuvwxyz")
for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} {
enc := m.encode(s)
dec := m.decode(enc)
fmt.Println(s, enc, dec)
if dec != s {
panic("Whoops!")
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Go. | Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True
| package main
import (
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("ls", "-l")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | Option explicit
Function fileexists(fn)
fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn)
End Function
Function xmlvalid(strfilename)
Dim xmldoc,xmldoc2,objSchemas
Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0")
If fileexists(Replace(strfilename,".xml",".dtd")) Then
xmlDoc.setProperty "ProhibitDTD", False
xmlDoc.setProperty "ResolveExternals", True
xmlDoc.validateOnParse = True
xmlDoc.async = False
xmlDoc.load(strFileName)
ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then
xmlDoc.setProperty "ProhibitDTD", True
xmlDoc.setProperty "ResolveExternals", True
xmlDoc.validateOnParse = True
xmlDoc.async = False
xmlDoc.load(strFileName)
Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0")
xmlDoc2.validateOnParse = True
xmlDoc2.async = False
xmlDoc2.load(Replace (strfilename,".xml",".xsd"))
Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0")
objSchemas.Add "", xmlDoc2
Else
Set xmlvalid= Nothing:Exit Function
End If
Set xmlvalid=xmldoc.parseError
End Function
Sub displayerror (parserr)
Dim strresult
If parserr is Nothing Then
strresult= "could not find dtd or xsd for " & strFileName
Else
With parserr
Select Case .errorcode
Case 0
strResult = "Valid: " & strFileName & vbCr
Case Else
strResult = vbCrLf & "ERROR! Failed to validate " & _
strFileName & vbCrLf &.reason & vbCr & _
"Error code: " & .errorCode & ", Line: " & _
.line & ", Character: " & _
.linepos & ", Source: """ & _
.srcText & """ - " & vbCrLf
End Select
End With
End If
WScript.Echo strresult
End Sub
Dim strfilename
strfilename="shiporder.xml"
displayerror xmlvalid (strfilename)
| package main
import (
"fmt"
"github.com/lestrrat-go/libxml2"
"github.com/lestrrat-go/libxml2/xsd"
"io/ioutil"
"log"
"os"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
xsdfile := "shiporder.xsd"
f, err := os.Open(xsdfile)
check(err)
defer f.Close()
buf, err := ioutil.ReadAll(f)
check(err)
s, err := xsd.Parse(buf)
check(err)
defer s.Free()
xmlfile := "shiporder.xml"
f2, err := os.Open(xmlfile)
check(err)
defer f2.Close()
buf2, err := ioutil.ReadAll(f2)
check(err)
d, err := libxml2.Parse(buf2)
check(err)
if err := s.Validate(d); err != nil {
for _, e := range err.(xsd.SchemaValidationError).Errors() {
log.Printf("error: %s", e.Error())
}
return
}
fmt.Println("Validation of", xmlfile, "against", xsdfile, "successful!")
}
|
Convert this VB snippet to Go and keep its semantics consistent. | Function LIS(arr)
n = UBound(arr)
Dim p()
ReDim p(n)
Dim m()
ReDim m(n)
l = 0
For i = 0 To n
lo = 1
hi = l
Do While lo <= hi
middle = Int((lo+hi)/2)
If arr(m(middle)) < arr(i) Then
lo = middle + 1
Else
hi = middle - 1
End If
Loop
newl = lo
p(i) = m(newl-1)
m(newl) = i
If newL > l Then
l = newl
End If
Next
Dim s()
ReDim s(l)
k = m(l)
For i = l-1 To 0 Step - 1
s(i) = arr(k)
k = p(k)
Next
LIS = Join(s,",")
End Function
WScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))
WScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))
| package main
import (
"fmt"
"sort"
)
type Node struct {
val int
back *Node
}
func lis (n []int) (result []int) {
var pileTops []*Node
for _, x := range n {
j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })
node := &Node{ x, nil }
if j != 0 { node.back = pileTops[j-1] }
if j != len(pileTops) {
pileTops[j] = node
} else {
pileTops = append(pileTops, node)
}
}
if len(pileTops) == 0 { return []int{} }
for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {
result = append(result, node.val)
}
for i := 0; i < len(result)/2; i++ {
result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]
}
return
}
func main() {
for _, d := range [][]int{{3, 2, 6, 4, 5, 1},
{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {
fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d))
}
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. |
option explicit
const x_=0
const y_=1
const z_=2
const r_=3
function clamp(x,b,t)
if x<b then
clamp=b
elseif x>t then
clamp =t
else
clamp=x
end if
end function
function dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function
function normal (byval v)
dim ilen:ilen=1/sqr(dot(v,v)):
v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen:
normal=v:
end function
function hittest(s,x,y)
dim z
z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2
if z>=0 then
z=sqr(z)
hittest=array(s(z_)-z,s(z_)+z)
else
hittest=0
end if
end function
sub deathstar(pos, neg, sun, k, amb)
dim x,y,shades,result,shade,hp,hn,xx,b
shades=array(" ",".",":","!","*","o","e","&","#","%","@")
for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5
for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5
hp=hittest (pos, x, y)
hn=hittest(neg,x,y)
if not isarray(hp) then
result=0
elseif not isarray(hn) then
result=1
elseif hn(0)>hp(0) then
result=1
elseif hn(1)>hp(1) then
result=0
elseif hn(1)>hp(0) then
result=2
else
result=1
end if
shade=-1
select case result
case 0
shade=0
case 1
xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_)))
case 2
xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1)))
end select
if shade <>0 then
b=dot(sun,xx)^k+amb
shade=clamp((1-b) *ubound(shades),1,ubound(shades))
end if
wscript.stdout.write string(2,shades(shade))
next
wscript.stdout.write vbcrlf
next
end sub
deathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1
| package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func (v *vector) normalize() {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
type sphere struct {
cx, cy, cz int
r int
}
func (s *sphere) hit(x, y int) (z1, z2 float64, hit bool) {
x -= s.cx
y -= s.cy
if zsq := s.r*s.r - (x*x + y*y); zsq >= 0 {
zsqrt := math.Sqrt(float64(zsq))
return float64(s.cz) - zsqrt, float64(s.cz) + zsqrt, true
}
return 0, 0, false
}
func deathStar(pos, neg *sphere, k, amb float64, dir *vector) *image.Gray {
w, h := pos.r*4, pos.r*3
bounds := image.Rect(pos.cx-w/2, pos.cy-h/2, pos.cx+w/2, pos.cy+h/2)
img := image.NewGray(bounds)
vec := new(vector)
for y, yMax := pos.cy-pos.r, pos.cy+pos.r; y <= yMax; y++ {
for x, xMax := pos.cx-pos.r, pos.cx+pos.r; x <= xMax; x++ {
zb1, zb2, hit := pos.hit(x, y)
if !hit {
continue
}
zs1, zs2, hit := neg.hit(x, y)
if hit {
if zs1 > zb1 {
hit = false
} else if zs2 > zb2 {
continue
}
}
if hit {
vec[0] = float64(neg.cx - x)
vec[1] = float64(neg.cy - y)
vec[2] = float64(neg.cz) - zs2
} else {
vec[0] = float64(x - pos.cx)
vec[1] = float64(y - pos.cy)
vec[2] = zb1 - float64(pos.cz)
}
vec.normalize()
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
return img
}
func main() {
dir := &vector{20, -40, -10}
dir.normalize()
pos := &sphere{0, 0, 0, 120}
neg := &sphere{-90, -90, -30, 100}
img := deathStar(pos, neg, 1.5, .2, dir)
f, err := os.Create("dstar.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.