Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Change the following Go code into VB without altering its purpose. | package main
import (
"fmt"
"math/rand"
"time"
)
type vector []float64
func e(n uint) vector {
if n > 4 {
panic("n must be less than 5")
}
result := make(vector, 32)
result[1<<n] = 1.0
return result
}
func cdot(a, b vector) vector {
return mul(vector{0.5}, add(mul(a, b), mul(b, a)))
}
func neg(x vector) vector {
return mul(vector{-1}, x)
}
func bitCount(i int) int {
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
i = (i + (i >> 4)) & 0x0F0F0F0F
i = i + (i >> 8)
i = i + (i >> 16)
return i & 0x0000003F
}
func reorderingSign(i, j int) float64 {
i >>= 1
sum := 0
for i != 0 {
sum += bitCount(i & j)
i >>= 1
}
cond := (sum & 1) == 0
if cond {
return 1.0
}
return -1.0
}
func add(a, b vector) vector {
result := make(vector, 32)
copy(result, a)
for i, _ := range b {
result[i] += b[i]
}
return result
}
func mul(a, b vector) vector {
result := make(vector, 32)
for i, _ := range a {
if a[i] != 0 {
for j, _ := range b {
if b[j] != 0 {
s := reorderingSign(i, j) * a[i] * b[j]
k := i ^ j
result[k] += s
}
}
}
}
return result
}
func randomVector() vector {
result := make(vector, 32)
for i := uint(0); i < 5; i++ {
result = add(result, mul(vector{rand.Float64()}, e(i)))
}
return result
}
func randomMultiVector() vector {
result := make(vector, 32)
for i := 0; i < 32; i++ {
result[i] = rand.Float64()
}
return result
}
func main() {
rand.Seed(time.Now().UnixNano())
for i := uint(0); i < 5; i++ {
for j := uint(0); j < 5; j++ {
if i < j {
if cdot(e(i), e(j))[0] != 0 {
fmt.Println("Unexpected non-null scalar product.")
return
}
} else if i == j {
if cdot(e(i), e(j))[0] == 0 {
fmt.Println("Unexpected null scalar product.")
}
}
}
}
a := randomMultiVector()
b := randomMultiVector()
c := randomMultiVector()
x := randomVector()
fmt.Println(mul(mul(a, b), c))
fmt.Println(mul(a, mul(b, c)))
fmt.Println(mul(a, add(b, c)))
fmt.Println(add(mul(a, b), mul(a, c)))
fmt.Println(mul(add(a, b), c))
fmt.Println(add(mul(a, c), mul(b, c)))
fmt.Println(mul(x, x))
}
| Option Strict On
Imports System.Text
Module Module1
Structure Vector
Private ReadOnly dims() As Double
Public Sub New(da() As Double)
dims = da
End Sub
Public Shared Operator -(v As Vector) As Vector
Return v * -1.0
End Operator
Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector
Dim result(31) As Double
Array.Copy(lhs.dims, 0, result, 0, lhs.Length)
For i = 1 To result.Length
Dim i2 = i - 1
result(i2) = lhs(i2) + rhs(i2)
Next
Return New Vector(result)
End Operator
Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector
Dim result(31) As Double
For i = 1 To lhs.Length
Dim i2 = i - 1
If lhs(i2) <> 0.0 Then
For j = 1 To lhs.Length
Dim j2 = j - 1
If rhs(j2) <> 0.0 Then
Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2)
Dim k = i2 Xor j2
result(k) += s
End If
Next
End If
Next
Return New Vector(result)
End Operator
Public Shared Operator *(v As Vector, scale As Double) As Vector
Dim result = CType(v.dims.Clone, Double())
For i = 1 To result.Length
Dim i2 = i - 1
result(i2) *= scale
Next
Return New Vector(result)
End Operator
Default Public Property Index(key As Integer) As Double
Get
Return dims(key)
End Get
Set(value As Double)
dims(key) = value
End Set
End Property
Public ReadOnly Property Length As Integer
Get
Return dims.Length
End Get
End Property
Public Function Dot(rhs As Vector) As Vector
Return (Me * rhs + rhs * Me) * 0.5
End Function
Private Shared Function BitCount(i As Integer) As Integer
i -= ((i >> 1) And &H55555555)
i = (i And &H33333333) + ((i >> 2) And &H33333333)
i = (i + (i >> 4)) And &HF0F0F0F
i += (i >> 8)
i += (i >> 16)
Return i And &H3F
End Function
Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double
Dim k = i >> 1
Dim sum = 0
While k <> 0
sum += BitCount(k And j)
k >>= 1
End While
Return If((sum And 1) = 0, 1.0, -1.0)
End Function
Public Overrides Function ToString() As String
Dim it = dims.GetEnumerator
Dim sb As New StringBuilder("[")
If it.MoveNext() Then
sb.Append(it.Current)
End If
While it.MoveNext
sb.Append(", ")
sb.Append(it.Current)
End While
sb.Append("]")
Return sb.ToString
End Function
End Structure
Function DoubleArray(size As Integer) As Double()
Dim result(size - 1) As Double
For i = 1 To size
Dim i2 = i - 1
result(i2) = 0.0
Next
Return result
End Function
Function E(n As Integer) As Vector
If n > 4 Then
Throw New ArgumentException("n must be less than 5")
End If
Dim result As New Vector(DoubleArray(32))
result(1 << n) = 1.0
Return result
End Function
ReadOnly r As New Random()
Function RandomVector() As Vector
Dim result As New Vector(DoubleArray(32))
For i = 1 To 5
Dim i2 = i - 1
Dim singleton() As Double = {r.NextDouble()}
result += New Vector(singleton) * E(i2)
Next
Return result
End Function
Function RandomMultiVector() As Vector
Dim result As New Vector(DoubleArray(32))
For i = 1 To result.Length
Dim i2 = i - 1
result(i2) = r.NextDouble()
Next
Return result
End Function
Sub Main()
For i = 1 To 5
Dim i2 = i - 1
For j = 1 To 5
Dim j2 = j - 1
If i2 < j2 Then
If E(i2).Dot(E(j2))(0) <> 0.0 Then
Console.Error.WriteLine("Unexpected non-null scalar product")
Return
End If
ElseIf i2 = j2 Then
If E(i2).Dot(E(j2))(0) = 0.0 Then
Console.Error.WriteLine("Unexpected null scalar product")
Return
End If
End If
Next
Next
Dim a = RandomMultiVector()
Dim b = RandomMultiVector()
Dim c = RandomMultiVector()
Dim x = RandomVector()
Console.WriteLine((a * b) * c)
Console.WriteLine(a * (b * c))
Console.WriteLine()
Console.WriteLine(a * (b + c))
Console.WriteLine(a * b + a * c)
Console.WriteLine()
Console.WriteLine((a + b) * c)
Console.WriteLine(a * c + b * c)
Console.WriteLine()
Console.WriteLine(x * x)
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in VB. | myMap := map[string]int {
"hello": 13,
"world": 31,
"!" : 71 }
for key, value := range myMap {
fmt.Printf("key = %s, value = %d\n", key, value)
}
for key := range myMap {
fmt.Printf("key = %s\n", key)
}
for _, value := range myMap {
fmt.Printf("value = %d\n", value)
}
| Option Explicit
Sub Test()
Dim h As Object, i As Long, u, v, s
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
For Each s In h.Keys
Debug.Print s
Next
For Each s In h.Items
Debug.Print s
Next
u = h.Keys
v = h.Items
For i = 0 To h.Count - 1
Debug.Print u(i), v(i)
Next
End Sub
|
Change the programming language of this snippet from Go to VB without modifying what it does. | package main
import "fmt"
type TinyInt int
func NewTinyInt(i int) TinyInt {
if i < 1 {
i = 1
} else if i > 10 {
i = 10
}
return TinyInt(i)
}
func (t1 TinyInt) Add(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) + int(t2))
}
func (t1 TinyInt) Sub(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) - int(t2))
}
func (t1 TinyInt) Mul(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) * int(t2))
}
func (t1 TinyInt) Div(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) / int(t2))
}
func (t1 TinyInt) Rem(t2 TinyInt) TinyInt {
return NewTinyInt(int(t1) % int(t2))
}
func (t TinyInt) Inc() TinyInt {
return t.Add(TinyInt(1))
}
func (t TinyInt) Dec() TinyInt {
return t.Sub(TinyInt(1))
}
func main() {
t1 := NewTinyInt(6)
t2 := NewTinyInt(3)
fmt.Println("t1 =", t1)
fmt.Println("t2 =", t2)
fmt.Println("t1 + t2 =", t1.Add(t2))
fmt.Println("t1 - t2 =", t1.Sub(t2))
fmt.Println("t1 * t2 =", t1.Mul(t2))
fmt.Println("t1 / t2 =", t1.Div(t2))
fmt.Println("t1 % t2 =", t1.Rem(t2))
fmt.Println("t1 + 1 =", t1.Inc())
fmt.Println("t1 - 1 =", t1.Dec())
}
| Private mvarValue As Integer
Public Property Let Value(ByVal vData As Integer)
If (vData > 10) Or (vData < 1) Then
Error 380
Else
mvarValue = vData
End If
End Property
Public Property Get Value() As Integer
Value = mvarValue
End Property
Private Sub Class_Initialize()
mvarValue = 1
End Sub
|
Change the programming language of this snippet from Go to VB without modifying what it does. | package main
import "fmt"
func main() {
tableA := []struct {
value int
key string
}{
{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"},
{28, "Alan"},
}
tableB := []struct {
key string
value string
}{
{"Jonah", "Whales"}, {"Jonah", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
}
h := map[string][]int{}
for i, r := range tableA {
h[r.key] = append(h[r.key], i)
}
for _, x := range tableB {
for _, a := range h[x.key] {
fmt.Println(tableA[a], x)
}
}
}
| Dim t_age(4,1)
t_age(0,0) = 27 : t_age(0,1) = "Jonah"
t_age(1,0) = 18 : t_age(1,1) = "Alan"
t_age(2,0) = 28 : t_age(2,1) = "Glory"
t_age(3,0) = 18 : t_age(3,1) = "Popeye"
t_age(4,0) = 28 : t_age(4,1) = "Alan"
Dim t_nemesis(4,1)
t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales"
t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders"
t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts"
t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies"
t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy"
Call hash_join(t_age,1,t_nemesis,0)
Sub hash_join(table_1,index_1,table_2,index_2)
Set hash = CreateObject("Scripting.Dictionary")
For i = 0 To UBound(table_1)
hash.Add i,Array(table_1(i,0),table_1(i,1))
Next
For j = 0 To UBound(table_2)
For Each key In hash.Keys
If hash(key)(index_1) = table_2(j,index_2) Then
WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_
" = " & table_2(j,0) & "," & table_2(j,1)
End If
Next
Next
End Sub
|
Write the same code in VB as shown below in Go. | package main
import (
"github.com/fogleman/gg"
"github.com/trubitsyn/go-lindenmayer"
"log"
"math"
)
const twoPi = 2 * math.Pi
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h, theta float64
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
cx, cy = 10, height/2+5
h = 6
sys := lindenmayer.Lsystem{
Variables: []rune{'X'},
Constants: []rune{'F', '+', '-'},
Axiom: "F+XF+F+XF",
Rules: []lindenmayer.Rule{
{"X", "XF-F+F-XF+F+XF-F+F-X"},
},
Angle: math.Pi / 2,
}
result := lindenmayer.Iterate(&sys, 5)
operations := map[rune]func(){
'F': func() {
newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)
dc.LineTo(newX, newY)
cx, cy = newX, newY
},
'+': func() {
theta = math.Mod(theta+sys.Angle, twoPi)
},
'-': func() {
theta = math.Mod(theta-sys.Angle, twoPi)
},
}
if err := lindenmayer.Process(result, operations); err != nil {
log.Fatal(err)
}
operations['+']()
operations['F']()
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_square_curve.png")
}
| option explicit
const pi180= 0.01745329251994329576923690768489
const pi=3.1415926535897932384626433832795
class turtle
dim fso
dim fn
dim svg
dim iang
dim ori
dim incr
dim pdown
dim clr
dim x
dim y
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
end sub
public sub lt(i):
ori=(ori + i*iang)
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
x=400:y=400:incr=100
ori=90*pi180
iang=90*pi180
clr=0
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
const raiz2=1.4142135623730950488016887242097
sub media_sierp (niv,sz)
if niv=0 then x.fw sz: exit sub
media_sierp niv-1,sz
x.lt 1
x.fw sz*raiz2
x.lt 1
media_sierp niv-1,sz
x.rt 2
x.fw sz
x.rt 2
media_sierp niv-1,sz
x.lt 1
x.fw sz*raiz2
x.lt 1
media_sierp niv-1,sz
end sub
sub sierp(niv,sz)
media_sierp niv,sz
x.rt 2
x.fw sz
x.rt 2
media_sierp niv,sz
x.rt 2
x.fw sz
x.rt 2
end sub
dim x
set x=new turtle
x.iangle=45
x.orient=0
x.incr=1
x.x=100:x.y=270
sierp 5,4
set x=nothing
|
Preserve the algorithm and functionality while converting the code from Go to VB. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
count := 0
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 5 && (s[0:3] == s[len(s)-3:]) {
count++
fmt.Printf("%d: %s\n", count, s)
}
}
}
| with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
set d= createobject("Scripting.Dictionary")
for each aa in a
x=trim(aa)
l=len(x)
if l>5 then
d.removeall
for i=1 to 3
m=mid(x,i,1)
if not d.exists(m) then d.add m,null
next
res=true
for i=l-2 to l
m=mid(x,i,1)
if not d.exists(m) then
res=false:exit for
else
d.remove(m)
end if
next
if res then
wscript.stdout.write left(x & space(15),15)
if left(x,3)=right(x,3) then wscript.stdout.write "*"
wscript.stdout.writeline
end if
end if
next
|
Produce a functionally identical VB code for the snippet given in Go. | package main
import (
"fmt"
"strings"
)
type dict map[string]bool
func newDict(words ...string) dict {
d := dict{}
for _, w := range words {
d[w] = true
}
return d
}
func (d dict) wordBreak(s string) (broken []string, ok bool) {
if s == "" {
return nil, true
}
type prefix struct {
length int
broken []string
}
bp := []prefix{{0, nil}}
for end := 1; end <= len(s); end++ {
for i := len(bp) - 1; i >= 0; i-- {
w := s[bp[i].length:end]
if d[w] {
b := append(bp[i].broken, w)
if end == len(s) {
return b, true
}
bp = append(bp, prefix{end, b})
break
}
}
}
return nil, false
}
func main() {
d := newDict("a", "bc", "abc", "cd", "b")
for _, s := range []string{"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} {
if b, ok := d.wordBreak(s); ok {
fmt.Printf("%s: %s\n", s, strings.Join(b, " "))
} else {
fmt.Println("can't break")
}
}
}
| Module Module1
Structure Node
Private ReadOnly m_val As String
Private ReadOnly m_parsed As List(Of String)
Sub New(initial As String)
m_val = initial
m_parsed = New List(Of String)
End Sub
Sub New(s As String, p As List(Of String))
m_val = s
m_parsed = p
End Sub
Public Function Value() As String
Return m_val
End Function
Public Function Parsed() As List(Of String)
Return m_parsed
End Function
End Structure
Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String))
Dim matches As New List(Of List(Of String))
Dim q As New Queue(Of Node)
q.Enqueue(New Node(s))
While q.Count > 0
Dim node = q.Dequeue()
REM check if fully parsed
If node.Value.Length = 0 Then
matches.Add(node.Parsed)
Else
For Each word In dictionary
REM check for match
If node.Value.StartsWith(word) Then
Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length)
Dim parsedNew As New List(Of String)
parsedNew.AddRange(node.Parsed)
parsedNew.Add(word)
q.Enqueue(New Node(valNew, parsedNew))
End If
Next
End If
End While
Return matches
End Function
Sub Main()
Dim dict As New List(Of String) From {"a", "aa", "b", "ab", "aab"}
For Each testString In {"aab", "aa b"}
Dim matches = WordBreak(testString, dict)
Console.WriteLine("String = {0}, Dictionary = {1}. Solutions = {2}", testString, dict, matches.Count)
For Each match In matches
Console.WriteLine(" Word Break = [{0}]", String.Join(", ", match))
Next
Console.WriteLine()
Next
dict = New List(Of String) From {"abc", "a", "ac", "b", "c", "cb", "d"}
For Each testString In {"abcd", "abbc", "abcbcd", "acdbc", "abcdd"}
Dim matches = WordBreak(testString, dict)
Console.WriteLine("String = {0}, Dictionary = {1}. Solutions = {2}", testString, dict, matches.Count)
For Each match In matches
Console.WriteLine(" Word Break = [{0}]", String.Join(", ", match))
Next
Console.WriteLine()
Next
End Sub
End Module
|
Please provide an equivalent version of this Go code in VB. | package main
import (
"fmt"
"sort"
)
type matrix [][]int
func dList(n, start int) (r matrix) {
start--
a := make([]int, n)
for i := range a {
a[i] = i
}
a[0], a[start] = start, a[0]
sort.Ints(a[1:])
first := a[1]
var recurse func(last int)
recurse = func(last int) {
if last == first {
for j, v := range a[1:] {
if j+1 == v {
return
}
}
b := make([]int, n)
copy(b, a)
for i := range b {
b[i]++
}
r = append(r, b)
return
}
for i := last; i >= 1; i-- {
a[i], a[last] = a[last], a[i]
recurse(last - 1)
a[i], a[last] = a[last], a[i]
}
}
recurse(n - 1)
return
}
func reducedLatinSquare(n int, echo bool) uint64 {
if n <= 0 {
if echo {
fmt.Println("[]\n")
}
return 0
} else if n == 1 {
if echo {
fmt.Println("[1]\n")
}
return 1
}
rlatin := make(matrix, n)
for i := 0; i < n; i++ {
rlatin[i] = make([]int, n)
}
for j := 0; j < n; j++ {
rlatin[0][j] = j + 1
}
count := uint64(0)
var recurse func(i int)
recurse = func(i int) {
rows := dList(n, i)
outer:
for r := 0; r < len(rows); r++ {
copy(rlatin[i-1], rows[r])
for k := 0; k < i-1; k++ {
for j := 1; j < n; j++ {
if rlatin[k][j] == rlatin[i-1][j] {
if r < len(rows)-1 {
continue outer
} else if i > 2 {
return
}
}
}
}
if i < n {
recurse(i + 1)
} else {
count++
if echo {
printSquare(rlatin, n)
}
}
}
return
}
recurse(2)
return count
}
func printSquare(latin matrix, n int) {
for i := 0; i < n; i++ {
fmt.Println(latin[i])
}
fmt.Println()
}
func factorial(n uint64) uint64 {
if n == 0 {
return 1
}
prod := uint64(1)
for i := uint64(2); i <= n; i++ {
prod *= i
}
return prod
}
func main() {
fmt.Println("The four reduced latin squares of order 4 are:\n")
reducedLatinSquare(4, true)
fmt.Println("The size of the set of reduced latin squares for the following orders")
fmt.Println("and hence the total number of latin squares of these orders are:\n")
for n := uint64(1); n <= 6; n++ {
size := reducedLatinSquare(int(n), false)
f := factorial(n - 1)
f *= f * n * size
fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f)
}
}
| Option Strict On
Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))
Module Module1
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim u = a
a = b
b = u
End Sub
Sub PrintSquare(latin As Matrix)
For Each row In latin
Dim it = row.GetEnumerator
Console.Write("[")
If it.MoveNext Then
Console.Write(it.Current)
End If
While it.MoveNext
Console.Write(", ")
Console.Write(it.Current)
End While
Console.WriteLine("]")
Next
Console.WriteLine()
End Sub
Function DList(n As Integer, start As Integer) As Matrix
start -= 1 REM use 0 based indexes
Dim a = Enumerable.Range(0, n).ToArray
a(start) = a(0)
a(0) = start
Array.Sort(a, 1, a.Length - 1)
Dim first = a(1)
REM recursive closure permutes a[1:]
Dim r As New Matrix
Dim Recurse As Action(Of Integer) = Sub(last As Integer)
If last = first Then
REM bottom of recursion. you get here once for each permutation
REM test if permutation is deranged.
For j = 1 To a.Length - 1
Dim v = a(j)
If j = v Then
Return REM no, ignore it
End If
Next
REM yes, save a copy with 1 based indexing
Dim b = a.Select(Function(v) v + 1).ToArray
r.Add(b.ToList)
Return
End If
For i = last To 1 Step -1
Swap(a(i), a(last))
Recurse(last - 1)
Swap(a(i), a(last))
Next
End Sub
Recurse(n - 1)
Return r
End Function
Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong
If n <= 0 Then
If echo Then
Console.WriteLine("[]")
Console.WriteLine()
End If
Return 0
End If
If n = 1 Then
If echo Then
Console.WriteLine("[1]")
Console.WriteLine()
End If
Return 1
End If
Dim rlatin As New Matrix
For i = 0 To n - 1
rlatin.Add(New List(Of Integer))
For j = 0 To n - 1
rlatin(i).Add(0)
Next
Next
REM first row
For j = 0 To n - 1
rlatin(0)(j) = j + 1
Next
Dim count As ULong = 0
Dim Recurse As Action(Of Integer) = Sub(i As Integer)
Dim rows = DList(n, i)
For r = 0 To rows.Count - 1
rlatin(i - 1) = rows(r)
For k = 0 To i - 2
For j = 1 To n - 1
If rlatin(k)(j) = rlatin(i - 1)(j) Then
If r < rows.Count - 1 Then
GoTo outer
End If
If i > 2 Then
Return
End If
End If
Next
Next
If i < n Then
Recurse(i + 1)
Else
count += 1UL
If echo Then
PrintSquare(rlatin)
End If
End If
outer:
While False
REM empty
End While
Next
End Sub
REM remiain rows
Recurse(2)
Return count
End Function
Function Factorial(n As ULong) As ULong
If n <= 0 Then
Return 1
End If
Dim prod = 1UL
For i = 2UL To n
prod *= i
Next
Return prod
End Function
Sub Main()
Console.WriteLine("The four reduced latin squares of order 4 are:")
Console.WriteLine()
ReducedLatinSquares(4, True)
Console.WriteLine("The size of the set of reduced latin squares for the following orders")
Console.WriteLine("and hence the total number of latin squares of these orders are:")
Console.WriteLine()
For n = 1 To 6
Dim nu As ULong = CULng(n)
Dim size = ReducedLatinSquares(n, False)
Dim f = Factorial(nu - 1UL)
f *= f * nu * size
Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f)
Next
End Sub
End Module
|
Translate this program into VB but keep the logic exactly as in Go. | package main
import (
"fmt"
"regexp"
)
var bits = []string{
"0 0 0 1 1 0 1 ",
"0 0 1 1 0 0 1 ",
"0 0 1 0 0 1 1 ",
"0 1 1 1 1 0 1 ",
"0 1 0 0 0 1 1 ",
"0 1 1 0 0 0 1 ",
"0 1 0 1 1 1 1 ",
"0 1 1 1 0 1 1 ",
"0 1 1 0 1 1 1 ",
"0 0 0 1 0 1 1 ",
}
var (
lhs = make(map[string]int)
rhs = make(map[string]int)
)
var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}
const (
s = "# #"
m = " # # "
e = "# #"
d = "(?:#| ){7}"
)
func init() {
for i := 0; i <= 9; i++ {
lt := make([]byte, 7)
rt := make([]byte, 7)
for j := 0; j < 14; j += 2 {
if bits[i][j] == '1' {
lt[j/2] = '#'
rt[j/2] = ' '
} else {
lt[j/2] = ' '
rt[j/2] = '#'
}
}
lhs[string(lt)] = i
rhs[string(rt)] = i
}
}
func reverse(s string) string {
b := []byte(s)
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
func main() {
barcodes := []string{
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
}
expr := fmt.Sprintf(`^\s*%s(%s)(%s)(%s)(%s)(%s)(%s)%s(%s)(%s)(%s)(%s)(%s)(%s)%s\s*$`,
s, d, d, d, d, d, d, m, d, d, d, d, d, d, e)
rx := regexp.MustCompile(expr)
fmt.Println("UPC-A barcodes:")
for i, bc := range barcodes {
for j := 0; j <= 1; j++ {
if !rx.MatchString(bc) {
fmt.Printf("%2d: Invalid format\n", i+1)
break
}
codes := rx.FindStringSubmatch(bc)
digits := make([]int, 12)
var invalid, ok bool
for i := 1; i <= 6; i++ {
digits[i-1], ok = lhs[codes[i]]
if !ok {
invalid = true
}
digits[i+5], ok = rhs[codes[i+6]]
if !ok {
invalid = true
}
}
if invalid {
if j == 0 {
bc = reverse(bc)
continue
} else {
fmt.Printf("%2d: Invalid digit(s)\n", i+1)
break
}
}
sum := 0
for i, d := range digits {
sum += weights[i] * d
}
if sum%10 != 0 {
fmt.Printf("%2d: Checksum error\n", i+1)
break
} else {
ud := ""
if j == 1 {
ud = "(upside down)"
}
fmt.Printf("%2d: %v %s\n", i+1, digits, ud)
break
}
}
}
}
|
Option Explicit
Const m_limit ="# #"
Const m_middle=" # # "
Dim a,bnum,i,check,odic
a=array(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",_
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",_
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",_
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",_
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",_
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",_
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",_
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",_
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",_
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ")
bnum=Array("0001101","0011001","0010011","0111101","0100011"," 0110001","0101111","0111011","0110111","0001011")
Set oDic = WScript.CreateObject("scripting.dictionary")
For i=0 To 9:
odic.Add bin2dec(bnum(i),Asc("1")),i+1
odic.Add bin2dec(bnum(i),Asc("0")),-i-1
Next
For i=0 To UBound(a) : print pad(i+1,-2) & ": "& upc(a(i)) :Next
WScript.Quit(1)
Function bin2dec(ByVal B,a)
Dim n
While len(b)
n =n *2 - (asc(b)=a)
b=mid(b,2)
Wend
bin2dec= n And 127
End Function
Sub print(s):
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else pad= left(s& space(n),n) end if :end function
Function iif(t,a,b) If t Then iif=a Else iif=b End If :End Function
Function getnum(s,r)
Dim n,s1,r1
s1=Left(s,7)
s=Mid(s,8)
r1=r
Do
If r Then s1=StrReverse(s1)
n=bin2dec(s1,asc("#"))
If odic.exists(n) Then
getnum=odic(n)
Exit Function
Else
If r1<>r Then getnum=0:Exit Function
r=Not r
End If
Loop
End Function
Function getmarker(s,m)
getmarker= (InStr(s,m)= 1)
s=Mid(s,Len(m)+1)
End Function
Function checksum(ByVal s)
Dim n,i : n=0
do
n=n+(Asc(s)-48)*3
s=Mid(s,2)
n=n+(Asc(s)-48)*1
s=Mid(s,2)
Loop until Len(s)=0
checksum= ((n mod 10)=0)
End function
Function upc(ByVal s1)
Dim i,n,s,out,rev,j
s=Trim(s1)
If getmarker(s,m_limit)=False Then upc= "bad start marker ":Exit function
rev=False
out=""
For j= 0 To 1
For i=0 To 5
n=getnum(s,rev)
If n=0 Then upc= pad(out,16) & pad ("bad code",-10) & pad("pos "& i+j*6+1,-11): Exit Function
out=out & Abs(n)-1
Next
If j=0 Then If getmarker(s,m_middle)=False Then upc= "bad middle marker " & out :Exit Function
Next
If getmarker(s,m_limit)=False Then upc= "bad end marker " :Exit function
If rev Then out=strreverse(out)
upc= pad(out,16) & pad(iif (checksum(out),"valid","not valid"),-10)& pad(iif(rev,"reversed",""),-11)
End Function
|
Rewrite this program in VB while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
type xy struct {
x, y float64
}
const n = 1000
const scale = 100.
func d(p1, p2 xy) float64 {
return math.Hypot(p2.x-p1.x, p2.y-p1.y)
}
func main() {
rand.Seed(time.Now().Unix())
points := make([]xy, n)
for i := range points {
points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}
}
p1, p2 := closestPair(points)
fmt.Println(p1, p2)
fmt.Println("distance:", d(p1, p2))
}
func closestPair(points []xy) (p1, p2 xy) {
if len(points) < 2 {
panic("at least two points expected")
}
min := 2 * scale
for i, q1 := range points[:len(points)-1] {
for _, q2 := range points[i+1:] {
if dq := d(q1, q2); dq < min {
p1, p2 = q1, q2
min = dq
}
}
}
return
}
| Option Explicit
Private Type MyPoint
X As Single
Y As Single
End Type
Private Type MyPair
p1 As MyPoint
p2 As MyPoint
End Type
Sub Main()
Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long
Dim T#
Randomize Timer
Nb = 10
Do
ReDim points(1 To Nb)
For i = 1 To Nb
points(i).X = Rnd * Nb
points(i).Y = Rnd * Nb
Next
d = 1000000000000#
T = Timer
BF = BruteForce(points, d)
Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec."
Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y
Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y
Debug.Print "dist : " & d
Debug.Print "--------------------------------------------------"
Nb = Nb * 10
Loop While Nb <= 10000
End Sub
Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair
Dim i As Long, j As Long, d As Single, ClosestPair As MyPair
For i = 1 To UBound(p) - 1
For j = i + 1 To UBound(p)
d = Dist(p(i), p(j))
If d < mindist Then
mindist = d
ClosestPair.p1 = p(i)
ClosestPair.p2 = p(j)
End If
Next
Next
BruteForce = ClosestPair
End Function
Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single
Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)
End Function
|
Change the programming language of this snippet from Go to VB without modifying what it does. | package main
import (
"fmt"
"unsafe"
)
func main() {
myVar := 3.14
myPointer := &myVar
fmt.Println("Address:", myPointer, &myVar)
fmt.Printf("Address: %p %p\n", myPointer, &myVar)
var addr64 int64
var addr32 int32
ptr := unsafe.Pointer(myPointer)
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
addr64 = int64(uintptr(ptr))
fmt.Printf("Pointer stored in int64: %#016x\n", addr64)
}
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {
addr32 = int32(uintptr(ptr))
fmt.Printf("Pointer stored in int32: %#08x\n", addr32)
}
addr := uintptr(ptr)
fmt.Printf("Pointer stored in uintptr: %#08x\n", addr)
fmt.Println("value as float:", myVar)
i := (*int32)(unsafe.Pointer(&myVar))
fmt.Printf("value as int32: %#08x\n", *i)
}
| Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
MyVar = 10
TheAddress = varptr(MyVar)
MEMSET(TheAddress, 102, SizeOf(byte))
showmessage "MyVar = " + str$(MyVar)
MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))
showmessage "SecVar = " + str$(SecVar)
|
Please provide an equivalent version of this Go code in VB. | package main
import (
"fmt"
"unsafe"
)
func main() {
myVar := 3.14
myPointer := &myVar
fmt.Println("Address:", myPointer, &myVar)
fmt.Printf("Address: %p %p\n", myPointer, &myVar)
var addr64 int64
var addr32 int32
ptr := unsafe.Pointer(myPointer)
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
addr64 = int64(uintptr(ptr))
fmt.Printf("Pointer stored in int64: %#016x\n", addr64)
}
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {
addr32 = int32(uintptr(ptr))
fmt.Printf("Pointer stored in int32: %#08x\n", addr32)
}
addr := uintptr(ptr)
fmt.Printf("Pointer stored in uintptr: %#08x\n", addr)
fmt.Println("value as float:", myVar)
i := (*int32)(unsafe.Pointer(&myVar))
fmt.Printf("value as int32: %#08x\n", *i)
}
| Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
MyVar = 10
TheAddress = varptr(MyVar)
MEMSET(TheAddress, 102, SizeOf(byte))
showmessage "MyVar = " + str$(MyVar)
MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))
showmessage "SecVar = " + str$(SecVar)
|
Translate this program into VB but keep the logic exactly as in Go. | package main
type animal struct {
alive bool
}
type dog struct {
animal
obedienceTrained bool
}
type cat struct {
animal
litterBoxTrained bool
}
type lab struct {
dog
color string
}
type collie struct {
dog
catchesFrisbee bool
}
func main() {
var pet lab
pet.alive = true
pet.obedienceTrained = false
pet.color = "yellow"
}
| Class Animal
End Class
Class Dog
Inherits Animal
End Class
Class Lab
Inherits Dog
End Class
Class Collie
Inherits Dog
End Class
Class Cat
Inherits Animal
End Class
|
Generate a VB translation of this Go snippet without changing its computational steps. |
var x map[string]int
x = make(map[string]int)
x = make(map[string]int, 42)
x["foo"] = 3
y1 := x["bar"]
y2, ok := x["bar"]
delete(x, "foo")
x = map[string]int{
"foo": 2, "bar": 42, "baz": -1,
}
| Option Explicit
Sub Test()
Dim h As Object
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
Debug.Print h.Item("A")
h.Item("C") = 4
h.Key("C") = "D"
Debug.Print h.exists("C")
h.Remove "B"
Debug.Print h.Count
h.RemoveAll
Debug.Print h.Count
End Sub
|
Generate an equivalent VB version of this Go code. | package main
import (
"github.com/fogleman/gg"
"math"
)
const tau = 2 * math.Pi
func hsb2rgb(hue, sat, bri float64) (r, g, b int) {
u := int(bri*255 + 0.5)
if sat == 0 {
r, g, b = u, u, u
} else {
h := (hue - math.Floor(hue)) * 6
f := h - math.Floor(h)
p := int(bri*(1-sat)*255 + 0.5)
q := int(bri*(1-sat*f)*255 + 0.5)
t := int(bri*(1-sat*(1-f))*255 + 0.5)
switch int(h) {
case 0:
r, g, b = u, t, p
case 1:
r, g, b = q, u, p
case 2:
r, g, b = p, u, t
case 3:
r, g, b = p, q, u
case 4:
r, g, b = t, p, u
case 5:
r, g, b = u, p, q
}
}
return
}
func colorWheel(dc *gg.Context) {
width, height := dc.Width(), dc.Height()
centerX, centerY := width/2, height/2
radius := centerX
if centerY < radius {
radius = centerY
}
for y := 0; y < height; y++ {
dy := float64(y - centerY)
for x := 0; x < width; x++ {
dx := float64(x - centerX)
dist := math.Sqrt(dx*dx + dy*dy)
if dist <= float64(radius) {
theta := math.Atan2(dy, dx)
hue := (theta + math.Pi) / tau
r, g, b := hsb2rgb(hue, 1, 1)
dc.SetRGB255(r, g, b)
dc.SetPixel(x, y)
}
}
}
}
func main() {
const width, height = 480, 480
dc := gg.NewContext(width, height)
dc.SetRGB(1, 1, 1)
dc.Clear()
colorWheel(dc)
dc.SavePNG("color_wheel.png")
}
| Option explicit
Class ImgClass
Private ImgL,ImgH,ImgDepth,bkclr,loc,tt
private xmini,xmaxi,ymini,ymaxi,dirx,diry
public ImgArray()
private filename
private Palette,szpal
public property get xmin():xmin=xmini:end property
public property get ymin():ymin=ymini:end property
public property get xmax():xmax=xmaxi:end property
public property get ymax():ymax=ymaxi:end property
public property let depth(x)
if x<>8 and x<>32 then err.raise 9
Imgdepth=x
end property
public sub set0 (x0,y0)
if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9
xmini=-x0
ymini=-y0
xmaxi=xmini+imgl-1
ymaxi=ymini+imgh-1
end sub
Public Default Function Init(name,w,h,orient,dep,bkg,mipal)
dim i,j
ImgL=w
ImgH=h
tt=timer
loc=getlocale
set0 0,0
redim imgArray(ImgL-1,ImgH-1)
bkclr=bkg
if bkg<>0 then
for i=0 to ImgL-1
for j=0 to ImgH-1
imgarray(i,j)=bkg
next
next
end if
Select Case orient
Case 1: dirx=1 : diry=1
Case 2: dirx=-1 : diry=1
Case 3: dirx=-1 : diry=-1
Case 4: dirx=1 : diry=-1
End select
filename=name
ImgDepth =dep
if imgdepth=8 then
loadpal(mipal)
end if
set init=me
end function
private sub loadpal(mipale)
if isarray(mipale) Then
palette=mipale
szpal=UBound(mipale)+1
Else
szpal=256
, not relevant
End if
End Sub
Private Sub Class_Terminate
if err<>0 then wscript.echo "Error " & err.number
wscript.echo "copying image to bmp file"
savebmp
wscript.echo "opening " & filename & " with your default bmp viewer"
CreateObject("Shell.Application").ShellExecute filename
wscript.echo timer-tt & " iseconds"
End Sub
function long2wstr( x)
dim k1,k2,x1
k1= (x and &hffff&)
k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0))
long2wstr=chrw(k1) & chrw(k2)
end function
function int2wstr(x)
int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))
End Function
Public Sub SaveBMP
Dim s,ostream, x,y,loc
const hdrs=54
dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4)
dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0
with CreateObject("ADODB.Stream")
.Charset = "UTF-16LE"
.Type = 2
.open
.writetext ChrW(&h4d42)
.writetext long2wstr(hdrs+palsize+bms)
.writetext long2wstr(0)
.writetext long2wstr (hdrs+palsize)
.writetext long2wstr(40)
.writetext long2wstr(Imgl)
.writetext long2wstr(imgh)
.writetext int2wstr(1)
.writetext int2wstr(imgdepth)
.writetext long2wstr(&H0)
.writetext long2wstr(bms)
.writetext long2wstr(&Hc4e)
.writetext long2wstr(&hc43)
.writetext long2wstr(szpal)
.writetext long2wstr(&H0)
Dim x1,x2,y1,y2
If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1
If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1
Select Case imgdepth
Case 32
For y=y1 To y2 step diry
For x=x1 To x2 Step dirx
.writetext long2wstr(Imgarray(x,y))
Next
Next
Case 8
For x=0 to szpal-1
.writetext long2wstr(palette(x))
Next
dim pad:pad=ImgL mod 4
For y=y1 to y2 step diry
For x=x1 To x2 step dirx*2
.writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))
Next
if pad and 1 then .writetext chrw(ImgArray(x2,y))
if pad >1 then .writetext chrw(0)
Next
Case Else
WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits"
End Select
Dim outf:Set outf= CreateObject("ADODB.Stream")
outf.Type = 1
outf.Open
.position=2
.CopyTo outf
.close
outf.savetofile filename,2
outf.close
end with
End Sub
end class
function hsv2rgb( Hue, Sat, Value)
dim Angle, Radius,Ur,Vr,Wr,Rdim
dim r,g,b, rgb
Angle = (Hue-150) *0.01745329251994329576923690768489
Ur = Value * 2.55
Radius = Ur * tan(Sat *0.01183199)
Vr = Radius * cos(Angle) *0.70710678
Wr = Radius * sin(Angle) *0.40824829
r = (Ur - Vr - Wr)
g = (Ur + Vr - Wr)
b = (Ur + Wr + Wr)
if r >255 then
Rdim = (Ur - 255) / (Vr + Wr)
r = 255
g = Ur + (Vr - Wr) * Rdim
b = Ur + 2 * Wr * Rdim
elseif r < 0 then
Rdim = Ur / (Vr + Wr)
r = 0
g = Ur + (Vr - Wr) * Rdim
b = Ur + 2 * Wr * Rdim
end if
if g >255 then
Rdim = (255 - Ur) / (Vr - Wr)
r = Ur - (Vr + Wr) * Rdim
g = 255
b = Ur + 2 * Wr * Rdim
elseif g<0 then
Rdim = -Ur / (Vr - Wr)
r = Ur - (Vr + Wr) * Rdim
g = 0
b = Ur + 2 * Wr * Rdim
end if
if b>255 then
Rdim = (255 - Ur) / (Wr + Wr)
r = Ur - (Vr + Wr) * Rdim
g = Ur + (Vr - Wr) * Rdim
b = 255
elseif b<0 then
Rdim = -Ur / (Wr + Wr)
r = Ur - (Vr + Wr) * Rdim
g = Ur + (Vr - Wr) * Rdim
b = 0
end If
hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff)
end function
function ang(col,row)
if col =0 then
if row<0 then ang=90 else ang=270 end if
else
if col>0 then
ang=atn(-row/col)*57.2957795130
else
ang=(atn(row/-col)*57.2957795130)+180
end if
end if
ang=(ang+360) mod 360
end function
Dim X,row,col,fn,tt,hr,sat,row2
const h=160
const w=160
const rad=159
const r2=25500
tt=timer
fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\testwchr.bmp"
Set X = (New ImgClass)(fn,w*2,h*2,1,32,0,0)
x.set0 w,h
for row=x.xmin+1 to x.xmax
row2=row*row
hr=int(Sqr(r2-row2))
For col=hr To 159
Dim a:a=((col\16 +row\16) And 1)* &hffffff
x.imgArray(col+160,row+160)=a
x.imgArray(-col+160,row+160)=a
next
for col=-hr to hr
sat=100-sqr(row2+col*col)/rad *50
x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat)
next
next
Set X = Nothing
|
Rewrite this program in VB while keeping its functionality equivalent to the Go version. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func contains(list []int, value int) bool {
for _, v := range list {
if v == value {
return true
}
}
return false
}
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := range bwords {
s := string(bword)
if utf8.RuneCountInString(s) > 10 {
words = append(words, s)
}
}
vowelIndices := []int{0, 4, 8, 14, 20}
wordGroups := make([][]string, 12)
for _, word := range words {
letters := make([]int, 26)
for _, c := range word {
index := c - 97
if index >= 0 && index < 26 {
letters[index]++
}
}
eligible := true
uc := 0
for i := 0; i < 26; i++ {
if !contains(vowelIndices, i) {
if letters[i] > 1 {
eligible = false
break
} else if letters[i] == 1 {
uc++
}
}
}
if eligible {
wordGroups[uc] = append(wordGroups[uc], word)
}
}
for i := 11; i >= 0; i-- {
count := len(wordGroups[i])
if count > 0 {
s := "s"
if count == 1 {
s = ""
}
fmt.Printf("%d word%s found with %d unique consonants:\n", count, s, i)
for j := 0; j < count; j++ {
fmt.Printf("%-15s", wordGroups[i][j])
if j > 0 && (j+1)%5 == 0 {
fmt.Println()
}
}
fmt.Println()
if count%5 != 0 {
fmt.Println()
}
}
}
}
| with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
dim b(25)
dim c(128)
with new regexp
.pattern="([^aeiou])"
.global=true
for each i in a
if len(trim(i))>10 then
set matches= .execute(i)
rep=false
for each m in matches
x=asc(m)
c(x)=c(x)+1
if c(x)>1 then rep=true :exit for
next
erase c
if not rep then
x1=matches.count
b(x1)=b(x1)&" "&i
end if
end if
next
end with
for i=25 to 0 step -1
if b(i)<>"" then wscript.echo i & " "& b(i) & vbcrlf
next
|
Write a version of this Go function in VB with identical behavior. | package main
import (
"bufio"
"fmt"
"math"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type cell struct {
isMine bool
display byte
}
const lMargin = 4
var (
grid [][]cell
mineCount int
minesMarked int
isGameOver bool
)
var scanner = bufio.NewScanner(os.Stdin)
func makeGrid(n, m int) {
if n <= 0 || m <= 0 {
panic("Grid dimensions must be positive.")
}
grid = make([][]cell, n)
for i := 0; i < n; i++ {
grid[i] = make([]cell, m)
for j := 0; j < m; j++ {
grid[i][j].display = '.'
}
}
min := int(math.Round(float64(n*m) * 0.1))
max := int(math.Round(float64(n*m) * 0.2))
mineCount = min + rand.Intn(max-min+1)
rm := mineCount
for rm > 0 {
x, y := rand.Intn(n), rand.Intn(m)
if !grid[x][y].isMine {
rm--
grid[x][y].isMine = true
}
}
minesMarked = 0
isGameOver = false
}
func displayGrid(isEndOfGame bool) {
if !isEndOfGame {
fmt.Println("Grid has", mineCount, "mine(s),", minesMarked, "mine(s) marked.")
}
margin := strings.Repeat(" ", lMargin)
fmt.Print(margin, " ")
for i := 1; i <= len(grid); i++ {
fmt.Print(i)
}
fmt.Println()
fmt.Println(margin, strings.Repeat("-", len(grid)))
for y := 0; y < len(grid[0]); y++ {
fmt.Printf("%*d:", lMargin, y+1)
for x := 0; x < len(grid); x++ {
fmt.Printf("%c", grid[x][y].display)
}
fmt.Println()
}
}
func endGame(msg string) {
isGameOver = true
fmt.Println(msg)
ans := ""
for ans != "y" && ans != "n" {
fmt.Print("Another game (y/n)? : ")
scanner.Scan()
ans = strings.ToLower(scanner.Text())
}
if scanner.Err() != nil || ans == "n" {
return
}
makeGrid(6, 4)
displayGrid(false)
}
func resign() {
found := 0
for y := 0; y < len(grid[0]); y++ {
for x := 0; x < len(grid); x++ {
if grid[x][y].isMine {
if grid[x][y].display == '?' {
grid[x][y].display = 'Y'
found++
} else if grid[x][y].display != 'x' {
grid[x][y].display = 'N'
}
}
}
}
displayGrid(true)
msg := fmt.Sprint("You found ", found, " out of ", mineCount, " mine(s).")
endGame(msg)
}
func usage() {
fmt.Println("h or ? - this help,")
fmt.Println("c x y - clear cell (x,y),")
fmt.Println("m x y - marks (toggles) cell (x,y),")
fmt.Println("n - start a new game,")
fmt.Println("q - quit/resign the game,")
fmt.Println("where x is the (horizontal) column number and y is the (vertical) row number.\n")
}
func markCell(x, y int) {
if grid[x][y].display == '?' {
minesMarked--
grid[x][y].display = '.'
} else if grid[x][y].display == '.' {
minesMarked++
grid[x][y].display = '?'
}
}
func countAdjMines(x, y int) int {
count := 0
for j := y - 1; j <= y+1; j++ {
if j >= 0 && j < len(grid[0]) {
for i := x - 1; i <= x+1; i++ {
if i >= 0 && i < len(grid) {
if grid[i][j].isMine {
count++
}
}
}
}
}
return count
}
func clearCell(x, y int) bool {
if x >= 0 && x < len(grid) && y >= 0 && y < len(grid[0]) {
if grid[x][y].display == '.' {
if !grid[x][y].isMine {
count := countAdjMines(x, y)
if count > 0 {
grid[x][y].display = string(48 + count)[0]
} else {
grid[x][y].display = ' '
clearCell(x+1, y)
clearCell(x+1, y+1)
clearCell(x, y+1)
clearCell(x-1, y+1)
clearCell(x-1, y)
clearCell(x-1, y-1)
clearCell(x, y-1)
clearCell(x+1, y-1)
}
} else {
grid[x][y].display = 'x'
fmt.Println("Kaboom! You lost!")
return false
}
}
}
return true
}
func testForWin() bool {
isCleared := false
if minesMarked == mineCount {
isCleared = true
for x := 0; x < len(grid); x++ {
for y := 0; y < len(grid[0]); y++ {
if grid[x][y].display == '.' {
isCleared = false
}
}
}
}
if isCleared {
fmt.Println("You won!")
}
return isCleared
}
func splitAction(action string) (int, int, bool) {
fields := strings.Fields(action)
if len(fields) != 3 {
return 0, 0, false
}
x, err := strconv.Atoi(fields[1])
if err != nil || x < 1 || x > len(grid) {
return 0, 0, false
}
y, err := strconv.Atoi(fields[2])
if err != nil || y < 1 || y > len(grid[0]) {
return 0, 0, false
}
return x, y, true
}
func main() {
rand.Seed(time.Now().UnixNano())
usage()
makeGrid(6, 4)
displayGrid(false)
for !isGameOver {
fmt.Print("\n>")
scanner.Scan()
action := strings.ToLower(scanner.Text())
if scanner.Err() != nil || len(action) == 0 {
continue
}
switch action[0] {
case 'h', '?':
usage()
case 'n':
makeGrid(6, 4)
displayGrid(false)
case 'c':
x, y, ok := splitAction(action)
if !ok {
continue
}
if clearCell(x-1, y-1) {
displayGrid(false)
if testForWin() {
resign()
}
} else {
resign()
}
case 'm':
x, y, ok := splitAction(action)
if !ok {
continue
}
markCell(x-1, y-1)
displayGrid(false)
if testForWin() {
resign()
}
case 'q':
resign()
}
}
}
| Option Explicit
Public vTime As Single
Public PlaysCount As Long
Sub Main_MineSweeper()
Dim Userf As New cMinesweeper
Userf.Show 0, True
End Sub
|
Produce a functionally identical VB code for the snippet given in Go. | package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
var ten = big.NewInt(10)
var twenty = big.NewInt(20)
var hundred = big.NewInt(100)
func sqrt(n float64, limit int) {
if n < 0 {
log.Fatal("Number cannot be negative")
}
count := 0
for n != math.Trunc(n) {
n *= 100
count--
}
i := big.NewInt(int64(n))
j := new(big.Int).Sqrt(i)
count += len(j.String())
k := new(big.Int).Set(j)
d := new(big.Int).Set(j)
t := new(big.Int)
digits := 0
var sb strings.Builder
for digits < limit {
sb.WriteString(d.String())
t.Mul(k, d)
i.Sub(i, t)
i.Mul(i, hundred)
k.Mul(j, twenty)
d.Set(one)
for d.Cmp(ten) <= 0 {
t.Add(k, d)
t.Mul(t, d)
if t.Cmp(i) > 0 {
d.Sub(d, one)
break
}
d.Add(d, one)
}
j.Mul(j, ten)
j.Add(j, d)
k.Add(k, d)
digits = digits + 1
}
root := strings.TrimRight(sb.String(), "0")
if len(root) == 0 {
root = "0"
}
if count > 0 {
root = root[0:count] + "." + root[count:]
} else if count == 0 {
root = "0." + root
} else {
root = "0." + strings.Repeat("0", -count) + root
}
root = strings.TrimSuffix(root, ".")
fmt.Println(root)
}
func main() {
numbers := []float64{2, 0.2, 10.89, 625, 0.0001}
digits := []int{500, 80, 8, 8, 8}
for i, n := range numbers {
fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n)
sqrt(n, digits[i])
fmt.Println()
}
}
| Imports System.Math, System.Console, BI = System.Numerics.BigInteger
Module Module1
Sub Main(ByVal args As String())
Dim i, j, k, d As BI : i = 2
j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j
Dim n As Integer = -1, n0 As Integer = -1,
st As DateTime = DateTime.Now
If args.Length > 0 Then Integer.TryParse(args(0), n)
If n > 0 Then n0 = n Else n = 1
Do
Write(d) : i = (i - k * d) * 100 : k = 20 * j
For d = 1 To 10
If (k + d) * d > i Then d -= 1 : Exit For
Next
j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1
Loop While n > 0
If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st)
End Sub
End Module
|
Write a version of this Go function in VB with identical behavior. | package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
var ten = big.NewInt(10)
var twenty = big.NewInt(20)
var hundred = big.NewInt(100)
func sqrt(n float64, limit int) {
if n < 0 {
log.Fatal("Number cannot be negative")
}
count := 0
for n != math.Trunc(n) {
n *= 100
count--
}
i := big.NewInt(int64(n))
j := new(big.Int).Sqrt(i)
count += len(j.String())
k := new(big.Int).Set(j)
d := new(big.Int).Set(j)
t := new(big.Int)
digits := 0
var sb strings.Builder
for digits < limit {
sb.WriteString(d.String())
t.Mul(k, d)
i.Sub(i, t)
i.Mul(i, hundred)
k.Mul(j, twenty)
d.Set(one)
for d.Cmp(ten) <= 0 {
t.Add(k, d)
t.Mul(t, d)
if t.Cmp(i) > 0 {
d.Sub(d, one)
break
}
d.Add(d, one)
}
j.Mul(j, ten)
j.Add(j, d)
k.Add(k, d)
digits = digits + 1
}
root := strings.TrimRight(sb.String(), "0")
if len(root) == 0 {
root = "0"
}
if count > 0 {
root = root[0:count] + "." + root[count:]
} else if count == 0 {
root = "0." + root
} else {
root = "0." + strings.Repeat("0", -count) + root
}
root = strings.TrimSuffix(root, ".")
fmt.Println(root)
}
func main() {
numbers := []float64{2, 0.2, 10.89, 625, 0.0001}
digits := []int{500, 80, 8, 8, 8}
for i, n := range numbers {
fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n)
sqrt(n, digits[i])
fmt.Println()
}
}
| Imports System.Math, System.Console, BI = System.Numerics.BigInteger
Module Module1
Sub Main(ByVal args As String())
Dim i, j, k, d As BI : i = 2
j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j
Dim n As Integer = -1, n0 As Integer = -1,
st As DateTime = DateTime.Now
If args.Length > 0 Then Integer.TryParse(args(0), n)
If n > 0 Then n0 = n Else n = 1
Do
Write(d) : i = (i - k * d) * 100 : k = 20 * j
For d = 1 To 10
If (k + d) * d > i Then d -= 1 : Exit For
Next
j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1
Loop While n > 0
If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st)
End Sub
End Module
|
Produce a language-to-language conversion: from Go to VB, same semantics. | package main
import (
"fmt"
"rcu"
)
func nonDescending(p int) bool {
var digits []int
for p > 0 {
digits = append(digits, p%10)
p = p / 10
}
for i := 0; i < len(digits)-1; i++ {
if digits[i+1] > digits[i] {
return false
}
}
return true
}
func main() {
primes := rcu.Primes(999)
var nonDesc []int
for _, p := range primes {
if nonDescending(p) {
nonDesc = append(nonDesc, p)
}
}
fmt.Println("Primes below 1,000 with digits in non-decreasing order:")
for i, n := range nonDesc {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n%d such primes found.\n", len(nonDesc))
}
| Imports System.Linq
Imports System.Collections.Generic
Imports System.Console
Imports System.Math
Module Module1
Dim ba As Integer
Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)
Dim flags(lim) As Boolean, j As Integer : Yield 2
For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3
Dim d As Integer = 8, sq As Integer = 9
While sq <= lim
If Not flags(j) Then
Yield j : Dim i As Integer = j << 1
For k As Integer = sq To lim step i : flags(k) = True : Next
End If
j += 2 : d += 8 : sq += d : End While
While j <= lim
If Not flags(j) Then Yield j
j += 2 : End While
End Function
Function from10(ByVal b As Integer) As String
Dim res As String = "", re As Integer
While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res
End Function
Function to10(ByVal s As String) As Integer
Dim res As Integer = 0
For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res
End Function
Function nd(ByVal s As String) As Boolean
If s.Length < 2 Then Return True
Dim l As Char = s(0)
For i As Integer = 1 To s.Length - 1
If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)
Next : Return True
End Function
Sub Main(ByVal args As String())
Dim c As Integer, lim As Integer = 1000, s As String
For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }
ba = b : c = 0 : For Each a As Integer In Primes(lim)
s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, ""))
Next
WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim))
Next
End Sub
End Module
|
Write a version of this Go function in VB with identical behavior. | package main
import (
"fmt"
"rcu"
)
func nonDescending(p int) bool {
var digits []int
for p > 0 {
digits = append(digits, p%10)
p = p / 10
}
for i := 0; i < len(digits)-1; i++ {
if digits[i+1] > digits[i] {
return false
}
}
return true
}
func main() {
primes := rcu.Primes(999)
var nonDesc []int
for _, p := range primes {
if nonDescending(p) {
nonDesc = append(nonDesc, p)
}
}
fmt.Println("Primes below 1,000 with digits in non-decreasing order:")
for i, n := range nonDesc {
fmt.Printf("%3d ", n)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\n%d such primes found.\n", len(nonDesc))
}
| Imports System.Linq
Imports System.Collections.Generic
Imports System.Console
Imports System.Math
Module Module1
Dim ba As Integer
Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer)
Dim flags(lim) As Boolean, j As Integer : Yield 2
For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3
Dim d As Integer = 8, sq As Integer = 9
While sq <= lim
If Not flags(j) Then
Yield j : Dim i As Integer = j << 1
For k As Integer = sq To lim step i : flags(k) = True : Next
End If
j += 2 : d += 8 : sq += d : End While
While j <= lim
If Not flags(j) Then Yield j
j += 2 : End While
End Function
Function from10(ByVal b As Integer) As String
Dim res As String = "", re As Integer
While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res
End Function
Function to10(ByVal s As String) As Integer
Dim res As Integer = 0
For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res
End Function
Function nd(ByVal s As String) As Boolean
If s.Length < 2 Then Return True
Dim l As Char = s(0)
For i As Integer = 1 To s.Length - 1
If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i)
Next : Return True
End Function
Sub Main(ByVal args As String())
Dim c As Integer, lim As Integer = 1000, s As String
For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }
ba = b : c = 0 : For Each a As Integer In Primes(lim)
s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, ""))
Next
WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim))
Next
End Sub
End Module
|
Write the same algorithm in VB as shown in this Go implementation. | package main
import (
"fmt"
"image"
"reflect"
)
type t struct {
X int
next *t
}
func main() {
report(t{})
report(image.Point{})
}
func report(x interface{}) {
t := reflect.TypeOf(x)
n := t.NumField()
fmt.Printf("Type %v has %d fields:\n", t, n)
fmt.Println("Name Type Exported")
for i := 0; i < n; i++ {
f := t.Field(i)
fmt.Printf("%-8s %-8v %-8t\n",
f.Name,
f.Type,
f.PkgPath == "",
)
}
fmt.Println()
}
| Imports System.Reflection
Module Module1
Class TestClass
Private privateField = 7
Public ReadOnly Property PublicNumber = 4
Private ReadOnly Property PrivateNumber = 2
End Class
Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
Return From p In obj.GetType().GetProperties(flags)
Where p.GetIndexParameters().Length = 0
Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}
End Function
Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})
End Function
Sub Main()
Dim t As New TestClass()
Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance
For Each prop In GetPropertyValues(t, flags)
Console.WriteLine(prop)
Next
For Each field In GetFieldValues(t, flags)
Console.WriteLine(field)
Next
End Sub
End Module
|
Ensure the translated VB code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"strings"
)
const text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.`
type formatter struct {
text [][]string
width []int
}
func newFormatter(text string) *formatter {
var f formatter
for _, line := range strings.Split(text, "\n") {
words := strings.Split(line, "$")
for words[len(words)-1] == "" {
words = words[:len(words)-1]
}
f.text = append(f.text, words)
for i, word := range words {
if i == len(f.width) {
f.width = append(f.width, len(word))
} else if len(word) > f.width[i] {
f.width[i] = len(word)
}
}
}
return &f
}
const (
left = iota
middle
right
)
func (f formatter) print(j int) {
for _, line := range f.text {
for i, word := range line {
fmt.Printf("%-*s ", f.width[i], fmt.Sprintf("%*s",
len(word)+(f.width[i]-len(word))*j/2, word))
}
fmt.Println("")
}
fmt.Println("")
}
func main() {
f := newFormatter(text)
f.print(left)
f.print(middle)
f.print(right)
}
| Dim MText as QMemorystream
MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
MText.WriteLine "are$delineated$by$a$single$
MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
MText.WriteLine "column$are$separated$by$at$least$one$space."
MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column."
DefStr TextLeft, TextRight, TextCenter
DefStr MLine, LWord, Newline = chr$(13)+chr$(10)
DefInt ColWidth(100), ColCount
DefSng NrSpaces
MText.position = 0
for x = 0 to MText.linecount -1
MLine = MText.ReadLine
for y = 0 to Tally(MLine, "$")
LWord = Field$(MLine, "$", y+1)
ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y))
next
next
MText.position = 0
for x = 0 to MText.linecount -1
MLine = MText.ReadLine
for y = 0 to Tally(MLine, "$")
LWord = Field$(MLine, "$", y+1)
NrSpaces = ColWidth(y) - len(LWord)
TextLeft = TextLeft + LWord + Space$(NrSpaces+1)
TextRight = TextRight + Space$(NrSpaces+1) + LWord
TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2))
next
TextLeft = TextLeft + Newline
TextRight = TextRight + Newline
TextCenter = TextCenter + Newline
next
|
Maintain the same structure and functionality when rewriting this code in VB. | package main
import (
"fmt"
"log"
"net"
"net/url"
)
func main() {
for _, in := range []string{
"foo:
"urn:example:animal:ferret:nose",
"jdbc:mysql:
"ftp:
"http:
"ldap:
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet:
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh:
"https:
"http:
} {
fmt.Println(in)
u, err := url.Parse(in)
if err != nil {
log.Println(err)
continue
}
if in != u.String() {
fmt.Printf("Note: reassmebles as %q\n", u)
}
printURL(u)
}
}
func printURL(u *url.URL) {
fmt.Println(" Scheme:", u.Scheme)
if u.Opaque != "" {
fmt.Println(" Opaque:", u.Opaque)
}
if u.User != nil {
fmt.Println(" Username:", u.User.Username())
if pwd, ok := u.User.Password(); ok {
fmt.Println(" Password:", pwd)
}
}
if u.Host != "" {
if host, port, err := net.SplitHostPort(u.Host); err == nil {
fmt.Println(" Host:", host)
fmt.Println(" Port:", port)
} else {
fmt.Println(" Host:", u.Host)
}
}
if u.Path != "" {
fmt.Println(" Path:", u.Path)
}
if u.RawQuery != "" {
fmt.Println(" RawQuery:", u.RawQuery)
m, err := url.ParseQuery(u.RawQuery)
if err == nil {
for k, v := range m {
fmt.Printf(" Key: %q Values: %q\n", k, v)
}
}
}
if u.Fragment != "" {
fmt.Println(" Fragment:", u.Fragment)
}
}
| Function parse_url(url)
parse_url = "URL: " & url
If InStr(url,"//") Then
scheme = Split(url,"//")
parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1)
domain = Split(scheme(1),"/")
If InStr(domain(0),"@") Then
cred = Split(domain(0),"@")
If InStr(cred(0),".") Then
username = Mid(cred(0),1,InStr(1,cred(0),".")-1)
password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),"."))
ElseIf InStr(cred(0),":") Then
username = Mid(cred(0),1,InStr(1,cred(0),":")-1)
password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":"))
End If
parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_
"Password: " & password
If InStr(cred(1),":") Then
host = Mid(cred(1),1,InStr(1,cred(1),":")-1)
port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & cred(1)
End If
ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then
host = Mid(domain(0),1,InStr(1,domain(0),":")-1)
port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then
host = Mid(domain(0),1,InStr(1,domain(0),"]"))
port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & domain(0)
End If
If UBound(domain) > 0 Then
For i = 1 To UBound(domain)
If i < UBound(domain) Then
path = path & domain(i) & "/"
ElseIf InStr(domain(i),"?") Then
path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1)
If InStr(domain(i),"#") Then
query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1)
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment
Else
query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?"))
path = path & vbcrlf & "Query: " & query
End If
ElseIf InStr(domain(i),"#") Then
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_
"Fragment: " & fragment
Else
path = path & domain(i)
End If
Next
parse_url = parse_url & vbCrLf & "Path: " & path
End If
ElseIf InStr(url,":") Then
scheme = Mid(url,1,InStr(1,url,":")-1)
path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":"))
parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path
Else
parse_url = parse_url & vbcrlf & "Invalid!!!"
End If
End Function
WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
|
Generate a VB translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"log"
"net"
"net/url"
)
func main() {
for _, in := range []string{
"foo:
"urn:example:animal:ferret:nose",
"jdbc:mysql:
"ftp:
"http:
"ldap:
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet:
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh:
"https:
"http:
} {
fmt.Println(in)
u, err := url.Parse(in)
if err != nil {
log.Println(err)
continue
}
if in != u.String() {
fmt.Printf("Note: reassmebles as %q\n", u)
}
printURL(u)
}
}
func printURL(u *url.URL) {
fmt.Println(" Scheme:", u.Scheme)
if u.Opaque != "" {
fmt.Println(" Opaque:", u.Opaque)
}
if u.User != nil {
fmt.Println(" Username:", u.User.Username())
if pwd, ok := u.User.Password(); ok {
fmt.Println(" Password:", pwd)
}
}
if u.Host != "" {
if host, port, err := net.SplitHostPort(u.Host); err == nil {
fmt.Println(" Host:", host)
fmt.Println(" Port:", port)
} else {
fmt.Println(" Host:", u.Host)
}
}
if u.Path != "" {
fmt.Println(" Path:", u.Path)
}
if u.RawQuery != "" {
fmt.Println(" RawQuery:", u.RawQuery)
m, err := url.ParseQuery(u.RawQuery)
if err == nil {
for k, v := range m {
fmt.Printf(" Key: %q Values: %q\n", k, v)
}
}
}
if u.Fragment != "" {
fmt.Println(" Fragment:", u.Fragment)
}
}
| Function parse_url(url)
parse_url = "URL: " & url
If InStr(url,"//") Then
scheme = Split(url,"//")
parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1)
domain = Split(scheme(1),"/")
If InStr(domain(0),"@") Then
cred = Split(domain(0),"@")
If InStr(cred(0),".") Then
username = Mid(cred(0),1,InStr(1,cred(0),".")-1)
password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),"."))
ElseIf InStr(cred(0),":") Then
username = Mid(cred(0),1,InStr(1,cred(0),":")-1)
password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":"))
End If
parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_
"Password: " & password
If InStr(cred(1),":") Then
host = Mid(cred(1),1,InStr(1,cred(1),":")-1)
port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & cred(1)
End If
ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then
host = Mid(domain(0),1,InStr(1,domain(0),":")-1)
port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then
host = Mid(domain(0),1,InStr(1,domain(0),"]"))
port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & domain(0)
End If
If UBound(domain) > 0 Then
For i = 1 To UBound(domain)
If i < UBound(domain) Then
path = path & domain(i) & "/"
ElseIf InStr(domain(i),"?") Then
path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1)
If InStr(domain(i),"#") Then
query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1)
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment
Else
query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?"))
path = path & vbcrlf & "Query: " & query
End If
ElseIf InStr(domain(i),"#") Then
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_
"Fragment: " & fragment
Else
path = path & domain(i)
End If
Next
parse_url = parse_url & vbCrLf & "Path: " & path
End If
ElseIf InStr(url,":") Then
scheme = Mid(url,1,InStr(1,url,":")-1)
path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":"))
parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path
Else
parse_url = parse_url & vbcrlf & "Invalid!!!"
End If
End Function
WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
|
Keep all operations the same but rewrite the snippet in VB. | package main
import (
"fmt"
"log"
"math/big"
"strings"
)
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
var big0 = new(big.Int)
var big58 = big.NewInt(58)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func convertToBase58(hash string, base int) (string, error) {
var x, ok = new(big.Int).SetString(hash, base)
if !ok {
return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base)
}
var sb strings.Builder
var rem = new(big.Int)
for x.Cmp(big0) == 1 {
x.QuoRem(x, big58, rem)
r := rem.Int64()
sb.WriteByte(alphabet[r])
}
return reverse(sb.String()), nil
}
func main() {
s := "25420294593250030202636073700053352635053786165627414518"
b, err := convertToBase58(s, 10)
if err != nil {
log.Fatal(err)
}
fmt.Println(s, "->", b)
hashes := [...]string{
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e",
}
for _, hash := range hashes {
b58, err := convertToBase58(hash, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-56s -> %s\n", hash, b58)
}
}
| Imports System.Numerics
Imports System.Text
Module Module1
ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
ReadOnly HEX As String = "0123456789ABCDEF"
Function ToBigInteger(value As String, base As Integer) As BigInteger
If base < 1 OrElse base > HEX.Length Then
Throw New ArgumentException("Base is out of range.")
End If
Dim bi = BigInteger.Zero
For Each c In value
Dim c2 = Char.ToUpper(c)
Dim idx = HEX.IndexOf(c2)
If idx = -1 OrElse idx >= base Then
Throw New ArgumentException("Illegal character encountered.")
End If
bi = bi * base + idx
Next
Return bi
End Function
Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String
Dim x As BigInteger
If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then
x = ToBigInteger(hash.Substring(2), base)
Else
x = ToBigInteger(hash, base)
End If
Dim sb As New StringBuilder
While x > 0
Dim r = x Mod 58
sb.Append(ALPHABET(r))
x = x / 58
End While
Dim ca = sb.ToString().ToCharArray()
Array.Reverse(ca)
Return New String(ca)
End Function
Sub Main()
Dim s = "25420294593250030202636073700053352635053786165627414518"
Dim b = ConvertToBase58(s, 10)
Console.WriteLine("{0} -> {1}", s, b)
Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"}
For Each hash In hashes
Dim b58 = ConvertToBase58(hash)
Console.WriteLine("{0,-56} -> {1}", hash, b58)
Next
End Sub
End Module
|
Convert this Go block to VB, preserving its control flow and logic. | package main
import (
"fmt"
"log"
"math/big"
"strings"
)
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
var big0 = new(big.Int)
var big58 = big.NewInt(58)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func convertToBase58(hash string, base int) (string, error) {
var x, ok = new(big.Int).SetString(hash, base)
if !ok {
return "", fmt.Errorf("'%v' is not a valid integer in base '%d'", hash, base)
}
var sb strings.Builder
var rem = new(big.Int)
for x.Cmp(big0) == 1 {
x.QuoRem(x, big58, rem)
r := rem.Int64()
sb.WriteByte(alphabet[r])
}
return reverse(sb.String()), nil
}
func main() {
s := "25420294593250030202636073700053352635053786165627414518"
b, err := convertToBase58(s, 10)
if err != nil {
log.Fatal(err)
}
fmt.Println(s, "->", b)
hashes := [...]string{
"0x61",
"0x626262",
"0x636363",
"0x73696d706c792061206c6f6e6720737472696e67",
"0x516b6fcd0f",
"0xbf4f89001e670274dd",
"0x572e4794",
"0xecac89cad93923c02321",
"0x10c8511e",
}
for _, hash := range hashes {
b58, err := convertToBase58(hash, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%-56s -> %s\n", hash, b58)
}
}
| Imports System.Numerics
Imports System.Text
Module Module1
ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
ReadOnly HEX As String = "0123456789ABCDEF"
Function ToBigInteger(value As String, base As Integer) As BigInteger
If base < 1 OrElse base > HEX.Length Then
Throw New ArgumentException("Base is out of range.")
End If
Dim bi = BigInteger.Zero
For Each c In value
Dim c2 = Char.ToUpper(c)
Dim idx = HEX.IndexOf(c2)
If idx = -1 OrElse idx >= base Then
Throw New ArgumentException("Illegal character encountered.")
End If
bi = bi * base + idx
Next
Return bi
End Function
Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String
Dim x As BigInteger
If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then
x = ToBigInteger(hash.Substring(2), base)
Else
x = ToBigInteger(hash, base)
End If
Dim sb As New StringBuilder
While x > 0
Dim r = x Mod 58
sb.Append(ALPHABET(r))
x = x / 58
End While
Dim ca = sb.ToString().ToCharArray()
Array.Reverse(ca)
Return New String(ca)
End Function
Sub Main()
Dim s = "25420294593250030202636073700053352635053786165627414518"
Dim b = ConvertToBase58(s, 10)
Console.WriteLine("{0} -> {1}", s, b)
Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"}
For Each hash In hashes
Dim b58 = ConvertToBase58(hash)
Console.WriteLine("{0,-56} -> {1}", hash, b58)
Next
End Sub
End Module
|
Produce a functionally identical VB code for the snippet given in Go. | package main
import (
"crypto/des"
"encoding/hex"
"fmt"
"log"
)
func main() {
key, err := hex.DecodeString("0e329232ea6d0d73")
if err != nil {
log.Fatal(err)
}
c, err := des.NewCipher(key)
if err != nil {
log.Fatal(err)
}
src, err := hex.DecodeString("8787878787878787")
if err != nil {
log.Fatal(err)
}
dst := make([]byte, des.BlockSize)
c.Encrypt(dst, src)
fmt.Printf("%x\n", dst)
}
| Imports System.IO
Imports System.Security.Cryptography
Module Module1
Function ByteArrayToString(ba As Byte()) As String
Return BitConverter.ToString(ba).Replace("-", "")
End Function
Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()
Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}
Dim provider As New DESCryptoServiceProvider
Dim transform = provider.CreateEncryptor(passwordBytes, iv)
Dim mode = CryptoStreamMode.Write
Dim memStream As New MemoryStream
Dim cryptoStream As New CryptoStream(memStream, transform, mode)
cryptoStream.Write(messageBytes, 0, messageBytes.Length)
cryptoStream.FlushFinalBlock()
Dim encryptedMessageBytes(memStream.Length - 1) As Byte
memStream.Position = 0
memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)
Return encryptedMessageBytes
End Function
Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()
Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}
Dim provider As New DESCryptoServiceProvider
Dim transform = provider.CreateDecryptor(passwordBytes, iv)
Dim mode = CryptoStreamMode.Write
Dim memStream As New MemoryStream
Dim cryptoStream As New CryptoStream(memStream, transform, mode)
cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)
cryptoStream.FlushFinalBlock()
Dim decryptedMessageBytes(memStream.Length - 1) As Byte
memStream.Position = 0
memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)
Return decryptedMessageBytes
End Function
Sub Main()
Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}
Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}
Dim encStr = Encrypt(plainBytes, keyBytes)
Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr))
Dim decStr = Decrypt(encStr, keyBytes)
Console.WriteLine("Decoded: {0}", ByteArrayToString(decStr))
End Sub
End Module
|
Produce a functionally identical VB code for the snippet given in Go. | package main
import (
"fmt"
"regexp"
"strings"
)
var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`)
func reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func commatize(s string, startIndex, period int, sep string) string {
if startIndex < 0 || startIndex >= len(s) || period < 1 || sep == "" {
return s
}
m := reg.FindString(s[startIndex:])
if m == "" {
return s
}
splits := strings.Split(m, ".")
ip := splits[0]
if len(ip) > period {
pi := reverse(ip)
for i := (len(ip) - 1) / period * period; i >= period; i -= period {
pi = pi[:i] + sep + pi[i:]
}
ip = reverse(pi)
}
if strings.Contains(m, ".") {
dp := splits[1]
if len(dp) > period {
for i := (len(dp) - 1) / period * period; i >= period; i -= period {
dp = dp[:i] + sep + dp[i:]
}
}
ip += "." + dp
}
return s[:startIndex] + strings.Replace(s[startIndex:], m, ip, 1)
}
func main() {
tests := [...]string{
"123456789.123456789",
".123456789",
"57256.1D-4",
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"-in Aus$+1411.8millions",
"===US$0017440 millions=== (in 2000 dollars)",
"123.e8000 is pretty big.",
"The land area of the earth is 57268900(29% of the surface) square miles.",
"Ain't no numbers in this here words, nohow, no way, Jose.",
"James was never known as 0000000007",
"Arthur Eddington wrote: I believe there are " +
"15747724136275002577605653961181555468044717914527116709366231425076185631031296" +
" protons in the universe.",
" $-140000±100 millions.",
"6/9/1946 was a good year for some.",
}
fmt.Println(commatize(tests[0], 0, 2, "*"))
fmt.Println(commatize(tests[1], 0, 3, "-"))
fmt.Println(commatize(tests[2], 0, 4, "__"))
fmt.Println(commatize(tests[3], 0, 5, " "))
fmt.Println(commatize(tests[4], 0, 3, "."))
for _, test := range tests[5:] {
fmt.Println(commatize(test, 0, 3, ","))
}
}
| Public Sub commatize(s As String, Optional sep As String = ",", Optional start As Integer = 1, Optional step As Integer = 3)
Dim l As Integer: l = Len(s)
For i = start To l
If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then
For j = i + 1 To l + 1
If j > l Then
For k = j - 1 - step To i Step -step
s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)
l = Len(s)
Next k
Exit For
Else
If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then
For k = j - 1 - step To i Step -step
s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1)
l = Len(s)
Next k
Exit For
End If
End If
Next j
Exit For
End If
Next i
Debug.Print s
End Sub
Public Sub main()
commatize "pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 6, 5
commatize "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "."
commatize """-in Aus$+1411.8millions"""
commatize "===US$0017440 millions=== (in 2000 dollars)"
commatize "123.e8000 is pretty big."
commatize "The land area of the earth is 57268900(29% of the surface) square miles."
commatize "Ain
commatize "James was never known as 0000000007"
commatize "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe."
commatize " $-140000±100 millions."
commatize "6/9/1946 was a good year for some."
End Sub
|
Please provide an equivalent version of this Go code in VB. | package main
import (
"fmt"
"math/big"
)
func cumulative_freq(freq map[byte]int64) map[byte]int64 {
total := int64(0)
cf := make(map[byte]int64)
for i := 0; i < 256; i++ {
b := byte(i)
if v, ok := freq[b]; ok {
cf[b] = total
total += v
}
}
return cf
}
func arithmethic_coding(str string, radix int64) (*big.Int,
*big.Int, map[byte]int64) {
chars := []byte(str)
freq := make(map[byte]int64)
for _, c := range chars {
freq[c] += 1
}
cf := cumulative_freq(freq)
base := len(chars)
L := big.NewInt(0)
pf := big.NewInt(1)
bigBase := big.NewInt(int64(base))
for _, c := range chars {
x := big.NewInt(cf[c])
L.Mul(L, bigBase)
L.Add(L, x.Mul(x, pf))
pf.Mul(pf, big.NewInt(freq[c]))
}
U := big.NewInt(0)
U.Set(L)
U.Add(U, pf)
bigOne := big.NewInt(1)
bigZero := big.NewInt(0)
bigRadix := big.NewInt(radix)
tmp := big.NewInt(0).Set(pf)
powr := big.NewInt(0)
for {
tmp.Div(tmp, bigRadix)
if tmp.Cmp(bigZero) == 0 {
break
}
powr.Add(powr, bigOne)
}
diff := big.NewInt(0)
diff.Sub(U, bigOne)
diff.Div(diff, big.NewInt(0).Exp(bigRadix, powr, nil))
return diff, powr, freq
}
func arithmethic_decoding(num *big.Int, radix int64,
pow *big.Int, freq map[byte]int64) string {
powr := big.NewInt(radix)
enc := big.NewInt(0).Set(num)
enc.Mul(enc, powr.Exp(powr, pow, nil))
base := int64(0)
for _, v := range freq {
base += v
}
cf := cumulative_freq(freq)
dict := make(map[int64]byte)
for k, v := range cf {
dict[v] = k
}
lchar := -1
for i := int64(0); i < base; i++ {
if v, ok := dict[i]; ok {
lchar = int(v)
} else if lchar != -1 {
dict[i] = byte(lchar)
}
}
decoded := make([]byte, base)
bigBase := big.NewInt(base)
for i := base - 1; i >= 0; i-- {
pow := big.NewInt(0)
pow.Exp(bigBase, big.NewInt(i), nil)
div := big.NewInt(0)
div.Div(enc, pow)
c := dict[div.Int64()]
fv := freq[c]
cv := cf[c]
prod := big.NewInt(0).Mul(pow, big.NewInt(cv))
diff := big.NewInt(0).Sub(enc, prod)
enc.Div(diff, big.NewInt(fv))
decoded[base-i-1] = c
}
return string(decoded)
}
func main() {
var radix = int64(10)
strSlice := []string{
`DABDDB`,
`DABDDBBDDBA`,
`ABRACADABRA`,
`TOBEORNOTTOBEORTOBEORNOT`,
}
for _, str := range strSlice {
enc, pow, freq := arithmethic_coding(str, radix)
dec := arithmethic_decoding(enc, radix, pow, freq)
fmt.Printf("%-25s=> %19s * %d^%s\n", str, enc, radix, pow)
if str != dec {
panic("\tHowever that is incorrect!")
}
}
}
| Imports System.Numerics
Imports System.Text
Imports Freq = System.Collections.Generic.Dictionary(Of Char, Long)
Imports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long))
Module Module1
Function CumulativeFreq(freq As Freq) As Freq
Dim total As Long = 0
Dim cf As New Freq
For i = 0 To 255
Dim c = Chr(i)
If freq.ContainsKey(c) Then
Dim v = freq(c)
cf(c) = total
total += v
End If
Next
Return cf
End Function
Function ArithmeticCoding(str As String, radix As Long) As Triple
Dim freq As New Freq
For Each c In str
If freq.ContainsKey(c) Then
freq(c) += 1
Else
freq(c) = 1
End If
Next
Dim cf = CumulativeFreq(freq)
Dim base As BigInteger = str.Length
Dim lower As BigInteger = 0
Dim pf As BigInteger = 1
For Each c In str
Dim x = cf(c)
lower = lower * base + x * pf
pf = pf * freq(c)
Next
Dim upper = lower + pf
Dim powr = 0
Dim bigRadix As BigInteger = radix
While True
pf = pf / bigRadix
If pf = 0 Then
Exit While
End If
powr = powr + 1
End While
Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr))
Return New Triple(diff, powr, freq)
End Function
Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String
Dim powr As BigInteger = radix
Dim enc = num * BigInteger.Pow(powr, pwr)
Dim base = freq.Values.Sum()
Dim cf = CumulativeFreq(freq)
Dim dict As New Dictionary(Of Long, Char)
For Each key In cf.Keys
Dim value = cf(key)
dict(value) = key
Next
Dim lchar As Long = -1
For i As Long = 0 To base - 1
If dict.ContainsKey(i) Then
lchar = AscW(dict(i))
Else
dict(i) = ChrW(lchar)
End If
Next
Dim decoded As New StringBuilder
Dim bigBase As BigInteger = base
For i As Long = base - 1 To 0 Step -1
Dim pow = BigInteger.Pow(bigBase, i)
Dim div = enc / pow
Dim c = dict(div)
Dim fv = freq(c)
Dim cv = cf(c)
Dim diff = enc - pow * cv
enc = diff / fv
decoded.Append(c)
Next
Return decoded.ToString()
End Function
Sub Main()
Dim radix As Long = 10
Dim strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"}
For Each St In strings
Dim encoded = ArithmeticCoding(St, radix)
Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3)
Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", St, encoded.Item1, radix, encoded.Item2)
If St <> dec Then
Throw New Exception(vbTab + "However that is incorrect!")
End If
Next
End Sub
End Module
|
Preserve the algorithm and functionality while converting the code from Go to VB. | package main
import "fmt"
var g = [][]int{
0: {1},
1: {2},
2: {0},
3: {1, 2, 4},
4: {3, 5},
5: {2, 6},
6: {5},
7: {4, 6, 7},
}
func main() {
fmt.Println(kosaraju(g))
}
func kosaraju(g [][]int) []int {
vis := make([]bool, len(g))
L := make([]int, len(g))
x := len(L)
t := make([][]int, len(g))
var Visit func(int)
Visit = func(u int) {
if !vis[u] {
vis[u] = true
for _, v := range g[u] {
Visit(v)
t[v] = append(t[v], u)
}
x--
L[x] = u
}
}
for u := range g {
Visit(u)
}
c := make([]int, len(g))
var Assign func(int, int)
Assign = func(u, root int) {
if vis[u] {
vis[u] = false
c[u] = root
for _, v := range t[u] {
Assign(v, root)
}
}
}
for _, u := range L {
Assign(u, u)
}
return c
}
| Module Module1
Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer)
Dim size = g.Count
Dim vis(size - 1) As Boolean
Dim l(size - 1) As Integer
Dim x = size
Dim t As New List(Of List(Of Integer))
For i = 1 To size
t.Add(New List(Of Integer))
Next
Dim visit As Action(Of Integer) = Sub(u As Integer)
If Not vis(u) Then
vis(u) = True
For Each v In g(u)
visit(v)
t(v).Add(u)
Next
x -= 1
l(x) = u
End If
End Sub
For i = 1 To size
visit(i - 1)
Next
Dim c(size - 1) As Integer
Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer)
If vis(u) Then
vis(u) = False
c(u) = root
For Each v In t(u)
assign(v, root)
Next
End If
End Sub
For Each u In l
assign(u, u)
Next
Return c.ToList
End Function
Sub Main()
Dim g = New List(Of List(Of Integer)) From {
New List(Of Integer) From {1},
New List(Of Integer) From {2},
New List(Of Integer) From {0},
New List(Of Integer) From {1, 2, 4},
New List(Of Integer) From {3, 5},
New List(Of Integer) From {2, 6},
New List(Of Integer) From {5},
New List(Of Integer) From {4, 6, 7}
}
Dim output = Kosaraju(g)
Console.WriteLine("[{0}]", String.Join(", ", output))
End Sub
End Module
|
Change the programming language of this snippet from Go to VB without modifying what it does. | package main
import (
"fmt"
"math/rand"
"time"
)
var F = [][]int{
{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},
{1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0},
{1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1},
{1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1},
}
var I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}
var L = [][]int{
{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},
{0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},
{0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0},
}
var N = [][]int{
{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},
{0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},
{1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1},
}
var P = [][]int{
{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},
{1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},
{1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0},
}
var T = [][]int{
{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},
{1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0},
}
var U = [][]int{
{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},
{0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1},
}
var V = [][]int{
{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},
{1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2},
}
var W = [][]int{
{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},
{0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1},
}
var X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}}
var Y = [][]int{
{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},
{0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},
{1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0},
}
var Z = [][]int{
{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},
{0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2},
}
var shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z}
var symbols = []byte("FILNPTUVWXYZ-")
const (
nRows = 8
nCols = 8
blank = 12
)
var grid [nRows][nCols]int
var placed [12]bool
func tryPlaceOrientation(o []int, r, c, shapeIndex int) bool {
for i := 0; i < len(o); i += 2 {
x := c + o[i+1]
y := r + o[i]
if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 {
return false
}
}
grid[r][c] = shapeIndex
for i := 0; i < len(o); i += 2 {
grid[r+o[i]][c+o[i+1]] = shapeIndex
}
return true
}
func removeOrientation(o []int, r, c int) {
grid[r][c] = -1
for i := 0; i < len(o); i += 2 {
grid[r+o[i]][c+o[i+1]] = -1
}
}
func solve(pos, numPlaced int) bool {
if numPlaced == len(shapes) {
return true
}
row := pos / nCols
col := pos % nCols
if grid[row][col] != -1 {
return solve(pos+1, numPlaced)
}
for i := range shapes {
if !placed[i] {
for _, orientation := range shapes[i] {
if !tryPlaceOrientation(orientation, row, col, i) {
continue
}
placed[i] = true
if solve(pos+1, numPlaced+1) {
return true
}
removeOrientation(orientation, row, col)
placed[i] = false
}
}
}
return false
}
func shuffleShapes() {
rand.Shuffle(len(shapes), func(i, j int) {
shapes[i], shapes[j] = shapes[j], shapes[i]
symbols[i], symbols[j] = symbols[j], symbols[i]
})
}
func printResult() {
for _, r := range grid {
for _, i := range r {
fmt.Printf("%c ", symbols[i])
}
fmt.Println()
}
}
func main() {
rand.Seed(time.Now().UnixNano())
shuffleShapes()
for r := 0; r < nRows; r++ {
for i := range grid[r] {
grid[r][i] = -1
}
}
for i := 0; i < 4; i++ {
var randRow, randCol int
for {
randRow = rand.Intn(nRows)
randCol = rand.Intn(nCols)
if grid[randRow][randCol] != blank {
break
}
}
grid[randRow][randCol] = blank
}
if solve(0, 0) {
printResult()
} else {
fmt.Println("No solution")
}
}
| Module Module1
Dim symbols As Char() = "XYPFTVNLUZWI█".ToCharArray(),
nRows As Integer = 8, nCols As Integer = 8,
target As Integer = 12, blank As Integer = 12,
grid As Integer()() = New Integer(nRows - 1)() {},
placed As Boolean() = New Boolean(target - 1) {},
pens As List(Of List(Of Integer())), rand As Random,
seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586}
Sub Main()
Unpack(seeds) : rand = New Random() : ShuffleShapes(2)
For r As Integer = 0 To nRows - 1
grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next
For i As Integer = 0 To 3
Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols)
Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank
Next
If Solve(0, 0) Then
PrintResult()
Else
Console.WriteLine("no solution for this configuration:") : PrintResult()
End If
If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
End Sub
Sub ShuffleShapes(count As Integer)
For i As Integer = 0 To count : For j = 0 To pens.Count - 1
Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j
Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp
Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch
Next : Next
End Sub
Sub PrintResult()
For Each r As Integer() In grid : For Each i As Integer In r
Console.Write("{0} ", If(i < 0, ".", symbols(i)))
Next : Console.WriteLine() : Next
End Sub
Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean
If numPlaced = target Then Return True
Dim row As Integer = pos \ nCols, col As Integer = pos Mod nCols
If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced)
For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then
For Each orientation As Integer() In pens(i)
If Not TPO(orientation, row, col, i) Then Continue For
placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True
RmvO(orientation, row, col) : placed(i) = False
Next : End If : Next : Return False
End Function
Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer)
grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2
grid(row + ori(i))(col + ori(i + 1)) = -1 : Next
End Sub
Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer,
ByVal sIdx As Integer) As Boolean
For i As Integer = 0 To ori.Length - 1 Step 2
Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i)
If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse
grid(y)(x) <> -1 Then Return False
Next : grid(row)(col) = sIdx
For i As Integer = 0 To ori.Length - 1 Step 2
grid(row + ori(i))(col + ori(i + 1)) = sIdx
Next : Return True
End Function
Sub Unpack(sv As Integer())
pens = New List(Of List(Of Integer())) : For Each item In sv
Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item),
fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7
If i = 4 Then Mir(exi) Else Rot(exi)
fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi))
Next : pens.Add(Gen) : Next
End Sub
Function Expand(i As Integer) As List(Of Integer)
Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next
End Function
Function ToP(p As List(Of Integer)) As Integer()
Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1)
tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next
tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next
Dim res As New List(Of Integer) : For Each item In tmp.Skip(1)
Dim adj = If((item And 7) > 4, 8, 0)
res.Add((adj + item) \ 8) : res.Add((item And 7) - adj)
Next : Return res.ToArray()
End Function
Function TheSame(a As Integer(), b As Integer()) As Boolean
For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False
Next : Return True
End Function
Sub Rot(ByRef p As List(Of Integer))
For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next
End Sub
Sub Mir(ByRef p As List(Of Integer))
For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next
End Sub
End Module
|
Translate the given Go code snippet into VB without altering its behavior. | package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
fn := "myth"
bx := ".backup"
var err error
if tf, err := os.Readlink(fn); err == nil {
fn = tf
}
var fi os.FileInfo
if fi, err = os.Stat(fn); err != nil {
fmt.Println(err)
return
}
if err = os.Rename(fn, fn+bx); err != nil {
fmt.Println(err)
return
}
err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm())
if err != nil {
fmt.Println(err)
}
}
| Public Sub backup(filename As String)
If Len(Dir(filename)) > 0 Then
On Error Resume Next
Name filename As filename & ".bak"
Else
If Len(Dir(filename & ".lnk")) > 0 Then
On Error Resume Next
With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk")
link = .TargetPath
.Close
End With
Name link As link & ".bak"
End If
End If
End Sub
Public Sub main()
backup "D:\test.txt"
End Sub
|
Write a version of this Go function in VB with identical behavior. | package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
fn := "myth"
bx := ".backup"
var err error
if tf, err := os.Readlink(fn); err == nil {
fn = tf
}
var fi os.FileInfo
if fi, err = os.Stat(fn); err != nil {
fmt.Println(err)
return
}
if err = os.Rename(fn, fn+bx); err != nil {
fmt.Println(err)
return
}
err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm())
if err != nil {
fmt.Println(err)
}
}
| Public Sub backup(filename As String)
If Len(Dir(filename)) > 0 Then
On Error Resume Next
Name filename As filename & ".bak"
Else
If Len(Dir(filename & ".lnk")) > 0 Then
On Error Resume Next
With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk")
link = .TargetPath
.Close
End With
Name link As link & ".bak"
End If
End If
End Sub
Public Sub main()
backup "D:\test.txt"
End Sub
|
Preserve the algorithm and functionality while converting the code from Go to VB. | package main
import (
"fmt"
"math/big"
)
type mTerm struct {
a, n, d int64
}
var testCases = [][]mTerm{
{{1, 1, 2}, {1, 1, 3}},
{{2, 1, 3}, {1, 1, 7}},
{{4, 1, 5}, {-1, 1, 239}},
{{5, 1, 7}, {2, 3, 79}},
{{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},
{{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},
{{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},
{{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},
{{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},
{{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},
{{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},
{{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},
{{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},
{{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},
}
func main() {
for _, m := range testCases {
fmt.Printf("tan %v = %v\n", m, tans(m))
}
}
var one = big.NewRat(1, 1)
func tans(m []mTerm) *big.Rat {
if len(m) == 1 {
return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))
}
half := len(m) / 2
a := tans(m[:half])
b := tans(m[half:])
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
func tanEval(coef int64, f *big.Rat) *big.Rat {
if coef == 1 {
return f
}
if coef < 0 {
r := tanEval(-coef, f)
return r.Neg(r)
}
ca := coef / 2
cb := coef - ca
a := tanEval(ca, f)
b := tanEval(cb, f)
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
| Imports System.Numerics
Public Class BigRat
Implements IComparable
Public nu, de As BigInteger
Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),
One = New BigRat(BigInteger.One, BigInteger.One)
Sub New(bRat As BigRat)
nu = bRat.nu : de = bRat.de
End Sub
Sub New(n As BigInteger, d As BigInteger)
If d = BigInteger.Zero Then _
Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d)))
Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)
If bi > BigInteger.One Then n /= bi : d /= bi
If d < BigInteger.Zero Then n = -n : d = -d
nu = n : de = d
End Sub
Shared Operator -(x As BigRat) As BigRat
Return New BigRat(-x.nu, x.de)
End Operator
Shared Operator +(x As BigRat, y As BigRat)
Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)
End Operator
Shared Operator -(x As BigRat, y As BigRat) As BigRat
Return x + (-y)
End Operator
Shared Operator *(x As BigRat, y As BigRat) As BigRat
Return New BigRat(x.nu * y.nu, x.de * y.de)
End Operator
Shared Operator /(x As BigRat, y As BigRat) As BigRat
Return New BigRat(x.nu * y.de, x.de * y.nu)
End Operator
Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Dim dif As BigRat = New BigRat(nu, de) - obj
If dif.nu < BigInteger.Zero Then Return -1
If dif.nu > BigInteger.Zero Then Return 1
Return 0
End Function
Shared Operator =(x As BigRat, y As BigRat) As Boolean
Return x.CompareTo(y) = 0
End Operator
Shared Operator <>(x As BigRat, y As BigRat) As Boolean
Return x.CompareTo(y) <> 0
End Operator
Overrides Function ToString() As String
If de = BigInteger.One Then Return nu.ToString
Return String.Format("({0}/{1})", nu, de)
End Function
Shared Function Combine(a As BigRat, b As BigRat) As BigRat
Return (a + b) / (BigRat.One - (a * b))
End Function
End Class
Public Structure Term
Dim c As Integer, br As BigRat
Sub New(cc As Integer, bigr As BigRat)
c = cc : br = bigr
End Sub
End Structure
Module Module1
Function Eval(c As Integer, x As BigRat) As BigRat
If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)
Dim hc As Integer = c \ 2
Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))
End Function
Function Sum(terms As List(Of Term)) As BigRat
If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)
Dim htc As Integer = terms.Count / 2
Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))
End Function
Function ParseLine(ByVal s As String) As List(Of Term)
ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)
While t.Contains(" ") : t = t.Replace(" ", "") : End While
p = t.IndexOf("pi/4=") : If p < 0 Then _
Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function
t = t.Substring(p + 5)
For Each item As String In t.Split(")")
If item.Length > 5 Then
If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse
item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then
Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item)
ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function
End If
x.c = 1 : x.br = New BigRat(BigRat.One)
p = item.IndexOf("/") : If p > 0 Then
x.br.de = UInt64.Parse(item.Substring(p + 1))
item = item.Substring(0, p)
p = item.IndexOf("(") : If p > 0 Then
x.br.nu = UInt64.Parse(item.Substring(p + 1))
p = item.IndexOf("a") : If p > 0 Then
Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c)
If x.c = 0 Then x.c = 1
If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c
End If
ParseLine.Add(x)
End If
End If
End If
Next
End Function
Sub Main(ByVal args As String())
Dim nl As String = vbLf
For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl &
"pi/4 = 2Atan(1/3) + ATan(1/7)" & nl &
"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl &
"pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl &
"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl &
"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl &
"PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl &
"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl &
"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl &
"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl &
"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl &
"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl &
"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl &
"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl &
"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl &
"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl &
"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl)
Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item)
Next
End Sub
End Module
|
Write a version of this Go function in VB with identical behavior. | package main
import (
"fmt"
"math/big"
)
type mTerm struct {
a, n, d int64
}
var testCases = [][]mTerm{
{{1, 1, 2}, {1, 1, 3}},
{{2, 1, 3}, {1, 1, 7}},
{{4, 1, 5}, {-1, 1, 239}},
{{5, 1, 7}, {2, 3, 79}},
{{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},
{{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},
{{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},
{{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},
{{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},
{{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},
{{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},
{{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},
{{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},
{{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},
{{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},
}
func main() {
for _, m := range testCases {
fmt.Printf("tan %v = %v\n", m, tans(m))
}
}
var one = big.NewRat(1, 1)
func tans(m []mTerm) *big.Rat {
if len(m) == 1 {
return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))
}
half := len(m) / 2
a := tans(m[:half])
b := tans(m[half:])
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
func tanEval(coef int64, f *big.Rat) *big.Rat {
if coef == 1 {
return f
}
if coef < 0 {
r := tanEval(-coef, f)
return r.Neg(r)
}
ca := coef / 2
cb := coef - ca
a := tanEval(ca, f)
b := tanEval(cb, f)
r := new(big.Rat)
return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}
| Imports System.Numerics
Public Class BigRat
Implements IComparable
Public nu, de As BigInteger
Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One),
One = New BigRat(BigInteger.One, BigInteger.One)
Sub New(bRat As BigRat)
nu = bRat.nu : de = bRat.de
End Sub
Sub New(n As BigInteger, d As BigInteger)
If d = BigInteger.Zero Then _
Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d)))
Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d)
If bi > BigInteger.One Then n /= bi : d /= bi
If d < BigInteger.Zero Then n = -n : d = -d
nu = n : de = d
End Sub
Shared Operator -(x As BigRat) As BigRat
Return New BigRat(-x.nu, x.de)
End Operator
Shared Operator +(x As BigRat, y As BigRat)
Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de)
End Operator
Shared Operator -(x As BigRat, y As BigRat) As BigRat
Return x + (-y)
End Operator
Shared Operator *(x As BigRat, y As BigRat) As BigRat
Return New BigRat(x.nu * y.nu, x.de * y.de)
End Operator
Shared Operator /(x As BigRat, y As BigRat) As BigRat
Return New BigRat(x.nu * y.de, x.de * y.nu)
End Operator
Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Dim dif As BigRat = New BigRat(nu, de) - obj
If dif.nu < BigInteger.Zero Then Return -1
If dif.nu > BigInteger.Zero Then Return 1
Return 0
End Function
Shared Operator =(x As BigRat, y As BigRat) As Boolean
Return x.CompareTo(y) = 0
End Operator
Shared Operator <>(x As BigRat, y As BigRat) As Boolean
Return x.CompareTo(y) <> 0
End Operator
Overrides Function ToString() As String
If de = BigInteger.One Then Return nu.ToString
Return String.Format("({0}/{1})", nu, de)
End Function
Shared Function Combine(a As BigRat, b As BigRat) As BigRat
Return (a + b) / (BigRat.One - (a * b))
End Function
End Class
Public Structure Term
Dim c As Integer, br As BigRat
Sub New(cc As Integer, bigr As BigRat)
c = cc : br = bigr
End Sub
End Structure
Module Module1
Function Eval(c As Integer, x As BigRat) As BigRat
If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x)
Dim hc As Integer = c \ 2
Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x))
End Function
Function Sum(terms As List(Of Term)) As BigRat
If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br)
Dim htc As Integer = terms.Count / 2
Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList))
End Function
Function ParseLine(ByVal s As String) As List(Of Term)
ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero)
While t.Contains(" ") : t = t.Replace(" ", "") : End While
p = t.IndexOf("pi/4=") : If p < 0 Then _
Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function
t = t.Substring(p + 5)
For Each item As String In t.Split(")")
If item.Length > 5 Then
If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse
item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then
Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item)
ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function
End If
x.c = 1 : x.br = New BigRat(BigRat.One)
p = item.IndexOf("/") : If p > 0 Then
x.br.de = UInt64.Parse(item.Substring(p + 1))
item = item.Substring(0, p)
p = item.IndexOf("(") : If p > 0 Then
x.br.nu = UInt64.Parse(item.Substring(p + 1))
p = item.IndexOf("a") : If p > 0 Then
Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c)
If x.c = 0 Then x.c = 1
If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c
End If
ParseLine.Add(x)
End If
End If
End If
Next
End Function
Sub Main(ByVal args As String())
Dim nl As String = vbLf
For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl &
"pi/4 = 2Atan(1/3) + ATan(1/7)" & nl &
"pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl &
"pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl &
"Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl &
"pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl &
"PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl &
"pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl &
"pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl &
"pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl &
"pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl &
"pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl &
"pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl &
"pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl &
"pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl &
"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl &
"pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl)
Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item)
Next
End Sub
End Module
|
Transform the following Go implementation into VB, maintaining the same output and logic. | package main
import "fmt"
type solution struct{ peg, over, land int }
type move struct{ from, to int }
var emptyStart = 1
var board [16]bool
var jumpMoves = [16][]move{
{},
{{2, 4}, {3, 6}},
{{4, 7}, {5, 9}},
{{5, 8}, {6, 10}},
{{2, 1}, {5, 6}, {7, 11}, {8, 13}},
{{8, 12}, {9, 14}},
{{3, 1}, {5, 4}, {9, 13}, {10, 15}},
{{4, 2}, {8, 9}},
{{5, 3}, {9, 10}},
{{5, 2}, {8, 7}},
{{9, 8}},
{{12, 13}},
{{8, 5}, {13, 14}},
{{8, 4}, {9, 6}, {12, 11}, {14, 15}},
{{9, 5}, {13, 12}},
{{10, 6}, {14, 13}},
}
var solutions []solution
func initBoard() {
for i := 1; i < 16; i++ {
board[i] = true
}
board[emptyStart] = false
}
func (sol solution) split() (int, int, int) {
return sol.peg, sol.over, sol.land
}
func (mv move) split() (int, int) {
return mv.from, mv.to
}
func drawBoard() {
var pegs [16]byte
for i := 1; i < 16; i++ {
if board[i] {
pegs[i] = fmt.Sprintf("%X", i)[0]
} else {
pegs[i] = '-'
}
}
fmt.Printf(" %c\n", pegs[1])
fmt.Printf(" %c %c\n", pegs[2], pegs[3])
fmt.Printf(" %c %c %c\n", pegs[4], pegs[5], pegs[6])
fmt.Printf(" %c %c %c %c\n", pegs[7], pegs[8], pegs[9], pegs[10])
fmt.Printf(" %c %c %c %c %c\n", pegs[11], pegs[12], pegs[13], pegs[14], pegs[15])
}
func solved() bool {
count := 0
for _, b := range board {
if b {
count++
}
}
return count == 1
}
func solve() {
if solved() {
return
}
for peg := 1; peg < 16; peg++ {
if board[peg] {
for _, mv := range jumpMoves[peg] {
over, land := mv.split()
if board[over] && !board[land] {
saveBoard := board
board[peg] = false
board[over] = false
board[land] = true
solutions = append(solutions, solution{peg, over, land})
solve()
if solved() {
return
}
board = saveBoard
solutions = solutions[:len(solutions)-1]
}
}
}
}
}
func main() {
initBoard()
solve()
initBoard()
drawBoard()
fmt.Printf("Starting with peg %X removed\n\n", emptyStart)
for _, solution := range solutions {
peg, over, land := solution.split()
board[peg] = false
board[over] = false
board[land] = true
drawBoard()
fmt.Printf("Peg %X jumped over %X to land on %X\n\n", peg, over, land)
}
}
| Imports System, Microsoft.VisualBasic.DateAndTime
Public Module Module1
Const n As Integer = 5
Dim Board As String
Dim Starting As Integer = 1
Dim Target As Integer = 13
Dim Moves As Integer()
Dim bi() As Integer
Dim ib() As Integer
Dim nl As Char = Convert.ToChar(10)
Public Function Dou(s As String) As String
Dou = "" : Dim b As Boolean = True
For Each ch As Char In s
If b Then b = ch <> " "
If b Then Dou &= ch & " " Else Dou = " " & Dou
Next : Dou = Dou.TrimEnd()
End Function
Public Function Fmt(s As String) As String
If s.Length < Board.Length Then Return s
Fmt = "" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) &
If(i = n, s.Substring(Board.Length), "") & nl
Next
End Function
Public Function Triangle(n As Integer) As Integer
Return (n * (n + 1)) / 2
End Function
Public Function Init(s As String, pos As Integer) As String
Init = s : Mid(Init, pos, 1) = "0"
End Function
Public Sub InitIndex()
ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0
For i As Integer = 0 To ib.Length - 1
If i = 0 Then
ib(i) = 0 : bi(j) = 0 : j += 1
Else
If Board(i - 1) = "1" Then ib(i) = j : bi(j) = i : j += 1
End If
Next
End Sub
Public Function solve(brd As String, pegsLeft As Integer) As String
If pegsLeft = 1 Then
If Target = 0 Then Return "Completed"
If brd(bi(Target) - 1) = "1" Then Return "Completed" Else Return "fail"
End If
For i = 1 To Board.Length
If brd(i - 1) = "1" Then
For Each mj In Moves
Dim over As Integer = i + mj
Dim land As Integer = i + 2 * mj
If land >= 1 AndAlso land <= brd.Length _
AndAlso brd(land - 1) = "0" _
AndAlso brd(over - 1) = "1" Then
setPegs(brd, "001", i, over, land)
Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1)
If Res.Length <> 4 Then _
Return brd & info(i, over, land) & nl & Res
setPegs(brd, "110", i, over, land)
End If
Next
End If
Next
Return "fail"
End Function
Function info(frm As Integer, over As Integer, dest As Integer) As String
Return " Peg from " & ib(frm).ToString() & " goes to " & ib(dest).ToString() &
", removing peg at " & ib(over).ToString()
End Function
Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer)
Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2)
End Sub
Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer)
x = Math.Max(Math.Min(x, hi), lo)
End Sub
Public Sub Main()
Dim t As Integer = Triangle(n)
LimitIt(Starting, 1, t)
LimitIt(Target, 0, t)
Dim stime As Date = Now()
Moves = {-n - 1, -n, -1, 1, n, n + 1}
Board = New String("1", n * n)
For i As Integer = 0 To n - 2
Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(" ", n - 1 - i)
Next
InitIndex()
Dim B As String = Init(Board, bi(Starting))
Console.WriteLine(Fmt(B & " Starting with peg removed from " & Starting.ToString()))
Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl)
Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & " ms."
If res(0).Length = 4 Then
If Target = 0 Then
Console.WriteLine("Unable to find a solution with last peg left anywhere.")
Else
Console.WriteLine("Unable to find a solution with last peg left at " &
Target.ToString() & ".")
End If
Console.WriteLine("Computation time: " & ts)
Else
For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next
Console.WriteLine("Computation time to first found solution: " & ts)
End If
If Diagnostics.Debugger.IsAttached Then Console.ReadLine()
End Sub
End Module
|
Write the same code in VB as shown below in Go. | package main
import "fmt"
var solution = make(chan int)
var nearMiss = make(chan int)
var done = make(chan bool)
func main() {
for i := 0; i < 4096; i++ {
go checkPerm(i)
}
var ms []int
for i := 0; i < 4096; {
select {
case <-done:
i++
case s := <-solution:
print12("solution", s)
case m := <-nearMiss:
ms = append(ms, m)
}
}
for _, m := range ms {
print12("near miss", m)
}
}
func print12(label string, bits int) {
fmt.Print(label, ":")
for i := 1; i <= 12; i++ {
if bits&1 == 1 {
fmt.Print(" ", i)
}
bits >>= 1
}
fmt.Println()
}
func checkPerm(tz int) {
ts := func(n uint) bool {
return tz>>(n-1)&1 == 1
}
ntrue := func(xs ...uint) int {
nt := 0
for _, x := range xs {
if ts(x) {
nt++
}
}
return nt
}
var con bool
test := func(statement uint, b bool) {
switch {
case ts(statement) == b:
case con:
panic("bail")
default:
con = true
}
}
defer func() {
if x := recover(); x != nil {
if msg, ok := x.(string); !ok && msg != "bail" {
panic(x)
}
}
done <- true
}()
test(1, true)
test(2, ntrue(7, 8, 9, 10, 11, 12) == 3)
test(3, ntrue(2, 4, 6, 8, 10, 12) == 2)
test(4, !ts(5) || ts(6) && ts(7))
test(5, !ts(4) && !ts(3) && !ts(2))
test(6, ntrue(1, 3, 5, 7, 9, 11) == 4)
test(7, ts(2) != ts(3))
test(8, !ts(7) || ts(5) && ts(6))
test(9, ntrue(1, 2, 3, 4, 5, 6) == 3)
test(10, ts(11) && ts(12))
test(11, ntrue(7, 8, 9) == 1)
test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4)
if con {
nearMiss <- tz
} else {
solution <- tz
}
}
| Public s As String
Public t As Integer
Function s1()
s1 = Len(s) = 12
End Function
Function s2()
t = 0
For i = 7 To 12
t = t - (Mid(s, i, 1) = "1")
Next i
s2 = t = 3
End Function
Function s3()
t = 0
For i = 2 To 12 Step 2
t = t - (Mid(s, i, 1) = "1")
Next i
s3 = t = 2
End Function
Function s4()
s4 = Mid(s, 5, 1) = "0" Or ((Mid(s, 6, 1) = "1" And Mid(s, 7, 1) = "1"))
End Function
Function s5()
s5 = Mid(s, 2, 1) = "0" And Mid(s, 3, 1) = "0" And Mid(s, 4, 1) = "0"
End Function
Function s6()
t = 0
For i = 1 To 12 Step 2
t = t - (Mid(s, i, 1) = "1")
Next i
s6 = t = 4
End Function
Function s7()
s7 = Mid(s, 2, 1) <> Mid(s, 3, 1)
End Function
Function s8()
s8 = Mid(s, 7, 1) = "0" Or (Mid(s, 5, 1) = "1" And Mid(s, 6, 1) = "1")
End Function
Function s9()
t = 0
For i = 1 To 6
t = t - (Mid(s, i, 1) = "1")
Next i
s9 = t = 3
End Function
Function s10()
s10 = Mid(s, 11, 1) = "1" And Mid(s, 12, 1) = "1"
End Function
Function s11()
t = 0
For i = 7 To 9
t = t - (Mid(s, i, 1) = "1")
Next i
s11 = t = 1
End Function
Function s12()
t = 0
For i = 1 To 11
t = t - (Mid(s, i, 1) = "1")
Next i
s12 = t = 4
End Function
Public Sub twelve_statements()
For i = 0 To 2 ^ 12 - 1
s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \ 128)), 5) _
& Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7)
For b = 1 To 12
Select Case b
Case 1: If s1 <> (Mid(s, b, 1) = "1") Then Exit For
Case 2: If s2 <> (Mid(s, b, 1) = "1") Then Exit For
Case 3: If s3 <> (Mid(s, b, 1) = "1") Then Exit For
Case 4: If s4 <> (Mid(s, b, 1) = "1") Then Exit For
Case 5: If s5 <> (Mid(s, b, 1) = "1") Then Exit For
Case 6: If s6 <> (Mid(s, b, 1) = "1") Then Exit For
Case 7: If s7 <> (Mid(s, b, 1) = "1") Then Exit For
Case 8: If s8 <> (Mid(s, b, 1) = "1") Then Exit For
Case 9: If s9 <> (Mid(s, b, 1) = "1") Then Exit For
Case 10: If s10 <> (Mid(s, b, 1) = "1") Then Exit For
Case 11: If s11 <> (Mid(s, b, 1) = "1") Then Exit For
Case 12: If s12 <> (Mid(s, b, 1) = "1") Then Exit For
End Select
If b = 12 Then Debug.Print s
Next
Next
End Sub
|
Write a version of this Go function in VB with identical behavior. | package main
import (
"fmt"
"math/big"
"strconv"
"strings"
)
var suffixes = " KMGTPEZYXWVU"
var ggl = googol()
func googol() *big.Float {
g1 := new(big.Float).SetPrec(500)
g1.SetInt64(10000000000)
g := new(big.Float)
g.Set(g1)
for i := 2; i <= 10; i++ {
g.Mul(g, g1)
}
return g
}
func suffize(arg string) {
fields := strings.Fields(arg)
a := fields[0]
if a == "" {
a = "0"
}
var places, base int
var frac, radix string
switch len(fields) {
case 1:
places = -1
base = 10
case 2:
places, _ = strconv.Atoi(fields[1])
base = 10
frac = strconv.Itoa(places)
case 3:
if fields[1] == "," {
places = 0
frac = ","
} else {
places, _ = strconv.Atoi(fields[1])
frac = strconv.Itoa(places)
}
base, _ = strconv.Atoi(fields[2])
if base != 2 && base != 10 {
base = 10
}
radix = strconv.Itoa(base)
}
a = strings.Replace(a, ",", "", -1)
sign := ""
if a[0] == '+' || a[0] == '-' {
sign = string(a[0])
a = a[1:]
}
b := new(big.Float).SetPrec(500)
d := new(big.Float).SetPrec(500)
b.SetString(a)
g := false
if b.Cmp(ggl) >= 0 {
g = true
}
if !g && base == 2 {
d.SetUint64(1024)
} else if !g && base == 10 {
d.SetUint64(1000)
} else {
d.Set(ggl)
}
c := 0
for b.Cmp(d) >= 0 && c < 12 {
b.Quo(b, d)
c++
}
var suffix string
if !g {
suffix = string(suffixes[c])
} else {
suffix = "googol"
}
if base == 2 {
suffix += "i"
}
fmt.Println(" input number =", fields[0])
fmt.Println(" fraction digs =", frac)
fmt.Println("specified radix =", radix)
fmt.Print(" new number = ")
if places >= 0 {
fmt.Printf("%s%.*f%s\n", sign, places, b, suffix)
} else {
fmt.Printf("%s%s%s\n", sign, b.Text('g', 50), suffix)
}
fmt.Println()
}
func main() {
tests := []string{
"87,654,321",
"-998,877,665,544,332,211,000 3",
"+112,233 0",
"16,777,216 1",
"456,789,100,000,000",
"456,789,100,000,000 2 10",
"456,789,100,000,000 5 2",
"456,789,100,000.000e+00 0 10",
"+16777216 , 2",
"1.2e101",
"446,835,273,728 1",
"1e36",
"1e39",
}
for _, test := range tests {
suffize(test)
}
}
| Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String
Dim suffix As String, parts() As String, exponent As String
Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean
flag = False
fractiondigits = Val(sfractiondigits)
suffixes = " KMGTPEZYXWVU"
number = Replace(number, ",", "", 1)
Dim c As Currency
Dim sign As Integer
If Left(number, 1) = "-" Then
number = Right(number, Len(number) - 1)
outstring = "-"
End If
If Left(number, 1) = "+" Then
number = Right(number, Len(number) - 1)
outstring = "+"
End If
parts = Split(number, "e")
number = parts(0)
If UBound(parts) > 0 Then exponent = parts(1)
parts = Split(number, ".")
number = parts(0)
If UBound(parts) > 0 Then frac = parts(1)
If base = "2" Then
Dim cnumber As Currency
cnumber = Val(number)
nsuffix = 0
Dim dnumber As Double
If cnumber > 1023 Then
cnumber = cnumber / 1024@
nsuffix = nsuffix + 1
dnumber = cnumber
Do While dnumber > 1023
dnumber = dnumber / 1024@
nsuffix = nsuffix + 1
Loop
number = CStr(dnumber)
Else
number = CStr(cnumber)
End If
leadingstring = Int(number)
number = Replace(number, ",", "")
leading = Len(leadingstring)
suffix = Mid(suffixes, nsuffix + 1, 1)
Else
nsuffix = (Len(number) + Val(exponent) - 1) \ 3
If nsuffix < 13 Then
suffix = Mid(suffixes, nsuffix + 1, 1)
leading = (Len(number) - 1) Mod 3 + 1
leadingstring = Left(number, leading)
Else
flag = True
If nsuffix > 32 Then
suffix = "googol"
leading = Len(number) + Val(exponent) - 99
leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), "0")
Else
suffix = "U"
leading = Len(number) + Val(exponent) - 35
If Val(exponent) > 36 Then
leadingstring = number & String$(Val(exponent) - 36, "0")
Else
leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))
End If
End If
End If
End If
If fractiondigits > 0 Then
If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then
fraction = Mid(number, leading + 1, fractiondigits - 1) & _
CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)
Else
fraction = Mid(number, leading + 1, fractiondigits)
End If
Else
If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> "" And sfractiondigits <> "," Then
leadingstring = Mid(number, 1, leading - 1) & _
CStr(Val(Mid(number, leading, 1)) + 1)
End If
End If
If flag Then
If sfractiondigits = "" Or sfractiondigits = "," Then
fraction = ""
End If
Else
If sfractiondigits = "" Or sfractiondigits = "," Then
fraction = Right(number, Len(number) - leading)
End If
End If
outstring = outstring & leadingstring
If Len(fraction) > 0 Then
outstring = outstring & "." & fraction
End If
If base = "2" Then
outstring = outstring & suffix & "i"
Else
outstring = outstring & suffix
End If
suffize = outstring
End Function
Sub program()
Dim s(10) As String, t As String, f As String, r As String
Dim tt() As String, temp As String
s(0) = " 87,654,321"
s(1) = " -998,877,665,544,332,211,000 3"
s(2) = " +112,233 0"
s(3) = " 16,777,216 1"
s(4) = " 456,789,100,000,000 2"
s(5) = " 456,789,100,000,000 2 10"
s(6) = " 456,789,100,000,000 5 2"
s(7) = " 456,789,100,000.000e+00 0 10"
s(8) = " +16777216 , 2"
s(9) = " 1.2e101"
For i = 0 To 9
ReDim tt(0)
t = Trim(s(i))
Do
temp = t
t = Replace(t, " ", " ")
Loop Until temp = t
tt = Split(t, " ")
If UBound(tt) > 0 Then f = tt(1) Else f = ""
If UBound(tt) > 1 Then r = tt(2) Else r = ""
Debug.Print String$(48, "-")
Debug.Print " input number = "; tt(0)
Debug.Print " fraction digs = "; f
Debug.Print " specified radix = "; r
Debug.Print " new number = "; suffize(tt(0), f, r)
Next i
End Sub
|
Change the programming language of this snippet from Go to VB without modifying what it does. | package main
import (
"fmt"
"math/big"
"strconv"
"strings"
)
var suffixes = " KMGTPEZYXWVU"
var ggl = googol()
func googol() *big.Float {
g1 := new(big.Float).SetPrec(500)
g1.SetInt64(10000000000)
g := new(big.Float)
g.Set(g1)
for i := 2; i <= 10; i++ {
g.Mul(g, g1)
}
return g
}
func suffize(arg string) {
fields := strings.Fields(arg)
a := fields[0]
if a == "" {
a = "0"
}
var places, base int
var frac, radix string
switch len(fields) {
case 1:
places = -1
base = 10
case 2:
places, _ = strconv.Atoi(fields[1])
base = 10
frac = strconv.Itoa(places)
case 3:
if fields[1] == "," {
places = 0
frac = ","
} else {
places, _ = strconv.Atoi(fields[1])
frac = strconv.Itoa(places)
}
base, _ = strconv.Atoi(fields[2])
if base != 2 && base != 10 {
base = 10
}
radix = strconv.Itoa(base)
}
a = strings.Replace(a, ",", "", -1)
sign := ""
if a[0] == '+' || a[0] == '-' {
sign = string(a[0])
a = a[1:]
}
b := new(big.Float).SetPrec(500)
d := new(big.Float).SetPrec(500)
b.SetString(a)
g := false
if b.Cmp(ggl) >= 0 {
g = true
}
if !g && base == 2 {
d.SetUint64(1024)
} else if !g && base == 10 {
d.SetUint64(1000)
} else {
d.Set(ggl)
}
c := 0
for b.Cmp(d) >= 0 && c < 12 {
b.Quo(b, d)
c++
}
var suffix string
if !g {
suffix = string(suffixes[c])
} else {
suffix = "googol"
}
if base == 2 {
suffix += "i"
}
fmt.Println(" input number =", fields[0])
fmt.Println(" fraction digs =", frac)
fmt.Println("specified radix =", radix)
fmt.Print(" new number = ")
if places >= 0 {
fmt.Printf("%s%.*f%s\n", sign, places, b, suffix)
} else {
fmt.Printf("%s%s%s\n", sign, b.Text('g', 50), suffix)
}
fmt.Println()
}
func main() {
tests := []string{
"87,654,321",
"-998,877,665,544,332,211,000 3",
"+112,233 0",
"16,777,216 1",
"456,789,100,000,000",
"456,789,100,000,000 2 10",
"456,789,100,000,000 5 2",
"456,789,100,000.000e+00 0 10",
"+16777216 , 2",
"1.2e101",
"446,835,273,728 1",
"1e36",
"1e39",
}
for _, test := range tests {
suffize(test)
}
}
| Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String
Dim suffix As String, parts() As String, exponent As String
Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean
flag = False
fractiondigits = Val(sfractiondigits)
suffixes = " KMGTPEZYXWVU"
number = Replace(number, ",", "", 1)
Dim c As Currency
Dim sign As Integer
If Left(number, 1) = "-" Then
number = Right(number, Len(number) - 1)
outstring = "-"
End If
If Left(number, 1) = "+" Then
number = Right(number, Len(number) - 1)
outstring = "+"
End If
parts = Split(number, "e")
number = parts(0)
If UBound(parts) > 0 Then exponent = parts(1)
parts = Split(number, ".")
number = parts(0)
If UBound(parts) > 0 Then frac = parts(1)
If base = "2" Then
Dim cnumber As Currency
cnumber = Val(number)
nsuffix = 0
Dim dnumber As Double
If cnumber > 1023 Then
cnumber = cnumber / 1024@
nsuffix = nsuffix + 1
dnumber = cnumber
Do While dnumber > 1023
dnumber = dnumber / 1024@
nsuffix = nsuffix + 1
Loop
number = CStr(dnumber)
Else
number = CStr(cnumber)
End If
leadingstring = Int(number)
number = Replace(number, ",", "")
leading = Len(leadingstring)
suffix = Mid(suffixes, nsuffix + 1, 1)
Else
nsuffix = (Len(number) + Val(exponent) - 1) \ 3
If nsuffix < 13 Then
suffix = Mid(suffixes, nsuffix + 1, 1)
leading = (Len(number) - 1) Mod 3 + 1
leadingstring = Left(number, leading)
Else
flag = True
If nsuffix > 32 Then
suffix = "googol"
leading = Len(number) + Val(exponent) - 99
leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), "0")
Else
suffix = "U"
leading = Len(number) + Val(exponent) - 35
If Val(exponent) > 36 Then
leadingstring = number & String$(Val(exponent) - 36, "0")
Else
leadingstring = Left(number, (Len(number) - 36 + Val(exponent)))
End If
End If
End If
End If
If fractiondigits > 0 Then
If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then
fraction = Mid(number, leading + 1, fractiondigits - 1) & _
CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1)
Else
fraction = Mid(number, leading + 1, fractiondigits)
End If
Else
If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> "" And sfractiondigits <> "," Then
leadingstring = Mid(number, 1, leading - 1) & _
CStr(Val(Mid(number, leading, 1)) + 1)
End If
End If
If flag Then
If sfractiondigits = "" Or sfractiondigits = "," Then
fraction = ""
End If
Else
If sfractiondigits = "" Or sfractiondigits = "," Then
fraction = Right(number, Len(number) - leading)
End If
End If
outstring = outstring & leadingstring
If Len(fraction) > 0 Then
outstring = outstring & "." & fraction
End If
If base = "2" Then
outstring = outstring & suffix & "i"
Else
outstring = outstring & suffix
End If
suffize = outstring
End Function
Sub program()
Dim s(10) As String, t As String, f As String, r As String
Dim tt() As String, temp As String
s(0) = " 87,654,321"
s(1) = " -998,877,665,544,332,211,000 3"
s(2) = " +112,233 0"
s(3) = " 16,777,216 1"
s(4) = " 456,789,100,000,000 2"
s(5) = " 456,789,100,000,000 2 10"
s(6) = " 456,789,100,000,000 5 2"
s(7) = " 456,789,100,000.000e+00 0 10"
s(8) = " +16777216 , 2"
s(9) = " 1.2e101"
For i = 0 To 9
ReDim tt(0)
t = Trim(s(i))
Do
temp = t
t = Replace(t, " ", " ")
Loop Until temp = t
tt = Split(t, " ")
If UBound(tt) > 0 Then f = tt(1) Else f = ""
If UBound(tt) > 1 Then r = tt(2) Else r = ""
Debug.Print String$(48, "-")
Debug.Print " input number = "; tt(0)
Debug.Print " fraction digs = "; f
Debug.Print " specified radix = "; r
Debug.Print " new number = "; suffize(tt(0), f, r)
Next i
End Sub
|
Generate a VB translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"os"
"sort"
"strings"
"text/template"
)
func main() {
const t = `[[[{{index .P 1}}, {{index .P 2}}],
[{{index .P 3}}, {{index .P 4}}, {{index .P 1}}],
{{index .P 5}}]]
`
type S struct {
P map[int]string
}
var s S
s.P = map[int]string{
0: "'Payload#0'", 1: "'Payload#1'", 2: "'Payload#2'", 3: "'Payload#3'",
4: "'Payload#4'", 5: "'Payload#5'", 6: "'Payload#6'",
}
tmpl := template.Must(template.New("").Parse(t))
tmpl.Execute(os.Stdout, s)
var unused []int
for k, _ := range s.P {
if !strings.Contains(t, fmt.Sprintf("{{index .P %d}}", k)) {
unused = append(unused, k)
}
}
sort.Ints(unused)
fmt.Println("\nThe unused payloads have indices of :", unused)
}
| Public Sub test()
Dim t(2) As Variant
t(0) = [{1,2}]
t(1) = [{3,4,1}]
t(2) = 5
p = [{"Payload#0","Payload#1","Payload#2","Payload#3","Payload#4","Payload#5","Payload#6"}]
Dim q(6) As Boolean
For i = LBound(t) To UBound(t)
If IsArray(t(i)) Then
For j = LBound(t(i)) To UBound(t(i))
q(t(i)(j)) = True
t(i)(j) = p(t(i)(j) + 1)
Next j
Else
q(t(i)) = True
t(i) = p(t(i) + 1)
End If
Next i
For i = LBound(t) To UBound(t)
If IsArray(t(i)) Then
Debug.Print Join(t(i), ", ")
Else
Debug.Print t(i)
End If
Next i
For i = LBound(q) To UBound(q)
If Not q(i) Then Debug.Print p(i + 1); " is not used"
Next i
End Sub
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
string readFile (string path) {
string contents;
string line;
ifstream inFile(path);
while (getline (inFile, line)) {
contents.append(line);
contents.append("\n");
}
inFile.close();
return contents;
}
double entropy (string X) {
const int MAXCHAR = 127;
int N = X.length();
int count[MAXCHAR];
double count_i;
char ch;
double sum = 0.0;
for (int i = 0; i < MAXCHAR; i++) count[i] = 0;
for (int pos = 0; pos < N; pos++) {
ch = X[pos];
count[(int)ch]++;
}
for (int n_i = 0; n_i < MAXCHAR; n_i++) {
count_i = count[n_i];
if (count_i > 0) sum -= count_i / N * log2(count_i / N);
}
return sum;
}
int main () {
cout<<entropy(readFile("entropy.cpp"));
return 0;
}
| package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <Rcpp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace Rcpp ;
CharacterVector getNameInfo(std::string fqdn) {
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);
if (error) { return(NA_STRING); }
int i = 0 ;
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (!error) { i++ ; }
}
CharacterVector results(i) ;
i = 0;
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (!error) { results[i++] = host ; }
}
freeaddrinfo(res0);
return(results) ;
}
| package main
import (
"fmt"
"net"
)
func main() {
if addrs, err := net.LookupHost("www.kame.net"); err == nil {
fmt.Println(addrs)
} else {
fmt.Println(err)
}
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class peano_curve {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std::string& s);
double x_;
double y_;
int angle_;
int length_;
};
void peano_curve::write(std::ostream& out, int size, int length, int order) {
length_ = length;
x_ = length;
y_ = length;
angle_ = 90;
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
std::string s = "L";
for (int i = 0; i < order; ++i)
s = rewrite(s);
execute(out, s);
out << "'/>\n</svg>\n";
}
std::string peano_curve::rewrite(const std::string& s) {
std::string t;
for (char c : s) {
switch (c) {
case 'L':
t += "LFRFL-F-RFLFR+F+LFRFL";
break;
case 'R':
t += "RFLFR+F+LFRFL-F-RFLFR";
break;
default:
t += c;
break;
}
}
return t;
}
void peano_curve::line(std::ostream& out) {
double theta = (3.14159265359 * angle_)/180.0;
x_ += length_ * std::cos(theta);
y_ += length_ * std::sin(theta);
out << " L" << x_ << ',' << y_;
}
void peano_curve::execute(std::ostream& out, const std::string& s) {
out << 'M' << x_ << ',' << y_;
for (char c : s) {
switch (c) {
case 'F':
line(out);
break;
case '+':
angle_ = (angle_ + 90) % 360;
break;
case '-':
angle_ = (angle_ - 90) % 360;
break;
}
}
}
int main() {
std::ofstream out("peano_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return 1;
}
peano_curve pc;
pc.write(out, 656, 8, 4);
return 0;
}
| package main
import "github.com/fogleman/gg"
var points []gg.Point
const width = 81
func peano(x, y, lg, i1, i2 int) {
if lg == 1 {
px := float64(width-x) * 10
py := float64(width-y) * 10
points = append(points, gg.Point{px, py})
return
}
lg /= 3
peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)
peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)
peano(x+lg, y+lg, lg, i1, 1-i2)
peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)
peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)
peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)
peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)
peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)
peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)
}
func main() {
peano(0, 0, width, 0, 0)
dc := gg.NewContext(820, 820)
dc.SetRGB(1, 1, 1)
dc.Clear()
for _, p := range points {
dc.LineTo(p.X, p.Y)
}
dc.SetRGB(1, 0, 1)
dc.SetLineWidth(1)
dc.Stroke()
dc.SavePNG("peano.png")
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | template<typename F> class fivetoseven
{
public:
fivetoseven(F f): d5(f), rem(0), max(1) {}
int operator()();
private:
F d5;
int rem, max;
};
template<typename F>
int fivetoseven<F>::operator()()
{
while (rem/7 == max/7)
{
while (max < 7)
{
int rand5 = d5()-1;
max *= 5;
rem = 5*rem + rand5;
}
int groups = max / 7;
if (rem >= 7*groups)
{
rem -= 7*groups;
max -= 7*groups;
}
}
int result = rem % 7;
rem /= 7;
max /= 7;
return result+1;
}
int d5()
{
return 5.0*std::rand()/(RAND_MAX + 1.0) + 1;
}
fivetoseven<int(*)()> d7(d5);
int main()
{
srand(time(0));
test_distribution(d5, 1000000, 0.001);
test_distribution(d7, 1000000, 0.001);
}
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func dice5() int {
return rand.Intn(5) + 1
}
func dice7() (i int) {
for {
i = 5*dice5() + dice5()
if i < 27 {
break
}
}
return (i / 3) - 1
}
func distCheck(f func() int, n int,
repeats int, delta float64) (max float64, flatEnough bool) {
count := make([]int, n)
for i := 0; i < repeats; i++ {
count[f()-1]++
}
expected := float64(repeats) / float64(n)
for _, c := range count {
max = math.Max(max, math.Abs(float64(c)-expected))
}
return max, max < delta
}
func main() {
rand.Seed(time.Now().UnixNano())
const calls = 1000000
max, flatEnough := distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
max, flatEnough = distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <array>
#include <iostream>
#include <vector>
std::vector<std::pair<int, int>> connections = {
{0, 2}, {0, 3}, {0, 4},
{1, 3}, {1, 4}, {1, 5},
{6, 2}, {6, 3}, {6, 4},
{7, 3}, {7, 4}, {7, 5},
{2, 3}, {3, 4}, {4, 5},
};
std::array<int, 8> pegs;
int num = 0;
void printSolution() {
std::cout << "----- " << num++ << " -----\n";
std::cout << " " << pegs[0] << ' ' << pegs[1] << '\n';
std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\n';
std::cout << " " << pegs[6] << ' ' << pegs[7] << '\n';
std::cout << '\n';
}
bool valid() {
for (size_t i = 0; i < connections.size(); i++) {
if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) {
return false;
}
}
return true;
}
void solution(int le, int ri) {
if (le == ri) {
if (valid()) {
printSolution();
}
} else {
for (size_t i = le; i <= ri; i++) {
std::swap(pegs[le], pegs[i]);
solution(le + 1, ri);
std::swap(pegs[le], pegs[i]);
}
}
}
int main() {
pegs = { 1, 2, 3, 4, 5, 6, 7, 8 };
solution(0, pegs.size() - 1);
return 0;
}
| package main
import (
"fmt"
"strings"
)
func main() {
p, tests, swaps := Solution()
fmt.Println(p)
fmt.Println("Tested", tests, "positions and did", swaps, "swaps.")
}
const conn = `
A B
/|\ /|\
/ | X | \
/ |/ \| \
C - D - E - F
\ |\ /| /
\ | X | /
\|/ \|/
G H`
var connections = []struct{ a, b int }{
{0, 2}, {0, 3}, {0, 4},
{1, 3}, {1, 4}, {1, 5},
{6, 2}, {6, 3}, {6, 4},
{7, 3}, {7, 4}, {7, 5},
{2, 3}, {3, 4}, {4, 5},
}
type pegs [8]int
func (p *pegs) Valid() bool {
for _, c := range connections {
if absdiff(p[c.a], p[c.b]) <= 1 {
return false
}
}
return true
}
func Solution() (p *pegs, tests, swaps int) {
var recurse func(int) bool
recurse = func(i int) bool {
if i >= len(p)-1 {
tests++
return p.Valid()
}
for j := i; j < len(p); j++ {
swaps++
p[i], p[j] = p[j], p[i]
if recurse(i + 1) {
return true
}
p[i], p[j] = p[j], p[i]
}
return false
}
p = &pegs{1, 2, 3, 4, 5, 6, 7, 8}
recurse(0)
return
}
func (p *pegs) String() string {
return strings.Map(func(r rune) rune {
if 'A' <= r && r <= 'H' {
return rune(p[r-'A'] + '0')
}
return r
}, conn)
}
func absdiff(a, b int) int {
if a > b {
return a - b
}
return b - a
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <iomanip>
#include <iostream>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
bool is_magnanimous(unsigned int n) {
for (unsigned int p = 10; n >= p; p *= 10) {
if (!is_prime(n % p + n / p))
return false;
}
return true;
}
int main() {
unsigned int count = 0, n = 0;
std::cout << "First 45 magnanimous numbers:\n";
for (; count < 45; ++n) {
if (is_magnanimous(n)) {
if (count > 0)
std::cout << (count % 15 == 0 ? "\n" : ", ");
std::cout << std::setw(3) << n;
++count;
}
}
std::cout << "\n\n241st through 250th magnanimous numbers:\n";
for (unsigned int i = 0; count < 250; ++n) {
if (is_magnanimous(n)) {
if (count++ >= 240) {
if (i++ > 0)
std::cout << ", ";
std::cout << n;
}
}
}
std::cout << "\n\n391st through 400th magnanimous numbers:\n";
for (unsigned int i = 0; count < 400; ++n) {
if (is_magnanimous(n)) {
if (count++ >= 390) {
if (i++ > 0)
std::cout << ", ";
std::cout << n;
}
}
}
std::cout << '\n';
return 0;
}
| package main
import "fmt"
func isPrime(n uint64) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := uint64(5)
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func ord(n int) string {
m := n % 100
if m >= 4 && m <= 20 {
return fmt.Sprintf("%dth", n)
}
m %= 10
suffix := "th"
if m < 4 {
switch m {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
}
}
return fmt.Sprintf("%d%s", n, suffix)
}
func isMagnanimous(n uint64) bool {
if n < 10 {
return true
}
for p := uint64(10); ; p *= 10 {
q := n / p
r := n % p
if !isPrime(q + r) {
return false
}
if q < 10 {
break
}
}
return true
}
func listMags(from, thru, digs, perLine int) {
if from < 2 {
fmt.Println("\nFirst", thru, "magnanimous numbers:")
} else {
fmt.Printf("\n%s through %s magnanimous numbers:\n", ord(from), ord(thru))
}
for i, c := uint64(0), 0; c < thru; i++ {
if isMagnanimous(i) {
c++
if c >= from {
fmt.Printf("%*d ", digs, i)
if c%perLine == 0 {
fmt.Println()
}
}
}
}
}
func main() {
listMags(1, 45, 3, 15)
listMags(241, 250, 1, 10)
listMags(391, 400, 1, 10)
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <iostream>
#include <cstdint>
#include <queue>
#include <utility>
#include <vector>
#include <limits>
template<typename integer>
class prime_generator {
public:
integer next_prime();
integer count() const {
return count_;
}
private:
struct queue_item {
queue_item(integer prime, integer multiple, unsigned int wheel_index) :
prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {}
integer prime_;
integer multiple_;
unsigned int wheel_index_;
};
struct cmp {
bool operator()(const queue_item& a, const queue_item& b) const {
return a.multiple_ > b.multiple_;
}
};
static integer wheel_next(unsigned int& index) {
integer offset = wheel_[index];
++index;
if (index == std::size(wheel_))
index = 0;
return offset;
}
typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue;
integer next_ = 11;
integer count_ = 0;
queue queue_;
unsigned int wheel_index_ = 0;
static const unsigned int wheel_[];
static const integer primes_[];
};
template<typename integer>
const unsigned int prime_generator<integer>::wheel_[] = {
2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,
6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6,
2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10
};
template<typename integer>
const integer prime_generator<integer>::primes_[] = {
2, 3, 5, 7
};
template<typename integer>
integer prime_generator<integer>::next_prime() {
if (count_ < std::size(primes_))
return primes_[count_++];
integer n = next_;
integer prev = 0;
while (!queue_.empty()) {
queue_item item = queue_.top();
if (prev != 0 && prev != item.multiple_)
n += wheel_next(wheel_index_);
if (item.multiple_ > n)
break;
else if (item.multiple_ == n) {
queue_.pop();
queue_item new_item(item);
new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_);
queue_.push(new_item);
}
else
throw std::overflow_error("prime_generator: overflow!");
prev = item.multiple_;
}
if (std::numeric_limits<integer>::max()/n > n)
queue_.emplace(n, n * n, wheel_index_);
next_ = n + wheel_next(wheel_index_);
++count_;
return n;
}
int main() {
typedef uint32_t integer;
prime_generator<integer> pgen;
std::cout << "First 20 primes:\n";
for (int i = 0; i < 20; ++i) {
integer p = pgen.next_prime();
if (i != 0)
std::cout << ", ";
std::cout << p;
}
std::cout << "\nPrimes between 100 and 150:\n";
for (int n = 0; ; ) {
integer p = pgen.next_prime();
if (p > 150)
break;
if (p >= 100) {
if (n != 0)
std::cout << ", ";
std::cout << p;
++n;
}
}
int count = 0;
for (;;) {
integer p = pgen.next_prime();
if (p > 8000)
break;
if (p >= 7700)
++count;
}
std::cout << "\nNumber of primes between 7700 and 8000: " << count << '\n';
for (integer n = 10000; n <= 10000000; n *= 10) {
integer prime;
while (pgen.count() != n)
prime = pgen.next_prime();
std::cout << n << "th prime: " << prime << '\n';
}
return 0;
}
| package main
import (
"container/heap"
"fmt"
)
func main() {
p := newP()
fmt.Print("First twenty: ")
for i := 0; i < 20; i++ {
fmt.Print(p(), " ")
}
fmt.Print("\nBetween 100 and 150: ")
n := p()
for n <= 100 {
n = p()
}
for ; n < 150; n = p() {
fmt.Print(n, " ")
}
for n <= 7700 {
n = p()
}
c := 0
for ; n < 8000; n = p() {
c++
}
fmt.Println("\nNumber beween 7,700 and 8,000:", c)
p = newP()
for i := 1; i < 10000; i++ {
p()
}
fmt.Println("10,000th prime:", p())
}
func newP() func() int {
n := 1
var pq pQueue
top := &pMult{2, 4, 0}
return func() int {
for {
n++
if n < top.pMult {
heap.Push(&pq, &pMult{prime: n, pMult: n * n})
top = pq[0]
return n
}
for top.pMult == n {
top.pMult += top.prime
heap.Fix(&pq, 0)
top = pq[0]
}
}
}
}
type pMult struct {
prime int
pMult int
index int
}
type pQueue []*pMult
func (q pQueue) Len() int { return len(q) }
func (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }
func (q pQueue) Swap(i, j int) {
q[i], q[j] = q[j], q[i]
q[i].index = i
q[j].index = j
}
func (p *pQueue) Push(x interface{}) {
q := *p
e := x.(*pMult)
e.index = len(q)
*p = append(q, e)
}
func (p *pQueue) Pop() interface{} {
q := *p
last := len(q) - 1
e := q[last]
*p = q[:last]
return e
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };
enum indexes { PLAYER, COMPUTER, DRAW };
class stats
{
public:
stats() : _draw( 0 )
{
ZeroMemory( _moves, sizeof( _moves ) );
ZeroMemory( _win, sizeof( _win ) );
}
void draw() { _draw++; }
void win( int p ) { _win[p]++; }
void move( int p, int m ) { _moves[p][m]++; }
int getMove( int p, int m ) { return _moves[p][m]; }
string format( int a )
{
char t[32];
wsprintf( t, "%.3d", a );
string d( t );
return d;
}
void print()
{
string d = format( _draw ),
pw = format( _win[PLAYER] ), cw = format( _win[COMPUTER] ),
pr = format( _moves[PLAYER][ROCK] ), cr = format( _moves[COMPUTER][ROCK] ),
pp = format( _moves[PLAYER][PAPER] ), cp = format( _moves[COMPUTER][PAPER] ),
ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),
pl = format( _moves[PLAYER][LIZARD] ), cl = format( _moves[COMPUTER][LIZARD] ),
pk = format( _moves[PLAYER][SPOCK] ), ck = format( _moves[COMPUTER][SPOCK] );
system( "cls" );
cout << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |" << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << "| PLAYER | " << pw << " | | " << pr << " | " << pp << " | " << ps << " | " << pl << " | " << pk << " |" << endl;
cout << "+----------+-------+ " << d << " +--------+---------+----------+--------+---------+" << endl;
cout << "| COMPUTER | " << cw << " | | " << cr << " | " << cp << " | " << cs << " | " << cl << " | " << ck << " |" << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << endl << endl;
system( "pause" );
}
private:
int _moves[2][MX_C], _win[2], _draw;
};
class rps
{
private:
int makeMove()
{
int total = 0, r, s;
for( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );
r = rand() % total;
for( int i = ROCK; i < SCISSORS; i++ )
{
s = statistics.getMove( PLAYER, i );
if( r < s ) return ( i + 1 );
r -= s;
}
return ROCK;
}
void printMove( int p, int m )
{
if( p == COMPUTER ) cout << "My move: ";
else cout << "Your move: ";
switch( m )
{
case ROCK: cout << "ROCK\n"; break;
case PAPER: cout << "PAPER\n"; break;
case SCISSORS: cout << "SCISSORS\n"; break;
case LIZARD: cout << "LIZARD\n"; break;
case SPOCK: cout << "SPOCK\n";
}
}
public:
rps()
{
checker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;
checker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;
checker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;
checker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;
checker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;
}
void play()
{
int p, r, m;
while( true )
{
cout << "What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? ";
cin >> p;
if( !p || p < 0 ) break;
if( p > 0 && p < 6 )
{
p--;
cout << endl;
printMove( PLAYER, p );
statistics.move( PLAYER, p );
m = makeMove();
statistics.move( COMPUTER, m );
printMove( COMPUTER, m );
r = checker[p][m];
switch( r )
{
case DRAW:
cout << endl << "DRAW!" << endl << endl;
statistics.draw();
break;
case COMPUTER:
cout << endl << "I WIN!" << endl << endl;
statistics.win( COMPUTER );
break;
case PLAYER:
cout << endl << "YOU WIN!" << endl << endl;
statistics.win( PLAYER );
}
system( "pause" );
}
system( "cls" );
}
statistics.print();
}
private:
stats statistics;
int checker[MX_C][MX_C];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
rps game;
game.play();
return 0;
}
| package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
const rps = "rps"
var msg = []string{
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("Rock Paper Scissors")
fmt.Println("Enter r, p, or s as your play. Anything else ends the game.")
fmt.Println("Running score shown as <your wins>:<my wins>")
var pi string
var aScore, pScore int
sl := 3
pcf := make([]int, 3)
var plays int
aChoice := rand.Intn(3)
for {
fmt.Print("Play: ")
_, err := fmt.Scanln(&pi)
if err != nil || len(pi) != 1 {
break
}
pChoice := strings.Index(rps, pi)
if pChoice < 0 {
break
}
pcf[pChoice]++
plays++
fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice])
switch (aChoice - pChoice + 3) % 3 {
case 0:
fmt.Println("Tie.")
case 1:
fmt.Printf("%s. My point.\n", msg[aChoice])
aScore++
case 2:
fmt.Printf("%s. Your point.\n", msg[pChoice])
pScore++
}
sl, _ = fmt.Printf("%d:%d ", pScore, aScore)
switch rn := rand.Intn(plays); {
case rn < pcf[0]:
aChoice = 1
case rn < pcf[0]+pcf[1]:
aChoice = 2
default:
aChoice = 0
}
}
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #include <iostream>
int main()
{
int dim1, dim2;
std::cin >> dim1 >> dim2;
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
for (int i = 0; i < dim1; ++i)
array[i] = array_data + dim2*i;
array[0][0] = 3.5;
std::cout << array[0][0] << std::endl;
delete[] array;
delete[] array_data;
return 0;
}
| package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
fmt.Println("a[0][0] =", a[0][0])
a[row-1][col-1] = 7
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
a = nil
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. |
#include <iostream>
#include <numeric>
#include <vector>
#include <execution>
template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {
_Ty b0 = b;
_Ty x0 = 0;
_Ty x1 = 1;
if (b == 1) {
return 1;
}
while (a > 1) {
_Ty q = a / b;
_Ty amb = a % b;
a = b;
b = amb;
_Ty xqx = x1 - q * x0;
x1 = x0;
x0 = xqx;
}
if (x1 < 0) {
x1 += b0;
}
return x1;
}
template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {
_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });
_Ty sm = 0;
for (int i = 0; i < n.size(); i++) {
_Ty p = prod / n[i];
sm += a[i] * mulInv(p, n[i]) * p;
}
return sm % prod;
}
int main() {
vector<int> n = { 3, 5, 7 };
vector<int> a = { 2, 3, 2 };
cout << chineseRemainder(n,a) << endl;
return 0;
}
| package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
func crt(a, n []*big.Int) (*big.Int, error) {
p := new(big.Int).Set(n[0])
for _, n1 := range n[1:] {
p.Mul(p, n1)
}
var x, q, s, z big.Int
for i, n1 := range n {
q.Div(p, n1)
z.GCD(nil, &s, n1, &q)
if z.Cmp(one) != 0 {
return nil, fmt.Errorf("%d not coprime", n1)
}
x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))
}
return x.Mod(&x, p), nil
}
func main() {
n := []*big.Int{
big.NewInt(3),
big.NewInt(5),
big.NewInt(7),
}
a := []*big.Int{
big.NewInt(2),
big.NewInt(3),
big.NewInt(2),
}
fmt.Println(crt(a, n))
}
|
Produce a functionally identical Go code for the snippet given in C++. |
#include <iostream>
#include <numeric>
#include <vector>
#include <execution>
template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) {
_Ty b0 = b;
_Ty x0 = 0;
_Ty x1 = 1;
if (b == 1) {
return 1;
}
while (a > 1) {
_Ty q = a / b;
_Ty amb = a % b;
a = b;
b = amb;
_Ty xqx = x1 - q * x0;
x1 = x0;
x0 = xqx;
}
if (x1 < 0) {
x1 += b0;
}
return x1;
}
template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) {
_Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });
_Ty sm = 0;
for (int i = 0; i < n.size(); i++) {
_Ty p = prod / n[i];
sm += a[i] * mulInv(p, n[i]) * p;
}
return sm % prod;
}
int main() {
vector<int> n = { 3, 5, 7 };
vector<int> a = { 2, 3, 2 };
cout << chineseRemainder(n,a) << endl;
return 0;
}
| package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
func crt(a, n []*big.Int) (*big.Int, error) {
p := new(big.Int).Set(n[0])
for _, n1 := range n[1:] {
p.Mul(p, n1)
}
var x, q, s, z big.Int
for i, n1 := range n {
q.Div(p, n1)
z.GCD(nil, &s, n1, &q)
if z.Cmp(one) != 0 {
return nil, fmt.Errorf("%d not coprime", n1)
}
x.Add(&x, s.Mul(a[i], s.Mul(&s, &q)))
}
return x.Mod(&x, p), nil
}
func main() {
n := []*big.Int{
big.NewInt(3),
big.NewInt(5),
big.NewInt(7),
}
a := []*big.Int{
big.NewInt(2),
big.NewInt(3),
big.NewInt(2),
}
fmt.Println(crt(a, n))
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <array>
using namespace std;
typedef array<pair<char, double>, 26> FreqArray;
class VigenereAnalyser
{
private:
array<double, 26> targets;
array<double, 26> sortedTargets;
FreqArray freq;
FreqArray& frequency(const string& input)
{
for (char c = 'A'; c <= 'Z'; ++c)
freq[c - 'A'] = make_pair(c, 0);
for (size_t i = 0; i < input.size(); ++i)
freq[input[i] - 'A'].second++;
return freq;
}
double correlation(const string& input)
{
double result = 0.0;
frequency(input);
sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool
{ return u.second < v.second; });
for (size_t i = 0; i < 26; ++i)
result += freq[i].second * sortedTargets[i];
return result;
}
public:
VigenereAnalyser(const array<double, 26>& targetFreqs)
{
targets = targetFreqs;
sortedTargets = targets;
sort(sortedTargets.begin(), sortedTargets.end());
}
pair<string, string> analyze(string input)
{
string cleaned;
for (size_t i = 0; i < input.size(); ++i)
{
if (input[i] >= 'A' && input[i] <= 'Z')
cleaned += input[i];
else if (input[i] >= 'a' && input[i] <= 'z')
cleaned += input[i] + 'A' - 'a';
}
size_t bestLength = 0;
double bestCorr = -100.0;
for (size_t i = 2; i < cleaned.size() / 20; ++i)
{
vector<string> pieces(i);
for (size_t j = 0; j < cleaned.size(); ++j)
pieces[j % i] += cleaned[j];
double corr = -0.5*i;
for (size_t j = 0; j < i; ++j)
corr += correlation(pieces[j]);
if (corr > bestCorr)
{
bestLength = i;
bestCorr = corr;
}
}
if (bestLength == 0)
return make_pair("Text is too short to analyze", "");
vector<string> pieces(bestLength);
for (size_t i = 0; i < cleaned.size(); ++i)
pieces[i % bestLength] += cleaned[i];
vector<FreqArray> freqs;
for (size_t i = 0; i < bestLength; ++i)
freqs.push_back(frequency(pieces[i]));
string key = "";
for (size_t i = 0; i < bestLength; ++i)
{
sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool
{ return u.second > v.second; });
size_t m = 0;
double mCorr = 0.0;
for (size_t j = 0; j < 26; ++j)
{
double corr = 0.0;
char c = 'A' + j;
for (size_t k = 0; k < 26; ++k)
{
int d = (freqs[i][k].first - c + 26) % 26;
corr += freqs[i][k].second * targets[d];
}
if (corr > mCorr)
{
m = j;
mCorr = corr;
}
}
key += m + 'A';
}
string result = "";
for (size_t i = 0; i < cleaned.size(); ++i)
result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';
return make_pair(result, key);
}
};
int main()
{
string input =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH"
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD"
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS"
"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG"
"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ"
"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS"
"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT"
"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST"
"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH"
"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV"
"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW"
"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO"
"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR"
"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX"
"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB"
"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA"
"FWAML ZZRXJ EKAHV FASMU LVVUT TGK";
array<double, 26> english = {
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,
0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,
0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,
0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,
0.01974, 0.00074};
VigenereAnalyser va(english);
pair<string, string> output = va.analyze(input);
cout << "Key: " << output.second << endl << endl;
cout << "Text: " << output.first << endl;
}
| package main
import (
"fmt"
"strings"
)
var encoded =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" +
"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" +
"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" +
"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" +
"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" +
"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" +
"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" +
"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" +
"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" +
"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" +
"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" +
"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" +
"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" +
"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" +
"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" +
"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" +
"FWAML ZZRXJ EKAHV FASMU LVVUT TGK"
var freq = [26]float64{
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074,
}
func sum(a []float64) (sum float64) {
for _, f := range a {
sum += f
}
return
}
func bestMatch(a []float64) int {
sum := sum(a)
bestFit, bestRotate := 1e100, 0
for rotate := 0; rotate < 26; rotate++ {
fit := 0.0
for i := 0; i < 26; i++ {
d := a[(i+rotate)%26]/sum - freq[i]
fit += d * d / freq[i]
}
if fit < bestFit {
bestFit, bestRotate = fit, rotate
}
}
return bestRotate
}
func freqEveryNth(msg []int, key []byte) float64 {
l := len(msg)
interval := len(key)
out := make([]float64, 26)
accu := make([]float64, 26)
for j := 0; j < interval; j++ {
for k := 0; k < 26; k++ {
out[k] = 0.0
}
for i := j; i < l; i += interval {
out[msg[i]]++
}
rot := bestMatch(out)
key[j] = byte(rot + 65)
for i := 0; i < 26; i++ {
accu[i] += out[(i+rot)%26]
}
}
sum := sum(accu)
ret := 0.0
for i := 0; i < 26; i++ {
d := accu[i]/sum - freq[i]
ret += d * d / freq[i]
}
return ret
}
func decrypt(text, key string) string {
var sb strings.Builder
ki := 0
for _, c := range text {
if c < 'A' || c > 'Z' {
continue
}
ci := (c - rune(key[ki]) + 26) % 26
sb.WriteRune(ci + 65)
ki = (ki + 1) % len(key)
}
return sb.String()
}
func main() {
enc := strings.Replace(encoded, " ", "", -1)
txt := make([]int, len(enc))
for i := 0; i < len(txt); i++ {
txt[i] = int(enc[i] - 'A')
}
bestFit, bestKey := 1e100, ""
fmt.Println(" Fit Length Key")
for j := 1; j <= 26; j++ {
key := make([]byte, j)
fit := freqEveryNth(txt, key)
sKey := string(key)
fmt.Printf("%f %2d %s", fit, j, sKey)
if fit < bestFit {
bestFit, bestKey = fit, sKey
fmt.Print(" <--- best so far")
}
fmt.Println()
}
fmt.Println("\nBest key :", bestKey)
fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey))
}
|
Change the following C++ code into Go without altering its purpose. | #include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
class Gospers
{
cpp_int q, r, t, i, n;
public:
Gospers() : q{1}, r{0}, t{1}, i{1}
{
++*this;
}
Gospers& operator++()
{
n = (q*(27*i-12)+5*r) / (5*t);
while(n != (q*(675*i-216)+125*r)/(125*t))
{
r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);
q = i*(2*i-1)*q;
t = 3*(3*i+1)*(3*i+2)*t;
i++;
n = (q*(27*i-12)+5*r) / (5*t);
}
q = 10*q;
r = 10*r-10*n*t;
return *this;
}
int operator*()
{
return (int)n;
}
};
int main()
{
Gospers g;
std::cout << *g << ".";
for(;;)
{
std::cout << *++g;
}
}
| package main
import (
"fmt"
"math/big"
)
type lft struct {
q,r,s,t big.Int
}
func (t *lft) extr(x *big.Int) *big.Rat {
var n, d big.Int
var r big.Rat
return r.SetFrac(
n.Add(n.Mul(&t.q, x), &t.r),
d.Add(d.Mul(&t.s, x), &t.t))
}
var three = big.NewInt(3)
var four = big.NewInt(4)
func (t *lft) next() *big.Int {
r := t.extr(three)
var f big.Int
return f.Div(r.Num(), r.Denom())
}
func (t *lft) safe(n *big.Int) bool {
r := t.extr(four)
var f big.Int
if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {
return true
}
return false
}
func (t *lft) comp(u *lft) *lft {
var r lft
var a, b big.Int
r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))
r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))
r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))
r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))
return &r
}
func (t *lft) prod(n *big.Int) *lft {
var r lft
r.q.SetInt64(10)
r.r.Mul(r.r.SetInt64(-10), n)
r.t.SetInt64(1)
return r.comp(t)
}
func main() {
z := new(lft)
z.q.SetInt64(1)
z.t.SetInt64(1)
var k int64
lfts := func() *lft {
k++
r := new(lft)
r.q.SetInt64(k)
r.r.SetInt64(4*k+2)
r.t.SetInt64(2*k+1)
return r
}
for {
y := z.next()
if z.safe(y) {
fmt.Print(y)
z = z.prod(y)
} else {
z = z.comp(lfts())
}
}
}
|
Please provide an equivalent version of this C++ code in Go. | #include <iostream>
int main() {
const int size = 100000;
int hofstadters[size] = { 1, 1 };
for (int i = 3 ; i < size; i++)
hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +
hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];
std::cout << "The first 10 numbers are: ";
for (int i = 0; i < 10; i++)
std::cout << hofstadters[ i ] << ' ';
std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl;
int less_than_preceding = 0;
for (int i = 0; i < size - 1; i++)
if (hofstadters[ i + 1 ] < hofstadters[ i ])
less_than_preceding++;
std::cout << "In array of size: " << size << ", ";
std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl;
return 0;
}
| package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap()
for n := 1; n <= 10; n++ {
showQ(n)
}
showQ(1000)
count, p := 0, 1
for n := 2; n <= 1e5; n++ {
qn := q(n)
if qn < p {
count++
}
p = qn
}
fmt.Println("count:", count)
initMap()
showQ(1e6)
}
func showQ(n int) {
fmt.Printf("Q(%d) = %d\n", n, q(n))
}
|
Change the following C++ code into Go without altering its purpose. | #include <iostream>
int main() {
const int size = 100000;
int hofstadters[size] = { 1, 1 };
for (int i = 3 ; i < size; i++)
hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] +
hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]];
std::cout << "The first 10 numbers are: ";
for (int i = 0; i < 10; i++)
std::cout << hofstadters[ i ] << ' ';
std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl;
int less_than_preceding = 0;
for (int i = 0; i < size - 1; i++)
if (hofstadters[ i + 1 ] < hofstadters[ i ])
less_than_preceding++;
std::cout << "In array of size: " << size << ", ";
std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl;
return 0;
}
| package main
import "fmt"
var m map[int]int
func initMap() {
m = make(map[int]int)
m[1] = 1
m[2] = 1
}
func q(n int) (r int) {
if r = m[n]; r == 0 {
r = q(n-q(n-1)) + q(n-q(n-2))
m[n] = r
}
return
}
func main() {
initMap()
for n := 1; n <= 10; n++ {
showQ(n)
}
showQ(1000)
count, p := 0, 1
for n := 2; n <= 1e5; n++ {
qn := q(n)
if qn < p {
count++
}
p = qn
}
fmt.Println("count:", count)
initMap()
showQ(1e6)
}
func showQ(n int) {
fmt.Printf("Q(%d) = %d\n", n, q(n))
}
|
Write a version of this C++ function in Go with identical behavior. | #include <iostream>
#include <functional>
template <typename F>
struct RecursiveFunc {
std::function<F(RecursiveFunc)> o;
};
template <typename A, typename B>
std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {
RecursiveFunc<std::function<B(A)>> r = {
std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {
return f(std::function<B(A)>([w](A x) {
return w.o(w)(x);
}));
})
};
return r.o(r);
}
typedef std::function<int(int)> Func;
typedef std::function<Func(Func)> FuncFunc;
FuncFunc almost_fac = [](Func f) {
return Func([f](int n) {
if (n <= 1) return 1;
return n * f(n - 1);
});
};
FuncFunc almost_fib = [](Func f) {
return Func([f](int n) {
if (n <= 2) return 1;
return f(n - 1) + f(n - 2);
});
};
int main() {
auto fib = Y(almost_fib);
auto fac = Y(almost_fac);
std::cout << "fib(10) = " << fib(10) << std::endl;
std::cout << "fac(10) = " << fac(10) << std::endl;
return 0;
}
| package main
import "fmt"
type Func func(int) int
type FuncFunc func(Func) Func
type RecursiveFunc func (RecursiveFunc) Func
func main() {
fac := Y(almost_fac)
fib := Y(almost_fib)
fmt.Println("fac(10) = ", fac(10))
fmt.Println("fib(10) = ", fib(10))
}
func Y(f FuncFunc) Func {
g := func(r RecursiveFunc) Func {
return f(func(x int) int {
return r(r)(x)
})
}
return g(g)
}
func almost_fac(f Func) Func {
return func(x int) int {
if x <= 1 {
return 1
}
return x * f(x-1)
}
}
func almost_fib(f Func) Func {
return func(x int) int {
if x <= 2 {
return 1
}
return f(x-1)+f(x-2)
}
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <tuple>
std::tuple<int, int> minmax(const int * numbers, const std::size_t num) {
const auto maximum = std::max_element(numbers, numbers + num);
const auto minimum = std::min_element(numbers, numbers + num);
return std::make_tuple(*minimum, *maximum) ;
}
int main( ) {
const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};
int min{};
int max{};
std::tie(min, max) = minmax(numbers.data(), numbers.size());
std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
}
| func addsub(x, y int) (int, int) {
return x + y, x - y
}
|
Generate an equivalent Go version of this C++ code. | #include <iostream>
#include <map>
class van_eck_generator {
public:
int next() {
int result = last_term;
auto iter = last_pos.find(last_term);
int next_term = (iter != last_pos.end()) ? index - iter->second : 0;
last_pos[last_term] = index;
last_term = next_term;
++index;
return result;
}
private:
int index = 0;
int last_term = 0;
std::map<int, int> last_pos;
};
int main() {
van_eck_generator gen;
int i = 0;
std::cout << "First 10 terms of the Van Eck sequence:\n";
for (; i < 10; ++i)
std::cout << gen.next() << ' ';
for (; i < 990; ++i)
gen.next();
std::cout << "\nTerms 991 to 1000 of the sequence:\n";
for (; i < 1000; ++i)
std::cout << gen.next() << ' ';
std::cout << '\n';
return 0;
}
| package main
import "fmt"
func main() {
const max = 1000
a := make([]int, max)
for n := 0; n < max-1; n++ {
for m := n - 1; m >= 0; m-- {
if a[m] == a[n] {
a[n+1] = n - m
break
}
}
}
fmt.Println("The first ten terms of the Van Eck sequence are:")
fmt.Println(a[:10])
fmt.Println("\nTerms 991 to 1000 of the sequence are:")
fmt.Println(a[990:])
}
|
Write the same code in Go as shown below in C++. | #include <iostream>
#include <map>
class van_eck_generator {
public:
int next() {
int result = last_term;
auto iter = last_pos.find(last_term);
int next_term = (iter != last_pos.end()) ? index - iter->second : 0;
last_pos[last_term] = index;
last_term = next_term;
++index;
return result;
}
private:
int index = 0;
int last_term = 0;
std::map<int, int> last_pos;
};
int main() {
van_eck_generator gen;
int i = 0;
std::cout << "First 10 terms of the Van Eck sequence:\n";
for (; i < 10; ++i)
std::cout << gen.next() << ' ';
for (; i < 990; ++i)
gen.next();
std::cout << "\nTerms 991 to 1000 of the sequence:\n";
for (; i < 1000; ++i)
std::cout << gen.next() << ' ';
std::cout << '\n';
return 0;
}
| package main
import "fmt"
func main() {
const max = 1000
a := make([]int, max)
for n := 0; n < max-1; n++ {
for m := n - 1; m >= 0; m-- {
if a[m] == a[n] {
a[n+1] = n - m
break
}
}
}
fmt.Println("The first ten terms of the Van Eck sequence are:")
fmt.Println(a[:10])
fmt.Println("\nTerms 991 to 1000 of the sequence are:")
fmt.Println(a[990:])
}
|
Write the same code in Go as shown below in C++. |
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <sys/stat.h>
#include <ftplib.h>
#include <ftp++.hpp>
int stat(const char *pathname, struct stat *buf);
char *strerror(int errnum);
char *basename(char *path);
namespace stl
{
using std::cout;
using std::cerr;
using std::string;
using std::ifstream;
using std::remove;
};
using namespace stl;
using Mode = ftp::Connection::Mode;
Mode PASV = Mode::PASSIVE;
Mode PORT = Mode::PORT;
using TransferMode = ftp::Connection::TransferMode;
TransferMode BINARY = TransferMode::BINARY;
TransferMode TEXT = TransferMode::TEXT;
struct session
{
const string server;
const string port;
const string user;
const string pass;
Mode mode;
TransferMode txmode;
string dir;
};
ftp::Connection connect_ftp( const session& sess);
size_t get_ftp( ftp::Connection& conn, string const& path);
string readFile( const string& filename);
string login_ftp(ftp::Connection& conn, const session& sess);
string dir_listing( ftp::Connection& conn, const string& path);
string readFile( const string& filename)
{
struct stat stat_buf;
string contents;
errno = 0;
if (stat(filename.c_str() , &stat_buf) != -1)
{
size_t len = stat_buf.st_size;
string bytes(len+1, '\0');
ifstream ifs(filename);
ifs.read(&bytes[0], len);
if (! ifs.fail() ) contents.swap(bytes);
ifs.close();
}
else
{
cerr << "stat error: " << strerror(errno);
}
return contents;
}
ftp::Connection connect_ftp( const session& sess)
try
{
string constr = sess.server + ":" + sess.port;
cerr << "connecting to " << constr << " ...\n";
ftp::Connection conn{ constr.c_str() };
cerr << "connected to " << constr << "\n";
conn.setConnectionMode(sess.mode);
return conn;
}
catch (ftp::ConnectException e)
{
cerr << "FTP error: could not connect to server" << "\n";
}
string login_ftp(ftp::Connection& conn, const session& sess)
{
conn.login(sess.user.c_str() , sess.pass.c_str() );
return conn.getLastResponse();
}
string dir_listing( ftp::Connection& conn, const string& path)
try
{
const char* dirdata = "/dev/shm/dirdata";
conn.getList(dirdata, path.c_str() );
string dir_string = readFile(dirdata);
cerr << conn.getLastResponse() << "\n";
errno = 0;
if ( remove(dirdata) != 0 )
{
cerr << "error: " << strerror(errno) << "\n";
}
return dir_string;
}
catch (...) {
cerr << "error: getting dir contents: \n"
<< strerror(errno) << "\n";
}
size_t get_ftp( ftp::Connection& conn, const string& r_path)
{
size_t received = 0;
const char* path = r_path.c_str();
unsigned remotefile_size = conn.size(path , BINARY);
const char* localfile = basename(path);
conn.get(localfile, path, BINARY);
cerr << conn.getLastResponse() << "\n";
struct stat stat_buf;
errno = 0;
if (stat(localfile, &stat_buf) != -1)
received = stat_buf.st_size;
else
cerr << strerror(errno);
return received;
}
const session sonic
{
"mirrors.sonic.net",
"21" ,
"anonymous",
"xxxx@nohost.org",
PASV,
BINARY,
"/pub/OpenBSD"
};
int main(int argc, char* argv[], char * env[] )
{
const session remote = sonic;
try
{
ftp::Connection conn = connect_ftp(remote);
cerr << login_ftp(conn, remote);
cout << "System type: " << conn.getSystemType() << "\n";
cerr << conn.getLastResponse() << "\n";
conn.cd(remote.dir.c_str());
cerr << conn.getLastResponse() << "\n";
string pwdstr = conn.getDirectory();
cout << "PWD: " << pwdstr << "\n";
cerr << conn.getLastResponse() << "\n";
string dirlist = dir_listing(conn, pwdstr.c_str() );
cout << dirlist << "\n";
string filename = "ftplist";
auto pos = dirlist.find(filename);
auto notfound = string::npos;
if (pos != notfound)
{
size_t received = get_ftp(conn, filename.c_str() );
if (received == 0)
cerr << "got 0 bytes\n";
else
cerr << "got " << filename
<< " (" << received << " bytes)\n";
}
else
{
cerr << "file " << filename
<< "not found on server. \n";
}
}
catch (ftp::ConnectException e)
{
cerr << "FTP error: could not connect to server" << "\n";
}
catch (ftp::Exception e)
{
cerr << "FTP error: " << e << "\n";
}
catch (...)
{
cerr << "error: " << strerror(errno) << "\n";
}
return 0;
}
| package main
import (
"fmt"
"io"
"log"
"os"
"github.com/stacktic/ftp"
)
func main() {
const (
hostport = "localhost:21"
username = "anonymous"
password = "anonymous"
dir = "pub"
file = "somefile.bin"
)
conn, err := ftp.Connect(hostport)
if err != nil {
log.Fatal(err)
}
defer conn.Quit()
fmt.Println(conn)
if err = conn.Login(username, password); err != nil {
log.Fatal(err)
}
if err = conn.ChangeDir(dir); err != nil {
log.Fatal(err)
}
fmt.Println(conn.CurrentDir())
files, err := conn.List(".")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name)
}
r, err := conn.Retr(file)
if err != nil {
log.Fatal(err)
}
defer r.Close()
f, err := os.Create(file)
if err != nil {
log.Fatal(err)
}
defer f.Close()
n, err := io.Copy(f, r)
if err != nil {
log.Fatal(err)
}
fmt.Println("Wrote", n, "bytes to", file)
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <random>
#include <iostream>
#include <stack>
#include <set>
#include <string>
#include <functional>
using namespace std;
class RPNParse
{
public:
stack<double> stk;
multiset<int> digits;
void op(function<double(double,double)> f)
{
if(stk.size() < 2)
throw "Improperly written expression";
int b = stk.top(); stk.pop();
int a = stk.top(); stk.pop();
stk.push(f(a, b));
}
void parse(char c)
{
if(c >= '0' && c <= '9')
{
stk.push(c - '0');
digits.insert(c - '0');
}
else if(c == '+')
op([](double a, double b) {return a+b;});
else if(c == '-')
op([](double a, double b) {return a-b;});
else if(c == '*')
op([](double a, double b) {return a*b;});
else if(c == '/')
op([](double a, double b) {return a/b;});
}
void parse(string s)
{
for(int i = 0; i < s.size(); ++i)
parse(s[i]);
}
double getResult()
{
if(stk.size() != 1)
throw "Improperly written expression";
return stk.top();
}
};
int main()
{
random_device seed;
mt19937 engine(seed());
uniform_int_distribution<> distribution(1, 9);
auto rnd = bind(distribution, engine);
multiset<int> digits;
cout << "Make 24 with the digits: ";
for(int i = 0; i < 4; ++i)
{
int n = rnd();
cout << " " << n;
digits.insert(n);
}
cout << endl;
RPNParse parser;
try
{
string input;
getline(cin, input);
parser.parse(input);
if(digits != parser.digits)
cout << "Error: Not using the given digits" << endl;
else
{
double r = parser.getResult();
cout << "Result: " << r << endl;
if(r > 23.999 && r < 24.001)
cout << "Good job!" << endl;
else
cout << "Try again." << endl;
}
}
catch(char* e)
{
cout << "Error: " << e << endl;
}
return 0;
}
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <random>
#include <iostream>
#include <stack>
#include <set>
#include <string>
#include <functional>
using namespace std;
class RPNParse
{
public:
stack<double> stk;
multiset<int> digits;
void op(function<double(double,double)> f)
{
if(stk.size() < 2)
throw "Improperly written expression";
int b = stk.top(); stk.pop();
int a = stk.top(); stk.pop();
stk.push(f(a, b));
}
void parse(char c)
{
if(c >= '0' && c <= '9')
{
stk.push(c - '0');
digits.insert(c - '0');
}
else if(c == '+')
op([](double a, double b) {return a+b;});
else if(c == '-')
op([](double a, double b) {return a-b;});
else if(c == '*')
op([](double a, double b) {return a*b;});
else if(c == '/')
op([](double a, double b) {return a/b;});
}
void parse(string s)
{
for(int i = 0; i < s.size(); ++i)
parse(s[i]);
}
double getResult()
{
if(stk.size() != 1)
throw "Improperly written expression";
return stk.top();
}
};
int main()
{
random_device seed;
mt19937 engine(seed());
uniform_int_distribution<> distribution(1, 9);
auto rnd = bind(distribution, engine);
multiset<int> digits;
cout << "Make 24 with the digits: ";
for(int i = 0; i < 4; ++i)
{
int n = rnd();
cout << " " << n;
digits.insert(n);
}
cout << endl;
RPNParse parser;
try
{
string input;
getline(cin, input);
parser.parse(input);
if(digits != parser.digits)
cout << "Error: Not using the given digits" << endl;
else
{
double r = parser.getResult();
cout << "Result: " << r << endl;
if(r > 23.999 && r < 24.001)
cout << "Good job!" << endl;
else
cout << "Try again." << endl;
}
}
catch(char* e)
{
cout << "Error: " << e << endl;
}
return 0;
}
| package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
}
|
Write the same algorithm in Go as shown in this C++ implementation. | for(int i = 1;i <= 10; i++){
cout << i;
if(i % 5 == 0){
cout << endl;
continue;
}
cout << ", ";
}
| package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf("%d", i)
if i%5 == 0 {
fmt.Printf("\n")
continue
}
fmt.Printf(", ")
}
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class QPaintEvent ;
class MyWidget : public QWidget {
public :
MyWidget( ) ;
protected :
void paintEvent( QPaintEvent * ) ;
private :
int width ;
int height ;
const int colornumber ;
} ;
#endif
| package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
|
Please provide an equivalent version of this C++ code in Go. | #ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class QPaintEvent ;
class MyWidget : public QWidget {
public :
MyWidget( ) ;
protected :
void paintEvent( QPaintEvent * ) ;
private :
int width ;
int height ;
const int colornumber ;
} ;
#endif
| package main
import "github.com/fogleman/gg"
var colors = [8]string{
"000000",
"FF0000",
"00FF00",
"0000FF",
"FF00FF",
"00FFFF",
"FFFF00",
"FFFFFF",
}
func drawBars(dc *gg.Context) {
w := float64(dc.Width() / len(colors))
h := float64(dc.Height())
for i := range colors {
dc.SetHexColor(colors[i])
dc.DrawRectangle(w*float64(i), 0, w, h)
dc.Fill()
}
}
func main() {
dc := gg.NewContext(400, 400)
drawBars(dc)
dc.SavePNG("color_bars.png")
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numeric>
#include <sstream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::wostream& out, const matrix<scalar_type>& a) {
const wchar_t* box_top_left = L"\x23a1";
const wchar_t* box_top_right = L"\x23a4";
const wchar_t* box_left = L"\x23a2";
const wchar_t* box_right = L"\x23a5";
const wchar_t* box_bottom_left = L"\x23a3";
const wchar_t* box_bottom_right = L"\x23a6";
const int precision = 5;
size_t rows = a.rows(), columns = a.columns();
std::vector<size_t> width(columns);
for (size_t column = 0; column < columns; ++column) {
size_t max_width = 0;
for (size_t row = 0; row < rows; ++row) {
std::ostringstream str;
str << std::fixed << std::setprecision(precision) << a(row, column);
max_width = std::max(max_width, str.str().length());
}
width[column] = max_width;
}
out << std::fixed << std::setprecision(precision);
for (size_t row = 0; row < rows; ++row) {
const bool top(row == 0), bottom(row + 1 == rows);
out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << L' ';
out << std::setw(width[column]) << a(row, column);
}
out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));
out << L'\n';
}
}
template <typename scalar_type>
auto lu_decompose(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
std::vector<size_t> perm(n);
std::iota(perm.begin(), perm.end(), 0);
matrix<scalar_type> lower(n, n);
matrix<scalar_type> upper(n, n);
matrix<scalar_type> input1(input);
for (size_t j = 0; j < n; ++j) {
size_t max_index = j;
scalar_type max_value = 0;
for (size_t i = j; i < n; ++i) {
scalar_type value = std::abs(input1(perm[i], j));
if (value > max_value) {
max_index = i;
max_value = value;
}
}
if (max_value <= std::numeric_limits<scalar_type>::epsilon())
throw std::runtime_error("matrix is singular");
if (j != max_index)
std::swap(perm[j], perm[max_index]);
size_t jj = perm[j];
for (size_t i = j + 1; i < n; ++i) {
size_t ii = perm[i];
input1(ii, j) /= input1(jj, j);
for (size_t k = j + 1; k < n; ++k)
input1(ii, k) -= input1(ii, j) * input1(jj, k);
}
}
for (size_t j = 0; j < n; ++j) {
lower(j, j) = 1;
for (size_t i = j + 1; i < n; ++i)
lower(i, j) = input1(perm[i], j);
for (size_t i = 0; i <= j; ++i)
upper(i, j) = input1(perm[i], j);
}
matrix<scalar_type> pivot(n, n);
for (size_t i = 0; i < n; ++i)
pivot(i, perm[i]) = 1;
return std::make_tuple(lower, upper, pivot);
}
template <typename scalar_type>
void show_lu_decomposition(const matrix<scalar_type>& input) {
try {
std::wcout << L"A\n";
print(std::wcout, input);
auto result(lu_decompose(input));
std::wcout << L"\nL\n";
print(std::wcout, std::get<0>(result));
std::wcout << L"\nU\n";
print(std::wcout, std::get<1>(result));
std::wcout << L"\nP\n";
print(std::wcout, std::get<2>(result));
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
}
}
int main() {
std::wcout.imbue(std::locale(""));
std::wcout << L"Example 1:\n";
matrix<double> matrix1(3, 3,
{{1, 3, 5},
{2, 4, 7},
{1, 1, 0}});
show_lu_decomposition(matrix1);
std::wcout << '\n';
std::wcout << L"Example 2:\n";
matrix<double> matrix2(4, 4,
{{11, 9, 24, 2},
{1, 5, 2, 6},
{3, 17, 18, 1},
{2, 5, 7, 1}});
show_lu_decomposition(matrix2);
std::wcout << '\n';
std::wcout << L"Example 3:\n";
matrix<double> matrix3(3, 3,
{{-5, -6, -3},
{-1, 0, -2},
{-3, -4, -7}});
show_lu_decomposition(matrix3);
std::wcout << '\n';
std::wcout << L"Example 4:\n";
matrix<double> matrix4(3, 3,
{{1, 2, 3},
{4, 5, 6},
{7, 8, 9}});
show_lu_decomposition(matrix4);
return 0;
}
| package main
import "fmt"
type matrix [][]float64
func zero(n int) matrix {
r := make([][]float64, n)
a := make([]float64, n*n)
for i := range r {
r[i] = a[n*i : n*(i+1)]
}
return r
}
func eye(n int) matrix {
r := zero(n)
for i := range r {
r[i][i] = 1
}
return r
}
func (m matrix) print(label string) {
if label > "" {
fmt.Printf("%s:\n", label)
}
for _, r := range m {
for _, e := range r {
fmt.Printf(" %9.5f", e)
}
fmt.Println()
}
}
func (a matrix) pivotize() matrix {
p := eye(len(a))
for j, r := range a {
max := r[j]
row := j
for i := j; i < len(a); i++ {
if a[i][j] > max {
max = a[i][j]
row = i
}
}
if j != row {
p[j], p[row] = p[row], p[j]
}
}
return p
}
func (m1 matrix) mul(m2 matrix) matrix {
r := zero(len(m1))
for i, r1 := range m1 {
for j := range m2 {
for k := range m1 {
r[i][j] += r1[k] * m2[k][j]
}
}
}
return r
}
func (a matrix) lu() (l, u, p matrix) {
l = zero(len(a))
u = zero(len(a))
p = a.pivotize()
a = p.mul(a)
for j := range a {
l[j][j] = 1
for i := 0; i <= j; i++ {
sum := 0.
for k := 0; k < i; k++ {
sum += u[k][j] * l[i][k]
}
u[i][j] = a[i][j] - sum
}
for i := j; i < len(a); i++ {
sum := 0.
for k := 0; k < j; k++ {
sum += u[k][j] * l[i][k]
}
l[i][j] = (a[i][j] - sum) / u[j][j]
}
}
return
}
func main() {
showLU(matrix{
{1, 3, 5},
{2, 4, 7},
{1, 1, 0}})
showLU(matrix{
{11, 9, 24, 2},
{1, 5, 2, 6},
{3, 17, 18, 1},
{2, 5, 7, 1}})
}
func showLU(a matrix) {
a.print("\na")
l, u, p := a.lu()
l.print("l")
u.print("u")
p.print("p")
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <algorithm>
#include <iostream>
#include <vector>
#include <string>
class pair {
public:
pair( int s, std::string z ) { p = std::make_pair( s, z ); }
bool operator < ( const pair& o ) const { return i() < o.i(); }
int i() const { return p.first; }
std::string s() const { return p.second; }
private:
std::pair<int, std::string> p;
};
void gFizzBuzz( int c, std::vector<pair>& v ) {
bool output;
for( int x = 1; x <= c; x++ ) {
output = false;
for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {
if( !( x % ( *i ).i() ) ) {
std::cout << ( *i ).s();
output = true;
}
}
if( !output ) std::cout << x;
std::cout << "\n";
}
}
int main( int argc, char* argv[] ) {
std::vector<pair> v;
v.push_back( pair( 7, "Baxx" ) );
v.push_back( pair( 3, "Fizz" ) );
v.push_back( pair( 5, "Buzz" ) );
std::sort( v.begin(), v.end() );
gFizzBuzz( 20, v );
return 0;
}
| package main
import (
"fmt"
)
const numbers = 3
func main() {
max := 20
words := map[int]string{
3: "Fizz",
5: "Buzz",
7: "Baxx",
}
keys := []int{3, 5, 7}
divisible := false
for i := 1; i <= max; i++ {
for _, n := range keys {
if i % n == 0 {
fmt.Print(words[n])
divisible = true
}
}
if !divisible {
fmt.Print(i)
}
fmt.Println()
divisible = false
}
}
|
Change the following C++ code into Go without altering its purpose. | #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ;
std::getline( std::cin , input ) ;
int linenumber = std::stoi( input ) ;
int lines_read = 0 ;
std::string line ;
if ( infile.is_open( ) ) {
while ( infile ) {
getline( infile , line ) ;
lines_read++ ;
if ( lines_read == linenumber ) {
std::cout << line << std::endl ;
break ;
}
}
infile.close( ) ;
if ( lines_read < linenumber )
std::cout << "No " << linenumber << " lines in " << file << " !\n" ;
return 0 ;
}
else {
std::cerr << "Could not find file " << file << " !\n" ;
return 1 ;
}
}
| package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
func rsl(fn string, n int) (string, error) {
if n < 1 {
return "", fmt.Errorf("invalid request: line %d", n)
}
f, err := os.Open(fn)
if err != nil {
return "", err
}
defer f.Close()
bf := bufio.NewReader(f)
var line string
for lnum := 0; lnum < n; lnum++ {
line, err = bf.ReadString('\n')
if err == io.EOF {
switch lnum {
case 0:
return "", errors.New("no lines in file")
case 1:
return "", errors.New("only 1 line")
default:
return "", fmt.Errorf("only %d lines", lnum)
}
}
if err != nil {
return "", err
}
}
if line == "" {
return "", fmt.Errorf("line %d empty", n)
}
return line, nil
}
|
Convert this C++ snippet to Go and keep its semantics consistent. | #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ;
std::getline( std::cin , input ) ;
int linenumber = std::stoi( input ) ;
int lines_read = 0 ;
std::string line ;
if ( infile.is_open( ) ) {
while ( infile ) {
getline( infile , line ) ;
lines_read++ ;
if ( lines_read == linenumber ) {
std::cout << line << std::endl ;
break ;
}
}
infile.close( ) ;
if ( lines_read < linenumber )
std::cout << "No " << linenumber << " lines in " << file << " !\n" ;
return 0 ;
}
else {
std::cerr << "Could not find file " << file << " !\n" ;
return 1 ;
}
}
| package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
func rsl(fn string, n int) (string, error) {
if n < 1 {
return "", fmt.Errorf("invalid request: line %d", n)
}
f, err := os.Open(fn)
if err != nil {
return "", err
}
defer f.Close()
bf := bufio.NewReader(f)
var line string
for lnum := 0; lnum < n; lnum++ {
line, err = bf.ReadString('\n')
if err == io.EOF {
switch lnum {
case 0:
return "", errors.New("no lines in file")
case 1:
return "", errors.New("only 1 line")
default:
return "", fmt.Errorf("only %d lines", lnum)
}
}
if err != nil {
return "", err
}
}
if line == "" {
return "", fmt.Errorf("line %d empty", n)
}
return line, nil
}
|
Convert the following code from C++ to Go, ensuring the logic remains intact. | #include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
const size_t n1 = str.length();
const size_t n2 = suffix.length();
if (n1 < n2)
return false;
return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),
[](char c1, char c2) {
return std::tolower(static_cast<unsigned char>(c1))
== std::tolower(static_cast<unsigned char>(c2));
});
}
bool filenameHasExtension(const std::string& filename,
const std::vector<std::string>& extensions) {
return std::any_of(extensions.begin(), extensions.end(),
[&filename](const std::string& extension) {
return endsWithIgnoreCase(filename, "." + extension);
});
}
void test(const std::string& filename,
const std::vector<std::string>& extensions) {
std::cout << std::setw(20) << std::left << filename
<< ": " << std::boolalpha
<< filenameHasExtension(filename, extensions) << '\n';
}
int main() {
const std::vector<std::string> extensions{"zip", "rar", "7z",
"gz", "archive", "A##", "tar.bz2"};
test("MyData.a##", extensions);
test("MyData.tar.Gz", extensions);
test("MyData.gzip", extensions);
test("MyData.7z.backup", extensions);
test("MyData...", extensions);
test("MyData", extensions);
test("MyData_v1.0.tar.bz2", extensions);
test("MyData_v1.0.bz2", extensions);
return 0;
}
| package main
import (
"fmt"
"strings"
)
var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}
func fileExtInList(filename string) (bool, string) {
filename2 := strings.ToLower(filename)
for _, ext := range extensions {
ext2 := "." + strings.ToLower(ext)
if strings.HasSuffix(filename2, ext2) {
return true, ext
}
}
s := strings.Split(filename, ".")
if len(s) > 1 {
t := s[len(s)-1]
if t != "" {
return false, t
} else {
return false, "<empty>"
}
} else {
return false, "<none>"
}
}
func main() {
fmt.Println("The listed extensions are:")
fmt.Println(extensions, "\n")
tests := []string{
"MyData.a##", "MyData.tar.Gz", "MyData.gzip",
"MyData.7z.backup", "MyData...", "MyData",
"MyData_v1.0.tar.bz2", "MyData_v1.0.bz2",
}
for _, test := range tests {
ok, ext := fileExtInList(test)
fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext)
}
}
|
Write the same algorithm in Go as shown in this C++ implementation. | #include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
const size_t n1 = str.length();
const size_t n2 = suffix.length();
if (n1 < n2)
return false;
return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),
[](char c1, char c2) {
return std::tolower(static_cast<unsigned char>(c1))
== std::tolower(static_cast<unsigned char>(c2));
});
}
bool filenameHasExtension(const std::string& filename,
const std::vector<std::string>& extensions) {
return std::any_of(extensions.begin(), extensions.end(),
[&filename](const std::string& extension) {
return endsWithIgnoreCase(filename, "." + extension);
});
}
void test(const std::string& filename,
const std::vector<std::string>& extensions) {
std::cout << std::setw(20) << std::left << filename
<< ": " << std::boolalpha
<< filenameHasExtension(filename, extensions) << '\n';
}
int main() {
const std::vector<std::string> extensions{"zip", "rar", "7z",
"gz", "archive", "A##", "tar.bz2"};
test("MyData.a##", extensions);
test("MyData.tar.Gz", extensions);
test("MyData.gzip", extensions);
test("MyData.7z.backup", extensions);
test("MyData...", extensions);
test("MyData", extensions);
test("MyData_v1.0.tar.bz2", extensions);
test("MyData_v1.0.bz2", extensions);
return 0;
}
| package main
import (
"fmt"
"strings"
)
var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}
func fileExtInList(filename string) (bool, string) {
filename2 := strings.ToLower(filename)
for _, ext := range extensions {
ext2 := "." + strings.ToLower(ext)
if strings.HasSuffix(filename2, ext2) {
return true, ext
}
}
s := strings.Split(filename, ".")
if len(s) > 1 {
t := s[len(s)-1]
if t != "" {
return false, t
} else {
return false, "<empty>"
}
} else {
return false, "<none>"
}
}
func main() {
fmt.Println("The listed extensions are:")
fmt.Println(extensions, "\n")
tests := []string{
"MyData.a##", "MyData.tar.Gz", "MyData.gzip",
"MyData.7z.backup", "MyData...", "MyData",
"MyData_v1.0.tar.bz2", "MyData_v1.0.bz2",
}
for _, test := range tests {
ok, ext := fileExtInList(test)
fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext)
}
}
|
Write a version of this C++ function in Go with identical behavior. | #include <iostream>
#include <ratio>
#include <array>
#include <algorithm>
#include <random>
typedef short int Digit;
constexpr Digit nDigits{4};
constexpr Digit maximumDigit{9};
constexpr short int gameGoal{24};
typedef std::array<Digit, nDigits> digitSet;
digitSet d;
void printTrivialOperation(std::string operation) {
bool printOperation(false);
for(const Digit& number : d) {
if(printOperation)
std::cout << operation;
else
printOperation = true;
std::cout << number;
}
std::cout << std::endl;
}
void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") {
std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;
}
int main() {
std::mt19937_64 randomGenerator;
std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};
for(int trial{10}; trial; --trial) {
for(Digit& digit : d) {
digit = digitDistro(randomGenerator);
std::cout << digit << " ";
}
std::cout << std::endl;
std::sort(d.begin(), d.end());
if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)
printTrivialOperation(" + ");
if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)
printTrivialOperation(" * ");
do {
if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - ");
if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + ");
if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + ");
if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )");
if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + ");
if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )");
if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )");
if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - ");
if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )");
if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )");
if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - ");
if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - ");
if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + ");
if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )");
if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )");
if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + ");
if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / ");
if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / ");
if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )");
if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - ");
if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / ");
if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / ");
if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )");
if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / ");
if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )");
if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )");
if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", "");
} while(std::next_permutation(d.begin(), d.end()));
}
return 0;
}
| package main
import (
"fmt"
"math/rand"
"time"
)
const (
op_num = iota
op_add
op_sub
op_mul
op_div
)
type frac struct {
num, denom int
}
type Expr struct {
op int
left, right *Expr
value frac
}
var n_cards = 4
var goal = 24
var digit_range = 9
func (x *Expr) String() string {
if x.op == op_num {
return fmt.Sprintf("%d", x.value.num)
}
var bl1, br1, bl2, br2, opstr string
switch {
case x.left.op == op_num:
case x.left.op >= x.op:
case x.left.op == op_add && x.op == op_sub:
bl1, br1 = "", ""
default:
bl1, br1 = "(", ")"
}
if x.right.op == op_num || x.op < x.right.op {
bl2, br2 = "", ""
} else {
bl2, br2 = "(", ")"
}
switch {
case x.op == op_add:
opstr = " + "
case x.op == op_sub:
opstr = " - "
case x.op == op_mul:
opstr = " * "
case x.op == op_div:
opstr = " / "
}
return bl1 + x.left.String() + br1 + opstr +
bl2 + x.right.String() + br2
}
func expr_eval(x *Expr) (f frac) {
if x.op == op_num {
return x.value
}
l, r := expr_eval(x.left), expr_eval(x.right)
switch x.op {
case op_add:
f.num = l.num*r.denom + l.denom*r.num
f.denom = l.denom * r.denom
return
case op_sub:
f.num = l.num*r.denom - l.denom*r.num
f.denom = l.denom * r.denom
return
case op_mul:
f.num = l.num * r.num
f.denom = l.denom * r.denom
return
case op_div:
f.num = l.num * r.denom
f.denom = l.denom * r.num
return
}
return
}
func solve(ex_in []*Expr) bool {
if len(ex_in) == 1 {
f := expr_eval(ex_in[0])
if f.denom != 0 && f.num == f.denom*goal {
fmt.Println(ex_in[0].String())
return true
}
return false
}
var node Expr
ex := make([]*Expr, len(ex_in)-1)
for i := range ex {
copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)])
ex[i] = &node
for j := i + 1; j < len(ex_in); j++ {
node.left = ex_in[i]
node.right = ex_in[j]
for o := op_add; o <= op_div; o++ {
node.op = o
if solve(ex) {
return true
}
}
node.left = ex_in[j]
node.right = ex_in[i]
node.op = op_sub
if solve(ex) {
return true
}
node.op = op_div
if solve(ex) {
return true
}
if j < len(ex) {
ex[j] = ex_in[j]
}
}
ex[i] = ex_in[i]
}
return false
}
func main() {
cards := make([]*Expr, n_cards)
rand.Seed(time.Now().Unix())
for k := 0; k < 10; k++ {
for i := 0; i < n_cards; i++ {
cards[i] = &Expr{op_num, nil, nil,
frac{rand.Intn(digit_range-1) + 1, 1}}
fmt.Printf(" %d", cards[i].value.num)
}
fmt.Print(": ")
if !solve(cards) {
fmt.Println("No solution")
}
}
}
|
Generate an equivalent Go version of this C++ code. | #include <iostream>
#include <ratio>
#include <array>
#include <algorithm>
#include <random>
typedef short int Digit;
constexpr Digit nDigits{4};
constexpr Digit maximumDigit{9};
constexpr short int gameGoal{24};
typedef std::array<Digit, nDigits> digitSet;
digitSet d;
void printTrivialOperation(std::string operation) {
bool printOperation(false);
for(const Digit& number : d) {
if(printOperation)
std::cout << operation;
else
printOperation = true;
std::cout << number;
}
std::cout << std::endl;
}
void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") {
std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;
}
int main() {
std::mt19937_64 randomGenerator;
std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};
for(int trial{10}; trial; --trial) {
for(Digit& digit : d) {
digit = digitDistro(randomGenerator);
std::cout << digit << " ";
}
std::cout << std::endl;
std::sort(d.begin(), d.end());
if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)
printTrivialOperation(" + ");
if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)
printTrivialOperation(" * ");
do {
if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - ");
if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + ");
if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + ");
if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )");
if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + ");
if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )");
if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )");
if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - ");
if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )");
if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )");
if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - ");
if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - ");
if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + ");
if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )");
if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )");
if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + ");
if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / ");
if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / ");
if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )");
if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - ");
if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / ");
if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / ");
if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )");
if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / ");
if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )");
if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )");
if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", "");
} while(std::next_permutation(d.begin(), d.end()));
}
return 0;
}
| package main
import (
"fmt"
"math/rand"
"time"
)
const (
op_num = iota
op_add
op_sub
op_mul
op_div
)
type frac struct {
num, denom int
}
type Expr struct {
op int
left, right *Expr
value frac
}
var n_cards = 4
var goal = 24
var digit_range = 9
func (x *Expr) String() string {
if x.op == op_num {
return fmt.Sprintf("%d", x.value.num)
}
var bl1, br1, bl2, br2, opstr string
switch {
case x.left.op == op_num:
case x.left.op >= x.op:
case x.left.op == op_add && x.op == op_sub:
bl1, br1 = "", ""
default:
bl1, br1 = "(", ")"
}
if x.right.op == op_num || x.op < x.right.op {
bl2, br2 = "", ""
} else {
bl2, br2 = "(", ")"
}
switch {
case x.op == op_add:
opstr = " + "
case x.op == op_sub:
opstr = " - "
case x.op == op_mul:
opstr = " * "
case x.op == op_div:
opstr = " / "
}
return bl1 + x.left.String() + br1 + opstr +
bl2 + x.right.String() + br2
}
func expr_eval(x *Expr) (f frac) {
if x.op == op_num {
return x.value
}
l, r := expr_eval(x.left), expr_eval(x.right)
switch x.op {
case op_add:
f.num = l.num*r.denom + l.denom*r.num
f.denom = l.denom * r.denom
return
case op_sub:
f.num = l.num*r.denom - l.denom*r.num
f.denom = l.denom * r.denom
return
case op_mul:
f.num = l.num * r.num
f.denom = l.denom * r.denom
return
case op_div:
f.num = l.num * r.denom
f.denom = l.denom * r.num
return
}
return
}
func solve(ex_in []*Expr) bool {
if len(ex_in) == 1 {
f := expr_eval(ex_in[0])
if f.denom != 0 && f.num == f.denom*goal {
fmt.Println(ex_in[0].String())
return true
}
return false
}
var node Expr
ex := make([]*Expr, len(ex_in)-1)
for i := range ex {
copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)])
ex[i] = &node
for j := i + 1; j < len(ex_in); j++ {
node.left = ex_in[i]
node.right = ex_in[j]
for o := op_add; o <= op_div; o++ {
node.op = o
if solve(ex) {
return true
}
}
node.left = ex_in[j]
node.right = ex_in[i]
node.op = op_sub
if solve(ex) {
return true
}
node.op = op_div
if solve(ex) {
return true
}
if j < len(ex) {
ex[j] = ex_in[j]
}
}
ex[i] = ex_in[i]
}
return false
}
func main() {
cards := make([]*Expr, n_cards)
rand.Seed(time.Now().Unix())
for k := 0; k < 10; k++ {
for i := 0; i < n_cards; i++ {
cards[i] = &Expr{op_num, nil, nil,
frac{rand.Intn(digit_range-1) + 1, 1}}
fmt.Printf(" %d", cards[i].value.num)
}
fmt.Print(": ")
if !solve(cards) {
fmt.Println("No solution")
}
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Port the following code from C++ to Go with equivalent syntax and logic. | #include <iomanip>
#include <iostream>
#include <vector>
std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << "[ ";
if (it != end) {
os << std::setfill('0') << std::setw(2) << (uint32_t)*it;
it = std::next(it);
}
while (it != end) {
os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;
it = std::next(it);
}
return os << " ]";
}
std::vector<uint8_t> to_seq(uint64_t x) {
int i;
for (i = 9; i > 0; i--) {
if (x & 127ULL << i * 7) {
break;
}
}
std::vector<uint8_t> out;
for (int j = 0; j <= i; j++) {
out.push_back(((x >> ((i - j) * 7)) & 127) | 128);
}
out[i] ^= 128;
return out;
}
uint64_t from_seq(const std::vector<uint8_t> &seq) {
uint64_t r = 0;
for (auto b : seq) {
r = (r << 7) | (b & 127);
}
return r;
}
int main() {
std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };
for (auto x : src) {
auto s = to_seq(x);
std::cout << std::hex;
std::cout << "seq from " << x << ' ' << s << " back: " << from_seq(s) << '\n';
std::cout << std::dec;
}
return 0;
}
| package main
import (
"fmt"
"encoding/binary"
)
func main() {
buf := make([]byte, binary.MaxVarintLen64)
for _, x := range []int64{0x200000, 0x1fffff} {
v := buf[:binary.PutVarint(buf, x)]
fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v)
x, _ = binary.Varint(v)
fmt.Println(x, "decoded")
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <string>
#include <windows.h>
#include <mmsystem.h>
#pragma comment ( lib, "winmm.lib" )
using namespace std;
class recorder
{
public:
void start()
{
paused = rec = false; action = "IDLE";
while( true )
{
cout << endl << "==" << action << "==" << endl << endl;
cout << "1) Record" << endl << "2) Play" << endl << "3) Pause" << endl << "4) Stop" << endl << "5) Quit" << endl;
char c; cin >> c;
if( c > '0' && c < '6' )
{
switch( c )
{
case '1': record(); break;
case '2': play(); break;
case '3': pause(); break;
case '4': stop(); break;
case '5': stop(); return;
}
}
}
}
private:
void record()
{
if( mciExecute( "open new type waveaudio alias my_sound") )
{
mciExecute( "record my_sound" );
action = "RECORDING"; rec = true;
}
}
void play()
{
if( paused )
mciExecute( "play my_sound" );
else
if( mciExecute( "open tmp.wav alias my_sound" ) )
mciExecute( "play my_sound" );
action = "PLAYING";
paused = false;
}
void pause()
{
if( rec ) return;
mciExecute( "pause my_sound" );
paused = true; action = "PAUSED";
}
void stop()
{
if( rec )
{
mciExecute( "stop my_sound" );
mciExecute( "save my_sound tmp.wav" );
mciExecute( "close my_sound" );
action = "IDLE"; rec = false;
}
else
{
mciExecute( "stop my_sound" );
mciExecute( "close my_sound" );
action = "IDLE";
}
}
bool mciExecute( string cmd )
{
if( mciSendString( cmd.c_str(), NULL, 0, NULL ) )
{
cout << "Can't do this: " << cmd << endl;
return false;
}
return true;
}
bool paused, rec;
string action;
};
int main( int argc, char* argv[] )
{
recorder r; r.start();
return 0;
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strconv"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
name := ""
for name == "" {
fmt.Print("Enter output file name (without extension) : ")
scanner.Scan()
name = scanner.Text()
check(scanner.Err())
}
name += ".wav"
rate := 0
for rate < 2000 || rate > 192000 {
fmt.Print("Enter sampling rate in Hz (2000 to 192000) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
rate, _ = strconv.Atoi(input)
}
rateS := strconv.Itoa(rate)
dur := 0.0
for dur < 5 || dur > 30 {
fmt.Print("Enter duration in seconds (5 to 30) : ")
scanner.Scan()
input := scanner.Text()
check(scanner.Err())
dur, _ = strconv.ParseFloat(input, 64)
}
durS := strconv.FormatFloat(dur, 'f', -1, 64)
fmt.Println("OK, start speaking now...")
args := []string{"-r", rateS, "-f", "S16_LE", "-d", durS, name}
cmd := exec.Command("arecord", args...)
err := cmd.Run()
check(err)
fmt.Printf("'%s' created on disk and will now be played back...\n", name)
cmd = exec.Command("aplay", name)
err = cmd.Run()
check(err)
fmt.Println("Play-back completed.")
}
|
Translate the given C++ code snippet into Go without altering its behavior. | #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
#include <openssl/sha.h>
class sha256_exception : public std::exception {
public:
const char* what() const noexcept override {
return "SHA-256 error";
}
};
class sha256 {
public:
sha256() { reset(); }
sha256(const sha256&) = delete;
sha256& operator=(const sha256&) = delete;
void reset() {
if (SHA256_Init(&context_) == 0)
throw sha256_exception();
}
void update(const void* data, size_t length) {
if (SHA256_Update(&context_, data, length) == 0)
throw sha256_exception();
}
std::vector<unsigned char> digest() {
std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);
if (SHA256_Final(digest.data(), &context_) == 0)
throw sha256_exception();
return digest;
}
private:
SHA256_CTX context_;
};
std::string digest_to_string(const std::vector<unsigned char>& digest) {
std::ostringstream out;
out << std::hex << std::setfill('0');
for (size_t i = 0; i < digest.size(); ++i)
out << std::setw(2) << static_cast<int>(digest[i]);
return out.str();
}
std::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {
std::vector<std::vector<unsigned char>> hashes;
std::vector<char> buffer(block_size);
sha256 md;
while (in) {
in.read(buffer.data(), block_size);
size_t bytes = in.gcount();
if (bytes == 0)
break;
md.reset();
md.update(buffer.data(), bytes);
hashes.push_back(md.digest());
}
if (hashes.empty())
return {};
size_t length = hashes.size();
while (length > 1) {
size_t j = 0;
for (size_t i = 0; i < length; i += 2, ++j) {
auto& digest1 = hashes[i];
auto& digest_out = hashes[j];
if (i + 1 < length) {
auto& digest2 = hashes[i + 1];
md.reset();
md.update(digest1.data(), digest1.size());
md.update(digest2.data(), digest2.size());
digest_out = md.digest();
} else {
digest_out = digest1;
}
}
length = j;
}
return hashes[0];
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cerr << "usage: " << argv[0] << " filename\n";
return EXIT_FAILURE;
}
std::ifstream in(argv[1], std::ios::binary);
if (!in) {
std::cerr << "Cannot open file " << argv[1] << ".\n";
return EXIT_FAILURE;
}
try {
std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\n';
} catch (const std::exception& ex) {
std::cerr << ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| package main
import (
"crypto/sha256"
"fmt"
"io"
"log"
"os"
)
func main() {
const blockSize = 1024
f, err := os.Open("title.png")
if err != nil {
log.Fatal(err)
}
defer f.Close()
var hashes [][]byte
buffer := make([]byte, blockSize)
h := sha256.New()
for {
bytesRead, err := f.Read(buffer)
if err != nil {
if err != io.EOF {
log.Fatal(err)
}
break
}
h.Reset()
h.Write(buffer[:bytesRead])
hashes = append(hashes, h.Sum(nil))
}
buffer = make([]byte, 64)
for len(hashes) > 1 {
var hashes2 [][]byte
for i := 0; i < len(hashes); i += 2 {
if i < len(hashes)-1 {
copy(buffer, hashes[i])
copy(buffer[32:], hashes[i+1])
h.Reset()
h.Write(buffer)
hashes2 = append(hashes2, h.Sum(nil))
} else {
hashes2 = append(hashes2, hashes[i])
}
}
hashes = hashes2
}
fmt.Printf("%x", hashes[0])
fmt.Println()
}
|
Change the programming language of this snippet from C++ to Go without modifying what it does. | #include <algorithm>
#include <string>
#include <cctype>
void str_toupper(std::string &str) {
std::transform(str.begin(),
str.end(),
str.begin(),
(int(*)(int)) std::toupper);
}
void str_tolower(std::string &str) {
std::transform(str.begin(),
str.end(),
str.begin(),
(int(*)(int)) std::tolower);
}
| package main
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
func main() {
show("alphaBETA")
show("alpha BETA")
show("DŽLjnj")
show("o'hare O'HARE o’hare don't")
}
func show(s string) {
fmt.Println("\nstring: ",
s, " len:", utf8.RuneCountInString(s), "runes")
fmt.Println("All upper case: ", strings.ToUpper(s))
fmt.Println("All lower case: ", strings.ToLower(s))
fmt.Println("All title case: ", strings.ToTitle(s))
fmt.Println("Title words: ", strings.Title(s))
fmt.Println("Swapping case: ",
strings.Map(unicode.SimpleFold, s))
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #ifndef TASK_H
#define TASK_H
#include <QWidget>
class QLabel ;
class QLineEdit ;
class QVBoxLayout ;
class QHBoxLayout ;
class EntryWidget : public QWidget {
Q_OBJECT
public :
EntryWidget( QWidget *parent = 0 ) ;
private :
QHBoxLayout *upperpart , *lowerpart ;
QVBoxLayout *entryLayout ;
QLineEdit *stringinput ;
QLineEdit *numberinput ;
QLabel *stringlabel ;
QLabel *numberlabel ;
} ;
#endif
| package main
import (
"github.com/gotk3/gotk3/gtk"
"log"
"math/rand"
"strconv"
"time"
)
func validateInput(window *gtk.Window, str1, str2 string) bool {
n, err := strconv.ParseFloat(str2, 64)
if len(str1) == 0 || err != nil || n != 75000 {
dialog := gtk.MessageDialogNew(
window,
gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_OK,
"Invalid input",
)
dialog.Run()
dialog.Destroy()
return false
}
return true
}
func check(err error, msg string) {
if err != nil {
log.Fatal(msg, err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
gtk.Init(nil)
window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
check(err, "Unable to create window:")
window.SetTitle("Rosetta Code")
window.SetPosition(gtk.WIN_POS_CENTER)
window.Connect("destroy", func() {
gtk.MainQuit()
})
vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1)
check(err, "Unable to create vertical box:")
vbox.SetBorderWidth(1)
hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create first horizontal box:")
hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
check(err, "Unable to create second horizontal box:")
label, err := gtk.LabelNew("Enter a string and the number 75000 \n")
check(err, "Unable to create label:")
sel, err := gtk.LabelNew("String: ")
check(err, "Unable to create string entry label:")
nel, err := gtk.LabelNew("Number: ")
check(err, "Unable to create number entry label:")
se, err := gtk.EntryNew()
check(err, "Unable to create string entry:")
ne, err := gtk.EntryNew()
check(err, "Unable to create number entry:")
hbox1.PackStart(sel, false, false, 2)
hbox1.PackStart(se, false, false, 2)
hbox2.PackStart(nel, false, false, 2)
hbox2.PackStart(ne, false, false, 2)
ab, err := gtk.ButtonNewWithLabel("Accept")
check(err, "Unable to create accept button:")
ab.Connect("clicked", func() {
str1, _ := se.GetText()
str2, _ := ne.GetText()
if validateInput(window, str1, str2) {
window.Destroy()
}
})
vbox.Add(label)
vbox.Add(hbox1)
vbox.Add(hbox2)
vbox.Add(ab)
window.Add(vbox)
window.ShowAll()
gtk.Main()
}
|
Please provide an equivalent version of this C++ code in Go. | #include <fstream>
#include <iostream>
#include <vector>
constexpr double sqrt3_2 = 0.86602540378444;
struct point {
double x;
double y;
};
std::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) {
size_t size = points.size();
std::vector<point> output(3*(size - 1) + 1);
double x0, y0, x1, y1;
size_t j = 0;
for (size_t i = 0; i + 1 < size; ++i, j += 3) {
x0 = points[i].x;
y0 = points[i].y;
x1 = points[i + 1].x;
y1 = points[i + 1].y;
double dx = x1 - x0;
output[j] = {x0, y0};
if (y0 == y1) {
double d = dx * sqrt3_2/2;
if (d < 0) d = -d;
output[j + 1] = {x0 + dx/4, y0 - d};
output[j + 2] = {x1 - dx/4, y0 - d};
} else if (y1 < y0) {
output[j + 1] = {x1, y0};
output[j + 2] = {x1 + dx/2, (y0 + y1)/2};
} else {
output[j + 1] = {x0 - dx/2, (y0 + y1)/2};
output[j + 2] = {x0, y1};
}
}
output[j] = {x1, y1};
return output;
}
void write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) {
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='white'/>\n";
out << "<path stroke-width='1' stroke='black' fill='none' d='";
const double margin = 20.0;
const double side = size - 2.0 * margin;
const double x = margin;
const double y = 0.5 * size + 0.5 * sqrt3_2 * side;
std::vector<point> points{{x, y}, {x + side, y}};
for (int i = 0; i < iterations; ++i)
points = sierpinski_arrowhead_next(points);
for (size_t i = 0, n = points.size(); i < n; ++i)
out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n';
out << "'/>\n</svg>\n";
}
int main() {
std::ofstream out("sierpinski_arrowhead.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
write_sierpinski_arrowhead(out, 600, 8);
return EXIT_SUCCESS;
}
| package main
import (
"github.com/fogleman/gg"
"math"
)
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
iy = 1.0
theta = 0
)
var cx, cy, h float64
func arrowhead(order int, length float64) {
if order&1 == 0 {
curve(order, length, 60)
} else {
turn(60)
curve(order, length, -60)
}
drawLine(length)
}
func drawLine(length float64) {
dc.LineTo(cx-width/2+h, (height-cy)*iy+2*h)
rads := gg.Radians(float64(theta))
cx += length * math.Cos(rads)
cy += length * math.Sin(rads)
}
func turn(angle int) {
theta = (theta + angle) % 360
}
func curve(order int, length float64, angle int) {
if order == 0 {
drawLine(length)
} else {
curve(order-1, length/2, -angle)
turn(angle)
curve(order-1, length/2, angle)
turn(angle)
curve(order-1, length/2, -angle)
}
}
func main() {
dc.SetRGB(0, 0, 0)
dc.Clear()
order := 6
if order&1 == 0 {
iy = -1
}
cx, cy = width/2, height
h = cx / 2
arrowhead(order, cx)
dc.SetRGB255(255, 0, 255)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_arrowhead_curve.png")
}
|
Maintain the same structure and functionality when rewriting this code in Go. | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iomanip>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
using std::cout;
using std::endl;
const int NumFlags = 24;
int main()
{
std::fstream file("readings.txt");
int badCount = 0;
std::string badDate;
int badCountMax = 0;
while(true)
{
std::string line;
getline(file, line);
if(!file.good())
break;
std::vector<std::string> tokens;
boost::algorithm::split(tokens, line, boost::is_space());
if(tokens.size() != NumFlags * 2 + 1)
{
cout << "Bad input file." << endl;
return 0;
}
double total = 0.0;
int accepted = 0;
for(size_t i = 1; i < tokens.size(); i += 2)
{
double val = boost::lexical_cast<double>(tokens[i]);
int flag = boost::lexical_cast<int>(tokens[i+1]);
if(flag > 0)
{
total += val;
++accepted;
badCount = 0;
}
else
{
++badCount;
if(badCount > badCountMax)
{
badCountMax = badCount;
badDate = tokens[0];
}
}
}
cout << tokens[0];
cout << " Reject: " << std::setw(2) << (NumFlags - accepted);
cout << " Accept: " << std::setw(2) << accepted;
cout << " Average: " << std::setprecision(5) << total / accepted << endl;
}
cout << endl;
cout << "Maximum number of consecutive bad readings is " << badCountMax << endl;
cout << "Ends on date " << badDate << endl;
}
| package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
const (
filename = "readings.txt"
readings = 24
fields = readings*2 + 1
)
func main() {
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
var (
badRun, maxRun int
badDate, maxDate string
fileSum float64
fileAccept int
)
endBadRun := func() {
if badRun > maxRun {
maxRun = badRun
maxDate = badDate
}
badRun = 0
}
s := bufio.NewScanner(file)
for s.Scan() {
f := strings.Fields(s.Text())
if len(f) != fields {
log.Fatal("unexpected format,", len(f), "fields.")
}
var accept int
var sum float64
for i := 1; i < fields; i += 2 {
flag, err := strconv.Atoi(f[i+1])
if err != nil {
log.Fatal(err)
}
if flag <= 0 {
if badRun++; badRun == 1 {
badDate = f[0]
}
} else {
endBadRun()
value, err := strconv.ParseFloat(f[i], 64)
if err != nil {
log.Fatal(err)
}
sum += value
accept++
}
}
fmt.Printf("Line: %s Reject %2d Accept: %2d Line_tot:%9.3f",
f[0], readings-accept, accept, sum)
if accept > 0 {
fmt.Printf(" Line_avg:%8.3f\n", sum/float64(accept))
} else {
fmt.Println()
}
fileSum += sum
fileAccept += accept
}
if err := s.Err(); err != nil {
log.Fatal(err)
}
endBadRun()
fmt.Println("\nFile =", filename)
fmt.Printf("Total = %.3f\n", fileSum)
fmt.Println("Readings = ", fileAccept)
if fileAccept > 0 {
fmt.Printf("Average = %.3f\n", fileSum/float64(fileAccept))
}
if maxRun == 0 {
fmt.Println("\nAll data valid.")
} else {
fmt.Printf("\nMax data gap = %d, beginning on line %s.\n",
maxRun, maxDate)
}
}
|
Write the same code in Go as shown below in C++. | #include <string>
#include <iostream>
#include "Poco/MD5Engine.h"
#include "Poco/DigestStream.h"
using Poco::DigestEngine ;
using Poco::MD5Engine ;
using Poco::DigestOutputStream ;
int main( ) {
std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ;
MD5Engine md5 ;
DigestOutputStream outstr( md5 ) ;
outstr << myphrase ;
outstr.flush( ) ;
const DigestEngine::Digest& digest = md5.digest( ) ;
std::cout << myphrase << " as a MD5 digest :\n" << DigestEngine::digestToHex( digest )
<< " !" << std::endl ;
return 0 ;
}
| package main
import (
"crypto/md5"
"fmt"
)
func main() {
for _, p := range [][2]string{
{"d41d8cd98f00b204e9800998ecf8427e", ""},
{"0cc175b9c0f1b6a831c399e269772661", "a"},
{"900150983cd24fb0d6963f7d28e17f72", "abc"},
{"f96b697d7cb7938d525a2f31aaf161d0", "message digest"},
{"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"},
{"d174ab98d277d9f5a5611c2c9f419d9f",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"},
{"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890"},
{"e38ca1d920c4b8b8d3946b2c72f01680",
"The quick brown fox jumped over the lazy dog's back"},
} {
validate(p[0], p[1])
}
}
var h = md5.New()
func validate(check, s string) {
h.Reset()
h.Write([]byte(s))
sum := fmt.Sprintf("%x", h.Sum(nil))
if sum != check {
fmt.Println("MD5 fail")
fmt.Println(" for string,", s)
fmt.Println(" expected: ", check)
fmt.Println(" got: ", sum)
}
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
integer divisor_sum(integer n) {
integer total = 1, power = 2;
for (; n % 2 == 0; power *= 2, n /= 2)
total += power;
for (integer p = 3; p * p <= n; p += 2) {
integer sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (n > 1)
total *= n + 1;
return total;
}
void classify_aliquot_sequence(integer n) {
constexpr int limit = 16;
integer terms[limit];
terms[0] = n;
std::string classification("non-terminating");
int length = 1;
for (int i = 1; i < limit; ++i) {
++length;
terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];
if (terms[i] == n) {
classification =
(i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable"));
break;
}
int j = 1;
for (; j < i; ++j) {
if (terms[i] == terms[i - j])
break;
}
if (j < i) {
classification = (j == 1 ? "aspiring" : "cyclic");
break;
}
if (terms[i] == 0) {
classification = "terminating";
break;
}
}
std::cout << n << ": " << classification << ", sequence: " << terms[0];
for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)
std::cout << ' ' << terms[i];
std::cout << '\n';
}
int main() {
for (integer i = 1; i <= 10; ++i)
classify_aliquot_sequence(i);
for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,
1064, 1488})
classify_aliquot_sequence(i);
classify_aliquot_sequence(15355717786080);
classify_aliquot_sequence(153557177860800);
return 0;
}
| package main
import (
"fmt"
"math"
"strings"
)
const threshold = uint64(1) << 47
func indexOf(s []uint64, search uint64) int {
for i, e := range s {
if e == search {
return i
}
}
return -1
}
func contains(s []uint64, search uint64) bool {
return indexOf(s, search) > -1
}
func maxOf(i1, i2 int) int {
if i1 > i2 {
return i1
}
return i2
}
func sumProperDivisors(n uint64) uint64 {
if n < 2 {
return 0
}
sqrt := uint64(math.Sqrt(float64(n)))
sum := uint64(1)
for i := uint64(2); i <= sqrt; i++ {
if n % i != 0 {
continue
}
sum += i + n / i
}
if sqrt * sqrt == n {
sum -= sqrt
}
return sum
}
func classifySequence(k uint64) ([]uint64, string) {
if k == 0 {
panic("Argument must be positive.")
}
last := k
var seq []uint64
seq = append(seq, k)
for {
last = sumProperDivisors(last)
seq = append(seq, last)
n := len(seq)
aliquot := ""
switch {
case last == 0:
aliquot = "Terminating"
case n == 2 && last == k:
aliquot = "Perfect"
case n == 3 && last == k:
aliquot = "Amicable"
case n >= 4 && last == k:
aliquot = fmt.Sprintf("Sociable[%d]", n - 1)
case last == seq[n - 2]:
aliquot = "Aspiring"
case contains(seq[1 : maxOf(1, n - 2)], last):
aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last))
case n == 16 || last > threshold:
aliquot = "Non-Terminating"
}
if aliquot != "" {
return seq, aliquot
}
}
}
func joinWithCommas(seq []uint64) string {
res := fmt.Sprint(seq)
res = strings.Replace(res, " ", ", ", -1)
return res
}
func main() {
fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n")
for k := uint64(1); k <= 10; k++ {
seq, aliquot := classifySequence(k)
fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq))
}
fmt.Println()
s := []uint64{
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,
}
for _, k := range s {
seq, aliquot := classifySequence(k)
fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq))
}
fmt.Println()
k := uint64(15355717786080)
seq, aliquot := classifySequence(k)
fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq))
}
|
Ensure the translated Go code behaves exactly like the original C++ snippet. | #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
integer divisor_sum(integer n) {
integer total = 1, power = 2;
for (; n % 2 == 0; power *= 2, n /= 2)
total += power;
for (integer p = 3; p * p <= n; p += 2) {
integer sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (n > 1)
total *= n + 1;
return total;
}
void classify_aliquot_sequence(integer n) {
constexpr int limit = 16;
integer terms[limit];
terms[0] = n;
std::string classification("non-terminating");
int length = 1;
for (int i = 1; i < limit; ++i) {
++length;
terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];
if (terms[i] == n) {
classification =
(i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable"));
break;
}
int j = 1;
for (; j < i; ++j) {
if (terms[i] == terms[i - j])
break;
}
if (j < i) {
classification = (j == 1 ? "aspiring" : "cyclic");
break;
}
if (terms[i] == 0) {
classification = "terminating";
break;
}
}
std::cout << n << ": " << classification << ", sequence: " << terms[0];
for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)
std::cout << ' ' << terms[i];
std::cout << '\n';
}
int main() {
for (integer i = 1; i <= 10; ++i)
classify_aliquot_sequence(i);
for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,
1064, 1488})
classify_aliquot_sequence(i);
classify_aliquot_sequence(15355717786080);
classify_aliquot_sequence(153557177860800);
return 0;
}
| package main
import (
"fmt"
"math"
"strings"
)
const threshold = uint64(1) << 47
func indexOf(s []uint64, search uint64) int {
for i, e := range s {
if e == search {
return i
}
}
return -1
}
func contains(s []uint64, search uint64) bool {
return indexOf(s, search) > -1
}
func maxOf(i1, i2 int) int {
if i1 > i2 {
return i1
}
return i2
}
func sumProperDivisors(n uint64) uint64 {
if n < 2 {
return 0
}
sqrt := uint64(math.Sqrt(float64(n)))
sum := uint64(1)
for i := uint64(2); i <= sqrt; i++ {
if n % i != 0 {
continue
}
sum += i + n / i
}
if sqrt * sqrt == n {
sum -= sqrt
}
return sum
}
func classifySequence(k uint64) ([]uint64, string) {
if k == 0 {
panic("Argument must be positive.")
}
last := k
var seq []uint64
seq = append(seq, k)
for {
last = sumProperDivisors(last)
seq = append(seq, last)
n := len(seq)
aliquot := ""
switch {
case last == 0:
aliquot = "Terminating"
case n == 2 && last == k:
aliquot = "Perfect"
case n == 3 && last == k:
aliquot = "Amicable"
case n >= 4 && last == k:
aliquot = fmt.Sprintf("Sociable[%d]", n - 1)
case last == seq[n - 2]:
aliquot = "Aspiring"
case contains(seq[1 : maxOf(1, n - 2)], last):
aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last))
case n == 16 || last > threshold:
aliquot = "Non-Terminating"
}
if aliquot != "" {
return seq, aliquot
}
}
}
func joinWithCommas(seq []uint64) string {
res := fmt.Sprint(seq)
res = strings.Replace(res, " ", ", ", -1)
return res
}
func main() {
fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n")
for k := uint64(1); k <= 10; k++ {
seq, aliquot := classifySequence(k)
fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq))
}
fmt.Println()
s := []uint64{
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,
}
for _, k := range s {
seq, aliquot := classifySequence(k)
fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq))
}
fmt.Println()
k := uint64(15355717786080)
seq, aliquot := classifySequence(k)
fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq))
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <cstdint>
#include <iostream>
#include <string>
using integer = uint64_t;
integer divisor_sum(integer n) {
integer total = 1, power = 2;
for (; n % 2 == 0; power *= 2, n /= 2)
total += power;
for (integer p = 3; p * p <= n; p += 2) {
integer sum = 1;
for (power = p; n % p == 0; power *= p, n /= p)
sum += power;
total *= sum;
}
if (n > 1)
total *= n + 1;
return total;
}
void classify_aliquot_sequence(integer n) {
constexpr int limit = 16;
integer terms[limit];
terms[0] = n;
std::string classification("non-terminating");
int length = 1;
for (int i = 1; i < limit; ++i) {
++length;
terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1];
if (terms[i] == n) {
classification =
(i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable"));
break;
}
int j = 1;
for (; j < i; ++j) {
if (terms[i] == terms[i - j])
break;
}
if (j < i) {
classification = (j == 1 ? "aspiring" : "cyclic");
break;
}
if (terms[i] == 0) {
classification = "terminating";
break;
}
}
std::cout << n << ": " << classification << ", sequence: " << terms[0];
for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i)
std::cout << ' ' << terms[i];
std::cout << '\n';
}
int main() {
for (integer i = 1; i <= 10; ++i)
classify_aliquot_sequence(i);
for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562,
1064, 1488})
classify_aliquot_sequence(i);
classify_aliquot_sequence(15355717786080);
classify_aliquot_sequence(153557177860800);
return 0;
}
| package main
import (
"fmt"
"math"
"strings"
)
const threshold = uint64(1) << 47
func indexOf(s []uint64, search uint64) int {
for i, e := range s {
if e == search {
return i
}
}
return -1
}
func contains(s []uint64, search uint64) bool {
return indexOf(s, search) > -1
}
func maxOf(i1, i2 int) int {
if i1 > i2 {
return i1
}
return i2
}
func sumProperDivisors(n uint64) uint64 {
if n < 2 {
return 0
}
sqrt := uint64(math.Sqrt(float64(n)))
sum := uint64(1)
for i := uint64(2); i <= sqrt; i++ {
if n % i != 0 {
continue
}
sum += i + n / i
}
if sqrt * sqrt == n {
sum -= sqrt
}
return sum
}
func classifySequence(k uint64) ([]uint64, string) {
if k == 0 {
panic("Argument must be positive.")
}
last := k
var seq []uint64
seq = append(seq, k)
for {
last = sumProperDivisors(last)
seq = append(seq, last)
n := len(seq)
aliquot := ""
switch {
case last == 0:
aliquot = "Terminating"
case n == 2 && last == k:
aliquot = "Perfect"
case n == 3 && last == k:
aliquot = "Amicable"
case n >= 4 && last == k:
aliquot = fmt.Sprintf("Sociable[%d]", n - 1)
case last == seq[n - 2]:
aliquot = "Aspiring"
case contains(seq[1 : maxOf(1, n - 2)], last):
aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last))
case n == 16 || last > threshold:
aliquot = "Non-Terminating"
}
if aliquot != "" {
return seq, aliquot
}
}
}
func joinWithCommas(seq []uint64) string {
res := fmt.Sprint(seq)
res = strings.Replace(res, " ", ", ", -1)
return res
}
func main() {
fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n")
for k := uint64(1); k <= 10; k++ {
seq, aliquot := classifySequence(k)
fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq))
}
fmt.Println()
s := []uint64{
11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488,
}
for _, k := range s {
seq, aliquot := classifySequence(k)
fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq))
}
fmt.Println()
k := uint64(15355717786080)
seq, aliquot := classifySequence(k)
fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq))
}
|
Please provide an equivalent version of this C++ code in Go. | #include <string>
#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>
#include <sstream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <locale>
int main( ) {
std::string datestring ("March 7 2009 7:30pm EST" ) ;
std::vector<std::string> elements ;
boost::split( elements , datestring , boost::is_any_of( " " ) ) ;
std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " +
elements[ 2 ] ;
std::string timepart = elements[ 3 ] ;
std::string timezone = elements[ 4 ] ;
const char meridians[ ] = { 'a' , 'p' } ;
std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;
std::string twelve_hour ( timepart.substr( found , 1 ) ) ;
timepart = timepart.substr( 0 , found ) ;
elements.clear( ) ;
boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ;
long hour = std::atol( (elements.begin( ))->c_str( ) ) ;
if ( twelve_hour == "p" )
hour += 12 ;
long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ;
boost::local_time::tz_database tz_db ;
tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ;
boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ;
boost::gregorian::date_input_facet *f =
new boost::gregorian::date_input_facet( "%B %d %Y" ) ;
std::stringstream ss ;
ss << datepart ;
ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;
boost::gregorian::date d ;
ss >> d ;
boost::posix_time::time_duration td ( hour , minute , 0 ) ;
boost::local_time::local_date_time lt ( d , td , dyc ,
boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;
std::cout << "local time: " << lt << '\n' ;
ss.str( "" ) ;
ss << lt ;
boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;
boost::local_time::local_date_time ltlater = lt + td2 ;
boost::gregorian::date_facet *f2 =
new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ;
std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;
std::cout << "12 hours after " << ss.str( ) << " it is " << ltlater << " !\n" ;
boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ;
std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ;
std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ;
return 0 ;
}
| package main
import (
"fmt"
"time"
)
const taskDate = "March 7 2009 7:30pm EST"
const taskFormat = "January 2 2006 3:04pm MST"
func main() {
if etz, err := time.LoadLocation("US/Eastern"); err == nil {
time.Local = etz
}
fmt.Println("Input: ", taskDate)
t, err := time.Parse(taskFormat, taskDate)
if err != nil {
fmt.Println(err)
return
}
t = t.Add(12 * time.Hour)
fmt.Println("+12 hrs: ", t)
if _, offset := t.Zone(); offset == 0 {
fmt.Println("No time zone info.")
return
}
atz, err := time.LoadLocation("US/Arizona")
if err == nil {
fmt.Println("+12 hrs in Arizona:", t.In(atz))
}
}
|
Rewrite the snippet below in Go so it works the same as the original C++ code. | #include <chrono>
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char* argv[]) {
std::vector<std::thread> threads;
for (int i = 1; i < argc; ++i) {
threads.emplace_back([i, &argv]() {
int arg = std::stoi(argv[i]);
std::this_thread::sleep_for(std::chrono::seconds(arg));
std::cout << argv[i] << std::endl;
});
}
for (auto& thread : threads) {
thread.join();
}
}
| package main
import (
"fmt"
"log"
"os"
"strconv"
"time"
)
func main() {
out := make(chan uint64)
for _, a := range os.Args[1:] {
i, err := strconv.ParseUint(a, 10, 64)
if err != nil {
log.Fatal(err)
}
go func(n uint64) {
time.Sleep(time.Duration(n) * time.Millisecond)
out <- n
}(i)
}
for _ = range os.Args[1:] {
fmt.Println(<-out)
}
}
|
Generate a Go translation of this C++ snippet without changing its computational steps. | #include<cstdlib>
#include<ctime>
#include<iostream>
using namespace std;
int main()
{
int arr[10][10];
srand(time(NULL));
for(auto& row: arr)
for(auto& col: row)
col = rand() % 20 + 1;
([&](){
for(auto& row : arr)
for(auto& col: row)
{
cout << col << endl;
if(col == 20)return;
}
})();
return 0;
}
| package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
values := make([][]int, 10)
for i := range values {
values[i] = make([]int, 10)
for j := range values[i] {
values[i][j] = rand.Intn(20) + 1
}
}
outerLoop:
for i, row := range values {
fmt.Printf("%3d)", i)
for _, value := range row {
fmt.Printf(" %3d", value)
if value == 20 {
break outerLoop
}
}
fmt.Printf("\n")
}
fmt.Printf("\n")
}
|
Please provide an equivalent version of this C++ code in Go. | #include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>
using namespace std;
auto CountTriplets(unsigned long long maxPerimeter)
{
unsigned long long totalCount = 0;
unsigned long long primitveCount = 0;
auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
for(unsigned long long m = 2; m < max_M; ++m)
{
for(unsigned long long n = 1 + m % 2; n < m; n+=2)
{
if(gcd(m,n) != 1)
{
continue;
}
auto a = m * m - n * n;
auto b = 2 * m * n;
auto c = m * m + n * n;
auto perimeter = a + b + c;
if(perimeter <= maxPerimeter)
{
primitveCount++;
totalCount+= maxPerimeter / perimeter;
}
}
}
return tuple(totalCount, primitveCount);
}
int main()
{
vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
1000'000, 10'000'000, 100'000'000, 1000'000'000,
10'000'000'000};
for(auto maxPerimeter : inputs)
{
auto [total, primitive] = CountTriplets(maxPerimeter);
cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
}
}
| package main
import "fmt"
var total, prim, maxPeri int64
func newTri(s0, s1, s2 int64) {
if p := s0 + s1 + s2; p <= maxPeri {
prim++
total += maxPeri / p
newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)
newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)
newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)
}
}
func main() {
for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {
prim = 0
total = 0
newTri(3, 4, 5)
fmt.Printf("Up to %d: %d triples, %d primitives\n",
maxPeri, total, prim)
}
}
|
Produce a language-to-language conversion: from C++ to Go, same semantics. | #include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>
using namespace std;
auto CountTriplets(unsigned long long maxPerimeter)
{
unsigned long long totalCount = 0;
unsigned long long primitveCount = 0;
auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
for(unsigned long long m = 2; m < max_M; ++m)
{
for(unsigned long long n = 1 + m % 2; n < m; n+=2)
{
if(gcd(m,n) != 1)
{
continue;
}
auto a = m * m - n * n;
auto b = 2 * m * n;
auto c = m * m + n * n;
auto perimeter = a + b + c;
if(perimeter <= maxPerimeter)
{
primitveCount++;
totalCount+= maxPerimeter / perimeter;
}
}
}
return tuple(totalCount, primitveCount);
}
int main()
{
vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
1000'000, 10'000'000, 100'000'000, 1000'000'000,
10'000'000'000};
for(auto maxPerimeter : inputs)
{
auto [total, primitive] = CountTriplets(maxPerimeter);
cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
}
}
| package main
import "fmt"
var total, prim, maxPeri int64
func newTri(s0, s1, s2 int64) {
if p := s0 + s1 + s2; p <= maxPeri {
prim++
total += maxPeri / p
newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)
newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)
newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)
}
}
func main() {
for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {
prim = 0
total = 0
newTri(3, 4, 5)
fmt.Printf("Up to %d: %d triples, %d primitives\n",
maxPeri, total, prim)
}
}
|
Keep all operations the same but rewrite the snippet in Go. | #include <set>
#include <iostream>
using namespace std;
int main() {
typedef set<int> TySet;
int data[] = {1, 2, 3, 2, 3, 4};
TySet unique_set(data, data + 6);
cout << "Set items:" << endl;
for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)
cout << *iter << " ";
cout << endl;
}
| package main
import "fmt"
func uniq(list []int) []int {
unique_set := make(map[int]bool, len(list))
for _, x := range list {
unique_set[x] = true
}
result := make([]int, 0, len(unique_set))
for x := range unique_set {
result = append(result, x)
}
return result
}
func main() {
fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4}))
}
|
Change the programming language of this snippet from C++ to Go without modifying what it does. | #include <iostream>
#include <sstream>
#include <string>
std::string lookandsay(const std::string& s)
{
std::ostringstream r;
for (std::size_t i = 0; i != s.length();) {
auto new_i = s.find_first_not_of(s[i], i + 1);
if (new_i == std::string::npos)
new_i = s.length();
r << new_i - i << s[i];
i = new_i;
}
return r.str();
}
int main()
{
std::string laf = "1";
std::cout << laf << '\n';
for (int i = 0; i < 10; ++i) {
laf = lookandsay(laf);
std::cout << laf << '\n';
}
}
| package main
import (
"fmt"
"strconv"
)
func lss(s string) (r string) {
c := s[0]
nc := 1
for i := 1; i < len(s); i++ {
d := s[i]
if d == c {
nc++
continue
}
r += strconv.Itoa(nc) + string(c)
c = d
nc = 1
}
return r + strconv.Itoa(nc) + string(c)
}
func main() {
s := "1"
fmt.Println(s)
for i := 0; i < 8; i++ {
s = lss(s)
fmt.Println(s)
}
}
|
Translate this program into Go but keep the logic exactly as in C++. | #include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
continue;
for (int j = i; j <= max; j += i)
totient_[j] -= totient_[j] / i;
}
}
int totient(int n) const {
assert (n >= 1 && n < totient_.size());
return totient_[n];
}
bool is_prime(int n) const {
return totient(n) == n - 1;
}
private:
std::vector<int> totient_;
};
int count_primes(const totient_calculator& tc, int min, int max) {
int count = 0;
for (int i = min; i <= max; ++i) {
if (tc.is_prime(i))
++count;
}
return count;
}
int main() {
const int max = 10000000;
totient_calculator tc(max);
std::cout << " n totient prime?\n";
for (int i = 1; i <= 25; ++i) {
std::cout << std::setw(2) << i
<< std::setw(9) << tc.totient(i)
<< std::setw(8) << (tc.is_prime(i) ? "yes" : "no") << '\n';
}
for (int n = 100; n <= max; n *= 10) {
std::cout << "Count of primes up to " << n << ": "
<< count_primes(tc, 1, n) << '\n';
}
return 0;
}
| package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
fmt.Println(" n phi prime")
fmt.Println("---------------")
count := 0
for n := 1; n <= 25; n++ {
tot := totient(n)
isPrime := n-1 == tot
if isPrime {
count++
}
fmt.Printf("%2d %2d %t\n", n, tot, isPrime)
}
fmt.Println("\nNumber of primes up to 25 =", count)
for n := 26; n <= 100000; n++ {
tot := totient(n)
if tot == n-1 {
count++
}
if n == 100 || n == 1000 || n%10000 == 0 {
fmt.Printf("\nNumber of primes up to %-6d = %d\n", n, count)
}
}
}
|
Generate an equivalent Go version of this C++ code. | template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;
template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>
{
typedef ThenType type;
};
template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>
{
typedef ElseType type;
};
ifthenelse<INT_MAX == 32767,
long int,
int>
::type myvar;
| if booleanExpression {
statements
}
|
Port the provided C++ code into Go while preserving the original functionality. | #include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <cmath>
using namespace std;
class fractran
{
public:
void run( std::string p, int s, int l )
{
start = s; limit = l;
istringstream iss( p ); vector<string> tmp;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );
string item; vector< pair<float, float> > v;
pair<float, float> a;
for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )
{
string::size_type pos = ( *i ).find( '/', 0 );
if( pos != std::string::npos )
{
a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );
v.push_back( a );
}
}
exec( &v );
}
private:
void exec( vector< pair<float, float> >* v )
{
int cnt = 0;
while( cnt < limit )
{
cout << cnt << " : " << start << "\n";
cnt++;
vector< pair<float, float> >::iterator it = v->begin();
bool found = false; float r;
while( it != v->end() )
{
r = start * ( ( *it ).first / ( *it ).second );
if( r == floor( r ) )
{
found = true;
break;
}
++it;
}
if( found ) start = ( int )r;
else break;
}
}
int start, limit;
};
int main( int argc, char* argv[] )
{
fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 );
cin.get();
return 0;
}
| package main
import (
"fmt"
"log"
"math/big"
"os"
"strconv"
"strings"
)
func compile(src string) ([]big.Rat, bool) {
s := strings.Fields(src)
r := make([]big.Rat, len(s))
for i, s1 := range s {
if _, ok := r[i].SetString(s1); !ok {
return nil, false
}
}
return r, true
}
func exec(p []big.Rat, n *big.Int, limit int) {
var q, r big.Int
rule:
for i := 0; i < limit; i++ {
fmt.Printf("%d ", n)
for j := range p {
q.QuoRem(n, p[j].Denom(), &r)
if r.BitLen() == 0 {
n.Mul(&q, p[j].Num())
continue rule
}
}
break
}
fmt.Println()
}
func usage() {
log.Fatal("usage: ft <limit> <n> <prog>")
}
func main() {
if len(os.Args) != 4 {
usage()
}
limit, err := strconv.Atoi(os.Args[1])
if err != nil {
usage()
}
var n big.Int
_, ok := n.SetString(os.Args[2], 10)
if !ok {
usage()
}
p, ok := compile(os.Args[3])
if !ok {
usage()
}
exec(p, &n, limit)
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include <iostream>
#include <time.h>
using namespace std;
class stooge
{
public:
void sort( int* arr, int start, int end )
{
if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );
int n = end - start; if( n > 2 )
{
n /= 3; sort( arr, start, end - n );
sort( arr, start + n, end ); sort( arr, start, end - n );
}
}
};
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80;
cout << "before:\n";
for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20; cout << a[x] << " "; }
s.sort( a, 0, m ); cout << "\n\nafter:\n";
for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n";
return system( "pause" );
}
| package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
stoogesort(a)
fmt.Println("after: ", a)
fmt.Println("nyuk nyuk nyuk")
}
func stoogesort(a []int) {
last := len(a) - 1
if a[last] < a[0] {
a[0], a[last] = a[last], a[0]
}
if last > 1 {
t := len(a) / 3
stoogesort(a[:len(a)-t])
stoogesort(a[t:])
stoogesort(a[:len(a)-t])
}
}
|
Transform the following C++ implementation into Go, maintaining the same output and logic. | #include <iostream>
#include <time.h>
using namespace std;
class stooge
{
public:
void sort( int* arr, int start, int end )
{
if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );
int n = end - start; if( n > 2 )
{
n /= 3; sort( arr, start, end - n );
sort( arr, start + n, end ); sort( arr, start, end - n );
}
}
};
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80;
cout << "before:\n";
for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20; cout << a[x] << " "; }
s.sort( a, 0, m ); cout << "\n\nafter:\n";
for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n";
return system( "pause" );
}
| package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
stoogesort(a)
fmt.Println("after: ", a)
fmt.Println("nyuk nyuk nyuk")
}
func stoogesort(a []int) {
last := len(a) - 1
if a[last] < a[0] {
a[0], a[last] = a[last], a[0]
}
if last > 1 {
t := len(a) / 3
stoogesort(a[:len(a)-t])
stoogesort(a[t:])
stoogesort(a[:len(a)-t])
}
}
|
Preserve the algorithm and functionality while converting the code from C++ to Go. | #include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void *pBits;
int width, height, wid;
DWORD clr;
};
class point {
public:
int x; float y;
void set( int a, float b ) { x = a; y = b; }
};
typedef struct {
point position, offset;
bool alive, start;
}ball;
class galton {
public :
galton() {
bmp.create( BMP_WID, BMP_HEI );
initialize();
}
void setHWND( HWND hwnd ) { _hwnd = hwnd; }
void simulate() {
draw(); update(); Sleep( 1 );
}
private:
void draw() {
bmp.clear();
bmp.setPenColor( RGB( 0, 255, 0 ) );
bmp.setBrushColor( RGB( 0, 255, 0 ) );
int xx, yy;
for( int y = 3; y < 14; y++ ) {
yy = 10 * y;
for( int x = 0; x < 41; x++ ) {
xx = 10 * x;
if( pins[y][x] )
Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 );
}
}
bmp.setPenColor( RGB( 255, 0, 0 ) );
bmp.setBrushColor( RGB( 255, 0, 0 ) );
ball* b;
for( int x = 0; x < MAX_BALLS; x++ ) {
b = &balls[x];
if( b->alive )
Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ),
static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) );
}
for( int x = 0; x < 70; x++ ) {
if( cols[x] > 0 ) {
xx = 10 * x;
Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] );
}
}
HDC dc = GetDC( _hwnd );
BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY );
ReleaseDC( _hwnd, dc );
}
void update() {
ball* b;
for( int x = 0; x < MAX_BALLS; x++ ) {
b = &balls[x];
if( b->alive ) {
b->position.x += b->offset.x; b->position.y += b->offset.y;
if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) {
b->start = true;
balls[x + 1].alive = true;
}
int c = ( int )b->position.x, d = ( int )b->position.y + 6;
if( d > 10 || d < 41 ) {
if( pins[d / 10][c / 10] ) {
if( rand() % 30 < 15 ) b->position.x -= 10;
else b->position.x += 10;
}
}
if( b->position.y > 160 ) {
b->alive = false;
cols[c / 10] += 1;
}
}
}
}
void initialize() {
for( int x = 0; x < MAX_BALLS; x++ ) {
balls[x].position.set( 200, -10 );
balls[x].offset.set( 0, 0.5f );
balls[x].alive = balls[x].start = false;
}
balls[0].alive = true;
for( int x = 0; x < 70; x++ )
cols[x] = 0;
for( int y = 0; y < 70; y++ )
for( int x = 0; x < 41; x++ )
pins[x][y] = false;
int p;
for( int y = 0; y < 11; y++ ) {
p = ( 41 / 2 ) - y;
for( int z = 0; z < y + 1; z++ ) {
pins[3 + y][p] = true;
p += 2;
}
}
}
myBitmap bmp;
HWND _hwnd;
bool pins[70][40];
ball balls[MAX_BALLS];
int cols[70];
};
class wnd {
public:
int wnd::Run( HINSTANCE hInst ) {
_hInst = hInst;
_hwnd = InitAll();
_gtn.setHWND( _hwnd );
ShowWindow( _hwnd, SW_SHOW );
UpdateWindow( _hwnd );
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT ) {
if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {
TranslateMessage( &msg );
DispatchMessage( &msg );
} else _gtn.simulate();
}
return UnregisterClass( "_GALTON_", _hInst );
}
private:
static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
switch( msg ) {
case WM_DESTROY: PostQuitMessage( 0 ); break;
default:
return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) );
}
return 0;
}
HWND InitAll() {
WNDCLASSEX wcex;
ZeroMemory( &wcex, sizeof( wcex ) );
wcex.cbSize = sizeof( WNDCLASSEX );
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = ( WNDPROC )WndProc;
wcex.hInstance = _hInst;
wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wcex.lpszClassName = "_GALTON_";
RegisterClassEx( &wcex );
RECT rc;
SetRect( &rc, 0, 0, BMP_WID, BMP_HEI );
AdjustWindowRect( &rc, WS_CAPTION, FALSE );
return CreateWindow( "_GALTON_", ".: Galton Box -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL );
}
HINSTANCE _hInst;
HWND _hwnd;
galton _gtn;
};
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {
srand( GetTickCount() );
wnd myWnd;
return myWnd.Run( hInstance );
}
| package main
import (
"fmt"
"math/rand"
"time"
)
const boxW = 41
const boxH = 37
const pinsBaseW = 19
const nMaxBalls = 55
const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1
const (
empty = ' '
ball = 'o'
wall = '|'
corner = '+'
floor = '-'
pin = '.'
)
type Ball struct{ x, y int }
func newBall(x, y int) *Ball {
if box[y][x] != empty {
panic("Tried to create a new ball in a non-empty cell. Program terminated.")
}
b := Ball{x, y}
box[y][x] = ball
return &b
}
func (b *Ball) doStep() {
if b.y <= 0 {
return
}
cell := box[b.y-1][b.x]
switch cell {
case empty:
box[b.y][b.x] = empty
b.y--
box[b.y][b.x] = ball
case pin:
box[b.y][b.x] = empty
b.y--
if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty {
b.x += rand.Intn(2)*2 - 1
box[b.y][b.x] = ball
return
} else if box[b.y][b.x-1] == empty {
b.x++
} else {
b.x--
}
box[b.y][b.x] = ball
default:
}
}
type Cell = byte
var box [boxH][boxW]Cell
func initializeBox() {
box[0][0] = corner
box[0][boxW-1] = corner
for i := 1; i < boxW-1; i++ {
box[0][i] = floor
}
for i := 0; i < boxW; i++ {
box[boxH-1][i] = box[0][i]
}
for r := 1; r < boxH-1; r++ {
box[r][0] = wall
box[r][boxW-1] = wall
}
for i := 1; i < boxH-1; i++ {
for j := 1; j < boxW-1; j++ {
box[i][j] = empty
}
}
for nPins := 1; nPins <= pinsBaseW; nPins++ {
for p := 0; p < nPins; p++ {
box[boxH-2-nPins][centerH+1-nPins+p*2] = pin
}
}
}
func drawBox() {
for r := boxH - 1; r >= 0; r-- {
for c := 0; c < boxW; c++ {
fmt.Printf("%c", box[r][c])
}
fmt.Println()
}
}
func main() {
rand.Seed(time.Now().UnixNano())
initializeBox()
var balls []*Ball
for i := 0; i < nMaxBalls+boxH; i++ {
fmt.Println("\nStep", i, ":")
if i < nMaxBalls {
balls = append(balls, newBall(centerH, boxH-2))
}
drawBox()
for _, b := range balls {
b.doStep()
}
}
}
|
Can you help me rewrite this code in Go instead of C++, keeping it the same logically? | #include <iostream>
int circlesort(int* arr, int lo, int hi, int swaps) {
if(lo == hi) {
return swaps;
}
int high = hi;
int low = lo;
int mid = (high - low) / 2;
while(lo < hi) {
if(arr[lo] > arr[hi]) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
swaps++;
}
lo++;
hi--;
}
if(lo == hi) {
if(arr[lo] > arr[hi+1]) {
int temp = arr[lo];
arr[lo] = arr[hi+1];
arr[hi+1] = temp;
swaps++;
}
}
swaps = circlesort(arr, low, low+mid, swaps);
swaps = circlesort(arr, low+mid+1, high, swaps);
return swaps;
}
void circlesortDriver(int* arr, int n) {
do {
for(int i = 0; i < n; i++) {
std::cout << arr[i] << ' ';
}
std::cout << std::endl;
} while(circlesort(arr, 0, n-1, 0));
}
int main() {
int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };
circlesortDriver(arr, sizeof(arr)/sizeof(int));
return 0;
}
| package main
import "fmt"
func circleSort(a []int, lo, hi, swaps int) int {
if lo == hi {
return swaps
}
high, low := hi, lo
mid := (hi - lo) / 2
for lo < hi {
if a[lo] > a[hi] {
a[lo], a[hi] = a[hi], a[lo]
swaps++
}
lo++
hi--
}
if lo == hi {
if a[lo] > a[hi+1] {
a[lo], a[hi+1] = a[hi+1], a[lo]
swaps++
}
}
swaps = circleSort(a, low, low+mid, swaps)
swaps = circleSort(a, low+mid+1, high, swaps)
return swaps
}
func main() {
aa := [][]int{
{6, 7, 8, 9, 2, 5, 3, 4, 1},
{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1},
}
for _, a := range aa {
fmt.Printf("Original: %v\n", a)
for circleSort(a, 0, len(a)-1, 0) != 0 {
}
fmt.Printf("Sorted : %v\n\n", a)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.