Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the following code from VB to Go with equivalent syntax and logic. | class playingcard
dim suit
dim pips
end class
class carddeck
private suitnames
private pipnames
private cardno
private deck(52)
private nTop
sub class_initialize
dim suit
dim pips
suitnames = split("H,D,C,S",",")
pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",")
cardno = 0
for suit = 1 to 4
for pips = 1 to 13
set deck(cardno) = new playingcard
deck(cardno).suit = suitnames(suit-1)
deck(cardno).pips = pipnames(pips-1)
cardno = cardno + 1
next
next
nTop = 0
end sub
public sub showdeck
dim a
redim a(51-nTop)
for i = nTop to 51
a(i) = deck(i).pips & deck(i).suit
next
wscript.echo join( a, ", ")
end sub
public sub shuffle
dim r
randomize timer
for i = nTop to 51
r = int( rnd * ( 52 - nTop ) )
if r <> i then
objswap deck(i),deck(r)
end if
next
end sub
public function deal()
set deal = deck( nTop )
nTop = nTop + 1
end function
public property get cardsRemaining
cardsRemaining = 52 - nTop
end property
private sub objswap( a, b )
dim tmp
set tmp = a
set a = b
set b = tmp
end sub
end class
| package cards
import (
"math/rand"
)
type Suit uint8
const (
Spade Suit = 3
Heart Suit = 2
Diamond Suit = 1
Club Suit = 0
)
func (s Suit) String() string {
const suites = "CDHS"
return suites[s : s+1]
}
type Rank uint8
const (
Ace Rank = 1
Two Rank = 2
Three Rank = 3
Four Rank = 4
Five Rank = 5
Six Rank = 6
Seven Rank = 7
Eight Rank = 8
Nine Rank = 9
Ten Rank = 10
Jack Rank = 11
Queen Rank = 12
King Rank = 13
)
func (r Rank) String() string {
const ranks = "A23456789TJQK"
return ranks[r-1 : r]
}
type Card uint8
func NewCard(r Rank, s Suit) Card {
return Card(13*uint8(s) + uint8(r-1))
}
func (c Card) RankSuit() (Rank, Suit) {
return Rank(c%13 + 1), Suit(c / 13)
}
func (c Card) Rank() Rank {
return Rank(c%13 + 1)
}
func (c Card) Suit() Suit {
return Suit(c / 13)
}
func (c Card) String() string {
return c.Rank().String() + c.Suit().String()
}
type Deck []Card
func NewDeck() Deck {
d := make(Deck, 52)
for i := range d {
d[i] = Card(i)
}
return d
}
func (d Deck) String() string {
s := ""
for i, c := range d {
switch {
case i == 0:
case i%13 == 0:
s += "\n"
default:
s += " "
}
s += c.String()
}
return s
}
func (d Deck) Shuffle() {
for i := range d {
j := rand.Intn(i + 1)
d[i], d[j] = d[j], d[i]
}
}
func (d Deck) Contains(tc Card) bool {
for _, c := range d {
if c == tc {
return true
}
}
return false
}
func (d *Deck) AddDeck(decks ...Deck) {
for _, o := range decks {
*d = append(*d, o...)
}
}
func (d *Deck) AddCard(c Card) {
*d = append(*d, c)
}
func (d *Deck) Draw(n int) Deck {
old := *d
*d = old[n:]
return old[:n:n]
}
func (d *Deck) DrawCard() (Card, bool) {
if len(*d) == 0 {
return 0, false
}
old := *d
*d = old[1:]
return old[0], true
}
func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) {
for i := 0; i < cards; i++ {
for j := range hands {
if len(*d) == 0 {
return hands, false
}
hands[j] = append(hands[j], (*d)[0])
*d = (*d)[1:]
}
}
return hands, true
}
|
Can you help me rewrite this code in Go instead of VB, keeping it the same logically? | Option Base {0|1}
| package main
import (
"fmt"
)
func main() {
var a [5]int
fmt.Println("len(a) =", len(a))
fmt.Println("a =", a)
a[0] = 3
fmt.Println("a =", a)
fmt.Println("a[0] =", a[0])
s := a[:4]
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
s = s[:5]
fmt.Println("s =", s)
a[0] = 22
fmt.Println("a =", a)
fmt.Println("s =", s)
s = append(s, 4, 5, 6)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
a[4] = -1
fmt.Println("a =", a)
fmt.Println("s =", s)
s = make([]int, 8)
fmt.Println("s =", s)
fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))
}
|
Translate the given VB code snippet into Go without altering its behavior. | Const Order = 4
Function InCarpet(ByVal x As Integer, ByVal y As Integer)
Do While x <> 0 And y <> 0
If x Mod 3 = 1 And y Mod 3 = 1 Then
InCarpet = " "
Exit Function
End If
x = x \ 3
y = y \ 3
Loop
InCarpet = "#"
End Function
Public Sub sierpinski_carpet()
Dim i As Integer, j As Integer
For i = 0 To 3 ^ Order - 1
For j = 0 To 3 ^ Order - 1
Debug.Print InCarpet(i, j);
Next j
Debug.Print
Next i
End Sub
| package main
import (
"fmt"
"strings"
"unicode/utf8"
)
var order = 3
var grain = "#"
func main() {
carpet := []string{grain}
for ; order > 0; order-- {
hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
middle := make([]string, len(carpet))
for i, s := range carpet {
middle[i] = s + hole + s
carpet[i] = strings.Repeat(s, 3)
}
carpet = append(append(carpet, middle...), carpet...)
}
for _, r := range carpet {
fmt.Println(r)
}
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. | Private Function Knuth(a As Variant) As Variant
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
For i = UBound(a) To LBound(a) + 1 Step -1
j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))
t = a(i)
a(i) = a(j)
a(j) = t
Next i
End If
Knuth = a
End Function
Private Function inOrder(s As Variant)
i = 2
Do While i <= UBound(s)
If s(i) < s(i - 1) Then
inOrder = False
Exit Function
End If
i = i + 1
Loop
inOrder = True
End Function
Private Function bogosort(ByVal s As Variant) As Variant
Do While Not inOrder(s)
Debug.Print Join(s, ", ")
s = Knuth(s)
Loop
bogosort = s
End Function
Public Sub main()
Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), ", ")
End Sub
| package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
func main() {
list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
rand.Seed(time.Now().UnixNano())
fmt.Println("unsorted:", list)
temp := make([]int, len(list))
copy(temp, list)
for !sort.IntsAreSorted(temp) {
for i, v := range rand.Perm(len(list)) {
temp[i] = list[v]
}
}
fmt.Println("sorted! ", temp)
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer)
Dim t As Integer
Debug.Print " Step "; step; ": ",
Do While t <= end_t
If t Mod 10 = 0 Then Debug.Print Format(y, "0.000"),
y = y + step * Application.Run(f, y)
t = t + step
Loop
Debug.Print
End Sub
Sub analytic()
Debug.Print " Time: ",
For t = 0 To 100 Step 10
Debug.Print " "; t,
Next t
Debug.Print
Debug.Print "Analytic: ",
For t = 0 To 100 Step 10
Debug.Print Format(20 + 80 * Exp(-0.07 * t), "0.000"),
Next t
Debug.Print
End Sub
Private Function cooling(temp As Double) As Double
cooling = -0.07 * (temp - 20)
End Function
Public Sub euler_method()
Dim r_cooling As String
r_cooling = "cooling"
analytic
ivp_euler r_cooling, 100, 2, 100
ivp_euler r_cooling, 100, 5, 100
ivp_euler r_cooling, 100, 10, 100
End Sub
| package main
import (
"fmt"
"math"
)
type fdy func(float64, float64) float64
func eulerStep(f fdy, x, y, h float64) float64 {
return y + h*f(x, y)
}
func newCoolingRate(k float64) func(float64) float64 {
return func(deltaTemp float64) float64 {
return -k * deltaTemp
}
}
func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {
return func(time float64) float64 {
return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)
}
}
func newCoolingRateDy(k, ambientTemp float64) fdy {
crf := newCoolingRate(k)
return func(_, objectTemp float64) float64 {
return crf(objectTemp - ambientTemp)
}
}
func main() {
k := .07
tempRoom := 20.
tempObject := 100.
fcr := newCoolingRateDy(k, tempRoom)
analytic := newTempFunc(k, tempRoom, tempObject)
for _, deltaTime := range []float64{2, 5, 10} {
fmt.Printf("Step size = %.1f\n", deltaTime)
fmt.Println(" Time Euler's Analytic")
temp := tempObject
for time := 0.; time <= 100; time += deltaTime {
fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time))
temp = eulerStep(fcr, time, temp, deltaTime)
}
fmt.Println()
}
}
|
Convert this VB snippet to Go and keep its semantics consistent. | Sub Main()
Dim i&, c&, j#, s$
Const N& = 1000000
s = "values for n in the range 1 to 22 : "
For i = 1 To 22
s = s & ns(i) & ", "
Next
For i = 1 To N
j = Sqr(ns(i))
If j = CInt(j) Then c = c + 1
Next
Debug.Print s
Debug.Print c & " squares less than " & N
End Sub
Private Function ns(l As Long) As Long
ns = l + Int(1 / 2 + Sqr(l))
End Function
| package main
import (
"fmt"
"math"
)
func remarkable(n int) int {
return n + int(.5+math.Sqrt(float64(n)))
}
func main() {
fmt.Println(" n r(n)")
fmt.Println("--- ---")
for n := 1; n <= 22; n++ {
fmt.Printf("%3d %3d\n", n, remarkable(n))
}
const limit = 1e6
fmt.Println("\nChecking for squares for n <", limit)
next := 2
nextSq := 4
for n := 1; n < limit; n++ {
r := remarkable(n)
switch {
case r == nextSq:
panic(n)
case r > nextSq:
fmt.Println(nextSq, "didn't occur")
next++
nextSq = next * next
}
}
fmt.Println("No squares occur for n <", limit)
}
|
Translate the given VB code snippet into Go without altering its behavior. | Public Sub substring()
sentence = "the last thing the man said was the"
n = 10: m = 5
Debug.Print Mid(sentence, n, 5)
Debug.Print Right(sentence, Len(sentence) - n + 1)
Debug.Print Left(sentence, Len(sentence) - 1)
k = InStr(1, sentence, "m")
Debug.Print Mid(sentence, k, 5)
k = InStr(1, sentence, "aid")
Debug.Print Mid(sentence, k, 5)
End Sub
| package main
import (
"fmt"
"strings"
)
func main() {
s := "ABCDEFGH"
n, m := 2, 3
fmt.Println("Index: ", "01234567")
fmt.Println("String:", s)
fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m])
fmt.Printf("Start %d, to end: %s\n", n, s[n:])
fmt.Printf("All but last: %s\n", s[:len(s)-1])
dx := strings.IndexByte(s, 'D')
fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m])
sx := strings.Index(s, "DE")
fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}
|
Write the same code in Go as shown below in VB. | Function JortSort(s)
JortSort = True
arrPreSort = Split(s,",")
Set arrSorted = CreateObject("System.Collections.ArrayList")
For i = 0 To UBound(arrPreSort)
arrSorted.Add(arrPreSort(i))
Next
arrSorted.Sort()
For j = 0 To UBound(arrPreSort)
If arrPreSort(j) <> arrSorted(j) Then
JortSort = False
Exit For
End If
Next
End Function
WScript.StdOut.Write JortSort("1,2,3,4,5")
WScript.StdOut.WriteLine
WScript.StdOut.Write JortSort("1,2,3,5,4")
WScript.StdOut.WriteLine
WScript.StdOut.Write JortSort("a,b,c")
WScript.StdOut.WriteLine
WScript.StdOut.Write JortSort("a,c,b")
| package main
import (
"log"
"sort"
)
func main() {
log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4}))
log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))
log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))
log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))
}
func jortSort(a []int) bool {
c := make([]int, len(a))
copy(c, a)
sort.Ints(a)
for k, v := range c {
if v == a[k] {
continue
} else {
return false
}
}
return true
}
|
Convert this VB snippet to Go and keep its semantics consistent. | Public Function Leap_year(year As Integer) As Boolean
Leap_year = (Month(DateSerial(year, 2, 29)) = 2)
End Function
| func isLeap(year int) bool {
return year%400 == 0 || year%4 == 0 && year%100 != 0
}
|
Write the same code in Go as shown below in VB. |
dim i,j
Wscript.StdOut.WriteLine "-- Long Integer - Permutations - from 1 to 12"
for i=1 to 12
for j=1 to i
Wscript.StdOut.Write "P(" & i & "," & j & ")=" & perm(i,j) & " "
next
Wscript.StdOut.WriteLine ""
next
Wscript.StdOut.WriteLine "-- Float integer - Combinations from 10 to 60"
for i=10 to 60 step 10
for j=1 to i step i\5
Wscript.StdOut.Write "C(" & i & "," & j & ")=" & comb(i,j) & " "
next
Wscript.StdOut.WriteLine ""
next
Wscript.StdOut.WriteLine "-- Float integer - Permutations from 5000 to 15000"
for i=5000 to 15000 step 5000
for j=10 to 70 step 20
Wscript.StdOut.Write "C(" & i & "," & j & ")=" & perm(i,j) & " "
next
Wscript.StdOut.WriteLine ""
next
Wscript.StdOut.WriteLine "-- Float integer - Combinations from 200 to 1000"
for i=200 to 1000 step 200
for j=20 to 100 step 20
Wscript.StdOut.Write "P(" & i & "," & j & ")=" & comb(i,j) & " "
next
Wscript.StdOut.WriteLine ""
next
function perm(x,y)
dim i,z
z=1
for i=x-y+1 to x
z=z*i
next
perm=z
end function
function fact(x)
dim i,z
z=1
for i=2 to x
z=z*i
next
fact=z
end function
function comb(byval x,byval y)
if y>x then
comb=0
elseif x=y then
comb=1
else
if x-y<y then y=x-y
comb=perm(x,y)/fact(y)
end if
end function
| package main
import (
"fmt"
"math/big"
)
func main() {
var n, p int64
fmt.Printf("A sample of permutations from 1 to 12:\n")
for n = 1; n < 13; n++ {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 10 to 60:\n")
for n = 10; n < 61; n += 10 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of permutations from 5 to 15000:\n")
nArr := [...]int64{5, 50, 500, 1000, 5000, 15000}
for _, n = range nArr {
p = n / 3
fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p)))
}
fmt.Printf("\nA sample of combinations from 100 to 1000:\n")
for n = 100; n < 1001; n += 100 {
p = n / 3
fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p)))
}
}
func fact(n *big.Int) *big.Int {
if n.Sign() < 1 {
return big.NewInt(0)
}
r := big.NewInt(1)
i := big.NewInt(2)
for i.Cmp(n) < 1 {
r.Mul(r, i)
i.Add(i, big.NewInt(1))
}
return r
}
func perm(n, k *big.Int) *big.Int {
r := fact(n)
r.Div(r, fact(n.Sub(n, k)))
return r
}
func comb(n, r *big.Int) *big.Int {
if r.Cmp(n) == 1 {
return big.NewInt(0)
}
if r.Cmp(n) == 0 {
return big.NewInt(1)
}
c := fact(n)
den := fact(n.Sub(n, r))
den.Mul(den, fact(r))
c.Div(c, den)
return c
}
|
Write a version of this VB function in Go with identical behavior. | Public Function sortlexicographically(N As Integer)
Dim arrList As Object
Set arrList = CreateObject("System.Collections.ArrayList")
For i = 1 To N
arrList.Add CStr(i)
Next i
arrList.Sort
Dim item As Variant
For Each item In arrList
Debug.Print item & ", ";
Next
End Function
Public Sub main()
Call sortlexicographically(13)
End Sub
| package main
import (
"fmt"
"sort"
"strconv"
)
func lexOrder(n int) []int {
first, last, k := 1, n, n
if n < 1 {
first, last, k = n, 1, 2-n
}
strs := make([]string, k)
for i := first; i <= last; i++ {
strs[i-first] = strconv.Itoa(i)
}
sort.Strings(strs)
ints := make([]int, k)
for i := 0; i < k; i++ {
ints[i], _ = strconv.Atoi(strs[i])
}
return ints
}
func main() {
fmt.Println("In lexicographical order:\n")
for _, n := range []int{0, 5, 13, 21, -22} {
fmt.Printf("%3d: %v\n", n, lexOrder(n))
}
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Public twenties As Variant
Public decades As Variant
Public orders As Variant
Private Sub init()
twenties = [{"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}]
decades = [{"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}]
orders = [{1E15,"quadrillion"; 1E12,"trillion"; 1E9,"billion"; 1E6,"million"; 1E3,"thousand"}]
End Sub
Private Function Twenty(N As Variant)
Twenty = twenties(N Mod 20 + 1)
End Function
Private Function Decade(N As Variant)
Decade = decades(N Mod 10 - 1)
End Function
Private Function Hundred(N As Variant)
If N < 20 Then
Hundred = Twenty(N)
Exit Function
Else
If N Mod 10 = 0 Then
Hundred = Decade((N \ 10) Mod 10)
Exit Function
End If
End If
Hundred = Decade(N \ 10) & "-" & Twenty(N Mod 10)
End Function
Private Function Thousand(N As Variant, withand As String)
If N < 100 Then
Thousand = withand & Hundred(N)
Exit Function
Else
If N Mod 100 = 0 Then
Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & " hundred"
Exit Function
End If
End If
Thousand = Twenty(N \ 100) & " hundred and " & Hundred(N Mod 100)
End Function
Private Function Triplet(N As Variant)
Dim Order, High As Variant, Low As Variant
Dim Name As String, res As String
For i = 1 To UBound(orders)
Order = orders(i, 1)
Name = orders(i, 2)
High = WorksheetFunction.Floor_Precise(N / Order)
Low = N - High * Order
If High <> 0 Then
res = res & Thousand(High, "") & " " & Name
End If
N = Low
If Low = 0 Then Exit For
If Len(res) And High <> 0 Then
res = res & ", "
End If
Next i
If N <> 0 Or res = "" Then
res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = "", "", "and "))
N = N - Int(N)
If N > 0.000001 Then
res = res & " point"
For i = 1 To 10
n_ = WorksheetFunction.Floor_Precise(N * 10.0000001)
res = res & " " & twenties(n_ + 1)
N = N * 10 - n_
If Abs(N) < 0.000001 Then Exit For
Next i
End If
End If
Triplet = res
End Function
Private Function spell(N As Variant)
Dim res As String
If N < 0 Then
res = "minus "
N = -N
End If
res = res & Triplet(N)
spell = res
End Function
Private Function smartp(N As Variant)
Dim res As String
If N = WorksheetFunction.Floor_Precise(N) Then
smartp = CStr(N)
Exit Function
End If
res = CStr(N)
If InStr(1, res, ".") Then
res = Left(res, InStr(1, res, "."))
End If
smartp = res
End Function
Sub Main()
Dim si As Variant
init
Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}]
Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}]
For i = 1 To UBound(Samples1)
si = Samples1(i)
Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si)
Next i
For i = 1 To UBound(Samples2)
si = Samples2(i)
Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si)
Next i
End Sub
| package main
import "fmt"
func main() {
for _, n := range []int64{12, 1048576, 9e18, -2, 0} {
fmt.Println(say(n))
}
}
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
}
|
Convert this VB block to Go, preserving its control flow and logic. | Sub arrShellSort(ByVal arrData As Variant)
Dim lngHold, lngGap As Long
Dim lngCount, lngMin, lngMax As Long
Dim varItem As Variant
lngMin = LBound(arrData)
lngMax = UBound(arrData)
lngGap = lngMin
Do While (lngGap < lngMax)
lngGap = 3 * lngGap + 1
Loop
Do While (lngGap > 1)
lngGap = lngGap \ 3
For lngCount = lngGap + lngMin To lngMax
varItem = arrData(lngCount)
lngHold = lngCount
Do While ((arrData(lngHold - lngGap) > varItem))
arrData(lngHold) = arrData(lngHold - lngGap)
lngHold = lngHold - lngGap
If (lngHold < lngMin + lngGap) Then Exit Do
Loop
arrData(lngHold) = varItem
Next
Loop
arrShellSort = arrData
End Sub
| package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 {
for i := inc; i < len(a); i++ {
j, temp := i, a[i]
for ; j >= inc && a[j-inc] > temp; j -= inc {
a[j] = a[j-inc]
}
a[j] = temp
}
}
fmt.Println("after: ", a)
}
|
Please provide an equivalent version of this VB code in Go. | Public Class DoubleLinkList(Of T)
Private m_Head As Node(Of T)
Private m_Tail As Node(Of T)
Public Sub AddHead(ByVal value As T)
Dim node As New Node(Of T)(Me, value)
If m_Head Is Nothing Then
m_Head = Node
m_Tail = m_Head
Else
node.Next = m_Head
m_Head = node
End If
End Sub
Public Sub AddTail(ByVal value As T)
Dim node As New Node(Of T)(Me, value)
If m_Tail Is Nothing Then
m_Head = node
m_Tail = m_Head
Else
node.Previous = m_Tail
m_Tail = node
End If
End Sub
Public ReadOnly Property Head() As Node(Of T)
Get
Return m_Head
End Get
End Property
Public ReadOnly Property Tail() As Node(Of T)
Get
Return m_Tail
End Get
End Property
Public Sub RemoveTail()
If m_Tail Is Nothing Then Return
If m_Tail.Previous Is Nothing Then
m_Head = Nothing
m_Tail = Nothing
Else
m_Tail = m_Tail.Previous
m_Tail.Next = Nothing
End If
End Sub
Public Sub RemoveHead()
If m_Head Is Nothing Then Return
If m_Head.Next Is Nothing Then
m_Head = Nothing
m_Tail = Nothing
Else
m_Head = m_Head.Next
m_Head.Previous = Nothing
End If
End Sub
End Class
Public Class Node(Of T)
Private ReadOnly m_Value As T
Private m_Next As Node(Of T)
Private m_Previous As Node(Of T)
Private ReadOnly m_Parent As DoubleLinkList(Of T)
Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)
m_Parent = parent
m_Value = value
End Sub
Public Property [Next]() As Node(Of T)
Get
Return m_Next
End Get
Friend Set(ByVal value As Node(Of T))
m_Next = value
End Set
End Property
Public Property Previous() As Node(Of T)
Get
Return m_Previous
End Get
Friend Set(ByVal value As Node(Of T))
m_Previous = value
End Set
End Property
Public ReadOnly Property Value() As T
Get
Return m_Value
End Get
End Property
Public Sub InsertAfter(ByVal value As T)
If m_Next Is Nothing Then
m_Parent.AddTail(value)
ElseIf m_Previous Is Nothing Then
m_Parent.AddHead(value)
Else
Dim node As New Node(Of T)(m_Parent, value)
node.Previous = Me
node.Next = Me.Next
Me.Next.Previous = node
Me.Next = node
End If
End Sub
Public Sub Remove()
If m_Next Is Nothing Then
m_Parent.RemoveTail()
ElseIf m_Previous Is Nothing Then
m_Parent.RemoveHead()
Else
m_Previous.Next = Me.Next
m_Next.Previous = Me.Previous
End If
End Sub
End Class
| type dlNode struct {
int
next, prev *dlNode
}
type dlList struct {
members map[*dlNode]int
head, tail **dlNode
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. |
TYPE regChar
Character AS STRING * 3
Count AS LONG
END TYPE
DIM iChar AS INTEGER
DIM iCL AS INTEGER
DIM iCountChars AS INTEGER
DIM iFile AS INTEGER
DIM i AS INTEGER
DIM lMUC AS LONG
DIM iMUI AS INTEGER
DIM lLUC AS LONG
DIM iLUI AS INTEGER
DIM iMaxIdx AS INTEGER
DIM iP AS INTEGER
DIM iPause AS INTEGER
DIM iPMI AS INTEGER
DIM iPrint AS INTEGER
DIM lHowMany AS LONG
DIM lTotChars AS LONG
DIM sTime AS SINGLE
DIM strFile AS STRING
DIM strTxt AS STRING
DIM strDate AS STRING
DIM strTime AS STRING
DIM strKey AS STRING
CONST LngReg = 256
CONST Letters = 1
CONST FALSE = 0
CONST TRUE = NOT FALSE
strDate = DATE$
strTime = TIME$
iFile = FREEFILE
DO
CLS
PRINT "This program counts letters or characters in a text file."
PRINT
INPUT "File to open: ", strFile
OPEN strFile FOR BINARY AS #iFile
IF LOF(iFile) > 0 THEN
PRINT "Count: 1) Letters 2) Characters (1 or 2)";
DO
strKey = INKEY$
LOOP UNTIL strKey = "1" OR strKey = "2"
PRINT ". Option selected: "; strKey
iCL = VAL(strKey)
sTime = TIMER
iP = POS(0)
lHowMany = LOF(iFile)
strTxt = SPACE$(LngReg)
IF iCL = Letters THEN
iMaxIdx = 26
ELSE
iMaxIdx = 255
END IF
IF iMaxIdx <> iPMI THEN
iPMI = iMaxIdx
REDIM rChar(0 TO iMaxIdx) AS regChar
FOR i = 0 TO iMaxIdx
IF iCL = Letters THEN
strTxt = CHR$(i + 65)
IF i = 26 THEN strTxt = CHR$(165)
ELSE
SELECT CASE i
CASE 0: strTxt = "nul"
CASE 7: strTxt = "bel"
CASE 9: strTxt = "tab"
CASE 10: strTxt = "lf"
CASE 11: strTxt = "vt"
CASE 12: strTxt = "ff"
CASE 13: strTxt = "cr"
CASE 28: strTxt = "fs"
CASE 29: strTxt = "gs"
CASE 30: strTxt = "rs"
CASE 31: strTxt = "us"
CASE 32: strTxt = "sp"
CASE ELSE: strTxt = CHR$(i)
END SELECT
END IF
rChar(i).Character = strTxt
NEXT i
ELSE
FOR i = 0 TO iMaxIdx
rChar(i).Count = 0
NEXT i
END IF
PRINT "Looking for ";
IF iCL = Letters THEN PRINT "letters."; ELSE PRINT "characters.";
PRINT " File is"; STR$(lHowMany); " in size. Working"; : COLOR 23: PRINT "..."; : COLOR (7)
DO WHILE LOC(iFile) < LOF(iFile)
IF LOC(iFile) + LngReg > LOF(iFile) THEN
strTxt = SPACE$(LOF(iFile) - LOC(iFile))
END IF
GET #iFile, , strTxt
FOR i = 1 TO LEN(strTxt)
IF iCL = Letters THEN
iChar = ASC(UCASE$(MID$(strTxt, i, 1)))
SELECT CASE iChar
CASE 164: iChar = 165
CASE 160: iChar = 65
CASE 130, 144: iChar = 69
CASE 161: iChar = 73
CASE 162: iChar = 79
CASE 163, 129: iChar = 85
END SELECT
iChar = iChar - 65
IF iChar >= 0 AND iChar <= 25 THEN
rChar(iChar).Count = rChar(iChar).Count + 1
ELSEIF iChar = 100 THEN
rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1
END IF
ELSE
iChar = ASC(MID$(strTxt, i, 1))
rChar(iChar).Count = rChar(iChar).Count + 1
END IF
NEXT i
LOOP
CLOSE #iFile
lMUC = 0
iMUI = 0
lLUC = 2147483647
iLUI = 0
iPrint = FALSE
lTotChars = 0
iCountChars = 0
iPause = FALSE
CLS
IF iCL = Letters THEN PRINT "Letters found: "; ELSE PRINT "Characters found: ";
FOR i = 0 TO iMaxIdx
IF lMUC < rChar(i).Count THEN
lMUC = rChar(i).Count
iMUI = i
END IF
IF rChar(i).Count > 0 THEN
strTxt = ""
IF iPrint THEN strTxt = ", " ELSE iPrint = TRUE
strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))
strTxt = strTxt + "=" + LTRIM$(STR$(rChar(i).Count))
iP = POS(0)
IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN
PRINT ","
IF CSRLIN >= 23 AND NOT iPause THEN
iPause = TRUE
PRINT "Press a key to continue..."
DO
strKey = INKEY$
LOOP UNTIL strKey <> ""
END IF
strTxt = MID$(strTxt, 3)
END IF
PRINT strTxt;
lTotChars = lTotChars + rChar(i).Count
iCountChars = iCountChars + 1
IF lLUC > rChar(i).Count THEN
lLUC = rChar(i).Count
iLUI = i
END IF
END IF
NEXT i
PRINT "."
PRINT
PRINT "File analyzed....................: "; strFile
PRINT "Looked for.......................: "; : IF iCL = Letters THEN PRINT "Letters" ELSE PRINT "Characters"
PRINT "Total characters in file.........:"; lHowMany
PRINT "Total characters counted.........:"; lTotChars
IF iCL = Letters THEN PRINT "Characters discarded on count....:"; lHowMany - lTotChars
PRINT "Distinct characters found in file:"; iCountChars; "of"; iMaxIdx + 1
PRINT "Most used character was..........: ";
iPrint = FALSE
FOR i = 0 TO iMaxIdx
IF rChar(i).Count = lMUC THEN
IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE
PRINT RTRIM$(LTRIM$(rChar(i).Character));
END IF
NEXT i
PRINT " ("; LTRIM$(STR$(rChar(iMUI).Count)); " times)"
PRINT "Least used character was.........: ";
iPrint = FALSE
FOR i = 0 TO iMaxIdx
IF rChar(i).Count = lLUC THEN
IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE
PRINT RTRIM$(LTRIM$(rChar(i).Character));
END IF
NEXT i
PRINT " ("; LTRIM$(STR$(rChar(iLUI).Count)); " times)"
PRINT "Time spent in the process........:"; TIMER - sTime; "seconds"
ELSE
CLOSE #iFile
KILL strFile
PRINT
PRINT "File does not exist."
END IF
PRINT
PRINT "Again? (Y/n)"
DO
strTxt = UCASE$(INKEY$)
LOOP UNTIL strTxt = "N" OR strTxt = "Y" OR strTxt = CHR$(13) OR strTxt = CHR$(27)
LOOP UNTIL strTxt = "N" OR strTxt = CHR$(27)
CLS
PRINT "End of execution."
PRINT "Start time: "; strDate; " "; strTime; ", end time: "; DATE$; " "; TIME$; "."
END
| package main
import (
"fmt"
"io/ioutil"
"sort"
"unicode"
)
const file = "unixdict.txt"
func main() {
bs, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
return
}
m := make(map[rune]int)
for _, r := range string(bs) {
m[r]++
}
lfs := make(lfList, 0, len(m))
for l, f := range m {
lfs = append(lfs, &letterFreq{l, f})
}
sort.Sort(lfs)
fmt.Println("file:", file)
fmt.Println("letter frequency")
for _, lf := range lfs {
if unicode.IsGraphic(lf.rune) {
fmt.Printf(" %c %7d\n", lf.rune, lf.freq)
} else {
fmt.Printf("%U %7d\n", lf.rune, lf.freq)
}
}
}
type letterFreq struct {
rune
freq int
}
type lfList []*letterFreq
func (lfs lfList) Len() int { return len(lfs) }
func (lfs lfList) Less(i, j int) bool {
switch fd := lfs[i].freq - lfs[j].freq; {
case fd < 0:
return false
case fd > 0:
return true
}
return lfs[i].rune < lfs[j].rune
}
func (lfs lfList) Swap(i, j int) {
lfs[i], lfs[j] = lfs[j], lfs[i]
}
|
Convert the following code from VB to Go, ensuring the logic remains intact. | Dim s As String = "123"
s = CStr(CInt("123") + 1)
s = (CInt("123") + 1).ToString
| package main
import "fmt"
import "strconv"
func main() {
i, _ := strconv.Atoi("1234")
fmt.Println(strconv.Itoa(i + 1))
}
|
Translate this program into Go but keep the logic exactly as in VB. | Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean)
Dim i As Integer, stReplace As String
If bSpace = True Then
stReplace = " "
Else
stReplace = ""
End If
For i = 1 To Len(stStripChars)
stString = Replace(stString, Mid(stStripChars, i, 1), stReplace)
Next i
StripChars = stString
End Function
| package main
import (
"fmt"
"strings"
)
func stripchars(str, chr string) string {
return strings.Map(func(r rune) rune {
if strings.IndexRune(chr, r) < 0 {
return r
}
return -1
}, str)
}
func main() {
fmt.Println(stripchars("She was a soul stripper. She took my heart!",
"aei"))
}
|
Write the same code in Go as shown below in VB. | Private Function mean(v() As Double, ByVal leng As Integer) As Variant
Dim sum As Double, i As Integer
sum = 0: i = 0
For i = 0 To leng - 1
sum = sum + vv
Next i
If leng = 0 Then
mean = CVErr(xlErrDiv0)
Else
mean = sum / leng
End If
End Function
Public Sub main()
Dim v(4) As Double
Dim i As Integer, leng As Integer
v(0) = 1#
v(1) = 2#
v(2) = 2.178
v(3) = 3#
v(4) = 3.142
For leng = 5 To 0 Step -1
Debug.Print "mean[";
For i = 0 To leng - 1
Debug.Print IIf(i, "; " & v(i), "" & v(i));
Next i
Debug.Print "] = "; mean(v, leng)
Next leng
End Sub
| package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
var parts []float64
for _, x := range v {
var i int
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(v)), true
}
func main() {
for _, v := range [][]float64{
[]float64{},
[]float64{math.Inf(1), math.Inf(1)},
[]float64{math.Inf(1), math.Inf(-1)},
[]float64{3, 1, 4, 1, 5, 9},
[]float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},
[]float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
[]float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
} {
fmt.Println("Vector:", v)
if m, ok := mean(v); ok {
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbreviations.CompareMode = TextCompare
Dim commandtable() As String
Dim commands As String
s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
commandtable = Split(s, " ")
Dim i As Integer, word As Variant, number As Integer
For i = LBound(commandtable) To UBound(commandtable)
word = commandtable(i)
If Len(word) > 0 Then
i = i + 1
Do While Len(commandtable(i)) = 0: i = i + 1: Loop
number = Val(commandtable(i))
If number > 0 Then
command_table.Add Key:=word, Item:=number
Else
command_table.Add Key:=word, Item:=Len(word)
i = i - 1
End If
End If
Next i
For Each word In command_table
For i = command_table(word) To Len(word)
On Error Resume Next
abbreviations.Add Key:=Left(word, i), Item:=UCase(word)
Next i
Next word
user_words() = Split(userstring, " ")
For Each word In user_words
If Len(word) > 0 Then
If abbreviations.exists(word) Then
commands = commands & abbreviations(word) & " "
Else
commands = commands & "*error* "
End If
End If
Next word
ValidateUserWords = commands
End Function
Public Sub program()
Dim guserstring As String
guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin"
Debug.Print "user words:", guserstring
Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
| package main
import (
"io"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func readTable(table string) ([]string, []int) {
fields := strings.Fields(table)
var commands []string
var minLens []int
for i, max := 0, len(fields); i < max; {
cmd := fields[i]
cmdLen := len(cmd)
i++
if i < max {
num, err := strconv.Atoi(fields[i])
if err == nil && 1 <= num && num < cmdLen {
cmdLen = num
i++
}
}
commands = append(commands, cmd)
minLens = append(minLens, cmdLen)
}
return commands, minLens
}
func validateCommands(commands []string, minLens []int, words []string) []string {
var results []string
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func printResults(words []string, results []string) {
wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
io.WriteString(wr, "user words:")
for _, word := range words {
io.WriteString(wr, "\t"+word)
}
io.WriteString(wr, "\n")
io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
wr.Flush()
}
func main() {
const table = "" +
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, minLens := readTable(table)
words := strings.Fields(sentence)
results := validateCommands(commands, minLens, words)
printResults(words, results)
}
|
Rewrite the snippet below in Go so it works the same as the original VB code. | Private Function ValidateUserWords(userstring As String) As String
Dim s As String
Dim user_words() As String
Dim command_table As Scripting.Dictionary
Set command_table = New Scripting.Dictionary
Dim abbreviations As Scripting.Dictionary
Set abbreviations = New Scripting.Dictionary
abbreviations.CompareMode = TextCompare
Dim commandtable() As String
Dim commands As String
s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 "
s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate "
s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load "
s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 "
s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 "
s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
commandtable = Split(s, " ")
Dim i As Integer, word As Variant, number As Integer
For i = LBound(commandtable) To UBound(commandtable)
word = commandtable(i)
If Len(word) > 0 Then
i = i + 1
Do While Len(commandtable(i)) = 0: i = i + 1: Loop
number = Val(commandtable(i))
If number > 0 Then
command_table.Add Key:=word, Item:=number
Else
command_table.Add Key:=word, Item:=Len(word)
i = i - 1
End If
End If
Next i
For Each word In command_table
For i = command_table(word) To Len(word)
On Error Resume Next
abbreviations.Add Key:=Left(word, i), Item:=UCase(word)
Next i
Next word
user_words() = Split(userstring, " ")
For Each word In user_words
If Len(word) > 0 Then
If abbreviations.exists(word) Then
commands = commands & abbreviations(word) & " "
Else
commands = commands & "*error* "
End If
End If
Next word
ValidateUserWords = commands
End Function
Public Sub program()
Dim guserstring As String
guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin"
Debug.Print "user words:", guserstring
Debug.Print "full words:", ValidateUserWords(guserstring)
End Sub
| package main
import (
"io"
"os"
"strconv"
"strings"
"text/tabwriter"
)
func readTable(table string) ([]string, []int) {
fields := strings.Fields(table)
var commands []string
var minLens []int
for i, max := 0, len(fields); i < max; {
cmd := fields[i]
cmdLen := len(cmd)
i++
if i < max {
num, err := strconv.Atoi(fields[i])
if err == nil && 1 <= num && num < cmdLen {
cmdLen = num
i++
}
}
commands = append(commands, cmd)
minLens = append(minLens, cmdLen)
}
return commands, minLens
}
func validateCommands(commands []string, minLens []int, words []string) []string {
var results []string
for _, word := range words {
matchFound := false
wlen := len(word)
for i, command := range commands {
if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
continue
}
c := strings.ToUpper(command)
w := strings.ToUpper(word)
if strings.HasPrefix(c, w) {
results = append(results, c)
matchFound = true
break
}
}
if !matchFound {
results = append(results, "*error*")
}
}
return results
}
func printResults(words []string, results []string) {
wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
io.WriteString(wr, "user words:")
for _, word := range words {
io.WriteString(wr, "\t"+word)
}
io.WriteString(wr, "\n")
io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
wr.Flush()
}
func main() {
const table = "" +
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 "
const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin"
commands, minLens := readTable(table)
words := strings.Fields(sentence)
results := validateCommands(commands, minLens, words)
printResults(words, results)
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. | Private Function tokenize(s As String, sep As String, esc As String) As Collection
Dim ret As New Collection
Dim this As String
Dim skip As Boolean
If Len(s) <> 0 Then
For i = 1 To Len(s)
si = Mid(s, i, 1)
If skip Then
this = this & si
skip = False
Else
If si = esc Then
skip = True
Else
If si = sep Then
ret.Add this
this = ""
Else
this = this & si
End If
End If
End If
Next i
ret.Add this
End If
Set tokenize = ret
End Function
Public Sub main()
Dim out As Collection
Set out = tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^")
Dim outstring() As String
ReDim outstring(out.Count - 1)
For i = 0 To out.Count - 1
outstring(i) = out(i + 1)
Next i
Debug.Print Join(outstring, ", ")
End Sub
| package main
import (
"errors"
"fmt"
)
func TokenizeString(s string, sep, escape rune) (tokens []string, err error) {
var runes []rune
inEscape := false
for _, r := range s {
switch {
case inEscape:
inEscape = false
fallthrough
default:
runes = append(runes, r)
case r == escape:
inEscape = true
case r == sep:
tokens = append(tokens, string(runes))
runes = runes[:0]
}
}
tokens = append(tokens, string(runes))
if inEscape {
err = errors.New("invalid terminal escape")
}
return tokens, err
}
func main() {
const sample = "one^|uno||three^^^^|four^^^|^cuatro|"
const separator = '|'
const escape = '^'
fmt.Printf("Input: %q\n", sample)
tokens, err := TokenizeString(sample, separator, escape)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Printf("Tokens: %q\n", tokens)
}
}
|
Produce a language-to-language conversion: from VB to Go, same semantics. | Private Function tokenize(s As String, sep As String, esc As String) As Collection
Dim ret As New Collection
Dim this As String
Dim skip As Boolean
If Len(s) <> 0 Then
For i = 1 To Len(s)
si = Mid(s, i, 1)
If skip Then
this = this & si
skip = False
Else
If si = esc Then
skip = True
Else
If si = sep Then
ret.Add this
this = ""
Else
this = this & si
End If
End If
End If
Next i
ret.Add this
End If
Set tokenize = ret
End Function
Public Sub main()
Dim out As Collection
Set out = tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^")
Dim outstring() As String
ReDim outstring(out.Count - 1)
For i = 0 To out.Count - 1
outstring(i) = out(i + 1)
Next i
Debug.Print Join(outstring, ", ")
End Sub
| package main
import (
"errors"
"fmt"
)
func TokenizeString(s string, sep, escape rune) (tokens []string, err error) {
var runes []rune
inEscape := false
for _, r := range s {
switch {
case inEscape:
inEscape = false
fallthrough
default:
runes = append(runes, r)
case r == escape:
inEscape = true
case r == sep:
tokens = append(tokens, string(runes))
runes = runes[:0]
}
}
tokens = append(tokens, string(runes))
if inEscape {
err = errors.New("invalid terminal escape")
}
return tokens, err
}
func main() {
const sample = "one^|uno||three^^^^|four^^^|^cuatro|"
const separator = '|'
const escape = '^'
fmt.Printf("Input: %q\n", sample)
tokens, err := TokenizeString(sample, separator, escape)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Printf("Tokens: %q\n", tokens)
}
}
|
Write the same algorithm in Go as shown in this VB implementation. | Public Sub hello_world_text
Debug.Print "Hello World!"
End Sub
| package main
import "fmt"
func main() { fmt.Println("Hello world!") }
|
Write a version of this VB function in Go with identical behavior. | Module ForwardDifference
Sub Main()
Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73})
For i As UInteger = 0 To 9
Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray()))
Next
Console.ReadKey()
End Sub
Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer)
If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers")
For i As Integer = 1 To Level
Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _
Select Numbers(n + 1) - Numbers(n)).ToList()
Next
Return Numbers
End Function
End Module
| package main
import "fmt"
func main() {
a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}
fmt.Println(a)
fmt.Println(fd(a, 9))
}
func fd(a []int, ord int) []int {
for i := 0; i < ord; i++ {
for j := 0; j < len(a)-i-1; j++ {
a[j] = a[j+1] - a[j]
}
}
return a[:len(a)-ord]
}
|
Write a version of this VB function in Go with identical behavior. | Option Explicit
Sub FirstTwentyPrimes()
Dim count As Integer, i As Long, t(19) As String
Do
i = i + 1
If IsPrime(i) Then
t(count) = i
count = count + 1
End If
Loop While count <= UBound(t)
Debug.Print Join(t, ", ")
End Sub
Function IsPrime(Nb As Long) As Boolean
If Nb = 2 Then
IsPrime = True
ElseIf Nb < 2 Or Nb Mod 2 = 0 Then
Exit Function
Else
Dim i As Long
For i = 3 To Sqr(Nb) Step 2
If Nb Mod i = 0 Then Exit Function
Next
IsPrime = True
End If
End Function
| func IsPrime(n int) bool {
if n < 0 { n = -n }
switch {
case n == 2:
return true
case n < 2 || n % 2 == 0:
return false
default:
for i = 3; i*i <= n; i += 2 {
if n % i == 0 { return false }
}
}
return true
}
|
Write the same algorithm in Go as shown in this VB implementation. | Function binomial(n,k)
binomial = factorial(n)/(factorial(n-k)*factorial(k))
End Function
Function factorial(n)
If n = 0 Then
factorial = 1
Else
For i = n To 1 Step -1
If i = n Then
factorial = n
Else
factorial = factorial * i
End If
Next
End If
End Function
WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3)
WScript.StdOut.WriteLine
| package main
import "fmt"
import "math/big"
func main() {
fmt.Println(new(big.Int).Binomial(5, 3))
fmt.Println(new(big.Int).Binomial(60, 30))
}
|
Please provide an equivalent version of this VB code in Go. | Dim coll As New Collection
coll.Add "apple"
coll.Add "banana"
| package main
import "fmt"
func main() {
var a []interface{}
a = append(a, 3)
a = append(a, "apples", "oranges")
fmt.Println(a)
}
|
Preserve the algorithm and functionality while converting the code from VB to Go. | Private Sub Iterate(ByVal list As LinkedList(Of Integer))
Dim node = list.First
Do Until node Is Nothing
node = node.Next
Loop
End Sub
| start := &Ele{"tacos", nil}
end := start.Append("burritos")
end = end.Append("fajitas")
end = end.Append("enchilatas")
for iter := start; iter != nil; iter = iter.Next {
fmt.Println(iter)
}
|
Change the programming language of this snippet from VB to Go without modifying what it does. | Private Sub Iterate(ByVal list As LinkedList(Of Integer))
Dim node = list.First
Do Until node Is Nothing
node = node.Next
Loop
End Sub
| start := &Ele{"tacos", nil}
end := start.Append("burritos")
end = end.Append("fajitas")
end = end.Append("enchilatas")
for iter := start; iter != nil; iter = iter.Next {
fmt.Println(iter)
}
|
Convert this VB snippet to Go and keep its semantics consistent. | Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)
Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height)
Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)
Dim bytes(bufferSize - 1) As Byte
Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)
Dim index As Integer = header.Length
For y As Integer = 0 To rasterBitmap.Height - 1
For x As Integer = 0 To rasterBitmap.Width - 1
Dim color As Rgb = rasterBitmap.GetPixel(x, y)
bytes(index) = color.R
bytes(index + 1) = color.G
bytes(index + 2) = color.B
index += 3
Next
Next
My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)
End Sub
| package raster
import (
"fmt"
"io"
"os"
)
func (b *Bitmap) WritePpmTo(w io.Writer) (err error) {
if _, err = fmt.Fprintln(w, "P6"); err != nil {
return
}
for _, c := range b.Comments {
if _, err = fmt.Fprintln(w, c); err != nil {
return
}
}
_, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows)
if err != nil {
return
}
b3 := make([]byte, 3*len(b.px))
n1 := 0
for _, px := range b.px {
b3[n1] = px.R
b3[n1+1] = px.G
b3[n1+2] = px.B
n1 += 3
}
if _, err = w.Write(b3); err != nil {
return
}
return
}
func (b *Bitmap) WritePpmFile(fn string) (err error) {
var f *os.File
if f, err = os.Create(fn); err != nil {
return
}
if err = b.WritePpmTo(f); err != nil {
return
}
return f.Close()
}
|
Translate this program into Go but keep the logic exactly as in VB. | Option Explicit
Sub DeleteFileOrDirectory()
Dim myPath As String
myPath = "C:\Users\surname.name\Desktop\Docs"
Kill myPath & "\input.txt"
RmDir myPath
End Sub
| package main
import "os"
func main() {
os.Remove("input.txt")
os.Remove("/input.txt")
os.Remove("docs")
os.Remove("/docs")
os.RemoveAll("docs")
os.RemoveAll("/docs")
}
|
Change the following VB code into Go without altering its purpose. | Const MAX = 20
Const ITER = 1000000
Function expected(n As Long) As Double
Dim sum As Double
For i = 1 To n
sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)
Next i
expected = sum
End Function
Function test(n As Long) As Double
Dim count As Long
Dim x As Long, bits As Long
For i = 1 To ITER
x = 1
bits = 0
Do While Not bits And x
count = count + 1
bits = bits Or x
x = 2 ^ (Int(n * Rnd()))
Loop
Next i
test = count / ITER
End Function
Public Sub main()
Dim n As Long
Debug.Print " n avg. exp. (error%)"
Debug.Print "== ====== ====== ========"
For n = 1 To MAX
av = test(n)
ex = expected(n)
Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " ";
Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")"
Next n
End Sub
| package main
import (
"fmt"
"math"
"math/rand"
)
const nmax = 20
func main() {
fmt.Println(" N average analytical (error)")
fmt.Println("=== ========= ============ =========")
for n := 1; n <= nmax; n++ {
a := avg(n)
b := ana(n)
fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n",
n, a, b, math.Abs(a-b)/b*100)
}
}
func avg(n int) float64 {
const tests = 1e4
sum := 0
for t := 0; t < tests; t++ {
var v [nmax]bool
for x := 0; !v[x]; x = rand.Intn(n) {
v[x] = true
sum++
}
}
return float64(sum) / tests
}
func ana(n int) float64 {
nn := float64(n)
term := 1.
sum := 1.
for i := nn - 1; i >= 1; i-- {
term *= i / nn
sum += term
}
return sum
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Const MAX = 20
Const ITER = 1000000
Function expected(n As Long) As Double
Dim sum As Double
For i = 1 To n
sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i)
Next i
expected = sum
End Function
Function test(n As Long) As Double
Dim count As Long
Dim x As Long, bits As Long
For i = 1 To ITER
x = 1
bits = 0
Do While Not bits And x
count = count + 1
bits = bits Or x
x = 2 ^ (Int(n * Rnd()))
Loop
Next i
test = count / ITER
End Function
Public Sub main()
Dim n As Long
Debug.Print " n avg. exp. (error%)"
Debug.Print "== ====== ====== ========"
For n = 1 To MAX
av = test(n)
ex = expected(n)
Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " ";
Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")"
Next n
End Sub
| package main
import (
"fmt"
"math"
"math/rand"
)
const nmax = 20
func main() {
fmt.Println(" N average analytical (error)")
fmt.Println("=== ========= ============ =========")
for n := 1; n <= nmax; n++ {
a := avg(n)
b := ana(n)
fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n",
n, a, b, math.Abs(a-b)/b*100)
}
}
func avg(n int) float64 {
const tests = 1e4
sum := 0
for t := 0; t < tests; t++ {
var v [nmax]bool
for x := 0; !v[x]; x = rand.Intn(n) {
v[x] = true
sum++
}
}
return float64(sum) / tests
}
func ana(n int) float64 {
nn := float64(n)
term := 1.
sum := 1.
for i := nn - 1; i >= 1; i-- {
term *= i / nn
sum += term
}
return sum
}
|
Port the following code from VB to Go with equivalent syntax and logic. | Dim name as String = "J. Doe"
Dim balance as Double = 123.45
Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance)
Console.WriteLine(prompt)
| package main
import (
"fmt"
)
func main() {
str := "Mary had a %s lamb"
txt := "little"
out := fmt.Sprintf(str, txt)
fmt.Println(out)
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. | Module Module1
Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)
Dim length = a.GetLength(0) - 1
Dim result(length - 1, length - 1) As Double
For i = 1 To length
For j = 1 To length
If i < x AndAlso j < y Then
result(i - 1, j - 1) = a(i - 1, j - 1)
ElseIf i >= x AndAlso j < y Then
result(i - 1, j - 1) = a(i, j - 1)
ElseIf i < x AndAlso j >= y Then
result(i - 1, j - 1) = a(i - 1, j)
Else
result(i - 1, j - 1) = a(i, j)
End If
Next
Next
Return result
End Function
Function Det(a As Double(,)) As Double
If a.GetLength(0) = 1 Then
Return a(0, 0)
Else
Dim sign = 1
Dim sum = 0.0
For i = 1 To a.GetLength(0)
sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))
sign *= -1
Next
Return sum
End If
End Function
Function Perm(a As Double(,)) As Double
If a.GetLength(0) = 1 Then
Return a(0, 0)
Else
Dim sum = 0.0
For i = 1 To a.GetLength(0)
sum += a(0, i - 1) * Perm(Minor(a, 0, i))
Next
Return sum
End If
End Function
Sub WriteLine(a As Double(,))
For i = 1 To a.GetLength(0)
Console.Write("[")
For j = 1 To a.GetLength(1)
If j > 1 Then
Console.Write(", ")
End If
Console.Write(a(i - 1, j - 1))
Next
Console.WriteLine("]")
Next
End Sub
Sub Test(a As Double(,))
If a.GetLength(0) <> a.GetLength(1) Then
Throw New ArgumentException("The dimensions must be equal")
End If
WriteLine(a)
Console.WriteLine("Permanant : {0}", Perm(a))
Console.WriteLine("Determinant: {0}", Det(a))
Console.WriteLine()
End Sub
Sub Main()
Test({{1, 2}, {3, 4}})
Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})
Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})
End Sub
End Module
| package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += float64(s) * pr
}
return
}
func permanent(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += pr
}
return
}
var m2 = [][]float64{
{1, 2},
{3, 4}}
var m3 = [][]float64{
{2, 9, 4},
{7, 5, 3},
{6, 1, 8}}
func main() {
fmt.Println(determinant(m2), permanent(m2))
fmt.Println(determinant(m3), permanent(m3))
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Module Module1
Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)
Dim length = a.GetLength(0) - 1
Dim result(length - 1, length - 1) As Double
For i = 1 To length
For j = 1 To length
If i < x AndAlso j < y Then
result(i - 1, j - 1) = a(i - 1, j - 1)
ElseIf i >= x AndAlso j < y Then
result(i - 1, j - 1) = a(i, j - 1)
ElseIf i < x AndAlso j >= y Then
result(i - 1, j - 1) = a(i - 1, j)
Else
result(i - 1, j - 1) = a(i, j)
End If
Next
Next
Return result
End Function
Function Det(a As Double(,)) As Double
If a.GetLength(0) = 1 Then
Return a(0, 0)
Else
Dim sign = 1
Dim sum = 0.0
For i = 1 To a.GetLength(0)
sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))
sign *= -1
Next
Return sum
End If
End Function
Function Perm(a As Double(,)) As Double
If a.GetLength(0) = 1 Then
Return a(0, 0)
Else
Dim sum = 0.0
For i = 1 To a.GetLength(0)
sum += a(0, i - 1) * Perm(Minor(a, 0, i))
Next
Return sum
End If
End Function
Sub WriteLine(a As Double(,))
For i = 1 To a.GetLength(0)
Console.Write("[")
For j = 1 To a.GetLength(1)
If j > 1 Then
Console.Write(", ")
End If
Console.Write(a(i - 1, j - 1))
Next
Console.WriteLine("]")
Next
End Sub
Sub Test(a As Double(,))
If a.GetLength(0) <> a.GetLength(1) Then
Throw New ArgumentException("The dimensions must be equal")
End If
WriteLine(a)
Console.WriteLine("Permanant : {0}", Perm(a))
Console.WriteLine("Determinant: {0}", Det(a))
Console.WriteLine()
End Sub
Sub Main()
Test({{1, 2}, {3, 4}})
Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})
Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})
End Sub
End Module
| package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += float64(s) * pr
}
return
}
func permanent(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += pr
}
return
}
var m2 = [][]float64{
{1, 2},
{3, 4}}
var m3 = [][]float64{
{2, 9, 4},
{7, 5, 3},
{6, 1, 8}}
func main() {
fmt.Println(determinant(m2), permanent(m2))
fmt.Println(determinant(m3), permanent(m3))
}
|
Please provide an equivalent version of this VB code in Go. | Imports System.Math
Module RayCasting
Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}}
Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}}
Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}}
Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}}
Private shapes As Integer()()() = {square, squareHole, strange, hexagon}
Public Sub Main()
Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}}
For Each shape As Integer()() In shapes
For Each point As Double() In testPoints
Console.Write(String.Format("{0} ", Contains(shape, point).ToString.PadLeft(7)))
Next
Console.WriteLine()
Next
End Sub
Private Function Contains(shape As Integer()(), point As Double()) As Boolean
Dim inside As Boolean = False
Dim length As Integer = shape.Length
For i As Integer = 0 To length - 1
If Intersects(shape(i), shape((i + 1) Mod length), point) Then
inside = Not inside
End If
Next
Return inside
End Function
Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean
If a(1) > b(1) Then Return Intersects(b, a, p)
If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001
If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False
If p(0) < Min(a(0), b(0)) Then Return True
Dim red As Double = (p(1) - a(1)) / (p(0) - a(0))
Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0))
Return red >= blue
End Function
End Module
| package main
import (
"fmt"
"math"
)
type xy struct {
x, y float64
}
type seg struct {
p1, p2 xy
}
type poly struct {
name string
sides []seg
}
func inside(pt xy, pg poly) (i bool) {
for _, side := range pg.sides {
if rayIntersectsSegment(pt, side) {
i = !i
}
}
return
}
func rayIntersectsSegment(p xy, s seg) bool {
var a, b xy
if s.p1.y < s.p2.y {
a, b = s.p1, s.p2
} else {
a, b = s.p2, s.p1
}
for p.y == a.y || p.y == b.y {
p.y = math.Nextafter(p.y, math.Inf(1))
}
if p.y < a.y || p.y > b.y {
return false
}
if a.x > b.x {
if p.x > a.x {
return false
}
if p.x < b.x {
return true
}
} else {
if p.x > b.x {
return false
}
if p.x < a.x {
return true
}
}
return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x)
}
var (
p1 = xy{0, 0}
p2 = xy{10, 0}
p3 = xy{10, 10}
p4 = xy{0, 10}
p5 = xy{2.5, 2.5}
p6 = xy{7.5, 2.5}
p7 = xy{7.5, 7.5}
p8 = xy{2.5, 7.5}
p9 = xy{0, 5}
p10 = xy{10, 5}
p11 = xy{3, 0}
p12 = xy{7, 0}
p13 = xy{7, 10}
p14 = xy{3, 10}
)
var tpg = []poly{
{"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}},
{"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1},
{p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}},
{"strange", []seg{{p1, p5},
{p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}},
{"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13},
{p13, p14}, {p14, p9}, {p9, p11}}},
}
var tpt = []xy{
{5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10},
{1, 2}, {2, 1},
}
func main() {
for _, pg := range tpg {
fmt.Printf("%s:\n", pg.name)
for _, pt := range tpt {
fmt.Println(pt, inside(pt, pg))
}
}
}
|
Ensure the translated Go code behaves exactly like the original VB snippet. | Function CountSubstring(str,substr)
CountSubstring = 0
For i = 1 To Len(str)
If Len(str) >= Len(substr) Then
If InStr(i,str,substr) Then
CountSubstring = CountSubstring + 1
i = InStr(i,str,substr) + Len(substr) - 1
End If
Else
Exit For
End If
Next
End Function
WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf
WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf
| package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("the three truths", "th"))
fmt.Println(strings.Count("ababababab", "abab"))
}
|
Preserve the algorithm and functionality while converting the code from VB to Go. | Imports System
Imports System.Console
Imports LI = System.Collections.Generic.SortedSet(Of Integer)
Module Module1
Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI
If lft = 0 Then
res.Add(vlu)
ElseIf lft > 0 Then
For Each itm As Integer In lst
res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)
Next
End If
Return res
End Function
Sub Main(ByVal args As String())
WriteLine(string.Join(" ",
unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))
End Sub
End Module
| package main
import (
"fmt"
"sort"
"strconv"
)
func combrep(n int, lst []byte) [][]byte {
if n == 0 {
return [][]byte{nil}
}
if len(lst) == 0 {
return nil
}
r := combrep(n, lst[1:])
for _, x := range combrep(n-1, lst) {
r = append(r, append(x, lst[0]))
}
return r
}
func shouldSwap(s []byte, start, curr int) bool {
for i := start; i < curr; i++ {
if s[i] == s[curr] {
return false
}
}
return true
}
func findPerms(s []byte, index, n int, res *[]string) {
if index >= n {
*res = append(*res, string(s))
return
}
for i := index; i < n; i++ {
check := shouldSwap(s, index, i)
if check {
s[index], s[i] = s[i], s[index]
findPerms(s, index+1, n, res)
s[index], s[i] = s[i], s[index]
}
}
}
func main() {
primes := []byte{2, 3, 5, 7}
var res []string
for n := 3; n <= 6; n++ {
reps := combrep(n, primes)
for _, rep := range reps {
sum := byte(0)
for _, r := range rep {
sum += r
}
if sum == 13 {
var perms []string
for i := 0; i < len(rep); i++ {
rep[i] += 48
}
findPerms(rep, 0, len(rep), &perms)
res = append(res, perms...)
}
}
}
res2 := make([]int, len(res))
for i, r := range res {
res2[i], _ = strconv.Atoi(r)
}
sort.Ints(res2)
fmt.Println("Those numbers whose digits are all prime and sum to 13 are:")
fmt.Println(res2)
}
|
Maintain the same structure and functionality when rewriting this code in Go. | Imports System
Imports System.Console
Imports LI = System.Collections.Generic.SortedSet(Of Integer)
Module Module1
Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI
If lft = 0 Then
res.Add(vlu)
ElseIf lft > 0 Then
For Each itm As Integer In lst
res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul)
Next
End If
Return res
End Function
Sub Main(ByVal args As String())
WriteLine(string.Join(" ",
unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13)))
End Sub
End Module
| package main
import (
"fmt"
"sort"
"strconv"
)
func combrep(n int, lst []byte) [][]byte {
if n == 0 {
return [][]byte{nil}
}
if len(lst) == 0 {
return nil
}
r := combrep(n, lst[1:])
for _, x := range combrep(n-1, lst) {
r = append(r, append(x, lst[0]))
}
return r
}
func shouldSwap(s []byte, start, curr int) bool {
for i := start; i < curr; i++ {
if s[i] == s[curr] {
return false
}
}
return true
}
func findPerms(s []byte, index, n int, res *[]string) {
if index >= n {
*res = append(*res, string(s))
return
}
for i := index; i < n; i++ {
check := shouldSwap(s, index, i)
if check {
s[index], s[i] = s[i], s[index]
findPerms(s, index+1, n, res)
s[index], s[i] = s[i], s[index]
}
}
}
func main() {
primes := []byte{2, 3, 5, 7}
var res []string
for n := 3; n <= 6; n++ {
reps := combrep(n, primes)
for _, rep := range reps {
sum := byte(0)
for _, r := range rep {
sum += r
}
if sum == 13 {
var perms []string
for i := 0; i < len(rep); i++ {
rep[i] += 48
}
findPerms(rep, 0, len(rep), &perms)
res = append(res, perms...)
}
}
}
res2 := make([]int, len(res))
for i, r := range res {
res2[i], _ = strconv.Atoi(r)
}
sort.Ints(res2)
fmt.Println("Those numbers whose digits are all prime and sum to 13 are:")
fmt.Println(res2)
}
|
Transform the following VB implementation into Go, maintaining the same output and logic. | Imports System.IO
Module Notes
Function Main(ByVal cmdArgs() As String) As Integer
Try
If cmdArgs.Length = 0 Then
Using sr As New StreamReader("NOTES.TXT")
Console.WriteLine(sr.ReadToEnd)
End Using
Else
Using sw As New StreamWriter("NOTES.TXT", True)
sw.WriteLine(Date.Now.ToString())
sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs))
End Using
End If
Catch
End Try
End Function
End Module
| package main
import (
"fmt"
"io"
"os"
"strings"
"time"
)
func addNote(fn string, note string) error {
f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
if cErr := f.Close(); err == nil {
err = cErr
}
return err
}
func showNotes(w io.Writer, fn string) error {
f, err := os.Open(fn)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
_, err = io.Copy(w, f)
f.Close()
return err
}
func main() {
const fn = "NOTES.TXT"
var err error
if len(os.Args) > 1 {
err = addNote(fn, strings.Join(os.Args[1:], " "))
} else {
err = showNotes(os.Stdout, fn)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
|
Write the same code in Go as shown below in VB. | Public Function CommonDirectoryPath(ParamArray Paths()) As String
Dim v As Variant
Dim Path() As String, s As String
Dim i As Long, j As Long, k As Long
Const PATH_SEPARATOR As String = "/"
For Each v In Paths
ReDim Preserve Path(0 To i)
Path(i) = v
i = i + 1
Next v
k = 1
Do
For i = 0 To UBound(Path)
If i Then
If InStr(k, Path(i), PATH_SEPARATOR) <> j Then
Exit Do
ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then
Exit Do
End If
Else
j = InStr(k, Path(i), PATH_SEPARATOR)
If j = 0 Then
Exit Do
End If
End If
Next i
s = Left$(Path(0), j + CLng(k <> 1))
k = j + 1
Loop
CommonDirectoryPath = s
End Function
Sub Main()
Debug.Assert CommonDirectoryPath( _
"/home/user1/tmp/coverage/test", _
"/home/user1/tmp/covert/operator", _
"/home/user1/tmp/coven/members") = _
"/home/user1/tmp"
Debug.Assert CommonDirectoryPath( _
"/home/user1/tmp/coverage/test", _
"/home/user1/tmp/covert/operator", _
"/home/user1/tmp/coven/members", _
"/home/user1/abc/coven/members") = _
"/home/user1"
Debug.Assert CommonDirectoryPath( _
"/home/user1/tmp/coverage/test", _
"/hope/user1/tmp/covert/operator", _
"/home/user1/tmp/coven/members") = _
"/"
End Sub
| package main
import (
"fmt"
"os"
"path"
)
func CommonPrefix(sep byte, paths ...string) string {
switch len(paths) {
case 0:
return ""
case 1:
return path.Clean(paths[0])
}
c := []byte(path.Clean(paths[0]))
c = append(c, sep)
for _, v := range paths[1:] {
v = path.Clean(v) + string(sep)
if len(v) < len(c) {
c = c[:len(v)]
}
for i := 0; i < len(c); i++ {
if v[i] != c[i] {
c = c[:i]
break
}
}
}
for i := len(c) - 1; i >= 0; i-- {
if c[i] == sep {
c = c[:i]
break
}
}
return string(c)
}
func main() {
c := CommonPrefix(os.PathSeparator,
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members",
"/home
"/home/user1/././tmp/covertly/foo",
"/home/bob/../user1/tmp/coved/bar",
)
if c == "" {
fmt.Println("No common path")
} else {
fmt.Println("Common path:", c)
}
}
|
Write the same code in Go as shown below in VB. | Option Explicit
sub verifydistribution(calledfunction, samples, delta)
Dim i, n, maxdiff
Dim d : Set d = CreateObject("Scripting.Dictionary")
wscript.echo "Running """ & calledfunction & """ " & samples & " times..."
for i = 1 to samples
Execute "n = " & calledfunction
d(n) = d(n) + 1
next
n = d.Count
maxdiff = 0
wscript.echo "Expected average count is " & Int(samples/n) & " across " & n & " buckets."
for each i in d.Keys
dim diff : diff = abs(1 - d(i) / (samples/n))
if diff > maxdiff then maxdiff = diff
wscript.echo "Bucket " & i & " had " & d(i) & " occurences" _
& vbTab & " difference from expected=" & FormatPercent(diff, 2)
next
wscript.echo "Maximum found variation is " & FormatPercent(maxdiff, 2) _
& ", desired limit is " & FormatPercent(delta, 2) & "."
if maxdiff > delta then wscript.echo "Skewed!" else wscript.echo "Smooth!"
end sub
| 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)
}
|
Change the programming language of this snippet from VB to Go without modifying what it does. | Imports System.Numerics
Module Module1
Class Sterling
Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)
Private Shared Function CacheKey(n As Integer, k As Integer) As String
Return String.Format("{0}:{1}", n, k)
End Function
Private Shared Function Impl(n As Integer, k As Integer) As BigInteger
If n = 0 AndAlso k = 0 Then
Return 1
End If
If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then
Return 0
End If
If n = k Then
Return 1
End If
If k > n Then
Return 0
End If
Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1)
End Function
Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger
Dim key = CacheKey(n, k)
If COMPUTED.ContainsKey(key) Then
Return COMPUTED(key)
End If
Dim result = Impl(n, k)
COMPUTED.Add(key, result)
Return result
End Function
End Class
Sub Main()
Console.WriteLine("Stirling numbers of the second kind:")
Dim max = 12
Console.Write("n/k")
For n = 0 To max
Console.Write("{0,10}", n)
Next
Console.WriteLine()
For n = 0 To max
Console.Write("{0,3}", n)
For k = 0 To n
Console.Write("{0,10}", Sterling.Sterling2(n, k))
Next
Console.WriteLine()
Next
Console.WriteLine("The maximum value of S2(100, k) = ")
Dim previous = BigInteger.Zero
For k = 1 To 100
Dim current = Sterling.Sterling2(100, k)
If current > previous Then
previous = current
Else
Console.WriteLine(previous)
Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1)
Exit For
End If
Next
End Sub
End Module
| package main
import (
"fmt"
"math/big"
)
func main() {
limit := 100
last := 12
s2 := make([][]*big.Int, limit+1)
for n := 0; n <= limit; n++ {
s2[n] = make([]*big.Int, limit+1)
for k := 0; k <= limit; k++ {
s2[n][k] = new(big.Int)
}
s2[n][n].SetInt64(int64(1))
}
var t big.Int
for n := 1; n <= limit; n++ {
for k := 1; k <= n; k++ {
t.SetInt64(int64(k))
t.Mul(&t, s2[n-1][k])
s2[n][k].Add(&t, s2[n-1][k-1])
}
}
fmt.Println("Stirling numbers of the second kind: S2(n, k):")
fmt.Printf("n/k")
for i := 0; i <= last; i++ {
fmt.Printf("%9d ", i)
}
fmt.Printf("\n--")
for i := 0; i <= last; i++ {
fmt.Printf("----------")
}
fmt.Println()
for n := 0; n <= last; n++ {
fmt.Printf("%2d ", n)
for k := 0; k <= n; k++ {
fmt.Printf("%9d ", s2[n][k])
}
fmt.Println()
}
fmt.Println("\nMaximum value from the S2(100, *) row:")
max := new(big.Int).Set(s2[limit][0])
for k := 1; k <= limit; k++ {
if s2[limit][k].Cmp(max) > 0 {
max.Set(s2[limit][k])
}
}
fmt.Println(max)
fmt.Printf("which has %d digits.\n", len(max.String()))
}
|
Translate the given VB code snippet into Go without altering its behavior. | Imports System.Numerics
Module Module1
Class Sterling
Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)
Private Shared Function CacheKey(n As Integer, k As Integer) As String
Return String.Format("{0}:{1}", n, k)
End Function
Private Shared Function Impl(n As Integer, k As Integer) As BigInteger
If n = 0 AndAlso k = 0 Then
Return 1
End If
If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then
Return 0
End If
If n = k Then
Return 1
End If
If k > n Then
Return 0
End If
Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1)
End Function
Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger
Dim key = CacheKey(n, k)
If COMPUTED.ContainsKey(key) Then
Return COMPUTED(key)
End If
Dim result = Impl(n, k)
COMPUTED.Add(key, result)
Return result
End Function
End Class
Sub Main()
Console.WriteLine("Stirling numbers of the second kind:")
Dim max = 12
Console.Write("n/k")
For n = 0 To max
Console.Write("{0,10}", n)
Next
Console.WriteLine()
For n = 0 To max
Console.Write("{0,3}", n)
For k = 0 To n
Console.Write("{0,10}", Sterling.Sterling2(n, k))
Next
Console.WriteLine()
Next
Console.WriteLine("The maximum value of S2(100, k) = ")
Dim previous = BigInteger.Zero
For k = 1 To 100
Dim current = Sterling.Sterling2(100, k)
If current > previous Then
previous = current
Else
Console.WriteLine(previous)
Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1)
Exit For
End If
Next
End Sub
End Module
| package main
import (
"fmt"
"math/big"
)
func main() {
limit := 100
last := 12
s2 := make([][]*big.Int, limit+1)
for n := 0; n <= limit; n++ {
s2[n] = make([]*big.Int, limit+1)
for k := 0; k <= limit; k++ {
s2[n][k] = new(big.Int)
}
s2[n][n].SetInt64(int64(1))
}
var t big.Int
for n := 1; n <= limit; n++ {
for k := 1; k <= n; k++ {
t.SetInt64(int64(k))
t.Mul(&t, s2[n-1][k])
s2[n][k].Add(&t, s2[n-1][k-1])
}
}
fmt.Println("Stirling numbers of the second kind: S2(n, k):")
fmt.Printf("n/k")
for i := 0; i <= last; i++ {
fmt.Printf("%9d ", i)
}
fmt.Printf("\n--")
for i := 0; i <= last; i++ {
fmt.Printf("----------")
}
fmt.Println()
for n := 0; n <= last; n++ {
fmt.Printf("%2d ", n)
for k := 0; k <= n; k++ {
fmt.Printf("%9d ", s2[n][k])
}
fmt.Println()
}
fmt.Println("\nMaximum value from the S2(100, *) row:")
max := new(big.Int).Set(s2[limit][0])
for k := 1; k <= limit; k++ {
if s2[limit][k].Cmp(max) > 0 {
max.Set(s2[limit][k])
}
}
fmt.Println(max)
fmt.Printf("which has %d digits.\n", len(max.String()))
}
|
Write a version of this VB function in Go with identical behavior. |
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()
function recaman(op,nn)
Dim b,d,h
Set b = CreateObject("Scripting.Dictionary")
Set d = CreateObject("Scripting.Dictionary")
list="0" : firstdup=0
if op="firstdup" then
nn=1000 : firstdup=1
end if
if op="numterm" then
h=nn : nn=10000000 : numterm=1
end if
ax=0
b.Add 0,1
s=0
for n=1 to nn-1
an=ax-n
if an<=0 then
an=ax+n
elseif b.Exists(an) then
an=ax+n
end if
ax=an
if not b.Exists(an) then b.Add an,1
if op="seq" then
list=list&" "&an
end if
if firstdup then
if d.Exists(an) then
recaman="a("&n&")="&an
exit function
else
d.Add an,1
end if
end if
if numterm then
if an<=h then
if not d.Exists(an) then
s=s+1
d.Add an,1
end if
if s>=h then
recaman=n
exit function
end if
end if
end if
next
recaman=list
end function
| package main
import "fmt"
func main() {
a := []int{0}
used := make(map[int]bool, 1001)
used[0] = true
used1000 := make(map[int]bool, 1001)
used1000[0] = true
for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
next := a[n-1] - n
if next < 1 || used[next] {
next += 2 * n
}
alreadyUsed := used[next]
a = append(a, next)
if !alreadyUsed {
used[next] = true
if next >= 0 && next <= 1000 {
used1000[next] = true
}
}
if n == 14 {
fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
}
if !foundDup && alreadyUsed {
fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
foundDup = true
}
if len(used1000) == 1001 {
fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
}
}
}
|
Generate a Go translation of this VB snippet without changing its computational steps. |
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()
function recaman(op,nn)
Dim b,d,h
Set b = CreateObject("Scripting.Dictionary")
Set d = CreateObject("Scripting.Dictionary")
list="0" : firstdup=0
if op="firstdup" then
nn=1000 : firstdup=1
end if
if op="numterm" then
h=nn : nn=10000000 : numterm=1
end if
ax=0
b.Add 0,1
s=0
for n=1 to nn-1
an=ax-n
if an<=0 then
an=ax+n
elseif b.Exists(an) then
an=ax+n
end if
ax=an
if not b.Exists(an) then b.Add an,1
if op="seq" then
list=list&" "&an
end if
if firstdup then
if d.Exists(an) then
recaman="a("&n&")="&an
exit function
else
d.Add an,1
end if
end if
if numterm then
if an<=h then
if not d.Exists(an) then
s=s+1
d.Add an,1
end if
if s>=h then
recaman=n
exit function
end if
end if
end if
next
recaman=list
end function
| package main
import "fmt"
func main() {
a := []int{0}
used := make(map[int]bool, 1001)
used[0] = true
used1000 := make(map[int]bool, 1001)
used1000[0] = true
for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
next := a[n-1] - n
if next < 1 || used[next] {
next += 2 * n
}
alreadyUsed := used[next]
a = append(a, next)
if !alreadyUsed {
used[next] = true
if next >= 0 && next <= 1000 {
used1000[next] = true
}
}
if n == 14 {
fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
}
if !foundDup && alreadyUsed {
fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
foundDup = true
}
if len(used1000) == 1001 {
fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
}
}
}
|
Generate an equivalent Go version of this VB code. | Option Explicit
Private Lines(1 To 3, 1 To 3) As String
Private Nb As Byte, player As Byte
Private GameWin As Boolean, GameOver As Boolean
Sub Main_TicTacToe()
Dim p As String
InitLines
printLines Nb
Do
p = WhoPlay
Debug.Print p & " play"
If p = "Human" Then
Call HumanPlay
GameWin = IsWinner("X")
Else
Call ComputerPlay
GameWin = IsWinner("O")
End If
If Not GameWin Then GameOver = IsEnd
Loop Until GameWin Or GameOver
If Not GameOver Then
Debug.Print p & " Win !"
Else
Debug.Print "Game Over!"
End If
End Sub
Sub InitLines(Optional S As String)
Dim i As Byte, j As Byte
Nb = 0: player = 0
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
Lines(i, j) = "#"
Next j
Next i
End Sub
Sub printLines(Nb As Byte)
Dim i As Byte, j As Byte, strT As String
Debug.Print "Loop " & Nb
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
strT = strT & Lines(i, j)
Next j
Debug.Print strT
strT = vbNullString
Next i
End Sub
Function WhoPlay(Optional S As String) As String
If player = 0 Then
player = 1
WhoPlay = "Human"
Else
player = 0
WhoPlay = "Computer"
End If
End Function
Sub HumanPlay(Optional S As String)
Dim L As Byte, C As Byte, GoodPlay As Boolean
Do
L = Application.InputBox("Choose the row", "Numeric only", Type:=1)
If L > 0 And L < 4 Then
C = Application.InputBox("Choose the column", "Numeric only", Type:=1)
If C > 0 And C < 4 Then
If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then
Lines(L, C) = "X"
Nb = Nb + 1
printLines Nb
GoodPlay = True
End If
End If
End If
Loop Until GoodPlay
End Sub
Sub ComputerPlay(Optional S As String)
Dim L As Byte, C As Byte, GoodPlay As Boolean
Randomize Timer
Do
L = Int((Rnd * 3) + 1)
C = Int((Rnd * 3) + 1)
If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then
Lines(L, C) = "O"
Nb = Nb + 1
printLines Nb
GoodPlay = True
End If
Loop Until GoodPlay
End Sub
Function IsWinner(S As String) As Boolean
Dim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String
Ch = String(UBound(Lines, 1), S)
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
strTL = strTL & Lines(i, j)
strTC = strTC & Lines(j, i)
Next j
If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For
strTL = vbNullString: strTC = vbNullString
Next i
strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3)
strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1)
If strTL = Ch Or strTC = Ch Then IsWinner = True
End Function
Function IsEnd() As Boolean
Dim i As Byte, j As Byte
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
If Lines(i, j) = "#" Then Exit Function
Next j
Next i
IsEnd = True
End Function
| package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
)
var b []byte
func printBoard() {
fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9])
}
var pScore, cScore int
var pMark, cMark byte = 'X', 'O'
var in = bufio.NewReader(os.Stdin)
func main() {
b = make([]byte, 9)
fmt.Println("Play by entering a digit.")
for {
for i := range b {
b[i] = '1' + byte(i)
}
computerStart := cMark == 'X'
if computerStart {
fmt.Println("I go first, playing X's")
} else {
fmt.Println("You go first, playing X's")
}
TakeTurns:
for {
if !computerStart {
if !playerTurn() {
return
}
if gameOver() {
break TakeTurns
}
}
computerStart = false
computerTurn()
if gameOver() {
break TakeTurns
}
}
fmt.Println("Score: you", pScore, "me", cScore)
fmt.Println("\nLet's play again.")
}
}
func playerTurn() bool {
var pm string
var err error
for i := 0; i < 3; i++ {
printBoard()
fmt.Printf("%c's move? ", pMark)
if pm, err = in.ReadString('\n'); err != nil {
fmt.Println(err)
return false
}
pm = strings.TrimSpace(pm)
if pm >= "1" && pm <= "9" && b[pm[0]-'1'] == pm[0] {
x := pm[0] - '1'
b[x] = pMark
return true
}
}
fmt.Println("You're not playing right.")
return false
}
var choices = make([]int, 9)
func computerTurn() {
printBoard()
var x int
defer func() {
fmt.Println("My move:", x+1)
b[x] = cMark
}()
block := -1
for _, l := range lines {
var mine, yours int
x = -1
for _, sq := range l {
switch b[sq] {
case cMark:
mine++
case pMark:
yours++
default:
x = sq
}
}
if mine == 2 && x >= 0 {
return
}
if yours == 2 && x >= 0 {
block = x
}
}
if block >= 0 {
x = block
return
}
choices = choices[:0]
for i, sq := range b {
if sq == '1'+byte(i) {
choices = append(choices, i)
}
}
x = choices[rand.Intn(len(choices))]
}
func gameOver() bool {
for _, l := range lines {
if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] {
printBoard()
if b[l[0]] == cMark {
fmt.Println("I win!")
cScore++
pMark, cMark = 'X', 'O'
} else {
fmt.Println("You win!")
pScore++
pMark, cMark = 'O', 'X'
}
return true
}
}
for i, sq := range b {
if sq == '1'+byte(i) {
return false
}
}
fmt.Println("Cat game.")
pMark, cMark = cMark, pMark
return true
}
var lines = [][]int{
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{0, 3, 6},
{1, 4, 7},
{2, 5, 8},
{0, 4, 8},
{2, 4, 6},
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import "fmt"
func bitwise(a, b int16) {
fmt.Printf("a: %016b\n", uint16(a))
fmt.Printf("b: %016b\n", uint16(b))
fmt.Printf("and: %016b\n", uint16(a&b))
fmt.Printf("or: %016b\n", uint16(a|b))
fmt.Printf("xor: %016b\n", uint16(a^b))
fmt.Printf("not: %016b\n", uint16(^a))
if b < 0 {
fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).")
return
}
ua := uint16(a)
ub := uint32(b)
fmt.Printf("shl: %016b\n", uint16(ua<<ub))
fmt.Printf("shr: %016b\n", uint16(ua>>ub))
fmt.Printf("las: %016b\n", uint16(a<<ub))
fmt.Printf("ras: %016b\n", uint16(a>>ub))
fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub))))
fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))
}
func main() {
var a, b int16 = -460, 6
bitwise(a, b)
}
| #include <iostream>
void bitwise(int a, int b)
{
std::cout << "a and b: " << (a & b) << '\n';
std::cout << "a or b: " << (a | b) << '\n';
std::cout << "a xor b: " << (a ^ b) << '\n';
std::cout << "not a: " << ~a << '\n';
std::cout << "a shl b: " << (a << b) << '\n';
std::cout << "a shr b: " << (a >> b) << '\n';
unsigned int ua = a;
std::cout << "a lsr b: " << (ua >> b) << '\n';
std::cout << "a rol b: " << std::rotl(ua, b) << '\n';
std::cout << "a ror b: " << std::rotr(ua, b) << '\n';
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"os"
)
const sep = 512
const depth = 14
var s = math.Sqrt2 / 2
var sin = []float64{0, s, 1, s, 0, -s, -1, -s}
var cos = []float64{1, s, 0, -s, -1, -s, 0, s}
var p = color.NRGBA{64, 192, 96, 255}
var b *image.NRGBA
func main() {
width := sep * 11 / 6
height := sep * 4 / 3
bounds := image.Rect(0, 0, width, height)
b = image.NewNRGBA(bounds)
draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)
dragon(14, 0, 1, sep, sep/2, sep*5/6)
f, err := os.Create("dragon.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, b); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
}
func dragon(n, a, t int, d, x, y float64) {
if n <= 1 {
x1 := int(x + .5)
y1 := int(y + .5)
x2 := int(x + d*cos[a] + .5)
y2 := int(y + d*sin[a] + .5)
xInc := 1
if x1 > x2 {
xInc = -1
}
yInc := 1
if y1 > y2 {
yInc = -1
}
for x, y := x1, y1; ; x, y = x+xInc, y+yInc {
b.Set(x, y, p)
if x == x2 {
break
}
}
return
}
d *= s
a1 := (a - t) & 7
a2 := (a + t) & 7
dragon(n-1, a1, 1, d, x, y)
dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])
}
| #include <windows.h>
#include <iostream>
using namespace std;
const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;
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();
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
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 dragonC
{
public:
dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }
void draw( int iterations ) { generate( iterations ); draw(); }
private:
void generate( int it )
{
generator.push_back( 1 );
string temp;
for( int y = 0; y < it - 1; y++ )
{
temp = generator; temp.push_back( 1 );
for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )
temp.push_back( !( *x ) );
generator = temp;
}
}
void draw()
{
HDC dc = bmp.getDC();
unsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };
int mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;
for( int t = 0; t < 4; t++ )
{
int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];
MoveToEx( dc, a, b, NULL );
bmp.setPenColor( clr[t] );
for( string::iterator x = generator.begin(); x < generator.end(); x++ )
{
switch( dir )
{
case NORTH:
if( *x ) { a += LEN; dir = EAST; }
else { a -= LEN; dir = WEST; }
break;
case EAST:
if( *x ) { b += LEN; dir = SOUTH; }
else { b -= LEN; dir = NORTH; }
break;
case SOUTH:
if( *x ) { a -= LEN; dir = WEST; }
else { a += LEN; dir = EAST; }
break;
case WEST:
if( *x ) { b -= LEN; dir = NORTH; }
else { b += LEN; dir = SOUTH; }
}
LineTo( dc, a, b );
}
}
bmp.saveBitmap( "f:/rc/dragonCpp.bmp" );
}
int dir;
myBitmap bmp;
string generator;
};
int main( int argc, char* argv[] )
{
dragonC d; d.draw( 17 );
return system( "pause" );
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Go version. | package main
import (
"bufio"
"fmt"
"log"
"os"
)
func init() {
log.SetFlags(log.Lshortfile)
}
func main() {
inputFile, err := os.Open("byline.go")
if err != nil {
log.Fatal("Error opening input file:", err)
}
defer inputFile.Close()
scanner := bufio.NewScanner(inputFile)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(scanner.Err())
}
}
| #include <fstream>
#include <string>
#include <iostream>
int main( int argc , char** argv ) {
int linecount = 0 ;
std::string line ;
std::ifstream infile( argv[ 1 ] ) ;
if ( infile ) {
while ( getline( infile , line ) ) {
std::cout << linecount << ": "
<< line << '\n' ;
linecount++ ;
}
}
infile.close( ) ;
return 0 ;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import "fmt"
type dlNode struct {
string
next, prev *dlNode
}
type dlList struct {
head, tail *dlNode
}
func (list *dlList) String() string {
if list.head == nil {
return fmt.Sprint(list.head)
}
r := "[" + list.head.string
for p := list.head.next; p != nil; p = p.next {
r += " " + p.string
}
return r + "]"
}
func (list *dlList) insertTail(node *dlNode) {
if list.tail == nil {
list.head = node
} else {
list.tail.next = node
}
node.next = nil
node.prev = list.tail
list.tail = node
}
func (list *dlList) insertAfter(existing, insert *dlNode) {
insert.prev = existing
insert.next = existing.next
existing.next.prev = insert
existing.next = insert
if existing == list.tail {
list.tail = insert
}
}
func main() {
dll := &dlList{}
fmt.Println(dll)
a := &dlNode{string: "A"}
dll.insertTail(a)
dll.insertTail(&dlNode{string: "B"})
fmt.Println(dll)
dll.insertAfter(a, &dlNode{string: "C"})
fmt.Println(dll)
}
| template <typename T>
void insert_after(Node<T>* N, T&& data)
{
auto node = new Node<T>{N, N->next, std::forward(data)};
if(N->next != nullptr)
N->next->prev = node;
N->next = node;
}
|
Preserve the algorithm and functionality while converting the code from Go to C++. | package main
import (
"fmt"
"math/big"
)
var b = new(big.Int)
func isSPDSPrime(n uint64) bool {
nn := n
for nn > 0 {
r := nn % 10
if r != 2 && r != 3 && r != 5 && r != 7 {
return false
}
nn /= 10
}
b.SetUint64(n)
if b.ProbablyPrime(0) {
return true
}
return false
}
func listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {
count := countFrom
for n := startFrom; ; n += 2 {
if isSPDSPrime(n) {
count++
if !printOne {
fmt.Printf("%2d. %d\n", count, n)
}
if count == countTo {
if printOne {
fmt.Println(n)
}
return n
}
}
}
}
func main() {
fmt.Println("The first 25 terms of the Smarandache prime-digital sequence are:")
fmt.Println(" 1. 2")
n := listSPDSPrimes(3, 1, 25, false)
fmt.Println("\nHigher terms:")
indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}
for i := 1; i < len(indices); i++ {
fmt.Printf("%6d. ", indices[i])
n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)
}
}
| #include <iostream>
#include <cstdint>
using integer = uint32_t;
integer next_prime_digit_number(integer n) {
if (n == 0)
return 2;
switch (n % 10) {
case 2:
return n + 1;
case 3:
case 5:
return n + 2;
default:
return 2 + next_prime_digit_number(n/10) * 10;
}
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
return n == 5;
constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };
integer p = 7;
for (;;) {
for (integer w : wheel) {
if (p * p > n)
return true;
if (n % p == 0)
return false;
p += w;
}
}
}
int main() {
std::cout.imbue(std::locale(""));
const integer limit = 1000000000;
integer n = 0, max = 0;
std::cout << "First 25 SPDS primes:\n";
for (int i = 0; n < limit; ) {
n = next_prime_digit_number(n);
if (!is_prime(n))
continue;
if (i < 25) {
if (i > 0)
std::cout << ' ';
std::cout << n;
}
else if (i == 25)
std::cout << '\n';
++i;
if (i == 100)
std::cout << "Hundredth SPDS prime: " << n << '\n';
else if (i == 1000)
std::cout << "Thousandth SPDS prime: " << n << '\n';
else if (i == 10000)
std::cout << "Ten thousandth SPDS prime: " << n << '\n';
max = n;
}
std::cout << "Largest SPDS prime less than " << limit << ": " << max << '\n';
return 0;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import "fmt"
func quickselect(list []int, k int) int {
for {
px := len(list) / 2
pv := list[px]
last := len(list) - 1
list[px], list[last] = list[last], list[px]
i := 0
for j := 0; j < last; j++ {
if list[j] < pv {
list[i], list[j] = list[j], list[i]
i++
}
}
if i == k {
return pv
}
if k < i {
list = list[:i]
} else {
list[i], list[last] = list[last], list[i]
list = list[i+1:]
k -= i + 1
}
}
}
func main() {
for i := 0; ; i++ {
v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}
if i == len(v) {
return
}
fmt.Println(quickselect(v, i))
}
}
| #include <algorithm>
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));
std::cout << a[i];
if (i < 9) std::cout << ", ";
}
std::cout << std::endl;
return 0;
}
|
Port the provided Go code into C++ while preserving the original functionality. | package main
import "fmt"
func quickselect(list []int, k int) int {
for {
px := len(list) / 2
pv := list[px]
last := len(list) - 1
list[px], list[last] = list[last], list[px]
i := 0
for j := 0; j < last; j++ {
if list[j] < pv {
list[i], list[j] = list[j], list[i]
i++
}
}
if i == k {
return pv
}
if k < i {
list = list[:i]
} else {
list[i], list[last] = list[last], list[i]
list = list[i+1:]
k -= i + 1
}
}
}
func main() {
for i := 0; ; i++ {
v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}
if i == len(v) {
return
}
fmt.Println(quickselect(v, i))
}
}
| #include <algorithm>
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));
std::cout << a[i];
if (i < 9) std::cout << ", ";
}
std::cout << std::endl;
return 0;
}
|
Port the provided Go code into C++ while preserving the original functionality. | package main
import (
"fmt"
"math/big"
"strconv"
)
func main () {
s := strconv.FormatInt(26, 16)
fmt.Println(s)
i, err := strconv.ParseInt("1a", 16, 64)
if err == nil {
fmt.Println(i)
}
b, ok := new(big.Int).SetString("1a", 16)
if ok {
fmt.Println(b)
}
}
| #include <string>
#include <cstdlib>
#include <algorithm>
#include <cassert>
std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
std::string to_base(unsigned long num, int base)
{
if (num == 0)
return "0";
std::string result;
while (num > 0) {
std::ldiv_t temp = std::div(num, (long)base);
result += digits[temp.rem];
num = temp.quot;
}
std::reverse(result.begin(), result.end());
return result;
}
unsigned long from_base(std::string const& num_str, int base)
{
unsigned long result = 0;
for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)
result = result * base + digits.find(num_str[pos]);
return result;
}
|
Convert this Go snippet to C++ and keep its semantics consistent. | package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Preserve the algorithm and functionality while converting the code from Go to C++. | package main
import "fmt"
type sBox [8][16]byte
type gost struct {
k87, k65, k43, k21 [256]byte
enc []byte
}
func newGost(s *sBox) *gost {
var g gost
for i := range g.k87 {
g.k87[i] = s[7][i>>4]<<4 | s[6][i&15]
g.k65[i] = s[5][i>>4]<<4 | s[4][i&15]
g.k43[i] = s[3][i>>4]<<4 | s[2][i&15]
g.k21[i] = s[1][i>>4]<<4 | s[0][i&15]
}
g.enc = make([]byte, 8)
return &g
}
func (g *gost) f(x uint32) uint32 {
x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 |
uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255])
return x<<11 | x>>(32-11)
}
var cbrf = sBox{
{4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3},
{14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9},
{5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11},
{7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3},
{6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2},
{4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14},
{13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12},
{1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12},
}
func u32(b []byte) uint32 {
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
}
func b4(u uint32, b []byte) {
b[0] = byte(u)
b[1] = byte(u >> 8)
b[2] = byte(u >> 16)
b[3] = byte(u >> 24)
}
func (g *gost) mainStep(input []byte, key []byte) {
key32 := u32(key)
input1 := u32(input[:4])
input2 := u32(input[4:])
b4(g.f(key32+input1)^input2, g.enc[:4])
copy(g.enc[4:], input[:4])
}
func main() {
input := []byte{0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04}
key := []byte{0xF9, 0x04, 0xC1, 0xE2}
g := newGost(&cbrf)
g.mainStep(input, key)
for _, b := range g.enc {
fmt.Printf("[%02x]", b)
}
fmt.Println()
}
| UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)
{
UINT_64 N;
N = N1;
N = (N<<32)|N2;
return UINT_64(N);
}
UINT_32 TGost::ReplaceBlock(UINT_32 x)
{
register i;
UINT_32 res = 0UL;
for(i=7;i>=0;i--)
{
ui4_0 = x>>(i*4);
ui4_0 = BS[ui4_0][i];
res = (res<<4)|ui4_0;
}
return res;
}
UINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)
{
UINT_32 N1,N2,S=0UL;
N1=UINT_32(N);
N2=N>>32;
S = N1 + X % 0x4000000000000;
S = ReplaceBlock(S);
S = (S<<11)|(S>>21);
S ^= N2;
N2 = N1;
N1 = S;
return SWAP32(N2,N1);
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import (
"fmt"
"unicode"
)
var states = []string{"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"}
func main() {
play(states)
play(append(states,
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"))
}
func play(states []string) {
fmt.Println(len(states), "states:")
set := make(map[string]bool, len(states))
for _, s := range states {
set[s] = true
}
s := make([]string, len(set))
h := make([][26]byte, len(set))
var i int
for us := range set {
s[i] = us
for _, c := range us {
if u := uint(unicode.ToLower(c)) - 'a'; u < 26 {
h[i][u]++
}
}
i++
}
type pair struct {
i1, i2 int
}
m := make(map[string][]pair)
b := make([]byte, 26)
for i1, h1 := range h {
for i2 := i1 + 1; i2 < len(h); i2++ {
for i := range b {
b[i] = h1[i] + h[i2][i]
}
k := string(b)
for _, x := range m[k] {
if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 {
fmt.Printf("%s, %s = %s, %s\n", s[i1], s[i2],
s[x.i1], s[x.i2])
}
}
m[k] = append(m[k], pair{i1, i2})
}
}
}
| #include <algorithm>
#include <iostream>
#include <string>
#include <array>
#include <vector>
template<typename T>
T unique(T&& src)
{
T retval(std::move(src));
std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());
retval.erase(std::unique(retval.begin(), retval.end()), retval.end());
return retval;
}
#define USE_FAKES 1
auto states = unique(std::vector<std::string>({
#if USE_FAKES
"Slender Dragon", "Abalamara",
#endif
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
}));
struct counted_pair
{
std::string name;
std::array<int, 26> count{};
void count_characters(const std::string& s)
{
for (auto&& c : s) {
if (c >= 'a' && c <= 'z') count[c - 'a']++;
if (c >= 'A' && c <= 'Z') count[c - 'A']++;
}
}
counted_pair(const std::string& s1, const std::string& s2)
: name(s1 + " + " + s2)
{
count_characters(s1);
count_characters(s2);
}
};
bool operator<(const counted_pair& lhs, const counted_pair& rhs)
{
auto lhs_size = lhs.name.size();
auto rhs_size = rhs.name.size();
return lhs_size == rhs_size
? std::lexicographical_compare(lhs.count.begin(),
lhs.count.end(),
rhs.count.begin(),
rhs.count.end())
: lhs_size < rhs_size;
}
bool operator==(const counted_pair& lhs, const counted_pair& rhs)
{
return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;
}
int main()
{
const int n_states = states.size();
std::vector<counted_pair> pairs;
for (int i = 0; i < n_states; i++) {
for (int j = 0; j < i; j++) {
pairs.emplace_back(counted_pair(states[i], states[j]));
}
}
std::sort(pairs.begin(), pairs.end());
auto start = pairs.begin();
while (true) {
auto match = std::adjacent_find(start, pairs.end());
if (match == pairs.end()) {
break;
}
auto next = match + 1;
std::cout << match->name << " => " << next->name << "\n";
start = next;
}
}
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"hash/crc32"
)
func main() {
s := []byte("The quick brown fox jumps over the lazy dog")
result := crc32.ChecksumIEEE(s)
fmt.Printf("%X\n", result)
}
| #include <algorithm>
#include <array>
#include <cstdint>
#include <numeric>
#include <iomanip>
#include <iostream>
#include <string>
std::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept
{
auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};
struct byte_checksum
{
std::uint_fast32_t operator()() noexcept
{
auto checksum = static_cast<std::uint_fast32_t>(n++);
for (auto i = 0; i < 8; ++i)
checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);
return checksum;
}
unsigned n = 0;
};
auto table = std::array<std::uint_fast32_t, 256>{};
std::generate(table.begin(), table.end(), byte_checksum{});
return table;
}
template <typename InputIterator>
std::uint_fast32_t crc(InputIterator first, InputIterator last)
{
static auto const table = generate_crc_lookup_table();
return std::uint_fast32_t{0xFFFFFFFFuL} &
~std::accumulate(first, last,
~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},
[](std::uint_fast32_t checksum, std::uint_fast8_t value)
{ return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });
}
int main()
{
auto const s = std::string{"The quick brown fox jumps over the lazy dog"};
std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\n';
}
|
Generate a C++ translation of this Go snippet without changing its computational steps. | package main
import (
"bytes"
"encoding/csv"
"fmt"
"html/template"
"strings"
)
var c = `Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!`
func main() {
if h, err := csvToHtml(c); err != nil {
fmt.Println(err)
} else {
fmt.Print(h)
}
}
func csvToHtml(c string) (string, error) {
data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()
if err != nil {
return "", err
}
var b strings.Builder
err = template.Must(template.New("").Parse(`<table>
{{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>
{{end}}</table>
`)).Execute(&b, data)
return b.String(), err
}
| #include <string>
#include <boost/regex.hpp>
#include <iostream>
std::string csvToHTML( const std::string & ) ;
int main( ) {
std::string text = "Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you?\n"
"Brians mother,I'm his mother; that's who!\n"
"The multitude,Behold his mother! Behold his mother!\n" ;
std::cout << csvToHTML( text ) ;
return 0 ;
}
std::string csvToHTML( const std::string & csvtext ) {
std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
const char* replacements [ 5 ] = { "<" , ">" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ;
boost::regex e1( regexes[ 0 ] ) ;
std::string tabletext = boost::regex_replace( csvtext , e1 ,
replacements[ 0 ] , boost::match_default | boost::format_all ) ;
for ( int i = 1 ; i < 5 ; i++ ) {
e1.assign( regexes[ i ] ) ;
tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
}
tabletext = std::string( "<TABLE>\n" ) + tabletext ;
tabletext.append( "</TABLE>\n" ) ;
return tabletext ;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import (
"bytes"
"encoding/csv"
"fmt"
"html/template"
"strings"
)
var c = `Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!`
func main() {
if h, err := csvToHtml(c); err != nil {
fmt.Println(err)
} else {
fmt.Print(h)
}
}
func csvToHtml(c string) (string, error) {
data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()
if err != nil {
return "", err
}
var b strings.Builder
err = template.Must(template.New("").Parse(`<table>
{{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>
{{end}}</table>
`)).Execute(&b, data)
return b.String(), err
}
| #include <string>
#include <boost/regex.hpp>
#include <iostream>
std::string csvToHTML( const std::string & ) ;
int main( ) {
std::string text = "Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you?\n"
"Brians mother,I'm his mother; that's who!\n"
"The multitude,Behold his mother! Behold his mother!\n" ;
std::cout << csvToHTML( text ) ;
return 0 ;
}
std::string csvToHTML( const std::string & csvtext ) {
std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
const char* replacements [ 5 ] = { "<" , ">" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ;
boost::regex e1( regexes[ 0 ] ) ;
std::string tabletext = boost::regex_replace( csvtext , e1 ,
replacements[ 0 ] , boost::match_default | boost::format_all ) ;
for ( int i = 1 ; i < 5 ; i++ ) {
e1.assign( regexes[ i ] ) ;
tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
}
tabletext = std::string( "<TABLE>\n" ) + tabletext ;
tabletext.append( "</TABLE>\n" ) ;
return tabletext ;
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import "fmt"
type picnicBasket struct {
nServings int
corkscrew bool
}
func (b *picnicBasket) happy() bool {
return b.nServings > 1 && b.corkscrew
}
func newPicnicBasket(nPeople int) *picnicBasket {
return &picnicBasket{nPeople, nPeople > 0}
}
func main() {
var pb picnicBasket
pbl := picnicBasket{}
pbp := &picnicBasket{}
pbn := new(picnicBasket)
forTwo := newPicnicBasket(2)
forToo := &picnicBasket{nServings: 2, corkscrew: true}
fmt.Println(pb.nServings, pb.corkscrew)
fmt.Println(pbl.nServings, pbl.corkscrew)
fmt.Println(pbp)
fmt.Println(pbn)
fmt.Println(forTwo)
fmt.Println(forToo)
}
| PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive
OPTION PARSE FALSE
'---The class does the declaring for you
CLASS Books
public:
const char* title;
const char* author;
const char* subject;
int book_id;
END CLASS
'---pointer to an object declaration (we use a class called Books)
DECLARE Book1 TYPE Books
'--- the correct syntax for class
Book1 = Books()
'--- initialize the strings const char* in c++
Book1.title = "C++ Programming to bacon "
Book1.author = "anyone"
Book1.subject ="RECORD Tutorial"
Book1.book_id = 1234567
PRINT "Book title : " ,Book1.title FORMAT "%s%s\n"
PRINT "Book author : ", Book1.author FORMAT "%s%s\n"
PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"
|
Rewrite this program in C++ while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"strconv"
)
func kaprekar(n uint64, base uint64) (bool, int) {
order := 0
if n == 1 {
return true, -1
}
nn, power := n*n, uint64(1)
for power <= nn {
power *= base
order++
}
power /= base
order--
for ; power > 1; power /= base {
q, r := nn/power, nn%power
if q >= n {
return false, -1
}
if q+r == n {
return true, order
}
order--
}
return false, -1
}
func main() {
max := uint64(10000)
fmt.Printf("Kaprekar numbers < %d:\n", max)
for m := uint64(0); m < max; m++ {
if is, _ := kaprekar(m, 10); is {
fmt.Println(" ", m)
}
}
max = 1e6
var count int
for m := uint64(0); m < max; m++ {
if is, _ := kaprekar(m, 10); is {
count++
}
}
fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max)
const base = 17
maxB := "1000000"
fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base)
max, _ = strconv.ParseUint(maxB, base, 64)
fmt.Printf("\n Base 10 Base %d Square Split\n", base)
for m := uint64(2); m < max; m++ {
is, pos := kaprekar(m, base)
if !is {
continue
}
sq := strconv.FormatUint(m*m, base)
str := strconv.FormatUint(m, base)
split := len(sq)-pos
fmt.Printf("%8d %7s %12s %6s + %s\n", m,
str, sq, sq[:split], sq[split:])
}
}
| #include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <utility>
long string2long( const std::string & s ) {
long result ;
std::istringstream( s ) >> result ;
return result ;
}
bool isKaprekar( long number ) {
long long squarenumber = ((long long)number) * number ;
std::ostringstream numberbuf ;
numberbuf << squarenumber ;
std::string numberstring = numberbuf.str( ) ;
for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {
std::string firstpart = numberstring.substr( 0 , i ) ,
secondpart = numberstring.substr( i ) ;
if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) {
return false ;
}
if ( string2long( firstpart ) + string2long( secondpart ) == number ) {
return true ;
}
}
return false ;
}
int main( ) {
std::vector<long> kaprekarnumbers ;
kaprekarnumbers.push_back( 1 ) ;
for ( int i = 2 ; i < 1000001 ; i++ ) {
if ( isKaprekar( i ) )
kaprekarnumbers.push_back( i ) ;
}
std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;
std::cout << "Kaprekar numbers up to 10000: \n" ;
while ( *svi < 10000 ) {
std::cout << *svi << " " ;
svi++ ;
}
std::cout << '\n' ;
std::cout << "All the Kaprekar numbers up to 1000000 :\n" ;
std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,
std::ostream_iterator<long>( std::cout , "\n" ) ) ;
std::cout << "There are " << kaprekarnumbers.size( )
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
"strconv"
)
func kaprekar(n uint64, base uint64) (bool, int) {
order := 0
if n == 1 {
return true, -1
}
nn, power := n*n, uint64(1)
for power <= nn {
power *= base
order++
}
power /= base
order--
for ; power > 1; power /= base {
q, r := nn/power, nn%power
if q >= n {
return false, -1
}
if q+r == n {
return true, order
}
order--
}
return false, -1
}
func main() {
max := uint64(10000)
fmt.Printf("Kaprekar numbers < %d:\n", max)
for m := uint64(0); m < max; m++ {
if is, _ := kaprekar(m, 10); is {
fmt.Println(" ", m)
}
}
max = 1e6
var count int
for m := uint64(0); m < max; m++ {
if is, _ := kaprekar(m, 10); is {
count++
}
}
fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max)
const base = 17
maxB := "1000000"
fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base)
max, _ = strconv.ParseUint(maxB, base, 64)
fmt.Printf("\n Base 10 Base %d Square Split\n", base)
for m := uint64(2); m < max; m++ {
is, pos := kaprekar(m, base)
if !is {
continue
}
sq := strconv.FormatUint(m*m, base)
str := strconv.FormatUint(m, base)
split := len(sq)-pos
fmt.Printf("%8d %7s %12s %6s + %s\n", m,
str, sq, sq[:split], sq[split:])
}
}
| #include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <utility>
long string2long( const std::string & s ) {
long result ;
std::istringstream( s ) >> result ;
return result ;
}
bool isKaprekar( long number ) {
long long squarenumber = ((long long)number) * number ;
std::ostringstream numberbuf ;
numberbuf << squarenumber ;
std::string numberstring = numberbuf.str( ) ;
for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {
std::string firstpart = numberstring.substr( 0 , i ) ,
secondpart = numberstring.substr( i ) ;
if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) {
return false ;
}
if ( string2long( firstpart ) + string2long( secondpart ) == number ) {
return true ;
}
}
return false ;
}
int main( ) {
std::vector<long> kaprekarnumbers ;
kaprekarnumbers.push_back( 1 ) ;
for ( int i = 2 ; i < 1000001 ; i++ ) {
if ( isKaprekar( i ) )
kaprekarnumbers.push_back( i ) ;
}
std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;
std::cout << "Kaprekar numbers up to 10000: \n" ;
while ( *svi < 10000 ) {
std::cout << *svi << " " ;
svi++ ;
}
std::cout << '\n' ;
std::cout << "All the Kaprekar numbers up to 1000000 :\n" ;
std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,
std::ostream_iterator<long>( std::cout , "\n" ) ) ;
std::cout << "There are " << kaprekarnumbers.size( )
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | package main
import (
"fmt"
"log"
"strings"
)
func compress(uncompressed string) []int {
dictSize := 256
dictionary := make(map[string]int, dictSize)
for i := 0; i < dictSize; i++ {
dictionary[string([]byte{byte(i)})] = i
}
var result []int
var w []byte
for i := 0; i < len(uncompressed); i++ {
c := uncompressed[i]
wc := append(w, c)
if _, ok := dictionary[string(wc)]; ok {
w = wc
} else {
result = append(result, dictionary[string(w)])
dictionary[string(wc)] = dictSize
dictSize++
wc[0] = c
w = wc[:1]
}
}
if len(w) > 0 {
result = append(result, dictionary[string(w)])
}
return result
}
type BadSymbolError int
func (e BadSymbolError) Error() string {
return fmt.Sprint("Bad compressed symbol ", int(e))
}
func decompress(compressed []int) (string, error) {
dictSize := 256
dictionary := make(map[int][]byte, dictSize)
for i := 0; i < dictSize; i++ {
dictionary[i] = []byte{byte(i)}
}
var result strings.Builder
var w []byte
for _, k := range compressed {
var entry []byte
if x, ok := dictionary[k]; ok {
entry = x[:len(x):len(x)]
} else if k == dictSize && len(w) > 0 {
entry = append(w, w[0])
} else {
return result.String(), BadSymbolError(k)
}
result.Write(entry)
if len(w) > 0 {
w = append(w, entry[0])
dictionary[dictSize] = w
dictSize++
}
w = entry
}
return result.String(), nil
}
func main() {
compressed := compress("TOBEORNOTTOBEORTOBEORNOT")
fmt.Println(compressed)
decompressed, err := decompress(compressed)
if err != nil {
log.Fatal(err)
}
fmt.Println(decompressed)
}
| #include <string>
#include <map>
template <typename Iterator>
Iterator compress(const std::string &uncompressed, Iterator result) {
int dictSize = 256;
std::map<std::string,int> dictionary;
for (int i = 0; i < 256; i++)
dictionary[std::string(1, i)] = i;
std::string w;
for (std::string::const_iterator it = uncompressed.begin();
it != uncompressed.end(); ++it) {
char c = *it;
std::string wc = w + c;
if (dictionary.count(wc))
w = wc;
else {
*result++ = dictionary[w];
dictionary[wc] = dictSize++;
w = std::string(1, c);
}
}
if (!w.empty())
*result++ = dictionary[w];
return result;
}
template <typename Iterator>
std::string decompress(Iterator begin, Iterator end) {
int dictSize = 256;
std::map<int,std::string> dictionary;
for (int i = 0; i < 256; i++)
dictionary[i] = std::string(1, i);
std::string w(1, *begin++);
std::string result = w;
std::string entry;
for ( ; begin != end; begin++) {
int k = *begin;
if (dictionary.count(k))
entry = dictionary[k];
else if (k == dictSize)
entry = w + w[0];
else
throw "Bad compressed k";
result += entry;
dictionary[dictSize++] = w + entry[0];
w = entry;
}
return result;
}
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> compressed;
compress("TOBEORNOTTOBEORTOBEORNOT", std::back_inserter(compressed));
copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", "));
std::cout << std::endl;
std::string decompressed = decompress(compressed.begin(), compressed.end());
std::cout << decompressed << std::endl;
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import "fmt"
var ffr, ffs func(int) int
func init() {
r := []int{0, 1}
s := []int{0, 2}
ffr = func(n int) int {
for len(r) <= n {
nrk := len(r) - 1
rNxt := r[nrk] + s[nrk]
r = append(r, rNxt)
for sn := r[nrk] + 2; sn < rNxt; sn++ {
s = append(s, sn)
}
s = append(s, rNxt+1)
}
return r[n]
}
ffs = func(n int) int {
for len(s) <= n {
ffr(len(r))
}
return s[n]
}
}
func main() {
for n := 1; n <= 10; n++ {
fmt.Printf("r(%d): %d\n", n, ffr(n))
}
var found [1001]int
for n := 1; n <= 40; n++ {
found[ffr(n)]++
}
for n := 1; n <= 960; n++ {
found[ffs(n)]++
}
for i := 1; i <= 1000; i++ {
if found[i] != 1 {
fmt.Println("task 4: FAIL")
return
}
}
fmt.Println("task 4: PASS")
}
| #include <iomanip>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
auto n = rlistSize > slistSize ? rlistSize : slistSize;
auto rlist = new vector<unsigned> { 1, 3, 7 };
auto slist = new vector<unsigned> { 2, 4, 5, 6 };
auto list = rlistSize > 0 ? rlist : slist;
auto target_size = rlistSize > 0 ? rlistSize : slistSize;
while (list->size() > target_size) list->pop_back();
while (list->size() < target_size)
{
auto lastIndex = rlist->size() - 1;
auto lastr = (*rlist)[lastIndex];
auto r = lastr + (*slist)[lastIndex];
rlist->push_back(r);
for (auto s = lastr + 1; s < r && list->size() < target_size;)
slist->push_back(s++);
}
auto v = (*list)[n - 1];
delete rlist;
delete slist;
return v;
}
ostream& operator<<(ostream& os, const set<unsigned>& s)
{
cout << '(' << s.size() << "):";
auto i = 0;
for (auto c = s.begin(); c != s.end();)
{
if (i++ % 20 == 0) os << endl;
os << setw(5) << *c++;
}
return os;
}
int main(int argc, const char* argv[])
{
const auto v1 = atoi(argv[1]);
const auto v2 = atoi(argv[2]);
set<unsigned> r, s;
for (auto n = 1; n <= v2; n++)
{
if (n <= v1)
r.insert(hofstadter(n, 0));
s.insert(hofstadter(0, n));
}
cout << "R" << r << endl;
cout << "S" << s << endl;
int m = max(*r.rbegin(), *s.rbegin());
for (auto n = 1; n <= m; n++)
if (r.count(n) == s.count(n))
clog << "integer " << n << " either in both or neither set" << endl;
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import "fmt"
var ffr, ffs func(int) int
func init() {
r := []int{0, 1}
s := []int{0, 2}
ffr = func(n int) int {
for len(r) <= n {
nrk := len(r) - 1
rNxt := r[nrk] + s[nrk]
r = append(r, rNxt)
for sn := r[nrk] + 2; sn < rNxt; sn++ {
s = append(s, sn)
}
s = append(s, rNxt+1)
}
return r[n]
}
ffs = func(n int) int {
for len(s) <= n {
ffr(len(r))
}
return s[n]
}
}
func main() {
for n := 1; n <= 10; n++ {
fmt.Printf("r(%d): %d\n", n, ffr(n))
}
var found [1001]int
for n := 1; n <= 40; n++ {
found[ffr(n)]++
}
for n := 1; n <= 960; n++ {
found[ffs(n)]++
}
for i := 1; i <= 1000; i++ {
if found[i] != 1 {
fmt.Println("task 4: FAIL")
return
}
}
fmt.Println("task 4: PASS")
}
| #include <iomanip>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
auto n = rlistSize > slistSize ? rlistSize : slistSize;
auto rlist = new vector<unsigned> { 1, 3, 7 };
auto slist = new vector<unsigned> { 2, 4, 5, 6 };
auto list = rlistSize > 0 ? rlist : slist;
auto target_size = rlistSize > 0 ? rlistSize : slistSize;
while (list->size() > target_size) list->pop_back();
while (list->size() < target_size)
{
auto lastIndex = rlist->size() - 1;
auto lastr = (*rlist)[lastIndex];
auto r = lastr + (*slist)[lastIndex];
rlist->push_back(r);
for (auto s = lastr + 1; s < r && list->size() < target_size;)
slist->push_back(s++);
}
auto v = (*list)[n - 1];
delete rlist;
delete slist;
return v;
}
ostream& operator<<(ostream& os, const set<unsigned>& s)
{
cout << '(' << s.size() << "):";
auto i = 0;
for (auto c = s.begin(); c != s.end();)
{
if (i++ % 20 == 0) os << endl;
os << setw(5) << *c++;
}
return os;
}
int main(int argc, const char* argv[])
{
const auto v1 = atoi(argv[1]);
const auto v2 = atoi(argv[2]);
set<unsigned> r, s;
for (auto n = 1; n <= v2; n++)
{
if (n <= v1)
r.insert(hofstadter(n, 0));
s.insert(hofstadter(0, n));
}
cout << "R" << r << endl;
cout << "S" << s << endl;
int m = max(*r.rbegin(), *s.rbegin());
for (auto n = 1; n <= m; n++)
if (r.count(n) == s.count(n))
clog << "integer " << n << " either in both or neither set" << endl;
return 0;
}
|
Translate the given Go code snippet into C++ without altering its behavior. | package main
import (
"fmt"
"log"
)
func ms(n int) (int, []int) {
M := func(x int) int { return (x + n - 1) % n }
if n <= 0 || n&1 == 0 {
n = 5
log.Println("forcing size", n)
}
m := make([]int, n*n)
i, j := 0, n/2
for k := 1; k <= n*n; k++ {
m[i*n+j] = k
if m[M(i)*n+M(j)] != 0 {
i = (i + 1) % n
} else {
i, j = M(i), M(j)
}
}
return n, m
}
func main() {
n, m := ms(5)
i := 2
for j := 1; j <= n*n; j *= 10 {
i++
}
f := fmt.Sprintf("%%%dd", i)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
fmt.Printf(f, m[i*n+j])
}
fmt.Println()
}
}
| #include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <vector>
using namespace std;
class MagicSquare
{
public:
MagicSquare(int d) : sqr(d*d,0), sz(d)
{
assert(d&1);
fillSqr();
}
void display()
{
cout << "Odd Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr;
cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ )
{
int yy = y * sz;
for( int x = 0; x < sz; x++ )
cout << setw( l + 2 ) << sqr[yy + x];
cout << "\n";
}
cout << "\n\n";
}
private:
void fillSqr()
{
int sx = sz / 2, sy = 0, c = 0;
while( c < sz * sz )
{
if( !sqr[sx + sy * sz] )
{
sqr[sx + sy * sz]= c + 1;
inc( sx ); dec( sy );
c++;
}
else
{
dec( sx ); inc( sy ); inc( sy );
}
}
}
int magicNumber()
{ return sz * ( ( sz * sz ) + 1 ) / 2; }
void inc( int& a )
{ if( ++a == sz ) a = 0; }
void dec( int& a )
{ if( --a < 0 ) a = sz - 1; }
bool checkPos( int x, int y )
{ return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
bool isInside( int s )
{ return ( s < sz && s > -1 ); }
vector<int> sqr;
int sz;
};
int main()
{
MagicSquare s(7);
s.display();
return 0;
}
|
Produce a language-to-language conversion: from Go to C++, same semantics. | package main
import (
"fmt"
"log"
)
func ms(n int) (int, []int) {
M := func(x int) int { return (x + n - 1) % n }
if n <= 0 || n&1 == 0 {
n = 5
log.Println("forcing size", n)
}
m := make([]int, n*n)
i, j := 0, n/2
for k := 1; k <= n*n; k++ {
m[i*n+j] = k
if m[M(i)*n+M(j)] != 0 {
i = (i + 1) % n
} else {
i, j = M(i), M(j)
}
}
return n, m
}
func main() {
n, m := ms(5)
i := 2
for j := 1; j <= n*n; j *= 10 {
i++
}
f := fmt.Sprintf("%%%dd", i)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
fmt.Printf(f, m[i*n+j])
}
fmt.Println()
}
}
| #include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <vector>
using namespace std;
class MagicSquare
{
public:
MagicSquare(int d) : sqr(d*d,0), sz(d)
{
assert(d&1);
fillSqr();
}
void display()
{
cout << "Odd Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr;
cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ )
{
int yy = y * sz;
for( int x = 0; x < sz; x++ )
cout << setw( l + 2 ) << sqr[yy + x];
cout << "\n";
}
cout << "\n\n";
}
private:
void fillSqr()
{
int sx = sz / 2, sy = 0, c = 0;
while( c < sz * sz )
{
if( !sqr[sx + sy * sz] )
{
sqr[sx + sy * sz]= c + 1;
inc( sx ); dec( sy );
c++;
}
else
{
dec( sx ); inc( sy ); inc( sy );
}
}
}
int magicNumber()
{ return sz * ( ( sz * sz ) + 1 ) / 2; }
void inc( int& a )
{ if( ++a == sz ) a = 0; }
void dec( int& a )
{ if( --a < 0 ) a = sz - 1; }
bool checkPos( int x, int y )
{ return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
bool isInside( int s )
{ return ( s < sz && s > -1 ); }
vector<int> sqr;
int sz;
};
int main()
{
MagicSquare s(7);
s.display();
return 0;
}
|
Transform the following Go implementation into C++, maintaining the same output and logic. | package main
import (
"fmt"
"log"
"os/exec"
)
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
func yellowstone(n int) []int {
m := make(map[int]bool)
a := make([]int, n+1)
for i := 1; i < 4; i++ {
a[i] = i
m[i] = true
}
min := 4
for c := 4; c <= n; c++ {
for i := min; ; i++ {
if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {
a[c] = i
m[i] = true
if i == min {
min++
}
break
}
}
}
return a[1:]
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
x := make([]int, 100)
for i := 0; i < 100; i++ {
x[i] = i + 1
}
y := yellowstone(100)
fmt.Println("The first 30 Yellowstone numbers are:")
fmt.Println(y[:30])
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
check(err)
check(g.Start())
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %d\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
| #include <iostream>
#include <numeric>
#include <set>
template <typename integer>
class yellowstone_generator {
public:
integer next() {
n2_ = n1_;
n1_ = n_;
if (n_ < 3) {
++n_;
} else {
for (n_ = min_; !(sequence_.count(n_) == 0
&& std::gcd(n1_, n_) == 1
&& std::gcd(n2_, n_) > 1); ++n_) {}
}
sequence_.insert(n_);
for (;;) {
auto it = sequence_.find(min_);
if (it == sequence_.end())
break;
sequence_.erase(it);
++min_;
}
return n_;
}
private:
std::set<integer> sequence_;
integer min_ = 1;
integer n_ = 0;
integer n1_ = 0;
integer n2_ = 0;
};
int main() {
std::cout << "First 30 Yellowstone numbers:\n";
yellowstone_generator<unsigned int> ygen;
std::cout << ygen.next();
for (int i = 1; i < 30; ++i)
std::cout << ' ' << ygen.next();
std::cout << '\n';
return 0;
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"log"
"os/exec"
)
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
func yellowstone(n int) []int {
m := make(map[int]bool)
a := make([]int, n+1)
for i := 1; i < 4; i++ {
a[i] = i
m[i] = true
}
min := 4
for c := 4; c <= n; c++ {
for i := min; ; i++ {
if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {
a[c] = i
m[i] = true
if i == min {
min++
}
break
}
}
}
return a[1:]
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
x := make([]int, 100)
for i := 0; i < 100; i++ {
x[i] = i + 1
}
y := yellowstone(100)
fmt.Println("The first 30 Yellowstone numbers are:")
fmt.Println(y[:30])
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
check(err)
check(g.Start())
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %d\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
}
| #include <iostream>
#include <numeric>
#include <set>
template <typename integer>
class yellowstone_generator {
public:
integer next() {
n2_ = n1_;
n1_ = n_;
if (n_ < 3) {
++n_;
} else {
for (n_ = min_; !(sequence_.count(n_) == 0
&& std::gcd(n1_, n_) == 1
&& std::gcd(n2_, n_) > 1); ++n_) {}
}
sequence_.insert(n_);
for (;;) {
auto it = sequence_.find(min_);
if (it == sequence_.end())
break;
sequence_.erase(it);
++min_;
}
return n_;
}
private:
std::set<integer> sequence_;
integer min_ = 1;
integer n_ = 0;
integer n1_ = 0;
integer n2_ = 0;
};
int main() {
std::cout << "First 30 Yellowstone numbers:\n";
yellowstone_generator<unsigned int> ygen;
std::cout << ygen.next();
for (int i = 1; i < 30; ++i)
std::cout << ' ' << ygen.next();
std::cout << '\n';
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Go to C++. | package main
import "fmt"
var grid []byte
var w, h, last int
var cnt int
var next [4]int
var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}
func walk(y, x int) {
if y == 0 || y == h || x == 0 || x == w {
cnt += 2
return
}
t := y*(w+1) + x
grid[t]++
grid[last-t]++
for i, d := range dir {
if grid[t+next[i]] == 0 {
walk(y+d[0], x+d[1])
}
}
grid[t]--
grid[last-t]--
}
func solve(hh, ww, recur int) int {
h = hh
w = ww
if h&1 != 0 {
h, w = w, h
}
switch {
case h&1 == 1:
return 0
case w == 1:
return 1
case w == 2:
return h
case h == 2:
return w
}
cy := h / 2
cx := w / 2
grid = make([]byte, (h+1)*(w+1))
last = len(grid) - 1
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if recur != 0 {
cnt = 0
}
for x := cx + 1; x < w; x++ {
t := cy*(w+1) + x
grid[t] = 1
grid[last-t] = 1
walk(cy-1, x)
}
cnt++
if h == w {
cnt *= 2
} else if w&1 == 0 && recur != 0 {
solve(w, h, 0)
}
return cnt
}
func main() {
for y := 1; y <= 10; y++ {
for x := 1; x <= y; x++ {
if x&1 == 0 || y&1 == 0 {
fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1))
}
}
}
}
| #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
}
void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return;
}
std::vector<std::vector<int>> grid(h, std::vector<int>(w));
std::stack<int> stack;
int half = (w * h) / 2;
long bits = (long)pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.top();
stack.pop();
int r = pos / w;
int c = pos % w;
for (auto dir : DIRS) {
int nextR = r + dir.first;
int nextC = c + dir.second;
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
std::cout << '\n';
}
}
}
int main() {
cutRectangle(2, 2);
cutRectangle(4, 3);
return 0;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import "fmt"
var grid []byte
var w, h, last int
var cnt int
var next [4]int
var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}
func walk(y, x int) {
if y == 0 || y == h || x == 0 || x == w {
cnt += 2
return
}
t := y*(w+1) + x
grid[t]++
grid[last-t]++
for i, d := range dir {
if grid[t+next[i]] == 0 {
walk(y+d[0], x+d[1])
}
}
grid[t]--
grid[last-t]--
}
func solve(hh, ww, recur int) int {
h = hh
w = ww
if h&1 != 0 {
h, w = w, h
}
switch {
case h&1 == 1:
return 0
case w == 1:
return 1
case w == 2:
return h
case h == 2:
return w
}
cy := h / 2
cx := w / 2
grid = make([]byte, (h+1)*(w+1))
last = len(grid) - 1
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if recur != 0 {
cnt = 0
}
for x := cx + 1; x < w; x++ {
t := cy*(w+1) + x
grid[t] = 1
grid[last-t] = 1
walk(cy-1, x)
}
cnt++
if h == w {
cnt *= 2
} else if w&1 == 0 && recur != 0 {
solve(w, h, 0)
}
return cnt
}
func main() {
for y := 1; y <= 10; y++ {
for x := 1; x <= y; x++ {
if x&1 == 0 || y&1 == 0 {
fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1))
}
}
}
}
| #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
}
void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return;
}
std::vector<std::vector<int>> grid(h, std::vector<int>(w));
std::stack<int> stack;
int half = (w * h) / 2;
long bits = (long)pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.top();
stack.pop();
int r = pos / w;
int c = pos % w;
for (auto dir : DIRS) {
int nextR = r + dir.first;
int nextC = c + dir.second;
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
std::cout << '\n';
}
}
}
int main() {
cutRectangle(2, 2);
cutRectangle(4, 3);
return 0;
}
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import "fmt"
var grid []byte
var w, h, last int
var cnt int
var next [4]int
var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}
func walk(y, x int) {
if y == 0 || y == h || x == 0 || x == w {
cnt += 2
return
}
t := y*(w+1) + x
grid[t]++
grid[last-t]++
for i, d := range dir {
if grid[t+next[i]] == 0 {
walk(y+d[0], x+d[1])
}
}
grid[t]--
grid[last-t]--
}
func solve(hh, ww, recur int) int {
h = hh
w = ww
if h&1 != 0 {
h, w = w, h
}
switch {
case h&1 == 1:
return 0
case w == 1:
return 1
case w == 2:
return h
case h == 2:
return w
}
cy := h / 2
cx := w / 2
grid = make([]byte, (h+1)*(w+1))
last = len(grid) - 1
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if recur != 0 {
cnt = 0
}
for x := cx + 1; x < w; x++ {
t := cy*(w+1) + x
grid[t] = 1
grid[last-t] = 1
walk(cy-1, x)
}
cnt++
if h == w {
cnt *= 2
} else if w&1 == 0 && recur != 0 {
solve(w, h, 0)
}
return cnt
}
func main() {
for y := 1; y <= 10; y++ {
for x := 1; x <= y; x++ {
if x&1 == 0 || y&1 == 0 {
fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1))
}
}
}
}
| #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
}
void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return;
}
std::vector<std::vector<int>> grid(h, std::vector<int>(w));
std::stack<int> stack;
int half = (w * h) / 2;
long bits = (long)pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.top();
stack.pop();
int r = pos / w;
int c = pos % w;
for (auto dir : DIRS) {
int nextR = r + dir.first;
int nextC = c + dir.second;
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
std::cout << '\n';
}
}
}
int main() {
cutRectangle(2, 2);
cutRectangle(4, 3);
return 0;
}
|
Change the following Go code into C++ without altering its purpose. | package main
import "fmt"
func mertens(to int) ([]int, int, int) {
if to < 1 {
to = 1
}
merts := make([]int, to+1)
primes := []int{2}
var sum, zeros, crosses int
for i := 1; i <= to; i++ {
j := i
cp := 0
spf := false
for _, p := range primes {
if p > j {
break
}
if j%p == 0 {
j /= p
cp++
}
if j%p == 0 {
spf = true
break
}
}
if cp == 0 && i > 2 {
cp = 1
primes = append(primes, i)
}
if !spf {
if cp%2 == 0 {
sum++
} else {
sum--
}
}
merts[i] = sum
if sum == 0 {
zeros++
if i > 1 && merts[i-1] != 0 {
crosses++
}
}
}
return merts, zeros, crosses
}
func main() {
merts, zeros, crosses := mertens(1000)
fmt.Println("Mertens sequence - First 199 terms:")
for i := 0; i < 200; i++ {
if i == 0 {
fmt.Print(" ")
continue
}
if i%20 == 0 {
fmt.Println()
}
fmt.Printf(" % d", merts[i])
}
fmt.Println("\n\nEquals zero", zeros, "times between 1 and 1000")
fmt.Println("\nCrosses zero", crosses, "times between 1 and 1000")
}
| #include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> mertens_numbers(int max) {
std::vector<int> m(max + 1, 1);
for (int n = 2; n <= max; ++n) {
for (int k = 2; k <= n; ++k)
m[n] -= m[n / k];
}
return m;
}
int main() {
const int max = 1000;
auto m(mertens_numbers(max));
std::cout << "First 199 Mertens numbers:\n";
for (int i = 0, column = 0; i < 200; ++i) {
if (column > 0)
std::cout << ' ';
if (i == 0)
std::cout << " ";
else
std::cout << std::setw(2) << m[i];
++column;
if (column == 20) {
std::cout << '\n';
column = 0;
}
}
int zero = 0, cross = 0, previous = 0;
for (int i = 1; i <= max; ++i) {
if (m[i] == 0) {
++zero;
if (previous != 0)
++cross;
}
previous = m[i];
}
std::cout << "M(n) is zero " << zero << " times for 1 <= n <= 1000.\n";
std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n";
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"sort"
"strings"
)
var count int = 0
func interactiveCompare(s1, s2 string) bool {
count++
fmt.Printf("(%d) Is %s < %s? ", count, s1, s2)
var response string
_, err := fmt.Scanln(&response)
return err == nil && strings.HasPrefix(response, "y")
}
func main() {
items := []string{"violet", "red", "green", "indigo", "blue", "yellow", "orange"}
var sortedItems []string
for _, item := range items {
fmt.Printf("Inserting '%s' into %s\n", item, sortedItems)
spotToInsert := sort.Search(len(sortedItems), func(i int) bool {
return interactiveCompare(item, sortedItems[i])
})
sortedItems = append(sortedItems[:spotToInsert],
append([]string{item}, sortedItems[spotToInsert:]...)...)
}
fmt.Println(sortedItems)
}
| #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool InteractiveCompare(const string& s1, const string& s2)
{
if(s1 == s2) return false;
static int count = 0;
string response;
cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
getline(cin, response);
return !response.empty() && response.front() == 'y';
}
void PrintOrder(const vector<string>& items)
{
cout << "{ ";
for(auto& item : items) cout << item << " ";
cout << "}\n";
}
int main()
{
const vector<string> items
{
"violet", "red", "green", "indigo", "blue", "yellow", "orange"
};
vector<string> sortedItems;
for(auto& item : items)
{
cout << "Inserting '" << item << "' into ";
PrintOrder(sortedItems);
auto spotToInsert = lower_bound(sortedItems.begin(),
sortedItems.end(), item, InteractiveCompare);
sortedItems.insert(spotToInsert, item);
}
PrintOrder(sortedItems);
return 0;
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"math"
)
func Fib1000() []float64 {
a, b, r := 0., 1., [1000]float64{}
for i := range r {
r[i], a, b = b, b, b+a
}
return r[:]
}
func main() {
show(Fib1000(), "First 1000 Fibonacci numbers")
}
func show(c []float64, title string) {
var f [9]int
for _, v := range c {
f[fmt.Sprintf("%g", v)[0]-'1']++
}
fmt.Println(title)
fmt.Println("Digit Observed Predicted")
for i, n := range f {
fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)),
math.Log10(1+1/float64(i+1)))
}
}
|
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;
class NextNum {
public :
NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }
cl_I operator( )( ) {
cl_I result = first + second ;
first = second ;
second = result ;
return result ;
}
private :
cl_I first ;
cl_I second ;
} ;
void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) {
for ( cl_I bignumber : fibos ) {
std::ostringstream os ;
fprintdecimal ( os , bignumber ) ;
int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;
auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;
if ( ! result.second )
numberfrequencies[ firstdigit ]++ ;
}
}
int main( ) {
std::vector<cl_I> fibonaccis( 1000 ) ;
fibonaccis[ 0 ] = 0 ;
fibonaccis[ 1 ] = 1 ;
cl_I a = 0 ;
cl_I b = 1 ;
std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;
std::cout << std::endl ;
std::map<int , int> frequencies ;
findFrequencies( fibonaccis , frequencies ) ;
std::cout << " found expected\n" ;
for ( int i = 1 ; i < 10 ; i++ ) {
double found = static_cast<double>( frequencies[ i ] ) / 1000 ;
double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;
std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ;
std::cout.precision( 3 ) ;
std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ;
}
return 0 ;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
"math"
)
func Fib1000() []float64 {
a, b, r := 0., 1., [1000]float64{}
for i := range r {
r[i], a, b = b, b, b+a
}
return r[:]
}
func main() {
show(Fib1000(), "First 1000 Fibonacci numbers")
}
func show(c []float64, title string) {
var f [9]int
for _, v := range c {
f[fmt.Sprintf("%g", v)[0]-'1']++
}
fmt.Println(title)
fmt.Println("Digit Observed Predicted")
for i, n := range f {
fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)),
math.Log10(1+1/float64(i+1)))
}
}
|
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;
class NextNum {
public :
NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }
cl_I operator( )( ) {
cl_I result = first + second ;
first = second ;
second = result ;
return result ;
}
private :
cl_I first ;
cl_I second ;
} ;
void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) {
for ( cl_I bignumber : fibos ) {
std::ostringstream os ;
fprintdecimal ( os , bignumber ) ;
int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;
auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;
if ( ! result.second )
numberfrequencies[ firstdigit ]++ ;
}
}
int main( ) {
std::vector<cl_I> fibonaccis( 1000 ) ;
fibonaccis[ 0 ] = 0 ;
fibonaccis[ 1 ] = 1 ;
cl_I a = 0 ;
cl_I b = 1 ;
std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;
std::cout << std::endl ;
std::map<int , int> frequencies ;
findFrequencies( fibonaccis , frequencies ) ;
std::cout << " found expected\n" ;
for ( int i = 1 ; i < 10 ; i++ ) {
double found = static_cast<double>( frequencies[ i ] ) / 1000 ;
double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;
std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ;
std::cout.precision( 3 ) ;
std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ;
}
return 0 ;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | package main
import (
"fmt"
"strings"
"time"
)
func main() {
watches := []string{
"First", "Middle", "Morning", "Forenoon",
"Afternoon", "Dog", "First",
}
for {
t := time.Now()
h := t.Hour()
m := t.Minute()
s := t.Second()
if (m == 0 || m == 30) && s == 0 {
bell := 0
if m == 30 {
bell = 1
}
bells := (h*2 + bell) % 8
watch := h/4 + 1
if bells == 0 {
bells = 8
watch--
}
sound := strings.Repeat("\a", bells)
pl := "s"
if bells == 1 {
pl = " "
}
w := watches[watch] + " watch"
if watch == 5 {
if bells < 5 {
w = "First " + w
} else {
w = "Last " + w
}
}
fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w)
}
time.Sleep(1 * time.Second)
}
}
| #include <iostream>
#include <string>
#include <windows.h>
using namespace std;
class bells
{
public:
void start()
{
watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First";
count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight";
_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );
}
private:
static DWORD WINAPI bell( LPVOID p )
{
DWORD wait = _inst->waitTime();
while( true )
{
Sleep( wait );
_inst->playBell();
wait = _inst->waitTime();
}
return 0;
}
DWORD waitTime()
{
GetLocalTime( &st );
int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;
return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );
}
void playBell()
{
GetLocalTime( &st );
int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;
int w = ( 60 * st.wHour + st.wMinute );
if( w < 1 ) w = 5; else w = ( w - 1 ) / 240;
char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute );
cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell";
if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl;
for( int x = 0, c = 1; x < b; x++, c++ )
{
cout << "\7"; Sleep( 500 );
if( !( c % 2 ) ) Sleep( 300 );
}
}
SYSTEMTIME st;
string watch[7], count[8];
static bells* _inst;
};
bells* bells::_inst = 0;
int main( int argc, char* argv[] )
{
bells b; b.start();
while( 1 );
return 0;
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"strings"
"time"
)
func main() {
watches := []string{
"First", "Middle", "Morning", "Forenoon",
"Afternoon", "Dog", "First",
}
for {
t := time.Now()
h := t.Hour()
m := t.Minute()
s := t.Second()
if (m == 0 || m == 30) && s == 0 {
bell := 0
if m == 30 {
bell = 1
}
bells := (h*2 + bell) % 8
watch := h/4 + 1
if bells == 0 {
bells = 8
watch--
}
sound := strings.Repeat("\a", bells)
pl := "s"
if bells == 1 {
pl = " "
}
w := watches[watch] + " watch"
if watch == 5 {
if bells < 5 {
w = "First " + w
} else {
w = "Last " + w
}
}
fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w)
}
time.Sleep(1 * time.Second)
}
}
| #include <iostream>
#include <string>
#include <windows.h>
using namespace std;
class bells
{
public:
void start()
{
watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First";
count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight";
_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );
}
private:
static DWORD WINAPI bell( LPVOID p )
{
DWORD wait = _inst->waitTime();
while( true )
{
Sleep( wait );
_inst->playBell();
wait = _inst->waitTime();
}
return 0;
}
DWORD waitTime()
{
GetLocalTime( &st );
int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;
return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );
}
void playBell()
{
GetLocalTime( &st );
int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;
int w = ( 60 * st.wHour + st.wMinute );
if( w < 1 ) w = 5; else w = ( w - 1 ) / 240;
char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute );
cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell";
if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl;
for( int x = 0, c = 1; x < b; x++, c++ )
{
cout << "\7"; Sleep( 500 );
if( !( c % 2 ) ) Sleep( 300 );
}
}
SYSTEMTIME st;
string watch[7], count[8];
static bells* _inst;
};
bells* bells::_inst = 0;
int main( int argc, char* argv[] )
{
bells b; b.start();
while( 1 );
return 0;
}
|
Please provide an equivalent version of this Go code in C++. | package main
import "fmt"
func main() {
for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {
f, ok := arFib(n)
if ok {
fmt.Printf("fib %d = %d\n", n, f)
} else {
fmt.Println("fib undefined for negative numbers")
}
}
}
func arFib(n int) (int, bool) {
switch {
case n < 0:
return 0, false
case n < 2:
return n, true
}
return yc(func(recurse fn) fn {
return func(left, term1, term2 int) int {
if left == 0 {
return term1+term2
}
return recurse(left-1, term1+term2, term1)
}
})(n-2, 1, 0), true
}
type fn func(int, int, int) int
type ff func(fn) fn
type fx func(fx) fn
func yc(f ff) fn {
return func(x fx) fn {
return x(x)
}(func(x fx) fn {
return f(func(a1, a2, a3 int) int {
return x(x)(a1, a2, a3)
})
})
}
| double fib(double n)
{
if(n < 0)
{
throw "Invalid argument passed to fib";
}
else
{
struct actual_fib
{
static double calc(double n)
{
if(n < 2)
{
return n;
}
else
{
return calc(n-1) + calc(n-2);
}
}
};
return actual_fib::calc(n);
}
}
|
Keep all operations the same but rewrite the snippet in C++. | package main
import (
"errors"
"fmt"
"log"
"math/rand"
"time"
termbox "github.com/nsf/termbox-go"
)
func main() {
rand.Seed(time.Now().UnixNano())
score, err := playSnake()
if err != nil {
log.Fatal(err)
}
fmt.Println("Final score:", score)
}
type snake struct {
body []position
heading direction
width, height int
cells []termbox.Cell
}
type position struct {
X int
Y int
}
type direction int
const (
North direction = iota
East
South
West
)
func (p position) next(d direction) position {
switch d {
case North:
p.Y--
case East:
p.X++
case South:
p.Y++
case West:
p.X--
}
return p
}
func playSnake() (int, error) {
err := termbox.Init()
if err != nil {
return 0, err
}
defer termbox.Close()
termbox.Clear(fg, bg)
termbox.HideCursor()
s := &snake{
body: make([]position, 0, 32),
cells: termbox.CellBuffer(),
}
s.width, s.height = termbox.Size()
s.drawBorder()
s.startSnake()
s.placeFood()
s.flush()
moveCh, errCh := s.startEventLoop()
const delay = 125 * time.Millisecond
for t := time.NewTimer(delay); ; t.Reset(delay) {
var move direction
select {
case err = <-errCh:
return len(s.body), err
case move = <-moveCh:
if !t.Stop() {
<-t.C
}
case <-t.C:
move = s.heading
}
if s.doMove(move) {
time.Sleep(1 * time.Second)
break
}
}
return len(s.body), err
}
func (s *snake) startEventLoop() (<-chan direction, <-chan error) {
moveCh := make(chan direction)
errCh := make(chan error, 1)
go func() {
defer close(errCh)
for {
switch ev := termbox.PollEvent(); ev.Type {
case termbox.EventKey:
switch ev.Ch {
case 'w', 'W', 'k', 'K':
moveCh <- North
case 'a', 'A', 'h', 'H':
moveCh <- West
case 's', 'S', 'j', 'J':
moveCh <- South
case 'd', 'D', 'l', 'L':
moveCh <- East
case 0:
switch ev.Key {
case termbox.KeyArrowUp:
moveCh <- North
case termbox.KeyArrowDown:
moveCh <- South
case termbox.KeyArrowLeft:
moveCh <- West
case termbox.KeyArrowRight:
moveCh <- East
case termbox.KeyEsc:
return
}
}
case termbox.EventResize:
errCh <- errors.New("terminal resizing unsupported")
return
case termbox.EventError:
errCh <- ev.Err
return
case termbox.EventInterrupt:
return
}
}
}()
return moveCh, errCh
}
func (s *snake) flush() {
termbox.Flush()
s.cells = termbox.CellBuffer()
}
func (s *snake) getCellRune(p position) rune {
i := p.Y*s.width + p.X
return s.cells[i].Ch
}
func (s *snake) setCell(p position, c termbox.Cell) {
i := p.Y*s.width + p.X
s.cells[i] = c
}
func (s *snake) drawBorder() {
for x := 0; x < s.width; x++ {
s.setCell(position{x, 0}, border)
s.setCell(position{x, s.height - 1}, border)
}
for y := 0; y < s.height-1; y++ {
s.setCell(position{0, y}, border)
s.setCell(position{s.width - 1, y}, border)
}
}
func (s *snake) placeFood() {
for {
x := rand.Intn(s.width-2) + 1
y := rand.Intn(s.height-2) + 1
foodp := position{x, y}
r := s.getCellRune(foodp)
if r != ' ' {
continue
}
s.setCell(foodp, food)
return
}
}
func (s *snake) startSnake() {
x := rand.Intn(s.width/2) + s.width/4
y := rand.Intn(s.height/2) + s.height/4
head := position{x, y}
s.setCell(head, snakeHead)
s.body = append(s.body[:0], head)
s.heading = direction(rand.Intn(4))
}
func (s *snake) doMove(move direction) bool {
head := s.body[len(s.body)-1]
s.setCell(head, snakeBody)
head = head.next(move)
s.heading = move
s.body = append(s.body, head)
r := s.getCellRune(head)
s.setCell(head, snakeHead)
gameOver := false
switch r {
case food.Ch:
s.placeFood()
case border.Ch, snakeBody.Ch:
gameOver = true
fallthrough
case empty.Ch:
s.setCell(s.body[0], empty)
s.body = s.body[1:]
default:
panic(r)
}
s.flush()
return gameOver
}
const (
fg = termbox.ColorWhite
bg = termbox.ColorBlack
)
var (
empty = termbox.Cell{Ch: ' ', Bg: bg, Fg: fg}
border = termbox.Cell{Ch: '+', Bg: bg, Fg: termbox.ColorBlue}
snakeBody = termbox.Cell{Ch: '#', Bg: bg, Fg: termbox.ColorGreen}
snakeHead = termbox.Cell{Ch: 'O', Bg: bg, Fg: termbox.ColorYellow | termbox.AttrBold}
food = termbox.Cell{Ch: '@', Bg: bg, Fg: termbox.ColorRed}
)
| #include <windows.h>
#include <ctime>
#include <iostream>
#include <string>
const int WID = 60, HEI = 30, MAX_LEN = 600;
enum DIR { NORTH, EAST, SOUTH, WEST };
class snake {
public:
snake() {
console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( "Snake" );
COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord );
SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc );
CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci );
}
void play() {
std::string a;
while( 1 ) {
createField(); alive = true;
while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); }
COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c );
SetConsoleTextAttribute( console, 0x000b );
std::cout << "Play again [Y/N]? "; std::cin >> a;
if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return;
}
}
private:
void createField() {
COORD coord = { 0, 0 }; DWORD c;
FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c );
FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c );
SetConsoleCursorPosition( console, coord );
int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0;
for( x = 0; x < WID; x++ ) {
brd[x] = brd[x + WID * ( HEI - 1 )] = '+';
}
for( ; y < HEI; y++ ) {
brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+';
}
do {
x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );
} while( brd[x + WID * y] );
brd[x + WID * y] = '@';
tailIdx = 0; headIdx = 4; x = 3; y = 2;
for( int c = tailIdx; c < headIdx; c++ ) {
brd[x + WID * y] = '#';
snk[c].X = 3 + c; snk[c].Y = 2;
}
head = snk[3]; dir = EAST; points = 0;
}
void readKey() {
if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST;
if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST;
if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH;
if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH;
}
void drawField() {
COORD coord; char t;
for( int y = 0; y < HEI; y++ ) {
coord.Y = y;
for( int x = 0; x < WID; x++ ) {
t = brd[x + WID * y]; if( !t ) continue;
coord.X = x; SetConsoleCursorPosition( console, coord );
if( coord.X == head.X && coord.Y == head.Y ) {
SetConsoleTextAttribute( console, 0x002e );
std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 );
continue;
}
switch( t ) {
case '#': SetConsoleTextAttribute( console, 0x002a ); break;
case '+': SetConsoleTextAttribute( console, 0x0019 ); break;
case '@': SetConsoleTextAttribute( console, 0x004c ); break;
}
std::cout << t; SetConsoleTextAttribute( console, 0x0000 );
}
}
std::cout << t; SetConsoleTextAttribute( console, 0x0007 );
COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c );
std::cout << "Points: " << points;
}
void moveSnake() {
switch( dir ) {
case NORTH: head.Y--; break;
case EAST: head.X++; break;
case SOUTH: head.Y++; break;
case WEST: head.X--; break;
}
char t = brd[head.X + WID * head.Y];
if( t && t != '@' ) { alive = false; return; }
brd[head.X + WID * head.Y] = '#';
snk[headIdx].X = head.X; snk[headIdx].Y = head.Y;
if( ++headIdx >= MAX_LEN ) headIdx = 0;
if( t == '@' ) {
points++; int x, y;
do {
x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );
} while( brd[x + WID * y] );
brd[x + WID * y] = '@'; return;
}
SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' ';
brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0;
if( ++tailIdx >= MAX_LEN ) tailIdx = 0;
}
bool alive; char brd[WID * HEI];
HANDLE console; DIR dir; COORD snk[MAX_LEN];
COORD head; int tailIdx, headIdx, points;
};
int main( int argc, char* argv[] ) {
srand( static_cast<unsigned>( time( NULL ) ) );
snake s; s.play(); return 0;
}
|
Write the same code in C++ as shown below in Go. | package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "ASCII"
fmt.Println("String: ", s)
fmt.Println("First byte removed: ", s[1:])
fmt.Println("Last byte removed: ", s[:len(s)-1])
fmt.Println("First and last removed:", s[1:len(s)-1])
u := "Δημοτική"
fmt.Println("String: ", u)
_, sizeFirst := utf8.DecodeRuneInString(u)
fmt.Println("First rune removed: ", u[sizeFirst:])
_, sizeLast := utf8.DecodeLastRuneInString(u)
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}
| #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "ASCII"
fmt.Println("String: ", s)
fmt.Println("First byte removed: ", s[1:])
fmt.Println("Last byte removed: ", s[:len(s)-1])
fmt.Println("First and last removed:", s[1:len(s)-1])
u := "Δημοτική"
fmt.Println("String: ", u)
_, sizeFirst := utf8.DecodeRuneInString(u)
fmt.Println("First rune removed: ", u[sizeFirst:])
_, sizeLast := utf8.DecodeLastRuneInString(u)
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}
| #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
}
|
Generate an equivalent C++ version of this Go code. | package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "ASCII"
fmt.Println("String: ", s)
fmt.Println("First byte removed: ", s[1:])
fmt.Println("Last byte removed: ", s[:len(s)-1])
fmt.Println("First and last removed:", s[1:len(s)-1])
u := "Δημοτική"
fmt.Println("String: ", u)
_, sizeFirst := utf8.DecodeRuneInString(u)
fmt.Println("First rune removed: ", u[sizeFirst:])
_, sizeLast := utf8.DecodeLastRuneInString(u)
fmt.Println("Last rune removed: ", u[:len(u)-sizeLast])
fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}
| #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"log"
"math"
"rcu"
)
func cantorPair(x, y int) int {
if x < 0 || y < 0 {
log.Fatal("Arguments must be non-negative integers.")
}
return (x*x + 3*x + 2*x*y + y + y*y) / 2
}
func pi(n int) int {
if n < 2 {
return 0
}
if n == 2 {
return 1
}
primes := rcu.Primes(int(math.Sqrt(float64(n))))
a := len(primes)
memoPhi := make(map[int]int)
var phi func(x, a int) int
phi = func(x, a int) int {
if a < 1 {
return x
}
if a == 1 {
return x - (x >> 1)
}
pa := primes[a-1]
if x <= pa {
return 1
}
key := cantorPair(x, a)
if v, ok := memoPhi[key]; ok {
return v
}
memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)
return memoPhi[key]
}
return phi(n, a) + a - 1
}
func main() {
for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {
fmt.Printf("10^%d %d\n", i, pi(n))
}
}
| #include <cmath>
#include <iostream>
#include <vector>
std::vector<int> generate_primes(int limit) {
std::vector<bool> sieve(limit >> 1, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve[q >> 1] = false;
}
s += (p + 1) << 2;
}
std::vector<int> primes;
if (limit > 2)
primes.push_back(2);
for (int i = 1; i < sieve.size(); ++i) {
if (sieve[i])
primes.push_back((i << 1) + 1);
}
return primes;
}
class legendre_prime_counter {
public:
explicit legendre_prime_counter(int limit);
int prime_count(int n);
private:
int phi(int x, int a);
std::vector<int> primes;
};
legendre_prime_counter::legendre_prime_counter(int limit) :
primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}
int legendre_prime_counter::prime_count(int n) {
if (n < 2)
return 0;
int a = prime_count(static_cast<int>(std::sqrt(n)));
return phi(n, a) + a - 1;
}
int legendre_prime_counter::phi(int x, int a) {
if (a == 0)
return x;
if (a == 1)
return x - (x >> 1);
int pa = primes[a - 1];
if (x <= pa)
return 1;
return phi(x, a - 1) - phi(x / pa, a - 1);
}
int main() {
legendre_prime_counter counter(1000000000);
for (int i = 0, n = 1; i < 10; ++i, n *= 10)
std::cout << "10^" << i << "\t" << counter.prime_count(n) << '\n';
}
|
Change the programming language of this snippet from Go to C++ without modifying what it does. | package main
import "C"
import "unsafe"
func main() {
C.Run()
}
const msg = "Here am I"
func Query(cbuf *C.char, csiz *C.size_t) C.int {
if int(*csiz) <= len(msg) {
return 0
}
pbuf := uintptr(unsafe.Pointer(cbuf))
for i := 0; i < len(msg); i++ {
*((*byte)(unsafe.Pointer(pbuf))) = msg[i]
pbuf++
}
*((*byte)(unsafe.Pointer(pbuf))) = 0
*csiz = C.size_t(len(msg) + 1)
return 1
}
| #include <string>
using std::string;
extern "C" int
Query (char *Data, size_t *Length)
{
const string Message = "Here am I";
if (*Length < Message.length())
return false;
*Length = Message.length();
Message.copy(Data, *Length);
return true;
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"bufio"
"os"
)
func main() {
in := bufio.NewReader(os.Stdin)
var blankLine = "\n"
var printLongest func(string) string
printLongest = func(candidate string) (longest string) {
longest = candidate
s, err := in.ReadString('\n')
defer func() {
recover()
defer func() {
recover()
}()
_ = blankLine[0]
func() {
defer func() {
recover()
}()
_ = s[len(longest)]
longest = s
}()
longest = printLongest(longest)
func() {
defer func() {
recover()
os.Stdout.WriteString(s)
}()
_ = longest[len(s)]
s = ""
}()
}()
_ = err.(error)
os.Stdout.WriteString(blankLine)
blankLine = ""
return
}
printLongest("")
}
| #include <iostream>
#include <string.h>
int main()
{
std::string longLine, longestLines, newLine;
while (std::cin >> newLine)
{
auto isNewLineShorter = longLine.c_str();
auto isLongLineShorter = newLine.c_str();
while (*isNewLineShorter && *isLongLineShorter)
{
isNewLineShorter = &isNewLineShorter[1];
isLongLineShorter = &isLongLineShorter[1];
}
if(*isNewLineShorter) continue;
if(*isLongLineShorter)
{
longLine = newLine;
longestLines = newLine;
}
else
{
longestLines+=newLine;
}
longestLines+="\n";
}
std::cout << "\nLongest string:\n" << longestLines;
}
|
Ensure the translated C++ code behaves exactly like the original Go snippet. | package turing
type Symbol byte
type Motion byte
const (
Left Motion = 'L'
Right Motion = 'R'
Stay Motion = 'N'
)
type Tape struct {
data []Symbol
pos, left int
blank Symbol
}
func NewTape(blank Symbol, start int, data []Symbol) *Tape {
t := &Tape{
data: data,
blank: blank,
}
if start < 0 {
t.Left(-start)
}
t.Right(start)
return t
}
func (t *Tape) Stay() {}
func (t *Tape) Data() []Symbol { return t.data[t.left:] }
func (t *Tape) Read() Symbol { return t.data[t.pos] }
func (t *Tape) Write(s Symbol) { t.data[t.pos] = s }
func (t *Tape) Dup() *Tape {
t2 := &Tape{
data: make([]Symbol, len(t.Data())),
blank: t.blank,
}
copy(t2.data, t.Data())
t2.pos = t.pos - t.left
return t2
}
func (t *Tape) String() string {
s := ""
for i := t.left; i < len(t.data); i++ {
b := t.data[i]
if i == t.pos {
s += "[" + string(b) + "]"
} else {
s += " " + string(b) + " "
}
}
return s
}
func (t *Tape) Move(a Motion) {
switch a {
case Left:
t.Left(1)
case Right:
t.Right(1)
case Stay:
t.Stay()
}
}
const minSz = 16
func (t *Tape) Left(n int) {
t.pos -= n
if t.pos < 0 {
var sz int
for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
newl := len(newd) - cap(t.data[t.left:])
n := copy(newd[newl:], t.data[t.left:])
t.data = newd[:newl+n]
t.pos += newl - t.left
t.left = newl
}
if t.pos < t.left {
if t.blank != 0 {
for i := t.pos; i < t.left; i++ {
t.data[i] = t.blank
}
}
t.left = t.pos
}
}
func (t *Tape) Right(n int) {
t.pos += n
if t.pos >= cap(t.data) {
var sz int
for sz = minSz; t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
n := copy(newd[t.left:], t.data[t.left:])
t.data = newd[:t.left+n]
}
if i := len(t.data); t.pos >= i {
t.data = t.data[:t.pos+1]
if t.blank != 0 {
for ; i < len(t.data); i++ {
t.data[i] = t.blank
}
}
}
}
type State string
type Rule struct {
State
Symbol
Write Symbol
Motion
Next State
}
func (i *Rule) key() key { return key{i.State, i.Symbol} }
func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }
type key struct {
State
Symbol
}
type action struct {
write Symbol
Motion
next State
}
type Machine struct {
tape *Tape
start, state State
transition map[key]action
l func(string, ...interface{})
}
func NewMachine(rules []Rule) *Machine {
m := &Machine{transition: make(map[key]action, len(rules))}
if len(rules) > 0 {
m.start = rules[0].State
}
for _, r := range rules {
m.transition[r.key()] = r.action()
}
return m
}
func (m *Machine) Run(input *Tape) (int, *Tape) {
m.tape = input.Dup()
m.state = m.start
for cnt := 0; ; cnt++ {
if m.l != nil {
m.l("%3d %4s: %v\n", cnt, m.state, m.tape)
}
sym := m.tape.Read()
act, ok := m.transition[key{m.state, sym}]
if !ok {
return cnt, m.tape
}
m.tape.Write(act.write)
m.tape.Move(act.Motion)
m.state = act.next
}
}
| #include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iomanip>
typedef unsigned int uint;
using namespace std;
const uint TAPE_MAX_LEN = 49152;
struct action { char write, direction; };
class tape
{
public:
tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }
void reset() { clear( '0' ); headPos = _sp; }
char read(){ return _t[headPos]; }
void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }
void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }
void action( const action* a ) { write( a->write ); move( a->direction ); }
void print( int c = 10 )
{
int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;
for( int x = st; x < ed; x++ )
{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; }
cout << endl << setw( c + 1 ) << "^" << endl;
}
private:
void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }
void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }
string _t; uint headPos, _sp; char blk; const uint MAX_LEN;
};
class state
{
public:
bool operator ==( const string o ) { return o == name; }
string name, next; char symbol, write, direction;
};
class actionTable
{
public:
bool loadTable( string file )
{
reset();
ifstream mf; mf.open( file.c_str() ); if( mf.is_open() )
{
string str; state stt;
while( mf.good() )
{
getline( mf, str ); if( str[0] == '\'' ) break;
parseState( str, stt ); states.push_back( stt );
}
while( mf.good() )
{
getline( mf, str ); if( str == "" ) continue;
if( str[0] == '!' ) blank = str.erase( 0, 1 )[0];
if( str[0] == '^' ) curState = str.erase( 0, 1 );
if( str[0] == '>' ) input = str.erase( 0, 1 );
}
mf.close(); return true;
}
cout << "Could not open " << file << endl; return false;
}
bool action( char symbol, action& a )
{
vector<state>::iterator f = states.begin();
while( true )
{
f = find( f, states.end(), curState );
if( f == states.end() ) return false;
if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )
{ a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }
f++;
}
return true;
}
void reset() { states.clear(); blank = '0'; curState = input = ""; }
string getInput() { return input; }
char getBlank() { return blank; }
private:
void parseState( string str, state& stt )
{
string a[5]; int idx = 0;
for( string::iterator si = str.begin(); si != str.end(); si++ )
{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }
stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];
}
vector<state> states; char blank; string curState, input;
};
class utm
{
public:
utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; }
void start()
{
while( true )
{
reset(); int t = showMenu(); if( t == 0 ) return;
if( !at.loadTable( files[t - 1] ) ) return; startMachine();
}
}
private:
void simulate()
{
char r; action a;
while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }
cout << endl << endl; system( "pause" );
}
int showMenu()
{
int t = -1;
while( t < 0 || t > 3 )
{
system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit";
cout << endl << endl << "Choose an action "; cin >> t;
}
return t;
}
void reset() { tp.reset(); at.reset(); }
void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }
tape tp; actionTable at; string files[7];
};
int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
|
Produce a language-to-language conversion: from Go to C++, same semantics. | package turing
type Symbol byte
type Motion byte
const (
Left Motion = 'L'
Right Motion = 'R'
Stay Motion = 'N'
)
type Tape struct {
data []Symbol
pos, left int
blank Symbol
}
func NewTape(blank Symbol, start int, data []Symbol) *Tape {
t := &Tape{
data: data,
blank: blank,
}
if start < 0 {
t.Left(-start)
}
t.Right(start)
return t
}
func (t *Tape) Stay() {}
func (t *Tape) Data() []Symbol { return t.data[t.left:] }
func (t *Tape) Read() Symbol { return t.data[t.pos] }
func (t *Tape) Write(s Symbol) { t.data[t.pos] = s }
func (t *Tape) Dup() *Tape {
t2 := &Tape{
data: make([]Symbol, len(t.Data())),
blank: t.blank,
}
copy(t2.data, t.Data())
t2.pos = t.pos - t.left
return t2
}
func (t *Tape) String() string {
s := ""
for i := t.left; i < len(t.data); i++ {
b := t.data[i]
if i == t.pos {
s += "[" + string(b) + "]"
} else {
s += " " + string(b) + " "
}
}
return s
}
func (t *Tape) Move(a Motion) {
switch a {
case Left:
t.Left(1)
case Right:
t.Right(1)
case Stay:
t.Stay()
}
}
const minSz = 16
func (t *Tape) Left(n int) {
t.pos -= n
if t.pos < 0 {
var sz int
for sz = minSz; cap(t.data[t.left:])-t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
newl := len(newd) - cap(t.data[t.left:])
n := copy(newd[newl:], t.data[t.left:])
t.data = newd[:newl+n]
t.pos += newl - t.left
t.left = newl
}
if t.pos < t.left {
if t.blank != 0 {
for i := t.pos; i < t.left; i++ {
t.data[i] = t.blank
}
}
t.left = t.pos
}
}
func (t *Tape) Right(n int) {
t.pos += n
if t.pos >= cap(t.data) {
var sz int
for sz = minSz; t.pos >= sz; sz <<= 1 {
}
newd := make([]Symbol, sz)
n := copy(newd[t.left:], t.data[t.left:])
t.data = newd[:t.left+n]
}
if i := len(t.data); t.pos >= i {
t.data = t.data[:t.pos+1]
if t.blank != 0 {
for ; i < len(t.data); i++ {
t.data[i] = t.blank
}
}
}
}
type State string
type Rule struct {
State
Symbol
Write Symbol
Motion
Next State
}
func (i *Rule) key() key { return key{i.State, i.Symbol} }
func (i *Rule) action() action { return action{i.Write, i.Motion, i.Next} }
type key struct {
State
Symbol
}
type action struct {
write Symbol
Motion
next State
}
type Machine struct {
tape *Tape
start, state State
transition map[key]action
l func(string, ...interface{})
}
func NewMachine(rules []Rule) *Machine {
m := &Machine{transition: make(map[key]action, len(rules))}
if len(rules) > 0 {
m.start = rules[0].State
}
for _, r := range rules {
m.transition[r.key()] = r.action()
}
return m
}
func (m *Machine) Run(input *Tape) (int, *Tape) {
m.tape = input.Dup()
m.state = m.start
for cnt := 0; ; cnt++ {
if m.l != nil {
m.l("%3d %4s: %v\n", cnt, m.state, m.tape)
}
sym := m.tape.Read()
act, ok := m.transition[key{m.state, sym}]
if !ok {
return cnt, m.tape
}
m.tape.Write(act.write)
m.tape.Move(act.Motion)
m.state = act.next
}
}
| #include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iomanip>
typedef unsigned int uint;
using namespace std;
const uint TAPE_MAX_LEN = 49152;
struct action { char write, direction; };
class tape
{
public:
tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }
void reset() { clear( '0' ); headPos = _sp; }
char read(){ return _t[headPos]; }
void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }
void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }
void action( const action* a ) { write( a->write ); move( a->direction ); }
void print( int c = 10 )
{
int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;
for( int x = st; x < ed; x++ )
{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; }
cout << endl << setw( c + 1 ) << "^" << endl;
}
private:
void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }
void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }
string _t; uint headPos, _sp; char blk; const uint MAX_LEN;
};
class state
{
public:
bool operator ==( const string o ) { return o == name; }
string name, next; char symbol, write, direction;
};
class actionTable
{
public:
bool loadTable( string file )
{
reset();
ifstream mf; mf.open( file.c_str() ); if( mf.is_open() )
{
string str; state stt;
while( mf.good() )
{
getline( mf, str ); if( str[0] == '\'' ) break;
parseState( str, stt ); states.push_back( stt );
}
while( mf.good() )
{
getline( mf, str ); if( str == "" ) continue;
if( str[0] == '!' ) blank = str.erase( 0, 1 )[0];
if( str[0] == '^' ) curState = str.erase( 0, 1 );
if( str[0] == '>' ) input = str.erase( 0, 1 );
}
mf.close(); return true;
}
cout << "Could not open " << file << endl; return false;
}
bool action( char symbol, action& a )
{
vector<state>::iterator f = states.begin();
while( true )
{
f = find( f, states.end(), curState );
if( f == states.end() ) return false;
if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )
{ a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }
f++;
}
return true;
}
void reset() { states.clear(); blank = '0'; curState = input = ""; }
string getInput() { return input; }
char getBlank() { return blank; }
private:
void parseState( string str, state& stt )
{
string a[5]; int idx = 0;
for( string::iterator si = str.begin(); si != str.end(); si++ )
{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }
stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];
}
vector<state> states; char blank; string curState, input;
};
class utm
{
public:
utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; }
void start()
{
while( true )
{
reset(); int t = showMenu(); if( t == 0 ) return;
if( !at.loadTable( files[t - 1] ) ) return; startMachine();
}
}
private:
void simulate()
{
char r; action a;
while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }
cout << endl << endl; system( "pause" );
}
int showMenu()
{
int t = -1;
while( t < 0 || t > 3 )
{
system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit";
cout << endl << endl << "Choose an action "; cin >> t;
}
return t;
}
void reset() { tp.reset(); at.reset(); }
void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }
tape tp; actionTable at; string files[7];
};
int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
|
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically? | package main
import (
"fmt"
"os"
)
func createFile(fn string) {
f, err := os.Create(fn)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("file", fn, "created!")
f.Close()
}
func createDir(dn string) {
err := os.Mkdir(dn, 0666)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("directory", dn, "created!")
}
func main() {
createFile("input.txt")
createFile("/input.txt")
createDir("docs")
createDir("/docs")
}
| #include <direct.h>
#include <fstream>
int main() {
std::fstream f("output.txt", std::ios::out);
f.close();
f.open("/output.txt", std::ios::out);
f.close();
_mkdir("docs");
_mkdir("/docs");
return 0;
}
|
Write the same algorithm in C++ as shown in this Go implementation. | package main
import (
"fmt"
"strconv"
)
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
fmt.Println("The first 35 unprimeable numbers are:")
count := 0
var firstNum [10]int
outer:
for i, countFirst := 100, 0; countFirst < 10; i++ {
if isPrime(i) {
continue
}
s := strconv.Itoa(i)
le := len(s)
b := []byte(s)
for j := 0; j < le; j++ {
for k := byte('0'); k <= '9'; k++ {
if s[j] == k {
continue
}
b[j] = k
n, _ := strconv.Atoi(string(b))
if isPrime(n) {
continue outer
}
}
b[j] = s[j]
}
lastDigit := s[le-1] - '0'
if firstNum[lastDigit] == 0 {
firstNum[lastDigit] = i
countFirst++
}
count++
if count <= 35 {
fmt.Printf("%d ", i)
}
if count == 35 {
fmt.Print("\n\nThe 600th unprimeable number is: ")
}
if count == 600 {
fmt.Printf("%s\n\n", commatize(i))
}
}
fmt.Println("The first unprimeable number that ends in:")
for i := 0; i < 10; i++ {
fmt.Printf(" %d is: %9s\n", i, commatize(firstNum[i]))
}
}
| #include <iostream>
#include <cstdint>
#include "prime_sieve.hpp"
typedef uint32_t integer;
int count_digits(integer n) {
int digits = 0;
for (; n > 0; ++digits)
n /= 10;
return digits;
}
integer change_digit(integer n, int index, int new_digit) {
integer p = 1;
integer changed = 0;
for (; index > 0; p *= 10, n /= 10, --index)
changed += p * (n % 10);
changed += (10 * (n/10) + new_digit) * p;
return changed;
}
bool unprimeable(const prime_sieve& sieve, integer n) {
if (sieve.is_prime(n))
return false;
int d = count_digits(n);
for (int i = 0; i < d; ++i) {
for (int j = 0; j <= 9; ++j) {
integer m = change_digit(n, i, j);
if (m != n && sieve.is_prime(m))
return false;
}
}
return true;
}
int main() {
const integer limit = 10000000;
prime_sieve sieve(limit);
std::cout.imbue(std::locale(""));
std::cout << "First 35 unprimeable numbers:\n";
integer n = 100;
integer lowest[10] = { 0 };
for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {
if (unprimeable(sieve, n)) {
if (count < 35) {
if (count != 0)
std::cout << ", ";
std::cout << n;
}
++count;
if (count == 600)
std::cout << "\n600th unprimeable number: " << n << '\n';
int last_digit = n % 10;
if (lowest[last_digit] == 0) {
lowest[last_digit] = n;
++found;
}
}
}
for (int i = 0; i < 10; ++i)
std::cout << "Least unprimeable number ending in " << i << ": " << lowest[i] << '\n';
return 0;
}
|
Convert this Go snippet to C++ and keep its semantics consistent. | package main
import "fmt"
type expr struct {
x, y, z float64
c float64
}
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
func subExpr(a, b expr) expr {
return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}
func mulExpr(a expr, c float64) expr {
return expr{a.x * c, a.y * c, a.z * c, a.c * c}
}
func addRow(l []expr) []expr {
if len(l) == 0 {
panic("wrong")
}
r := make([]expr, len(l)-1)
for i := range r {
r[i] = addExpr(l[i], l[i+1])
}
return r
}
func substX(a, b expr) expr {
if b.x == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.x/b.x))
}
func substY(a, b expr) expr {
if b.y == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.y/b.y))
}
func substZ(a, b expr) expr {
if b.z == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.z/b.z))
}
func solveX(a expr) float64 {
if a.x == 0 || a.y != 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.x
}
func solveY(a expr) float64 {
if a.x != 0 || a.y == 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.y
}
func solveZ(a expr) float64 {
if a.x != 0 || a.y != 0 || a.z == 0 {
panic("wrong")
}
return -a.c / a.z
}
func main() {
r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}
fmt.Println("bottom row:", r5)
r4 := addRow(r5)
fmt.Println("next row up:", r4)
r3 := addRow(r4)
fmt.Println("middle row:", r3)
xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})
fmt.Println("xyz relation:", xyz)
r3[2] = substZ(r3[2], xyz)
fmt.Println("middle row after substituting for z:", r3)
b := expr{c: 40}
xy := subExpr(r3[0], b)
fmt.Println("xy relation:", xy)
r3[0] = b
r3[2] = substX(r3[2], xy)
fmt.Println("middle row after substituting for x:", r3)
r2 := addRow(r3)
fmt.Println("next row up:", r2)
r1 := addRow(r2)
fmt.Println("top row:", r1)
y := subExpr(r1[0], expr{c: 151})
fmt.Println("y relation:", y)
x := substY(xy, y)
fmt.Println("x relation:", x)
z := substX(substY(xyz, y), x)
fmt.Println("z relation:", z)
fmt.Println("x =", solveX(x))
fmt.Println("y =", solveY(y))
fmt.Println("z =", solveZ(z))
}
| #include <iostream>
#include <iomanip>
inline int sign(int i) {
return i < 0 ? -1 : i > 0;
}
inline int& E(int *x, int row, int col) {
return x[row * (row + 1) / 2 + col];
}
int iter(int *v, int *diff) {
E(v, 0, 0) = 151;
E(v, 2, 0) = 40;
E(v, 4, 1) = 11;
E(v, 4, 3) = 4;
for (auto i = 1u; i < 5u; i++)
for (auto j = 0u; j <= i; j++) {
E(diff, i, j) = 0;
if (j < i)
E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);
if (j)
E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);
}
for (auto i = 0u; i < 4u; i++)
for (auto j = 0u; j < i; j++)
E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);
E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);
uint sum;
int e = 0;
for (auto i = sum = 0u; i < 15u; i++) {
sum += !!sign(e = diff[i]);
if (e >= 4 || e <= -4)
v[i] += e / 5;
else if (rand() < RAND_MAX / 4)
v[i] += sign(e);
}
return sum;
}
void show(int *x) {
for (auto i = 0u; i < 5u; i++)
for (auto j = 0u; j <= i; j++)
std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n');
}
int main() {
int v[15] = { 0 }, diff[15] = { 0 };
for (auto i = 1u, s = 1u; s; i++) {
s = iter(v, diff);
std::cout << "pass " << i << ": " << s << std::endl;
}
show(v);
return 0;
}
|
Convert this Go block to C++, preserving its control flow and logic. | package main
import "fmt"
type expr struct {
x, y, z float64
c float64
}
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
func subExpr(a, b expr) expr {
return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}
func mulExpr(a expr, c float64) expr {
return expr{a.x * c, a.y * c, a.z * c, a.c * c}
}
func addRow(l []expr) []expr {
if len(l) == 0 {
panic("wrong")
}
r := make([]expr, len(l)-1)
for i := range r {
r[i] = addExpr(l[i], l[i+1])
}
return r
}
func substX(a, b expr) expr {
if b.x == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.x/b.x))
}
func substY(a, b expr) expr {
if b.y == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.y/b.y))
}
func substZ(a, b expr) expr {
if b.z == 0 {
panic("wrong")
}
return subExpr(a, mulExpr(b, a.z/b.z))
}
func solveX(a expr) float64 {
if a.x == 0 || a.y != 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.x
}
func solveY(a expr) float64 {
if a.x != 0 || a.y == 0 || a.z != 0 {
panic("wrong")
}
return -a.c / a.y
}
func solveZ(a expr) float64 {
if a.x != 0 || a.y != 0 || a.z == 0 {
panic("wrong")
}
return -a.c / a.z
}
func main() {
r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}
fmt.Println("bottom row:", r5)
r4 := addRow(r5)
fmt.Println("next row up:", r4)
r3 := addRow(r4)
fmt.Println("middle row:", r3)
xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})
fmt.Println("xyz relation:", xyz)
r3[2] = substZ(r3[2], xyz)
fmt.Println("middle row after substituting for z:", r3)
b := expr{c: 40}
xy := subExpr(r3[0], b)
fmt.Println("xy relation:", xy)
r3[0] = b
r3[2] = substX(r3[2], xy)
fmt.Println("middle row after substituting for x:", r3)
r2 := addRow(r3)
fmt.Println("next row up:", r2)
r1 := addRow(r2)
fmt.Println("top row:", r1)
y := subExpr(r1[0], expr{c: 151})
fmt.Println("y relation:", y)
x := substY(xy, y)
fmt.Println("x relation:", x)
z := substX(substY(xyz, y), x)
fmt.Println("z relation:", z)
fmt.Println("x =", solveX(x))
fmt.Println("y =", solveY(y))
fmt.Println("z =", solveZ(z))
}
| #include <iostream>
#include <iomanip>
inline int sign(int i) {
return i < 0 ? -1 : i > 0;
}
inline int& E(int *x, int row, int col) {
return x[row * (row + 1) / 2 + col];
}
int iter(int *v, int *diff) {
E(v, 0, 0) = 151;
E(v, 2, 0) = 40;
E(v, 4, 1) = 11;
E(v, 4, 3) = 4;
for (auto i = 1u; i < 5u; i++)
for (auto j = 0u; j <= i; j++) {
E(diff, i, j) = 0;
if (j < i)
E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);
if (j)
E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);
}
for (auto i = 0u; i < 4u; i++)
for (auto j = 0u; j < i; j++)
E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);
E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);
uint sum;
int e = 0;
for (auto i = sum = 0u; i < 15u; i++) {
sum += !!sign(e = diff[i]);
if (e >= 4 || e <= -4)
v[i] += e / 5;
else if (rand() < RAND_MAX / 4)
v[i] += sign(e);
}
return sum;
}
void show(int *x) {
for (auto i = 0u; i < 5u; i++)
for (auto j = 0u; j <= i; j++)
std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n');
}
int main() {
int v[15] = { 0 }, diff[15] = { 0 };
for (auto i = 1u, s = 1u; s; i++) {
s = iter(v, diff);
std::cout << "pass " << i << ": " << s << std::endl;
}
show(v);
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Go. | package main
import (
"fmt"
"math/big"
)
var (
zero = new(big.Int)
prod = new(big.Int)
fact = new(big.Int)
)
func ccFactors(n, m uint64) (*big.Int, bool) {
prod.SetUint64(6*m + 1)
if !prod.ProbablyPrime(0) {
return zero, false
}
fact.SetUint64(12*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
for i := uint64(1); i <= n-2; i++ {
fact.SetUint64((1<<i)*9*m + 1)
if !fact.ProbablyPrime(0) {
return zero, false
}
prod.Mul(prod, fact)
}
return prod, true
}
func ccNumbers(start, end uint64) {
for n := start; n <= end; n++ {
m := uint64(1)
if n > 4 {
m = 1 << (n - 4)
}
for {
num, ok := ccFactors(n, m)
if ok {
fmt.Printf("a(%d) = %d\n", n, num)
break
}
if n <= 4 {
m++
} else {
m += 1 << (n - 4)
}
}
}
}
func main() {
ccNumbers(3, 9)
}
| #include <gmp.h>
#include <iostream>
using namespace std;
typedef unsigned long long int u64;
bool primality_pretest(u64 k) {
if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) ||
!(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)
) {
return (k <= 23);
}
return true;
}
bool probprime(u64 k, mpz_t n) {
mpz_set_ui(n, k);
return mpz_probab_prime_p(n, 0);
}
bool is_chernick(int n, u64 m, mpz_t z) {
if (!primality_pretest(6 * m + 1)) {
return false;
}
if (!primality_pretest(12 * m + 1)) {
return false;
}
u64 t = 9 * m;
for (int i = 1; i <= n - 2; i++) {
if (!primality_pretest((t << i) + 1)) {
return false;
}
}
if (!probprime(6 * m + 1, z)) {
return false;
}
if (!probprime(12 * m + 1, z)) {
return false;
}
for (int i = 1; i <= n - 2; i++) {
if (!probprime((t << i) + 1, z)) {
return false;
}
}
return true;
}
int main() {
mpz_t z;
mpz_inits(z, NULL);
for (int n = 3; n <= 10; n++) {
u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;
if (n > 5) {
multiplier *= 5;
}
for (u64 k = 1; ; k++) {
u64 m = k * multiplier;
if (is_chernick(n, m, z)) {
cout << "a(" << n << ") has m = " << m << endl;
break;
}
}
}
return 0;
}
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
}
| #include <iostream>
const double EPS = 0.001;
const double EPS_SQUARE = EPS * EPS;
double side(double x1, double y1, double x2, double y2, double x, double y) {
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);
}
bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;
double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;
double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double xMin = std::min(x1, std::min(x2, x3)) - EPS;
double xMax = std::max(x1, std::max(x2, x3)) + EPS;
double yMin = std::min(y1, std::min(y2, y3)) - EPS;
double yMax = std::max(y1, std::max(y2, y3)) + EPS;
return !(x < xMin || xMax < x || y < yMin || yMax < y);
}
double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {
double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;
if (dotProduct < 0) {
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
} else if (dotProduct <= 1) {
double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
} else {
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
}
bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {
return false;
}
if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
return true;
}
if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {
return true;
}
return false;
}
void printPoint(double x, double y) {
std::cout << '(' << x << ", " << y << ')';
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
std::cout << "Triangle is [";
printPoint(x1, y1);
std::cout << ", ";
printPoint(x2, y2);
std::cout << ", ";
printPoint(x3, y3);
std::cout << "]\n";
}
void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
printTriangle(x1, y1, x2, y2, x3, y3);
std::cout << "Point ";
printPoint(x, y);
std::cout << " is within triangle? ";
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
std::cout << "true\n";
} else {
std::cout << "false\n";
}
}
int main() {
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
return 0;
}
|
Please provide an equivalent version of this Go code in C++. | package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
}
| #include <iostream>
const double EPS = 0.001;
const double EPS_SQUARE = EPS * EPS;
double side(double x1, double y1, double x2, double y2, double x, double y) {
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);
}
bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;
double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;
double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double xMin = std::min(x1, std::min(x2, x3)) - EPS;
double xMax = std::max(x1, std::max(x2, x3)) + EPS;
double yMin = std::min(y1, std::min(y2, y3)) - EPS;
double yMax = std::max(y1, std::max(y2, y3)) + EPS;
return !(x < xMin || xMax < x || y < yMin || yMax < y);
}
double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {
double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;
if (dotProduct < 0) {
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
} else if (dotProduct <= 1) {
double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
} else {
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
}
bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {
return false;
}
if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
return true;
}
if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {
return true;
}
return false;
}
void printPoint(double x, double y) {
std::cout << '(' << x << ", " << y << ')';
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
std::cout << "Triangle is [";
printPoint(x1, y1);
std::cout << ", ";
printPoint(x2, y2);
std::cout << ", ";
printPoint(x3, y3);
std::cout << "]\n";
}
void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
printTriangle(x1, y1, x2, y2, x3, y3);
std::cout << "Point ";
printPoint(x, y);
std::cout << " is within triangle? ";
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
std::cout << "true\n";
} else {
std::cout << "false\n";
}
}
int main() {
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
return 0;
}
|
Port the following code from Go to C++ with equivalent syntax and logic. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The tau functions for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%2d ", countDivisors(i))
if i%20 == 0 {
fmt.Println()
}
}
}
| #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(3) << divisor_count(n);
if (n % 20 == 0)
std::cout << '\n';
}
}
|
Change the programming language of this snippet from Go to C++ without modifying what it does. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
return count
}
func main() {
fmt.Println("The tau functions for the first 100 positive integers are:")
for i := 1; i <= 100; i++ {
fmt.Printf("%2d ", countDivisors(i))
if i%20 == 0 {
fmt.Println()
}
}
}
| #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(3) << divisor_count(n);
if (n % 20 == 0)
std::cout << '\n';
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.