Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert this VB block to AWK, preserving its control flow and logic.
Dim fact() nn1=9 : nn2=12 lim=1499999 ReDim fact(nn2) fact(0)=1 For i=1 To nn2 fact(i)=fact(i-1)*i Next For base=nn1 To nn2 list="" For i=1 To lim s=0 t=i Do While t<>0 d=t Mod base s=s+fact(d) t=t\base Loop If s=i Then list=list &" "& i Next Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list Next
BEGIN { fact[0] = 1 for (n=1; n<12; ++n) { fact[n] = fact[n-1] * n } for (b=9; b<=12; ++b) { printf("base %d factorions:",b) for (i=1; i<1500000; ++i) { sum = 0 j = i while (j > 0) { d = j % b sum += fact[d] j = int(j/b) } if (sum == i) { printf(" %d",i) } } printf("\n") } exit(0) }
Convert this VB snippet to AWK and keep its semantics consistent.
Module Module1 Sub Print(ls As List(Of Integer)) Dim iter = ls.GetEnumerator Console.Write("[") If iter.MoveNext Then Console.Write(iter.Current) End If While iter.MoveNext Console.Write(", ") Console.Write(iter.Current) End While Console.WriteLine("]") End Sub Function CastOut(base As Integer, start As Integer, last As Integer) As List(Of Integer) Dim ran = Enumerable.Range(0, base - 1).Where(Function(y) y Mod (base - 1) = (y * y) Mod (base - 1)).ToArray() Dim x = start \ (base - 1) Dim result As New List(Of Integer) While True For Each n In ran Dim k = (base - 1) * x + n If k < start Then Continue For End If If k > last Then Return result End If result.Add(k) Next x += 1 End While Return result End Function Sub Main() Print(CastOut(16, 1, 255)) Print(CastOut(10, 1, 99)) Print(CastOut(17, 1, 288)) End Sub End Module
BEGIN { base = 10 for (k=1; k<=base^2; k++) { c1++ if (k % (base-1) == (k*k) % (base-1)) { c2++ printf("%d ",k) } } printf("\nTrying %d numbers instead of %d numbers saves %.2f%%\n",c2,c1,100-(100*c2/c1)) exit(0) }
Please provide an equivalent version of this VB code in AWK.
Module Module1 Sub Print(ls As List(Of Integer)) Dim iter = ls.GetEnumerator Console.Write("[") If iter.MoveNext Then Console.Write(iter.Current) End If While iter.MoveNext Console.Write(", ") Console.Write(iter.Current) End While Console.WriteLine("]") End Sub Function CastOut(base As Integer, start As Integer, last As Integer) As List(Of Integer) Dim ran = Enumerable.Range(0, base - 1).Where(Function(y) y Mod (base - 1) = (y * y) Mod (base - 1)).ToArray() Dim x = start \ (base - 1) Dim result As New List(Of Integer) While True For Each n In ran Dim k = (base - 1) * x + n If k < start Then Continue For End If If k > last Then Return result End If result.Add(k) Next x += 1 End While Return result End Function Sub Main() Print(CastOut(16, 1, 255)) Print(CastOut(10, 1, 99)) Print(CastOut(17, 1, 288)) End Sub End Module
BEGIN { base = 10 for (k=1; k<=base^2; k++) { c1++ if (k % (base-1) == (k*k) % (base-1)) { c2++ printf("%d ",k) } } printf("\nTrying %d numbers instead of %d numbers saves %.2f%%\n",c2,c1,100-(100*c2/c1)) exit(0) }
Write a version of this VB function in AWK with identical behavior.
Public Sub Main() Print "The tau functions for the first 100 positive integers are:\n" For i As Integer = 1 To 100 Print Format$(numdiv(i), "####"); If i Mod 10 = 0 Then Print Next End Public Function numdiv(n As Integer) As Integer Dim c As Integer = 1 For i As Integer = 1 To (n + 1) \ 2 If n Mod i = 0 Then c += 1 Next If n = 1 Then c -= 1 Return c End Function
BEGIN { print("The tau functions for the first 100 positive integers:") for (i=1; i<=100; i++) { printf("%2d ",count_divisors(i)) if (i % 10 == 0) { printf("\n") } } exit(0) } function count_divisors(n, count,i) { for (i=1; i*i<=n; i++) { if (n % i == 0) { count += (i == n / i) ? 1 : 2 } } return(count) }
Keep all operations the same but rewrite the snippet in AWK.
Public Sub Main() Print "The tau functions for the first 100 positive integers are:\n" For i As Integer = 1 To 100 Print Format$(numdiv(i), "####"); If i Mod 10 = 0 Then Print Next End Public Function numdiv(n As Integer) As Integer Dim c As Integer = 1 For i As Integer = 1 To (n + 1) \ 2 If n Mod i = 0 Then c += 1 Next If n = 1 Then c -= 1 Return c End Function
BEGIN { print("The tau functions for the first 100 positive integers:") for (i=1; i<=100; i++) { printf("%2d ",count_divisors(i)) if (i % 10 == 0) { printf("\n") } } exit(0) } function count_divisors(n, count,i) { for (i=1; i*i<=n; i++) { if (n % i == 0) { count += (i == n / i) ? 1 : 2 } } return(count) }
Convert this VB snippet to AWK and keep its semantics consistent.
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 If newd < 0 Then newd = (newd Mod 256) + 256 d(dp) = Chr(newd) Case ">" dp = dp + 1 If dp > UBound(d) Then ReDim Preserve d(UBound(d) + 1) d(dp) = Chr(0) End If Case "<" dp = dp - 1 Case "." o = o & d(dp) Case "," If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1) Case "[" If Asc(d(dp)) = 0 Then bracket = 1 While bracket And sp < Len(s) sp = sp + 1 If Mid(s, sp + 1, 1) = "[" Then bracket = bracket + 1 ElseIf Mid(s, sp + 1, 1) = "]" Then bracket = bracket - 1 End If WEnd Else pos = sp - 1 sp = sp + 1 If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos End If Case "]" BFInpt = Asc(d(dp)) <> 0 Exit Function End Select sp = sp + 1 WEnd End Function Function BFuck(source, input) Dim data() : ReDim data(0) data(0) = Chr(0) DataPtr = 0 SrcPtr = 0 InputPtr = 0 output = "" BFInpt source , SrcPtr , _ data , DataPtr , _ input , InputPtr , _ output BFuck = output End Function code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _ ">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++." inpstr = "" WScript.StdOut.Write BFuck(code, inpstr)
BEGIN { bf=ARGV[1]; ARGV[1] = "" compile(bf) execute() } function compile(s, i,j,k,f) { c = split(s, src, "") j = 0 for(i = 1; i <= c; i++) { if(src[i] ~ /[\-\+\[\]\<\>,\.]/) code[j++] = src[i] if(src[i] == "[") { marks[j] = 1 } else if(src[i] == "]") { f = 0 for(k = j; k > 0; k--) { if(k in marks) { jump[k-1] = j - 1 jump[j-1] = k - 1 f = 1 delete marks[k] break } } if(!f) { print "Unmatched ]" exit 1 } } } } function execute( pc,p,i) { pc = p = 0 while(pc in code) { i = code[pc] if(i == "+") arena[p]++ else if(i == "-") arena[p]-- else if(i == "<") p-- else if(i == ">") p++ else if(i == ".") printf("%c", arena[p]) else if(i == ",") { while(1) { if (goteof) break if (!gotline) { gotline = getline if(!gotline) goteof = 1 if (goteof) break line = $0 } if (line == "") { gotline=0 m[p]=10 break } if (!genord) { for(i=1; i<256; i++) ord[sprintf("%c",i)] = i genord=1 } c = substr(line, 1, 1) line=substr(line, 2) arena[p] = ord[c] break } } else if((i == "[" && arena[p] == 0) || (i == "]" && arena[p] != 0)) pc = jump[pc] pc++ } }
Translate the given VB code snippet into AWK without altering its behavior.
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 If newd < 0 Then newd = (newd Mod 256) + 256 d(dp) = Chr(newd) Case ">" dp = dp + 1 If dp > UBound(d) Then ReDim Preserve d(UBound(d) + 1) d(dp) = Chr(0) End If Case "<" dp = dp - 1 Case "." o = o & d(dp) Case "," If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1) Case "[" If Asc(d(dp)) = 0 Then bracket = 1 While bracket And sp < Len(s) sp = sp + 1 If Mid(s, sp + 1, 1) = "[" Then bracket = bracket + 1 ElseIf Mid(s, sp + 1, 1) = "]" Then bracket = bracket - 1 End If WEnd Else pos = sp - 1 sp = sp + 1 If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos End If Case "]" BFInpt = Asc(d(dp)) <> 0 Exit Function End Select sp = sp + 1 WEnd End Function Function BFuck(source, input) Dim data() : ReDim data(0) data(0) = Chr(0) DataPtr = 0 SrcPtr = 0 InputPtr = 0 output = "" BFInpt source , SrcPtr , _ data , DataPtr , _ input , InputPtr , _ output BFuck = output End Function code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _ ">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++." inpstr = "" WScript.StdOut.Write BFuck(code, inpstr)
BEGIN { bf=ARGV[1]; ARGV[1] = "" compile(bf) execute() } function compile(s, i,j,k,f) { c = split(s, src, "") j = 0 for(i = 1; i <= c; i++) { if(src[i] ~ /[\-\+\[\]\<\>,\.]/) code[j++] = src[i] if(src[i] == "[") { marks[j] = 1 } else if(src[i] == "]") { f = 0 for(k = j; k > 0; k--) { if(k in marks) { jump[k-1] = j - 1 jump[j-1] = k - 1 f = 1 delete marks[k] break } } if(!f) { print "Unmatched ]" exit 1 } } } } function execute( pc,p,i) { pc = p = 0 while(pc in code) { i = code[pc] if(i == "+") arena[p]++ else if(i == "-") arena[p]-- else if(i == "<") p-- else if(i == ">") p++ else if(i == ".") printf("%c", arena[p]) else if(i == ",") { while(1) { if (goteof) break if (!gotline) { gotline = getline if(!gotline) goteof = 1 if (goteof) break line = $0 } if (line == "") { gotline=0 m[p]=10 break } if (!genord) { for(i=1; i<256; i++) ord[sprintf("%c",i)] = i genord=1 } c = substr(line, 1, 1) line=substr(line, 2) arena[p] = ord[c] break } } else if((i == "[" && arena[p] == 0) || (i == "]" && arena[p] != 0)) pc = jump[pc] pc++ } }
Convert this VB block to AWK, preserving its control flow and logic.
Function F(i,n) Dim c: c=CCur(i): If n>Len(c) Then F=Space(n-Len(c))&c Else F=c End Function Function Fact(ByVal n) Dim res If n=0 Then Fact = 1 Else res = 1 While n>0 res = res*n n = n-1 Wend Fact = res End If End Function Function Lah(n, k) If k=1 Then Lah = Fact(n) ElseIf k=n Then Lah = 1 ElseIf k>n Then Lah=0 ElseIf k < 1 Or n < 1 Then Lah = 0 Else Lah = (Fact(n) * Fact(n-1)) / (Fact(k) * Fact(k-1)) / Fact(n-k) End If End Function Sub Main() ns=12: p=10 WScript.Echo "Unsigned Lah numbers: Lah(n,k):" buf = "n/k " For k=1 To ns buf = buf & F(k,p) & " " Next WScript.Echo buf For n=1 To ns buf = F(n,3) & " " For k=1 To n l = Lah(n,k) buf = buf & F(l,p) & " " Next WScript.Echo buf Next End Sub Main()
BEGIN { print("unsigned Lah numbers: L(n,k)") printf("n/k") for (i=0; i<13; i++) { printf("%11d",i) } printf("\n") for (row=0; row<13; row++) { printf("%-3d",row) for (i=0; i<row+1; i++) { printf(" %10d",lah(row,i)) } printf("\n") } exit(0) } function factorial(n, res) { res = 1 if (n == 0) { return(res) } while (n > 0) { res *= n-- } return(res) } function lah(n,k) { if (k == 1) { return factorial(n) } if (k == n) { return(1) } if (k > n) { return(0) } if (k < 1 || n < 1) { return(0) } return (factorial(n) * factorial(n-1)) / (factorial(k) * factorial(k-1)) / factorial(n-k) }
Port the following code from VB to AWK with equivalent syntax and logic.
Function F(i,n) Dim c: c=CCur(i): If n>Len(c) Then F=Space(n-Len(c))&c Else F=c End Function Function Fact(ByVal n) Dim res If n=0 Then Fact = 1 Else res = 1 While n>0 res = res*n n = n-1 Wend Fact = res End If End Function Function Lah(n, k) If k=1 Then Lah = Fact(n) ElseIf k=n Then Lah = 1 ElseIf k>n Then Lah=0 ElseIf k < 1 Or n < 1 Then Lah = 0 Else Lah = (Fact(n) * Fact(n-1)) / (Fact(k) * Fact(k-1)) / Fact(n-k) End If End Function Sub Main() ns=12: p=10 WScript.Echo "Unsigned Lah numbers: Lah(n,k):" buf = "n/k " For k=1 To ns buf = buf & F(k,p) & " " Next WScript.Echo buf For n=1 To ns buf = F(n,3) & " " For k=1 To n l = Lah(n,k) buf = buf & F(l,p) & " " Next WScript.Echo buf Next End Sub Main()
BEGIN { print("unsigned Lah numbers: L(n,k)") printf("n/k") for (i=0; i<13; i++) { printf("%11d",i) } printf("\n") for (row=0; row<13; row++) { printf("%-3d",row) for (i=0; i<row+1; i++) { printf(" %10d",lah(row,i)) } printf("\n") } exit(0) } function factorial(n, res) { res = 1 if (n == 0) { return(res) } while (n > 0) { res *= n-- } return(res) } function lah(n,k) { if (k == 1) { return factorial(n) } if (k == n) { return(1) } if (k > n) { return(0) } if (k < 1 || n < 1) { return(0) } return (factorial(n) * factorial(n-1)) / (factorial(k) * factorial(k-1)) / factorial(n-k) }
Change the following VB code into AWK without altering its purpose.
Option Explicit Function two_sum(a As Variant, t As Integer) As Variant Dim i, j As Integer i = 0 j = UBound(a) Do While (i < j) If (a(i) + a(j) = t) Then two_sum = Array(i, j) Exit Function ElseIf (a(i) + a(j) < t) Then i = i + 1 ElseIf (a(i) + a(j) > t) Then j = j - 1 End If Loop two_sum = Array() End Function Sub prnt(a As Variant) If UBound(a) = 1 Then Selection.TypeText Text:="(" & a(0) & ", " & a(1) & ")" & vbCrLf Else Selection.TypeText Text:="()" & vbCrLf End If End Sub Sub main() Call prnt(two_sum(Array(0, 2, 11, 19, 90), 21)) Call prnt(two_sum(Array(-8, -2, 0, 1, 5, 8, 11), 3)) Call prnt(two_sum(Array(-3, -2, 0, 1, 5, 8, 11), 17)) Call prnt(two_sum(Array(-8, -2, -1, 1, 5, 9, 11), 0)) End Sub
BEGIN { numbers = "0,2,11,19,90" print(two_sum(numbers,21)) print(two_sum(numbers,25)) exit(0) } function two_sum(numbers,sum, arr,i,j,s) { i = 1 j = split(numbers,arr,",") while (i < j) { s = arr[i] + arr[j] if (s == sum) { return(sprintf("[%d,%d]",i,j)) } else if (s < sum) { i++ } else { j-- } } return("[]") }
Rewrite this program in AWK while keeping its functionality equivalent to the VB version.
Option Explicit Function two_sum(a As Variant, t As Integer) As Variant Dim i, j As Integer i = 0 j = UBound(a) Do While (i < j) If (a(i) + a(j) = t) Then two_sum = Array(i, j) Exit Function ElseIf (a(i) + a(j) < t) Then i = i + 1 ElseIf (a(i) + a(j) > t) Then j = j - 1 End If Loop two_sum = Array() End Function Sub prnt(a As Variant) If UBound(a) = 1 Then Selection.TypeText Text:="(" & a(0) & ", " & a(1) & ")" & vbCrLf Else Selection.TypeText Text:="()" & vbCrLf End If End Sub Sub main() Call prnt(two_sum(Array(0, 2, 11, 19, 90), 21)) Call prnt(two_sum(Array(-8, -2, 0, 1, 5, 8, 11), 3)) Call prnt(two_sum(Array(-3, -2, 0, 1, 5, 8, 11), 17)) Call prnt(two_sum(Array(-8, -2, -1, 1, 5, 9, 11), 0)) End Sub
BEGIN { numbers = "0,2,11,19,90" print(two_sum(numbers,21)) print(two_sum(numbers,25)) exit(0) } function two_sum(numbers,sum, arr,i,j,s) { i = 1 j = split(numbers,arr,",") while (i < j) { s = arr[i] + arr[j] if (s == sum) { return(sprintf("[%d,%d]",i,j)) } else if (s < sum) { i++ } else { j-- } } return("[]") }
Maintain the same structure and functionality when rewriting this code in AWK.
print "The first 100 tau numbers are:" n = 0 num = 0 limit = 100 while num < limit n = n +1 tau = 0 for m = 1 to n if n mod m = 0 then tau = tau +1 next m if n mod tau = 0 then num = num +1 if num mod 10 = 1 then print print using("######", n); end if wend end
BEGIN { print("The first 100 tau numbers:") while (count < 100) { i++ if (i % count_divisors(i) == 0) { printf("%4d ",i) if (++count % 10 == 0) { printf("\n") } } } exit(0) } function count_divisors(n, count,i) { for (i=1; i*i<=n; i++) { if (n % i == 0) { count += (i == n / i) ? 1 : 2 } } return(count) }
Keep all operations the same but rewrite the snippet in AWK.
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
BEGIN { for (i=1; i<=1000000; i++) { if (prime_digits_sum13(i)) { printf("%6d ",i) if (++count % 10 == 0) { printf("\n") } } } printf("\n") exit(0) } function prime_digits_sum13(n, r,sum) { while (n > 0) { r = int(n % 10) switch (r) { case 2: case 3: case 5: case 7: break default: return(0) } n = int(n / 10) sum += r } return(sum == 13) }
Keep all operations the same but rewrite the snippet in AWK.
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
BEGIN { for (i=1; i<=1000000; i++) { if (prime_digits_sum13(i)) { printf("%6d ",i) if (++count % 10 == 0) { printf("\n") } } } printf("\n") exit(0) } function prime_digits_sum13(n, r,sum) { while (n > 0) { r = int(n % 10) switch (r) { case 2: case 3: case 5: case 7: break default: return(0) } n = int(n / 10) sum += r } return(sum == 13) }
Convert this VB block to AWK, preserving its control flow and logic.
Option Strict On Option Explicit On Imports System.IO Module vMain Public Sub Main Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5} For i As Integer = 0 To Ubound(s) Dim curr As Integer = s(i) Dim prev As Integer If i > 1 AndAlso curr = prev Then Console.Out.WriteLine(i) End If prev = curr Next i End Sub End Module
BEGIN { n = split("1,2,2,3,4,4,5",arr,",") for (i=1; i<=n; i++) { curr = arr[i] if (i > 1 && prev == curr) { printf("%s\n",i) } prev = curr } exit(0) }
Port the provided VB code into AWK while preserving the original functionality.
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) set d=createobject("scripting.dictionary") redim b(ubound(a)) i=0 for each x in a s=trim(x) if len(s)>=9 then if len(s)= 9 then d.add s,"" b(i)=s i=i+1 end if next redim preserve b(i-1) wscript.echo i j=1 for i=0 to ubound(b)-9 s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_ mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1) if d.exists(s9) then wscript.echo j,s9 d.remove(s9) j=j+1 end if next
{ if (length($0) < 9) { next } arr1[++n] = $0 arr2[$0] = "" } END { for (i=1; i<=n; i++) { word = substr(arr1[i],1,1) for (j=2; j<=9; j++) { if (!((i+j) in arr1)) { continue } word = word substr(arr1[i+j],j,1) } if (word in arr2) { printf("%s\n",word) delete arr2[word] } } exit(0) }
Convert this VB snippet to AWK and keep its semantics consistent.
Imports System.Linq Imports System.Collections.Generic Imports System.Console Imports System.Math Module Module1 Dim ba As Integer Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer) Dim flags(lim) As Boolean, j As Integer : Yield 2 For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3 Dim d As Integer = 8, sq As Integer = 9 While sq <= lim If Not flags(j) Then Yield j : Dim i As Integer = j << 1 For k As Integer = sq To lim step i : flags(k) = True : Next End If j += 2 : d += 8 : sq += d : End While While j <= lim If Not flags(j) Then Yield j j += 2 : End While End Function Function from10(ByVal b As Integer) As String Dim res As String = "", re As Integer While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res End Function Function to10(ByVal s As String) As Integer Dim res As Integer = 0 For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res End Function Function nd(ByVal s As String) As Boolean If s.Length < 2 Then Return True Dim l As Char = s(0) For i As Integer = 1 To s.Length - 1 If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i) Next : Return True End Function Sub Main(ByVal args As String()) Dim c As Integer, lim As Integer = 1000, s As String For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 } ba = b : c = 0 : For Each a As Integer In Primes(lim) s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, "")) Next WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim)) Next End Sub End Module
BEGIN { start = 1 stop = 1000 for (i=start; i<=stop; i++) { if (is_prime(i)) { flag = 1 for (j=1; j<length(i); j++) { if (substr(i,j,1) > substr(i,j+1,1)) { flag = 0 } } if (flag == 1) { printf("%4d%1s",i,++count%10?"":"\n") } } } printf("\nPrimes with digits in nondecreasing order %d-%d: %d\n",start,stop,count) exit(0) } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) }
Convert the following code from VB to AWK, ensuring the logic remains intact.
Imports System.Linq Imports System.Collections.Generic Imports System.Console Imports System.Math Module Module1 Dim ba As Integer Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer) Dim flags(lim) As Boolean, j As Integer : Yield 2 For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3 Dim d As Integer = 8, sq As Integer = 9 While sq <= lim If Not flags(j) Then Yield j : Dim i As Integer = j << 1 For k As Integer = sq To lim step i : flags(k) = True : Next End If j += 2 : d += 8 : sq += d : End While While j <= lim If Not flags(j) Then Yield j j += 2 : End While End Function Function from10(ByVal b As Integer) As String Dim res As String = "", re As Integer While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res End Function Function to10(ByVal s As String) As Integer Dim res As Integer = 0 For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res End Function Function nd(ByVal s As String) As Boolean If s.Length < 2 Then Return True Dim l As Char = s(0) For i As Integer = 1 To s.Length - 1 If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i) Next : Return True End Function Sub Main(ByVal args As String()) Dim c As Integer, lim As Integer = 1000, s As String For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 } ba = b : c = 0 : For Each a As Integer In Primes(lim) s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, "")) Next WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim)) Next End Sub End Module
BEGIN { start = 1 stop = 1000 for (i=start; i<=stop; i++) { if (is_prime(i)) { flag = 1 for (j=1; j<length(i); j++) { if (substr(i,j,1) > substr(i,j+1,1)) { flag = 0 } } if (flag == 1) { printf("%4d%1s",i,++count%10?"":"\n") } } } printf("\nPrimes with digits in nondecreasing order %d-%d: %d\n",start,stop,count) exit(0) } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) }
Translate the given VB code snippet into AWK without altering its behavior.
Public Sub Main() Dim h As Float = 0 Dim n As Integer, i As Integer Print "The first twenty harmonic numbers are:" For n = 1 To 20 h += 1 / n Print n, h Next Print h = 1 n = 2 For i = 2 To 10 While h < i h += 1 / n n += 1 Wend Print "The first harmonic number greater than "; i; " is "; h; ", at position "; n - 1 Next End
BEGIN { limit = 20 printf("The first %d harmonic numbers:\n",limit) for (n=1; n<=limit; n++) { h += 1/n printf("%2d %11.8f\n",n,h) } print("") h = 1 n = 2 for (i=2; i<=10; i++) { while (h < i) { h += 1/n n++ } printf("The first harmonic number > %2d is %11.8f at position %d\n",i,h,n-1) } exit(0) }
Write a version of this VB function in AWK with identical behavior.
Dim As Uinteger n, num Print "First 20 Cullen numbers:" For n = 1 To 20 num = n * (2^n)+1 Print num; " "; Next Print !"\n\nFirst 20 Woodall numbers:" For n = 1 To 20 num = n * (2^n)-1 Print num; " "; Next n Sleep
BEGIN { start = 1 stop = 20 printf("Cullen %d-%d:",start,stop) for (n=start; n<=stop; n++) { printf(" %d",n*(2^n)+1) } printf("\n") printf("Woodall %d-%d:",start,stop) for (n=start; n<=stop; n++) { printf(" %d",n*(2^n)-1) } printf("\n") exit(0) }
Convert this VB block to AWK, preserving its control flow and logic.
Const wheel="ndeokgelw" Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub Dim oDic Set oDic = WScript.CreateObject("scripting.dictionary") Dim cnt(127) Dim fso Set fso = WScript.CreateObject("Scripting.Filesystemobject") Set ff=fso.OpenTextFile("unixdict.txt") i=0 print "reading words of 3 or more letters" While Not ff.AtEndOfStream x=LCase(ff.ReadLine) If Len(x)>=3 Then If Not odic.exists(x) Then oDic.Add x,0 End If Wend print "remaining words: "& oDic.Count & vbcrlf ff.Close Set ff=Nothing Set fso=Nothing Set re=New RegExp print "removing words with chars not in the wheel" re.pattern="[^"& wheel &"]" For Each w In oDic.Keys If re.test(w) Then oDic.remove(w) Next print "remaining words: "& oDic.Count & vbcrlf print "ensuring the mandatory letter "& Mid(wheel,5,1) & " is present" re.Pattern=Mid(wheel,5,1) For Each w In oDic.Keys If Not re.test(w) Then oDic.remove(w) Next print "remaining words: "& oDic.Count & vbcrlf print "checking number of chars" Dim nDic Set nDic = WScript.CreateObject("scripting.dictionary") For i=1 To Len(wheel) x=Mid(wheel,i,1) If nDic.Exists(x) Then a=nDic(x) nDic(x)=Array(a(0)+1,0) Else nDic.add x,Array(1,0) End If Next For Each w In oDic.Keys For Each c In nDic.Keys ndic(c)=Array(nDic(c)(0),0) Next For ii = 1 To len(w) c=Mid(w,ii,1) a=nDic(c) If (a(0)=a(1)) Then oDic.Remove(w):Exit For End If nDic(c)=Array(a(0),a(1)+1) Next Next print "Remaining words "& oDic.count For Each w In oDic.Keys print w Next
BEGIN { letters = tolower(ARGV[1]) required = substr(letters,1,1) size = 3 ARGV[1] = "" } { word = tolower($0) leng_word = length(word) if (word ~ required && leng_word >= size) { hits = 0 for (i=1; i<=leng_word; i++) { if (letters ~ substr(word,i,1)) { hits++ } } if (leng_word == hits && hits >= size) { for (i=1; i<=leng_word; i++) { c = substr(word,i,1) if (gsub(c,"&",word) > gsub(c,"&",letters)) { next } } words++ printf("%s ",word) } } } END { printf("\nletters: %s, '%s' required, %d words >= %d characters\n",letters,required,words,size) exit(0) }
Port the provided VB code into AWK while preserving the original functionality.
Public Sub circles() tests = [{0.1234, 0.9876, 0.8765, 0.2345, 2.0; 0.0000, 2.0000, 0.0000, 0.0000, 1.0; 0.1234, 0.9876, 0.1234, 0.9876, 2.0; 0.1234, 0.9876, 0.8765, 0.2345, 0.5; 0.1234, 0.9876, 0.1234, 0.9876, 0.0}] For i = 1 To UBound(tests) x1 = tests(i, 1) y1 = tests(i, 2) x2 = tests(i, 3) y2 = tests(i, 4) R = tests(i, 5) xd = x2 - x1 yd = y1 - y2 s2 = xd * xd + yd * yd sep = Sqr(s2) xh = (x1 + x2) / 2 yh = (y1 + y2) / 2 Dim txt As String If sep = 0 Then txt = "same points/" & IIf(R = 0, "radius is zero", "infinite solutions") Else If sep = 2 * R Then txt = "opposite ends of diameter with centre " & xh & ", " & yh & "." Else If sep > 2 * R Then txt = "too far apart " & sep & " > " & 2 * R Else md = Sqr(R * R - s2 / 4) xs = md * xd / sep ys = md * yd / sep txt = "{" & Format(xh + ys, "0.0000") & ", " & Format(yh + xs, "0.0000") & _ "} and {" & Format(xh - ys, "0.0000") & ", " & Format(yh - xs, "0.0000") & "}" End If End If End If Debug.Print "points " & "{" & x1 & ", " & y1 & "}" & ", " & "{" & x2 & ", " & y2 & "}" & " with radius " & R & " ==> " & txt Next i End Sub
BEGIN { split("0.1234,0,0.1234,0.1234,0.1234",m1x,",") split("0.9876,2,0.9876,0.9876,0.9876",m1y,",") split("0.8765,0,0.1234,0.8765,0.1234",m2x,",") split("0.2345,0,0.9876,0.2345,0.9876",m2y,",") leng = split("2,1,2,0.5,0",r,",") print(" x1 y1 x2 y2 r cir1x cir1y cir2x cir2y") print("------- ------- ------- ------- ---- ------- ------- ------- -------") for (i=1; i<=leng; i++) { printf("%7.4f %7.4f %7.4f %7.4f %4.2f %s\n",m1x[i],m1y[i],m2x[i],m2y[i],r[i],main(m1x[i],m1y[i],m2x[i],m2y[i],r[i])) } exit(0) } function main(m1x,m1y,m2x,m2y,r, bx,by,pb,x,x1,y,y1) { if (r == 0) { return("radius of zero gives no circles") } x = (m2x - m1x) / 2 y = (m2y - m1y) / 2 bx = m1x + x by = m1y + y pb = sqrt(x^2 + y^2) if (pb == 0) { return("coincident points give infinite circles") } if (pb > r) { return("points are too far apart for the given radius") } cb = sqrt(r^2 - pb^2) x1 = y * cb / pb y1 = x * cb / pb return(sprintf("%7.4f %7.4f %7.4f %7.4f",bx-x1,by+y1,bx+x1,by-y1)) }
Keep all operations the same but rewrite the snippet in AWK.
Public Sub circles() tests = [{0.1234, 0.9876, 0.8765, 0.2345, 2.0; 0.0000, 2.0000, 0.0000, 0.0000, 1.0; 0.1234, 0.9876, 0.1234, 0.9876, 2.0; 0.1234, 0.9876, 0.8765, 0.2345, 0.5; 0.1234, 0.9876, 0.1234, 0.9876, 0.0}] For i = 1 To UBound(tests) x1 = tests(i, 1) y1 = tests(i, 2) x2 = tests(i, 3) y2 = tests(i, 4) R = tests(i, 5) xd = x2 - x1 yd = y1 - y2 s2 = xd * xd + yd * yd sep = Sqr(s2) xh = (x1 + x2) / 2 yh = (y1 + y2) / 2 Dim txt As String If sep = 0 Then txt = "same points/" & IIf(R = 0, "radius is zero", "infinite solutions") Else If sep = 2 * R Then txt = "opposite ends of diameter with centre " & xh & ", " & yh & "." Else If sep > 2 * R Then txt = "too far apart " & sep & " > " & 2 * R Else md = Sqr(R * R - s2 / 4) xs = md * xd / sep ys = md * yd / sep txt = "{" & Format(xh + ys, "0.0000") & ", " & Format(yh + xs, "0.0000") & _ "} and {" & Format(xh - ys, "0.0000") & ", " & Format(yh - xs, "0.0000") & "}" End If End If End If Debug.Print "points " & "{" & x1 & ", " & y1 & "}" & ", " & "{" & x2 & ", " & y2 & "}" & " with radius " & R & " ==> " & txt Next i End Sub
BEGIN { split("0.1234,0,0.1234,0.1234,0.1234",m1x,",") split("0.9876,2,0.9876,0.9876,0.9876",m1y,",") split("0.8765,0,0.1234,0.8765,0.1234",m2x,",") split("0.2345,0,0.9876,0.2345,0.9876",m2y,",") leng = split("2,1,2,0.5,0",r,",") print(" x1 y1 x2 y2 r cir1x cir1y cir2x cir2y") print("------- ------- ------- ------- ---- ------- ------- ------- -------") for (i=1; i<=leng; i++) { printf("%7.4f %7.4f %7.4f %7.4f %4.2f %s\n",m1x[i],m1y[i],m2x[i],m2y[i],r[i],main(m1x[i],m1y[i],m2x[i],m2y[i],r[i])) } exit(0) } function main(m1x,m1y,m2x,m2y,r, bx,by,pb,x,x1,y,y1) { if (r == 0) { return("radius of zero gives no circles") } x = (m2x - m1x) / 2 y = (m2y - m1y) / 2 bx = m1x + x by = m1y + y pb = sqrt(x^2 + y^2) if (pb == 0) { return("coincident points give infinite circles") } if (pb > r) { return("points are too far apart for the given radius") } cb = sqrt(r^2 - pb^2) x1 = y * cb / pb y1 = x * cb / pb return(sprintf("%7.4f %7.4f %7.4f %7.4f",bx-x1,by+y1,bx+x1,by-y1)) }
Write the same algorithm in AWK as shown in this VB implementation.
Module Module1 Structure Interval Dim start As Integer Dim last As Integer Dim print As Boolean Sub New(s As Integer, l As Integer, p As Boolean) start = s last = l print = p End Sub End Structure Sub Main() Dim intervals As Interval() = { New Interval(2, 1_000, True), New Interval(1_000, 4_000, True), New Interval(2, 10_000, False), New Interval(2, 100_000, False), New Interval(2, 1_000_000, False), New Interval(2, 10_000_000, False), New Interval(2, 100_000_000, False), New Interval(2, 1_000_000_000, False) } For Each intv In intervals If intv.start = 2 Then Console.WriteLine("eban numbers up to and including {0}:", intv.last) Else Console.WriteLine("eban numbers between {0} and {1} (inclusive):", intv.start, intv.last) End If Dim count = 0 For i = intv.start To intv.last Step 2 Dim b = i \ 1_000_000_000 Dim r = i Mod 1_000_000_000 Dim m = r \ 1_000_000 r = i Mod 1_000_000 Dim t = r \ 1_000 r = r Mod 1_000 If m >= 30 AndAlso m <= 66 Then m = m Mod 10 End If If t >= 30 AndAlso t <= 66 Then t = t Mod 10 End If If r >= 30 AndAlso r <= 66 Then r = r Mod 10 End If If b = 0 OrElse b = 2 OrElse b = 4 OrElse b = 6 Then If m = 0 OrElse m = 2 OrElse m = 4 OrElse m = 6 Then If t = 0 OrElse t = 2 OrElse t = 4 OrElse t = 6 Then If r = 0 OrElse r = 2 OrElse r = 4 OrElse r = 6 Then If intv.print Then Console.Write("{0} ", i) End If count += 1 End If End If End If End If Next If intv.print Then Console.WriteLine() End If Console.WriteLine("count = {0}", count) Console.WriteLine() Next End Sub End Module
BEGIN { main(2,1000,1) main(1000,4000,1) main(2,10000,0) main(2,100000,0) main(2,1000000,0) main(2,10000000,0) main(2,100000000,0) exit(0) } function main(start,stop,printable, b,count,i,m,r,t) { printf("%d-%d:",start,stop) for (i=start; i<=stop; i+=2) { b = int(i / 1000000000) r = i % 1000000000 m = int(r / 1000000) r = i % 1000000 t = int(r / 1000) r = r % 1000 if (m >= 30 && m <= 66) { m %= 10 } if (t >= 30 && t <= 66) { t %= 10 } if (r >= 30 && r <= 66) { r %= 10 } if (x(b) && x(m) && x(t) && x(r)) { count++ if (printable) { printf(" %d",i) } } } printf(" (count=%d)\n",count) } function x(n) { return(n == 0 || n == 2 || n == 4 || n == 6) }
Generate a AWK translation of this VB snippet without changing its computational steps.
Module Module1 Structure Interval Dim start As Integer Dim last As Integer Dim print As Boolean Sub New(s As Integer, l As Integer, p As Boolean) start = s last = l print = p End Sub End Structure Sub Main() Dim intervals As Interval() = { New Interval(2, 1_000, True), New Interval(1_000, 4_000, True), New Interval(2, 10_000, False), New Interval(2, 100_000, False), New Interval(2, 1_000_000, False), New Interval(2, 10_000_000, False), New Interval(2, 100_000_000, False), New Interval(2, 1_000_000_000, False) } For Each intv In intervals If intv.start = 2 Then Console.WriteLine("eban numbers up to and including {0}:", intv.last) Else Console.WriteLine("eban numbers between {0} and {1} (inclusive):", intv.start, intv.last) End If Dim count = 0 For i = intv.start To intv.last Step 2 Dim b = i \ 1_000_000_000 Dim r = i Mod 1_000_000_000 Dim m = r \ 1_000_000 r = i Mod 1_000_000 Dim t = r \ 1_000 r = r Mod 1_000 If m >= 30 AndAlso m <= 66 Then m = m Mod 10 End If If t >= 30 AndAlso t <= 66 Then t = t Mod 10 End If If r >= 30 AndAlso r <= 66 Then r = r Mod 10 End If If b = 0 OrElse b = 2 OrElse b = 4 OrElse b = 6 Then If m = 0 OrElse m = 2 OrElse m = 4 OrElse m = 6 Then If t = 0 OrElse t = 2 OrElse t = 4 OrElse t = 6 Then If r = 0 OrElse r = 2 OrElse r = 4 OrElse r = 6 Then If intv.print Then Console.Write("{0} ", i) End If count += 1 End If End If End If End If Next If intv.print Then Console.WriteLine() End If Console.WriteLine("count = {0}", count) Console.WriteLine() Next End Sub End Module
BEGIN { main(2,1000,1) main(1000,4000,1) main(2,10000,0) main(2,100000,0) main(2,1000000,0) main(2,10000000,0) main(2,100000000,0) exit(0) } function main(start,stop,printable, b,count,i,m,r,t) { printf("%d-%d:",start,stop) for (i=start; i<=stop; i+=2) { b = int(i / 1000000000) r = i % 1000000000 m = int(r / 1000000) r = i % 1000000 t = int(r / 1000) r = r % 1000 if (m >= 30 && m <= 66) { m %= 10 } if (t >= 30 && t <= 66) { t %= 10 } if (r >= 30 && r <= 66) { r %= 10 } if (x(b) && x(m) && x(t) && x(r)) { count++ if (printable) { printf(" %d",i) } } } printf(" (count=%d)\n",count) } function x(n) { return(n == 0 || n == 2 || n == 4 || n == 6) }
Convert this VB block to AWK, preserving its control flow and logic.
Option Explicit Public Sub coconuts() Dim sailors As Integer Dim share As Long Dim finalshare As Integer Dim minimum As Long, pile As Long Dim i As Long, j As Integer Debug.Print "Sailors", "Pile", "Final share" For sailors = 2 To 6 i = 1 Do While True pile = i For j = 1 To sailors If (pile - 1) Mod sailors <> 0 Then Exit For share = (pile - 1) / sailors pile = pile - share - 1 Next j If j > sailors Then If share Mod sailors = 0 And share > 0 Then minimum = i finalshare = pile / sailors Exit Do End If End If i = i + 1 Loop Debug.Print sailors, minimum, finalshare Next sailors End Sub
BEGIN { for (n=2; n<=9; n++) { x = 0 while (!valid(n,x)) { x++ } printf("%d %d\n",n,x) } exit(0) } function valid(n,nuts, k) { k = n while (k != 0) { if ((nuts % n) != 1) { return(0) } k-- nuts = nuts - 1 - int(nuts / n) } return((nuts != 0) && (nuts % n == 0)) }
Preserve the algorithm and functionality while converting the code from VB to AWK.
Option Explicit Public Sub coconuts() Dim sailors As Integer Dim share As Long Dim finalshare As Integer Dim minimum As Long, pile As Long Dim i As Long, j As Integer Debug.Print "Sailors", "Pile", "Final share" For sailors = 2 To 6 i = 1 Do While True pile = i For j = 1 To sailors If (pile - 1) Mod sailors <> 0 Then Exit For share = (pile - 1) / sailors pile = pile - share - 1 Next j If j > sailors Then If share Mod sailors = 0 And share > 0 Then minimum = i finalshare = pile / sailors Exit Do End If End If i = i + 1 Loop Debug.Print sailors, minimum, finalshare Next sailors End Sub
BEGIN { for (n=2; n<=9; n++) { x = 0 while (!valid(n,x)) { x++ } printf("%d %d\n",n,x) } exit(0) } function valid(n,nuts, k) { k = n while (k != 0) { if ((nuts % n) != 1) { return(0) } k-- nuts = nuts - 1 - int(nuts / n) } return((nuts != 0) && (nuts % n == 0)) }
Write a version of this VB function in AWK with identical behavior.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1,False,0) cei = 0 : cie = 0 : ei = 0 : ie = 0 Do Until srcFile.AtEndOfStream word = srcFile.ReadLine If InStr(word,"cei") Then cei = cei + 1 ElseIf InStr(word,"cie") Then cie = cie + 1 ElseIf InStr(word,"ei") Then ei = ei + 1 ElseIf InStr(word,"ie") Then ie = ie + 1 End If Loop FirstClause = False SecondClause = False Overall = False If ie > ei*2 Then WScript.StdOut.WriteLine "I before E when not preceded by C is plausible." FirstClause = True Else WScript.StdOut.WriteLine "I before E when not preceded by C is NOT plausible." End If If cei > cie*2 Then WScript.StdOut.WriteLine "E before I when not preceded by C is plausible." SecondClause = True Else WScript.StdOut.WriteLine "E before I when not preceded by C is NOT plausible." End If If FirstClause And SecondClause Then WScript.StdOut.WriteLine "Overall it is plausible." Else WScript.StdOut.WriteLine "Overall it is NOT plausible." End If srcFile.Close Set objFSO = Nothing
/.ei/ {nei+=cnt($3)} /cei/ {cei+=cnt($3)} /.ie/ {nie+=cnt($3)} /cie/ {cie+=cnt($3)} function cnt(c) { if (c<1) return 1; return c; } END { printf("cie: %i\nnie: %i\ncei: %i\nnei: %i\n",cie,nie-cie,cei,nei-cei); v = v2 = ""; if (nie < 3 * cie) { v =" not"; } print "I before E when not preceded by C: is"v" plausible"; if (nei > 3 * cei) { v = v2 =" not"; } print "E before I when preceded by C: is"v2" plausible"; print "Overall rule is"v" plausible"; }
Convert this VB snippet to AWK and keep its semantics consistent.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1,False,0) cei = 0 : cie = 0 : ei = 0 : ie = 0 Do Until srcFile.AtEndOfStream word = srcFile.ReadLine If InStr(word,"cei") Then cei = cei + 1 ElseIf InStr(word,"cie") Then cie = cie + 1 ElseIf InStr(word,"ei") Then ei = ei + 1 ElseIf InStr(word,"ie") Then ie = ie + 1 End If Loop FirstClause = False SecondClause = False Overall = False If ie > ei*2 Then WScript.StdOut.WriteLine "I before E when not preceded by C is plausible." FirstClause = True Else WScript.StdOut.WriteLine "I before E when not preceded by C is NOT plausible." End If If cei > cie*2 Then WScript.StdOut.WriteLine "E before I when not preceded by C is plausible." SecondClause = True Else WScript.StdOut.WriteLine "E before I when not preceded by C is NOT plausible." End If If FirstClause And SecondClause Then WScript.StdOut.WriteLine "Overall it is plausible." Else WScript.StdOut.WriteLine "Overall it is NOT plausible." End If srcFile.Close Set objFSO = Nothing
/.ei/ {nei+=cnt($3)} /cei/ {cei+=cnt($3)} /.ie/ {nie+=cnt($3)} /cie/ {cie+=cnt($3)} function cnt(c) { if (c<1) return 1; return c; } END { printf("cie: %i\nnie: %i\ncei: %i\nnei: %i\n",cie,nie-cie,cei,nei-cei); v = v2 = ""; if (nie < 3 * cie) { v =" not"; } print "I before E when not preceded by C: is"v" plausible"; if (nei > 3 * cei) { v = v2 =" not"; } print "E before I when preceded by C: is"v2" plausible"; print "Overall rule is"v" plausible"; }
Can you help me rewrite this code in AWK instead of VB, keeping it the same logically?
Option Explicit Const m_limit ="# #" Const m_middle=" # # " Dim a,bnum,i,check,odic a=array(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",_ " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",_ " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",_ " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",_ " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",_ " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",_ " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",_ " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",_ " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",_ " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ") bnum=Array("0001101","0011001","0010011","0111101","0100011"," 0110001","0101111","0111011","0110111","0001011") Set oDic = WScript.CreateObject("scripting.dictionary") For i=0 To 9: odic.Add bin2dec(bnum(i),Asc("1")),i+1 odic.Add bin2dec(bnum(i),Asc("0")),-i-1 Next For i=0 To UBound(a) : print pad(i+1,-2) & ": "& upc(a(i)) :Next WScript.Quit(1) Function bin2dec(ByVal B,a) Dim n While len(b) n =n *2 - (asc(b)=a) b=mid(b,2) Wend bin2dec= n And 127 End Function Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else pad= left(s& space(n),n) end if :end function Function iif(t,a,b) If t Then iif=a Else iif=b End If :End Function Function getnum(s,r) Dim n,s1,r1 s1=Left(s,7) s=Mid(s,8) r1=r Do If r Then s1=StrReverse(s1) n=bin2dec(s1,asc("#")) If odic.exists(n) Then getnum=odic(n) Exit Function Else If r1<>r Then getnum=0:Exit Function r=Not r End If Loop End Function Function getmarker(s,m) getmarker= (InStr(s,m)= 1) s=Mid(s,Len(m)+1) End Function Function checksum(ByVal s) Dim n,i : n=0 do n=n+(Asc(s)-48)*3 s=Mid(s,2) n=n+(Asc(s)-48)*1 s=Mid(s,2) Loop until Len(s)=0 checksum= ((n mod 10)=0) End function Function upc(ByVal s1) Dim i,n,s,out,rev,j s=Trim(s1) If getmarker(s,m_limit)=False Then upc= "bad start marker ":Exit function rev=False out="" For j= 0 To 1 For i=0 To 5 n=getnum(s,rev) If n=0 Then upc= pad(out,16) & pad ("bad code",-10) & pad("pos "& i+j*6+1,-11): Exit Function out=out & Abs(n)-1 Next If j=0 Then If getmarker(s,m_middle)=False Then upc= "bad middle marker " & out :Exit Function Next If getmarker(s,m_limit)=False Then upc= "bad end marker " :Exit function If rev Then out=strreverse(out) upc= pad(out,16) & pad(iif (checksum(out),"valid","not valid"),-10)& pad(iif(rev,"reversed",""),-11) End Function
BEGIN { ls_arr[" ls_arr[" ls_arr[" ls_arr[" ls_arr[" ls_arr[" ls_arr[" ls_arr[" ls_arr[" ls_arr[" for (i in ls_arr) { tmp = i gsub(/ gsub(/ /," gsub(/x/," ",tmp) rs_arr[tmp] = ls_arr[i] } split("3,1,3,1,3,1,3,1,3,1,3,1",weight_arr,",") bc_arr[++n] = " bc_arr[++n] = " bc_arr[++n] = " bc_arr[++n] = " bc_arr[++n] = " bc_arr[++n] = " bc_arr[++n] = " bc_arr[++n] = " bc_arr[++n] = " bc_arr[++n] = " bc_arr[++n] = " tmp = "123456712345671234567123456712345671234567" printf("%2s: %-18s---%s-----%s---\n","N","UPC-A",tmp,tmp) for (i=1; i<=n; i++) { sub(/^ +/,"",bc_arr[i]) sub(/ +$/,"",bc_arr[i]) bc = bc_arr[i] if (length(bc) == 95 && substr(bc,1,3) == " upc = "" sum = upc_build(ls_arr,1,substr(bc,4,42)) sum += upc_build(rs_arr,7,substr(bc,51,42)) if (upc ~ /^x+$/) { msg = "reversed" } else if (upc ~ /x/) { msg = "invalid digit(s)" } else if (sum % 10 != 0) { msg = "bad check digit" } else { msg = upc } } else { msg = "invalid format" } printf("%2d: %-18s%s\n",i,msg,bc) } exit(0) } function upc_build(arr,pos,bc, i,s,sum) { pos-- for (i=1; i<=42; i+=7) { s = substr(bc,i,7) pos++ if (s in arr) { upc = upc arr[s] sum += arr[s] * weight_arr[pos] } else { upc = upc "x" } } return(sum) }
Convert the following code from VB to AWK, ensuring the logic remains intact.
Sub write_event(event_type,msg) Set objShell = CreateObject("WScript.Shell") Select Case event_type Case "SUCCESS" n = 0 Case "ERROR" n = 1 Case "WARNING" n = 2 Case "INFORMATION" n = 4 Case "AUDIT_SUCCESS" n = 8 Case "AUDIT_FAILURE" n = 16 End Select objShell.LogEvent n, msg Set objShell = Nothing End Sub Call write_event("INFORMATION","This is a test information.")
BEGIN { write("INFORMATION",1,"Rosetta Code") exit (errors == 0) ? 0 : 1 } function write(type,id,description, cmd,esf) { esf = errors cmd = sprintf("EVENTCREATE.EXE /T %s /ID %d /D \"%s\" >NUL",type,id,description) printf("%s\n",cmd) if (toupper(type) !~ /^(SUCCESS|ERROR|WARNING|INFORMATION)$/) { error("/T is invalid") } if (id+0 < 1 || id+0 > 1000) { error("/ID is invalid") } if (description == "") { error("/D is invalid") } if (errors == esf) { system(cmd) } return(errors) } function error(message) { printf("error: %s\n",message) ; errors++ }
Generate a AWK translation of this VB snippet without changing its computational steps.
function isPrime(n) if n < 2 then isPrime = 0 : goto [exit] if n = 2 then isPrime = 1 : goto [exit] if n mod 2 = 0 then isPrime = 0 : goto [exit] isPrime = 1 for i = 3 to int(n^.5) step 2 if n mod i = 0 then isPrime = 0 : goto [exit] next i [exit] end function n = 600851475143 j = 3 while isPrime(n) <> 1 if n mod j = 0 then n = n / j j = j +2 wend print n n = 600851475143 j = 3 while j <> n if int(n/j) = n / j then n = n / j j = j +2 wend print n end
BEGIN { N = n = "600851475143" j = 3 while (!is_prime(n)) { if (n % j == 0) { n /= j } j += 2 } printf("The largest prime factor of %s is %d\n",N,n) exit(0) } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) }
Write the same algorithm in AWK as shown in this VB implementation.
Public Sub backup(filename As String) If Len(Dir(filename)) > 0 Then On Error Resume Next Name filename As filename & ".bak" Else If Len(Dir(filename & ".lnk")) > 0 Then On Error Resume Next With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk") link = .TargetPath .Close End With Name link As link & ".bak" End If End If End Sub Public Sub main() backup "D:\test.txt" End Sub
@load "inplace" BEGIN { INPLACE_SUFFIX = ".BAK" } BEGINFILE { inplace_begin(FILENAME,INPLACE_SUFFIX) } 1 ENDFILE { inplace_end(FILENAME,INPLACE_SUFFIX) } END { exit(0) }
Translate the given VB code snippet into AWK without altering its behavior.
Public Sub backup(filename As String) If Len(Dir(filename)) > 0 Then On Error Resume Next Name filename As filename & ".bak" Else If Len(Dir(filename & ".lnk")) > 0 Then On Error Resume Next With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk") link = .TargetPath .Close End With Name link As link & ".bak" End If End If End Sub Public Sub main() backup "D:\test.txt" End Sub
@load "inplace" BEGIN { INPLACE_SUFFIX = ".BAK" } BEGINFILE { inplace_begin(FILENAME,INPLACE_SUFFIX) } 1 ENDFILE { inplace_end(FILENAME,INPLACE_SUFFIX) } END { exit(0) }
Rewrite the snippet below in AWK so it works the same as the original VB code.
Module Module1 ReadOnly SNL As New Dictionary(Of Integer, Integer) From { {4, 14}, {9, 31}, {17, 7}, {20, 38}, {28, 84}, {40, 59}, {51, 67}, {54, 34}, {62, 19}, {63, 81}, {64, 60}, {71, 91}, {87, 24}, {93, 73}, {95, 75}, {99, 78} } ReadOnly rand As New Random Const sixesThrowAgain = True Function Turn(player As Integer, square As Integer) As Integer Do Dim roll = rand.Next(1, 6) Console.Write("Player {0}, on square {1}, rolls a {2}", player, square, roll) If square + roll > 100 Then Console.WriteLine(" but cannot move.") Else square += roll Console.WriteLine(" and moves to square {0}", square) If square = 100 Then Return 100 End If Dim nxt = square If SNL.ContainsKey(square) Then nxt = SNL(nxt) End If If square < nxt Then Console.WriteLine("Yay! Landed on a ladder. Climb up to {0}.", nxt) If nxt = 100 Then Return 100 End If square = nxt ElseIf square > nxt Then Console.WriteLine("Oops! Landed on a snake. Slither down to {0}.", nxt) square = nxt End If End If If roll < 6 OrElse Not sixesThrowAgain Then Return square End If Console.WriteLine("Rolled a 6 so roll again.") Loop End Function Sub Main() Dim players = {1, 1, 1} Do For i = 1 To players.Length Dim ns = Turn(i, players(i - 1)) If ns = 100 Then Console.WriteLine("Player {0} wins!", i) Return End If players(i - 1) = ns Console.WriteLine() Next Loop End Sub End Module
BEGIN { players = (ARGV[1] ~ /^[0-9]+$/) ? ARGV[1] : 2 load_board() show_board() if (players == 0) { exit(0) } for (i=1; i<=players; i++) { sq_arr[i] = 1 } srand() while (1) { printf("\nTurn for (i=1; i<=players; i++) { ns = turn(i,sq_arr[i]) if (ns == 100) { printf("Player %d wins after %d moves\n",i,moves) exit(0) } sq_arr[i] = ns } } } function load_board() { sl_arr[ 4] = 14 sl_arr[ 9] = 31 sl_arr[17] = 7 sl_arr[20] = 38 sl_arr[28] = 84 sl_arr[40] = 59 sl_arr[51] = 67 sl_arr[54] = 34 sl_arr[62] = 19 sl_arr[63] = 81 sl_arr[64] = 60 sl_arr[71] = 91 sl_arr[87] = 24 sl_arr[93] = 73 sl_arr[95] = 75 sl_arr[99] = 78 } function show_board( board_arr,i,pos,row,L,S) { PROCINFO["sorted_in"] = "@ind_num_asc" for (i=1; i<=100; i++) { board_arr[i] = i } for (i in sl_arr) { board_arr[sl_arr[i]] = board_arr[i] = (i+0 < sl_arr[i]) ? sprintf("L%02d",++L) : sprintf("S%02d",++S) } print("board: L=ladder S=snake") for (row=10; row>=1; row--) { if (row ~ /[02468]$/) { pos = row * 10 for (i=1; i<=10; i++) { printf("%5s",board_arr[pos--]) } } else { pos = row * 10 - 9 for (i=1; i<=10; i++) { printf("%5s",board_arr[pos++]) } } printf("\n") } } function turn(player,square, position,roll) { while (1) { moves++ roll = int(rand() * 6) + 1 printf("Player %d on square %d rolls a %d",player,square,roll) if (square + roll > 100) { printf(" but cannot move\n") } else { square += roll printf(" and moves to square %d\n",square) if (square == 100) { return(100) } position = (square in sl_arr) ? sl_arr[square] : square if (square < position) { printf("Yay! Landed on a ladder so climb up to %d\n",position) } else if (position < square) { printf("Oops! Landed on a snake so slither down to %d\n",position) } square = position } if (roll < 6) { return(square) } printf("Rolled a 6 so roll again\n") } }
Change the programming language of this snippet from VB to AWK without modifying what it does.
Module Module1 ReadOnly SNL As New Dictionary(Of Integer, Integer) From { {4, 14}, {9, 31}, {17, 7}, {20, 38}, {28, 84}, {40, 59}, {51, 67}, {54, 34}, {62, 19}, {63, 81}, {64, 60}, {71, 91}, {87, 24}, {93, 73}, {95, 75}, {99, 78} } ReadOnly rand As New Random Const sixesThrowAgain = True Function Turn(player As Integer, square As Integer) As Integer Do Dim roll = rand.Next(1, 6) Console.Write("Player {0}, on square {1}, rolls a {2}", player, square, roll) If square + roll > 100 Then Console.WriteLine(" but cannot move.") Else square += roll Console.WriteLine(" and moves to square {0}", square) If square = 100 Then Return 100 End If Dim nxt = square If SNL.ContainsKey(square) Then nxt = SNL(nxt) End If If square < nxt Then Console.WriteLine("Yay! Landed on a ladder. Climb up to {0}.", nxt) If nxt = 100 Then Return 100 End If square = nxt ElseIf square > nxt Then Console.WriteLine("Oops! Landed on a snake. Slither down to {0}.", nxt) square = nxt End If End If If roll < 6 OrElse Not sixesThrowAgain Then Return square End If Console.WriteLine("Rolled a 6 so roll again.") Loop End Function Sub Main() Dim players = {1, 1, 1} Do For i = 1 To players.Length Dim ns = Turn(i, players(i - 1)) If ns = 100 Then Console.WriteLine("Player {0} wins!", i) Return End If players(i - 1) = ns Console.WriteLine() Next Loop End Sub End Module
BEGIN { players = (ARGV[1] ~ /^[0-9]+$/) ? ARGV[1] : 2 load_board() show_board() if (players == 0) { exit(0) } for (i=1; i<=players; i++) { sq_arr[i] = 1 } srand() while (1) { printf("\nTurn for (i=1; i<=players; i++) { ns = turn(i,sq_arr[i]) if (ns == 100) { printf("Player %d wins after %d moves\n",i,moves) exit(0) } sq_arr[i] = ns } } } function load_board() { sl_arr[ 4] = 14 sl_arr[ 9] = 31 sl_arr[17] = 7 sl_arr[20] = 38 sl_arr[28] = 84 sl_arr[40] = 59 sl_arr[51] = 67 sl_arr[54] = 34 sl_arr[62] = 19 sl_arr[63] = 81 sl_arr[64] = 60 sl_arr[71] = 91 sl_arr[87] = 24 sl_arr[93] = 73 sl_arr[95] = 75 sl_arr[99] = 78 } function show_board( board_arr,i,pos,row,L,S) { PROCINFO["sorted_in"] = "@ind_num_asc" for (i=1; i<=100; i++) { board_arr[i] = i } for (i in sl_arr) { board_arr[sl_arr[i]] = board_arr[i] = (i+0 < sl_arr[i]) ? sprintf("L%02d",++L) : sprintf("S%02d",++S) } print("board: L=ladder S=snake") for (row=10; row>=1; row--) { if (row ~ /[02468]$/) { pos = row * 10 for (i=1; i<=10; i++) { printf("%5s",board_arr[pos--]) } } else { pos = row * 10 - 9 for (i=1; i<=10; i++) { printf("%5s",board_arr[pos++]) } } printf("\n") } } function turn(player,square, position,roll) { while (1) { moves++ roll = int(rand() * 6) + 1 printf("Player %d on square %d rolls a %d",player,square,roll) if (square + roll > 100) { printf(" but cannot move\n") } else { square += roll printf(" and moves to square %d\n",square) if (square == 100) { return(100) } position = (square in sl_arr) ? sl_arr[square] : square if (square < position) { printf("Yay! Landed on a ladder so climb up to %d\n",position) } else if (position < square) { printf("Oops! Landed on a snake so slither down to %d\n",position) } square = position } if (roll < 6) { return(square) } printf("Rolled a 6 so roll again\n") } }
Rewrite the snippet below in AWK so it works the same as the original VB code.
Dim dblDistance as Double
Port the following code from VB to AWK with equivalent syntax and logic.
Function farey(n As Long, descending As Long) As Long Dim a, b, c, d, k As Long Dim aa, bb, cc, dd, count As Long b = 1 c = 1 d = n count = 0 If descending = True Then a = 1 c = n - 1 End If count += 1 If n < 12 Then Print Str(a); "/"; Str(b); " "; While ((c <= n) And Not descending) Or ((a > 0) And descending) aa = a bb = b cc = c dd = d k = (n + b) \ d a = cc b = dd c = k * cc - aa d = k * dd - bb count += 1 If n < 12 Then Print Str(a); "/"; Str(b); " "; Wend If n < 12 Then Print Return count End Function Public Sub Main() Dim i As Long For i = 1 To 11 Print "F"; Str(i); " = "; farey(i, False) Next Print For i = 100 To 1000 Step 100 Print "F"; Str(i); IIf(i <> 1000, " ", ""); " = "; Format$(farey(i, False), "######") Next End
BEGIN { for (i=1; i<=11; i++) { farey(i); printf("\n") } for (i=100; i<=1000; i+=100) { printf(" %d items\n",farey(i)) } exit(0) } function farey(n, a,aa,b,bb,c,cc,d,dd,items,k) { a = 0; b = 1; c = 1; d = n printf("%d:",n) if (n <= 11) { printf(" %d/%d",a,b) } while (c <= n) { k = int((n+b)/d) aa = c; bb = d; cc = k*c-a; dd = k*d-b a = aa; b = bb; c = cc; d = dd items++ if (n <= 11) { printf(" %d/%d",a,b) } } return(1+items) }
Convert the following code from VB to AWK, ensuring the logic remains intact.
Function farey(n As Long, descending As Long) As Long Dim a, b, c, d, k As Long Dim aa, bb, cc, dd, count As Long b = 1 c = 1 d = n count = 0 If descending = True Then a = 1 c = n - 1 End If count += 1 If n < 12 Then Print Str(a); "/"; Str(b); " "; While ((c <= n) And Not descending) Or ((a > 0) And descending) aa = a bb = b cc = c dd = d k = (n + b) \ d a = cc b = dd c = k * cc - aa d = k * dd - bb count += 1 If n < 12 Then Print Str(a); "/"; Str(b); " "; Wend If n < 12 Then Print Return count End Function Public Sub Main() Dim i As Long For i = 1 To 11 Print "F"; Str(i); " = "; farey(i, False) Next Print For i = 100 To 1000 Step 100 Print "F"; Str(i); IIf(i <> 1000, " ", ""); " = "; Format$(farey(i, False), "######") Next End
BEGIN { for (i=1; i<=11; i++) { farey(i); printf("\n") } for (i=100; i<=1000; i+=100) { printf(" %d items\n",farey(i)) } exit(0) } function farey(n, a,aa,b,bb,c,cc,d,dd,items,k) { a = 0; b = 1; c = 1; d = n printf("%d:",n) if (n <= 11) { printf(" %d/%d",a,b) } while (c <= n) { k = int((n+b)/d) aa = c; bb = d; cc = k*c-a; dd = k*d-b a = aa; b = bb; c = cc; d = dd items++ if (n <= 11) { printf(" %d/%d",a,b) } } return(1+items) }
Ensure the translated AWK code behaves exactly like the original VB snippet.
Option Explicit Private Type Aliquot Sequence() As Double Classification As String End Type Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String For j = 1 To 10 result = Aliq(j) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next j Dim a a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488) For j = LBound(a) To UBound(a) result = Aliq(CDbl(a(j))) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next End Sub Private Function Aliq(Nb As Double) As Aliquot Dim s() As Double, i As Long, temp, j As Long, cpt As Long temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic") ReDim s(0) s(0) = Nb For i = 1 To 15 cpt = cpt + 1 ReDim Preserve s(cpt) s(i) = SumPDiv(s(i - 1)) If s(i) > 140737488355328# Then Exit For If s(i) = 0 Then j = 1 If s(1) = s(0) Then j = 2 If s(i) = s(0) And i > 1 And i <> 2 Then j = 4 If s(i) = s(i - 1) And i > 1 Then j = 5 If i >= 2 Then If s(2) = s(0) Then j = 3 If s(i) = s(i - 2) And i <> 2 Then j = 6 End If If j > 0 Then Exit For Next Aliq.Classification = temp(j) Aliq.Sequence = s End Function Private Function SumPDiv(n As Double) As Double Dim j As Long, t As Long If n > 1 Then For j = 1 To n \ 2 If n Mod j = 0 Then t = t + j Next End If SumPDiv = t End Function
function sumprop(num, i,sum,root) { if (num == 1) return 0 sum=1 root=sqrt(num) for ( i=2; i < root; i++) { if (num % i == 0 ) { sum = sum + i + num/i } } if (num % root == 0) { sum = sum + root } return sum } function class(k, oldk,newk,seq){ oldk = k seq = " " newk = sumprop(oldk) oldk = newk seq = seq " " newk if (newk == 0) return "terminating " seq if (newk == k) return "perfect " seq newk = sumprop(oldk) oldk = newk seq = seq " " newk if (newk == 0) return "terminating " seq if (newk == k) return "amicable " seq for (t=4; t<17; t++) { newk = sumprop(oldk) seq = seq " " newk if (newk == 0) return "terminating " seq if (newk == k) return "sociable (period " t-1 ") "seq if (newk == oldk) return "aspiring " seq if (index(seq," " newk " ") > 0) return "cyclic (at " newk ") " seq if (newk > 140737488355328) return "non-terminating (term > 140737488355328) " seq oldk = newk } return "non-terminating (after 16 terms) " seq } BEGIN{ print "Number classification sequence" for (j=1; j < 11; j++) { print j,class(j)} print 11,class(11) print 12,class(12) print 28,class(28) print 496,class(496) print 220,class(220) print 1184,class(1184) print 12496,class(12496) print 1264460,class(1264460) print 790,class(790) print 909,class(909) print 562,class(562) print 1064,class(1064) print 1488,class(1488) print 15355717786080,class(15355717786080) }
Translate the given VB code snippet into AWK without altering its behavior.
Option Explicit Private Type Aliquot Sequence() As Double Classification As String End Type Sub Main() Dim result As Aliquot, i As Long, j As Double, temp As String For j = 1 To 10 result = Aliq(j) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next j Dim a a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488) For j = LBound(a) To UBound(a) result = Aliq(CDbl(a(j))) temp = vbNullString For i = 0 To UBound(result.Sequence) temp = temp & result.Sequence(i) & ", " Next i Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2) Next End Sub Private Function Aliq(Nb As Double) As Aliquot Dim s() As Double, i As Long, temp, j As Long, cpt As Long temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic") ReDim s(0) s(0) = Nb For i = 1 To 15 cpt = cpt + 1 ReDim Preserve s(cpt) s(i) = SumPDiv(s(i - 1)) If s(i) > 140737488355328# Then Exit For If s(i) = 0 Then j = 1 If s(1) = s(0) Then j = 2 If s(i) = s(0) And i > 1 And i <> 2 Then j = 4 If s(i) = s(i - 1) And i > 1 Then j = 5 If i >= 2 Then If s(2) = s(0) Then j = 3 If s(i) = s(i - 2) And i <> 2 Then j = 6 End If If j > 0 Then Exit For Next Aliq.Classification = temp(j) Aliq.Sequence = s End Function Private Function SumPDiv(n As Double) As Double Dim j As Long, t As Long If n > 1 Then For j = 1 To n \ 2 If n Mod j = 0 Then t = t + j Next End If SumPDiv = t End Function
function sumprop(num, i,sum,root) { if (num == 1) return 0 sum=1 root=sqrt(num) for ( i=2; i < root; i++) { if (num % i == 0 ) { sum = sum + i + num/i } } if (num % root == 0) { sum = sum + root } return sum } function class(k, oldk,newk,seq){ oldk = k seq = " " newk = sumprop(oldk) oldk = newk seq = seq " " newk if (newk == 0) return "terminating " seq if (newk == k) return "perfect " seq newk = sumprop(oldk) oldk = newk seq = seq " " newk if (newk == 0) return "terminating " seq if (newk == k) return "amicable " seq for (t=4; t<17; t++) { newk = sumprop(oldk) seq = seq " " newk if (newk == 0) return "terminating " seq if (newk == k) return "sociable (period " t-1 ") "seq if (newk == oldk) return "aspiring " seq if (index(seq," " newk " ") > 0) return "cyclic (at " newk ") " seq if (newk > 140737488355328) return "non-terminating (term > 140737488355328) " seq oldk = newk } return "non-terminating (after 16 terms) " seq } BEGIN{ print "Number classification sequence" for (j=1; j < 11; j++) { print j,class(j)} print 11,class(11) print 12,class(12) print 28,class(28) print 496,class(496) print 220,class(220) print 1184,class(1184) print 12496,class(12496) print 1264460,class(1264460) print 790,class(790) print 909,class(909) print 562,class(562) print 1064,class(1064) print 1488,class(1488) print 15355717786080,class(15355717786080) }
Rewrite the snippet below in AWK so it works the same as the original VB code.
Imports System, System.Console Module Module1 Dim np As Boolean() Sub ms(ByVal lmt As Long) np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True Dim n As Integer = 2, j As Integer = 1 : While n < lmt If Not np(n) Then Dim k As Long = CLng(n) * n While k < lmt : np(CInt(k)) = True : k += n : End While End If : n += j : j = 2 : End While End Sub Function is_Mag(ByVal n As Integer) As Boolean Dim res, rm As Integer, p As Integer = 10 While n >= p res = Math.DivRem(n, p, rm) If np(res + rm) Then Return False p = p * 10 : End While : Return True End Function Sub Main(ByVal args As String()) ms(100_009) : Dim mn As String = " magnanimous numbers:" WriteLine("First 45{0}", mn) : Dim l As Integer = 0, c As Integer = 0 While c < 400 : If is_Mag(l) Then c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, "{0,4} ", "{0,8:n0} "), l) If c < 45 AndAlso c Mod 15 = 0 Then WriteLine() If c = 240 Then WriteLine(vbLf & vbLf & "241st through 250th{0}", mn) If c = 390 Then WriteLine(vbLf & vbLf & "391st through 400th{0}", mn) End If : l += 1 : End While End Sub End Module
BEGIN { magnanimous(1,45) magnanimous(241,250) magnanimous(391,400) exit(0) } function is_magnanimous(n, p,q,r) { if (n < 10) { return(1) } for (p=10; ; p*=10) { q = int(n/p) r = n % p if (!is_prime(q+r)) { return(0) } if (q < 10) { break } } return(1) } function is_prime(n, d) { d = 5 if (n < 2) { return(0) } if (!(n % 2)) { return(n == 2) } if (!(n % 3)) { return(n == 3) } while (d*d <= n) { if (!(n % d)) { return(0) } d += 2 if (!(n % d)) { return(0) } d += 4 } return(1) } function magnanimous(start,stop, count,i) { printf("%d-%d:",start,stop) for (i=0; count<stop; ++i) { if (is_magnanimous(i)) { if (++count >= start) { printf(" %d",i) } } } printf("\n") }
Generate an equivalent AWK version of this VB code.
Imports System.Numerics Module Module1 Function Sqrt(x As BigInteger) As BigInteger If x < 0 Then Throw New ArgumentException("Negative argument.") End If If x < 2 Then Return x End If Dim y = x / 2 While y > (x / y) y = ((x / y) + y) / 2 End While Return y End Function Function IsPrime(bi As BigInteger) As Boolean If bi < 2 Then Return False End If If bi Mod 2 = 0 Then Return bi = 2 End If If bi Mod 3 = 0 Then Return bi = 3 End If If bi Mod 5 = 0 Then Return bi = 5 End If If bi Mod 7 = 0 Then Return bi = 7 End If If bi Mod 11 = 0 Then Return bi = 11 End If If bi Mod 13 = 0 Then Return bi = 13 End If If bi Mod 17 = 0 Then Return bi = 17 End If If bi Mod 19 = 0 Then Return bi = 19 End If Dim limit = Sqrt(bi) Dim test As BigInteger = 23 While test < limit If bi Mod test = 0 Then Return False End If test += 2 If bi Mod test = 0 Then Return False End If test += 4 End While Return True End Function Sub Main() Const MAX = 9 Dim pow = 2 Dim count = 0 While True If IsPrime(pow) Then Dim p = BigInteger.Pow(2, pow) - 1 If IsPrime(p) Then Console.WriteLine("2 ^ {0} - 1", pow) count += 1 If count >= MAX Then Exit While End If End If End If pow += 1 End While End Sub End Module
BEGIN { base = 2 for (i=1; i<62; i++) { if (is_prime(base-1)) { printf("2 ^ %d - 1\n",i) } base *= 2 } exit(0) } function is_prime(n, d) { d = 5 if (n < 2) { return(0) } if (n % 2 == 0) { return(n == 2) } if (n % 3 == 0) { return(n == 3) } while (d*d <= n) { if (n % d == 0) { return(0) } d += 2 if (n % d == 0) { return(0) } d += 4 } return(1) }
Can you help me rewrite this code in AWK instead of VB, keeping it the same logically?
Option Strict On Option Explicit On Imports System.IO Module KlarnerRado Private Const bitsWidth As Integer = 31 Private bitMask() As Integer = _ New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _ , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _ , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _ , 16777216, 33554432, 67108864, 134217728, 268435456 _ , 536870912, 1073741824 _ } Private Const maxElement As Integer = 1100000000 Private Function BitSet(bit As Integer, v As Integer) As Boolean Return (v And bitMask(bit - 1)) <> 0 End Function Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer Return b Or bitMask(bit - 1) End Function Public Sub Main Dim kr(maxElement \ bitsWidth) As Integer For i As Integer = 0 To kr.Count() - 1 kr(i) = 0 Next i Dim krCount As Integer = 0 Dim n21 As Integer = 3 Dim n31 As Integer = 4 Dim p10 As Integer = 1000 Dim iBit As Integer = 0 Dim iOverBw As Integer = 0 Dim p2Bit As Integer = 1 Dim p2OverBw As Integer = 0 Dim p3Bit As Integer = 1 Dim p3OverBw As Integer = 0 kr(0) = SetBit(1, kr(0)) Dim kri As Boolean = True Dim lastI As Integer = 0 For i As Integer = 1 To maxElement iBit += 1 If iBit > bitsWidth Then iBit = 1 iOverBw += 1 End If If i = n21 Then If BitSet(p2Bit, kr(p2OverBw)) Then kri = True End If p2Bit += 1 If p2Bit > bitsWidth Then p2Bit = 1 p2OverBw += 1 End If n21 += 2 End If If i = n31 Then If BitSet(p3Bit, kr(p3OverBw)) Then kri = True End If p3Bit += 1 If p3Bit > bitsWidth Then p3Bit = 1 p3OverBw += 1 End If n31 += 3 End If If kri Then lastI = i kr(iOverBw) = SetBit(iBit, kr(iOverBw)) krCount += 1 If krCount <= 100 Then Console.Out.Write(" " & i.ToString().PadLeft(3)) If krCount Mod 20 = 0 Then Console.Out.WriteLine() End If ElseIf krCount = p10 Then Console.Out.WriteLine("Element " & p10.ToString().PadLeft(10) & " is " & i.ToString().PadLeft(10)) p10 *= 10 End If kri = False End If Next i Console.Out.WriteLine("Element " & krCount.ToString().PadLeft(10) & " is " & lastI.ToString().PadLeft(10)) End Sub End Module
BEGIN { for (m2 = m3 = o = 1; o <= 1000000; ++o) { klarner_rado[o] = m = m2 < m3 ? m2 : m3 if (m2 == m) m2 = klarner_rado[++i2] * 2 + 1 if (m3 == m) m3 = klarner_rado[++i3] * 3 + 1 } for (i = 1; i < 100; ++i) printf "%u ", klarner_rado[i] for (i = 100; i < o; i *= 10) print klarner_rado[i] }
Translate the given VB code snippet into AWK without altering its behavior.
Option Strict On Option Explicit On Imports System.IO Module KlarnerRado Private Const bitsWidth As Integer = 31 Private bitMask() As Integer = _ New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _ , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _ , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _ , 16777216, 33554432, 67108864, 134217728, 268435456 _ , 536870912, 1073741824 _ } Private Const maxElement As Integer = 1100000000 Private Function BitSet(bit As Integer, v As Integer) As Boolean Return (v And bitMask(bit - 1)) <> 0 End Function Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer Return b Or bitMask(bit - 1) End Function Public Sub Main Dim kr(maxElement \ bitsWidth) As Integer For i As Integer = 0 To kr.Count() - 1 kr(i) = 0 Next i Dim krCount As Integer = 0 Dim n21 As Integer = 3 Dim n31 As Integer = 4 Dim p10 As Integer = 1000 Dim iBit As Integer = 0 Dim iOverBw As Integer = 0 Dim p2Bit As Integer = 1 Dim p2OverBw As Integer = 0 Dim p3Bit As Integer = 1 Dim p3OverBw As Integer = 0 kr(0) = SetBit(1, kr(0)) Dim kri As Boolean = True Dim lastI As Integer = 0 For i As Integer = 1 To maxElement iBit += 1 If iBit > bitsWidth Then iBit = 1 iOverBw += 1 End If If i = n21 Then If BitSet(p2Bit, kr(p2OverBw)) Then kri = True End If p2Bit += 1 If p2Bit > bitsWidth Then p2Bit = 1 p2OverBw += 1 End If n21 += 2 End If If i = n31 Then If BitSet(p3Bit, kr(p3OverBw)) Then kri = True End If p3Bit += 1 If p3Bit > bitsWidth Then p3Bit = 1 p3OverBw += 1 End If n31 += 3 End If If kri Then lastI = i kr(iOverBw) = SetBit(iBit, kr(iOverBw)) krCount += 1 If krCount <= 100 Then Console.Out.Write(" " & i.ToString().PadLeft(3)) If krCount Mod 20 = 0 Then Console.Out.WriteLine() End If ElseIf krCount = p10 Then Console.Out.WriteLine("Element " & p10.ToString().PadLeft(10) & " is " & i.ToString().PadLeft(10)) p10 *= 10 End If kri = False End If Next i Console.Out.WriteLine("Element " & krCount.ToString().PadLeft(10) & " is " & lastI.ToString().PadLeft(10)) End Sub End Module
BEGIN { for (m2 = m3 = o = 1; o <= 1000000; ++o) { klarner_rado[o] = m = m2 < m3 ? m2 : m3 if (m2 == m) m2 = klarner_rado[++i2] * 2 + 1 if (m3 == m) m3 = klarner_rado[++i3] * 3 + 1 } for (i = 1; i < 100; ++i) printf "%u ", klarner_rado[i] for (i = 100; i < o; i *= 10) print klarner_rado[i] }
Convert this VB snippet to AWK and keep its semantics consistent.
Public Type tuple i As Variant j As Variant sum As Variant End Type Public Type tuple3 i1 As Variant j1 As Variant i2 As Variant j2 As Variant i3 As Variant j3 As Variant sum As Variant End Type Sub taxicab_numbers() Dim i As Variant, j As Variant Dim k As Long Const MAX = 2019 Dim p(MAX) As Variant Const bigMAX = (MAX + 1) * (MAX / 2) Dim big(1 To bigMAX) As tuple Const resMAX = 4400 Dim res(1 To resMAX) As tuple3 For i = 1 To MAX p(i) = CDec(i * i * i) Next i k = 1 For i = 1 To MAX For j = i To MAX big(k).i = CDec(i) big(k).j = CDec(j) big(k).sum = CDec(p(i) + p(j)) k = k + 1 Next j Next i n = 1 Quicksort big, LBound(big), UBound(big) For i = 1 To bigMAX - 1 If big(i).sum = big(i + 1).sum Then res(n).i1 = CStr(big(i).i) res(n).j1 = CStr(big(i).j) res(n).i2 = CStr(big(i + 1).i) res(n).j2 = CStr(big(i + 1).j) If big(i + 1).sum = big(i + 2).sum Then res(n).i3 = CStr(big(i + 2).i) res(n).j3 = CStr(big(i + 2).j) i = i + 1 End If res(n).sum = CStr(big(i).sum) n = n + 1 i = i + 1 End If Next i Debug.Print n - 1; " taxis" For i = 1 To 25 With res(i) Debug.Print String$(4 - Len(CStr(i)), " "); i; Debug.Print String$(11 - Len(.sum), " "); .sum; " = "; Debug.Print String$(4 - Len(.i1), " "); .i1; "^3 +"; Debug.Print String$(4 - Len(.j1), " "); .j1; "^3 = "; Debug.Print String$(4 - Len(.i2), " "); .i2; "^3 +"; Debug.Print String$(4 - Len(.j2), " "); .j2; "^3" End With Next i Debug.Print For i = 2000 To 2006 With res(i) Debug.Print String$(4 - Len(CStr(i)), " "); i; Debug.Print String$(11 - Len(.sum), " "); .sum; " = "; Debug.Print String$(4 - Len(.i1), " "); .i1; "^3 +"; Debug.Print String$(4 - Len(.j1), " "); .j1; "^3 = "; Debug.Print String$(4 - Len(.i2), " "); .i2; "^3 +"; Debug.Print String$(4 - Len(.j2), " "); .j2; "^3" End With Next i Debug.Print For i = 1 To resMAX If res(i).i3 <> "" Then With res(i) Debug.Print String$(4 - Len(CStr(i)), " "); i; Debug.Print String$(11 - Len(.sum), " "); .sum; " = "; Debug.Print String$(4 - Len(.i1), " "); .i1; "^3 +"; Debug.Print String$(4 - Len(.j1), " "); .j1; "^3 = "; Debug.Print String$(4 - Len(.i2), " "); .i2; "^3 +"; Debug.Print String$(4 - Len(.j2), " "); .j2; "^3"; Debug.Print String$(4 - Len(.i3), " "); .i3; "^3 +"; Debug.Print String$(4 - Len(.j3), " "); .j3; "^3" End With End If Next i End Sub Sub Quicksort(vArray() As tuple, arrLbound As Long, arrUbound As Long) Dim pivotVal As Variant Dim vSwap As tuple Dim tmpLow As Long Dim tmpHi As Long tmpLow = arrLbound tmpHi = arrUbound pivotVal = vArray((arrLbound + arrUbound) \ 2).sum While (tmpLow <= tmpHi) While (vArray(tmpLow).sum < pivotVal And tmpLow < arrUbound) tmpLow = tmpLow + 1 Wend While (pivotVal < vArray(tmpHi).sum And tmpHi > arrLbound) tmpHi = tmpHi - 1 Wend If (tmpLow <= tmpHi) Then vSwap.i = vArray(tmpLow).i vSwap.j = vArray(tmpLow).j vSwap.sum = vArray(tmpLow).sum vArray(tmpLow).i = vArray(tmpHi).i vArray(tmpLow).j = vArray(tmpHi).j vArray(tmpLow).sum = vArray(tmpHi).sum vArray(tmpHi).i = vSwap.i vArray(tmpHi).j = vSwap.j vArray(tmpHi).sum = vSwap.sum tmpLow = tmpLow + 1 tmpHi = tmpHi - 1 End If Wend If (arrLbound < tmpHi) Then Quicksort vArray, arrLbound, tmpHi If (tmpLow < arrUbound) Then Quicksort vArray, tmpLow, arrUbound End Sub
BEGIN { stop = 99 for (a=1; a<=stop; a++) { for (b=1; b<=stop; b++) { n1 = a^3 + b^3 for (c=1; c<=stop; c++) { if (a == c) { continue } for (d=1; d<=stop; d++) { n2 = c^3 + d^3 if (n1 == n2 && (a != d || b != c)) { if (n1 in arr) { continue } arr[n1] = sprintf("%7d = %2d^3 + %2d^3 = %2d^3 + %2d^3",n1,a,b,c,d) } } } } } PROCINFO["sorted_in"] = "@ind_num_asc" for (i in arr) { if (++count <= 25) { printf("%2d: %s\n",count,arr[i]) } } printf("\nThere are %d taxicab numbers using bounds of %d\n",length(arr),stop) exit(0) }
Maintain the same structure and functionality when rewriting this code in AWK.
Imports DT = System.DateTime Module Module1 Iterator Function Primes(lim As Integer) As IEnumerable(Of Integer) Dim flags(lim) As Boolean Dim j = 2 Dim d = 3 Dim sq = 4 While sq <= lim If Not flags(j) Then Yield j For k = sq To lim Step j flags(k) = True Next End If j += 1 d += 2 sq += d End While While j <= lim If Not flags(j) Then Yield j End If j += 1 End While End Function Sub Main() For Each lmt In {90, 300, 3000, 30000, 111000} Dim pr = Primes(lmt).Skip(1).ToList() Dim st = DT.Now Dim f = 0 Dim r As New List(Of String) Dim i = -1 Dim m = lmt \ 3 Dim h = m While i < 0 i = pr.IndexOf(h) h -= 1 End While Dim j = i - 1 Dim k = j - 1 For a = 0 To k Dim pra = pr(a) For b = a + 1 To j Dim prab = pra + pr(b) For c = b + 1 To i Dim d = prab + pr(c) If Not pr.Contains(d) Then Continue For End If f += 1 If lmt < 100 Then r.Add(String.Format("{3,5} = {0,2} + {1,2} + {2,2}", pra, pr(b), pr(c), d)) End If Next Next Next Dim s = "s.u.p.t.s under " r.Sort() If r.Count > 0 Then Console.WriteLine("{0}{1}:" + vbNewLine + "{2}", s, m, String.Join(vbNewLine, r)) End If If lmt > 100 Then Console.WriteLine("Count of {0}{1,6:n0}: {2,13:n0} {3} sec", s, m, f, (DT.Now - st).ToString().Substring(6)) End If Next End Sub End Module
BEGIN { main(29,1) main(999,0) exit(0) } function main(n,show, count,i,j,k,s) { for (i=3; i<=n-4; i+=2) { if (is_prime(i)) { for (j=i+2; j<=n-2; j+=2) { if (is_prime(j)) { for (k=j+2; k<=n; k+=2) { if (is_prime(k)) { s = i + j + k if (is_prime(s)) { count++ if (show == 1) { printf("%2d + %2d + %2d = %d\n",i,j,k,s) } } } } } } } } printf("Unique prime triples 2-%d which sum to a prime: %'d\n\n",n,count) } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) }
Change the following VB code into AWK without altering its purpose.
Imports DT = System.DateTime Module Module1 Iterator Function Primes(lim As Integer) As IEnumerable(Of Integer) Dim flags(lim) As Boolean Dim j = 2 Dim d = 3 Dim sq = 4 While sq <= lim If Not flags(j) Then Yield j For k = sq To lim Step j flags(k) = True Next End If j += 1 d += 2 sq += d End While While j <= lim If Not flags(j) Then Yield j End If j += 1 End While End Function Sub Main() For Each lmt In {90, 300, 3000, 30000, 111000} Dim pr = Primes(lmt).Skip(1).ToList() Dim st = DT.Now Dim f = 0 Dim r As New List(Of String) Dim i = -1 Dim m = lmt \ 3 Dim h = m While i < 0 i = pr.IndexOf(h) h -= 1 End While Dim j = i - 1 Dim k = j - 1 For a = 0 To k Dim pra = pr(a) For b = a + 1 To j Dim prab = pra + pr(b) For c = b + 1 To i Dim d = prab + pr(c) If Not pr.Contains(d) Then Continue For End If f += 1 If lmt < 100 Then r.Add(String.Format("{3,5} = {0,2} + {1,2} + {2,2}", pra, pr(b), pr(c), d)) End If Next Next Next Dim s = "s.u.p.t.s under " r.Sort() If r.Count > 0 Then Console.WriteLine("{0}{1}:" + vbNewLine + "{2}", s, m, String.Join(vbNewLine, r)) End If If lmt > 100 Then Console.WriteLine("Count of {0}{1,6:n0}: {2,13:n0} {3} sec", s, m, f, (DT.Now - st).ToString().Substring(6)) End If Next End Sub End Module
BEGIN { main(29,1) main(999,0) exit(0) } function main(n,show, count,i,j,k,s) { for (i=3; i<=n-4; i+=2) { if (is_prime(i)) { for (j=i+2; j<=n-2; j+=2) { if (is_prime(j)) { for (k=j+2; k<=n; k+=2) { if (is_prime(k)) { s = i + j + k if (is_prime(s)) { count++ if (show == 1) { printf("%2d + %2d + %2d = %d\n",i,j,k,s) } } } } } } } } printf("Unique prime triples 2-%d which sum to a prime: %'d\n\n",n,count) } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) }
Rewrite the snippet below in AWK so it works the same as the original VB code.
n=8 pattern="1001011001101001" size=n*n: w=len(size) mult=n\4 wscript.echo "Magic square : " & n & " x " & n i=0 For r=0 To n-1 l="" For c=0 To n-1 bit=Mid(pattern, c\mult+(r\mult)*4+1, 1) If bit="1" Then t=i+1 Else t=size-i l=l & Right(Space(w) & t, w) & " " i=i+1 Next wscript.echo l Next wscript.echo "Magic constant=" & (n*n+1)*n/2
BEGIN { n = 8 msquare[0, 0] = 0 if (magicsquaredoublyeven(msquare, n)) { for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%2d ", msquare[i, j]) } printf("\n") } printf("\nMagic constant: %d\n", (n * n + 1) * n / 2) exit 1 } else { exit 0 } } function magicsquaredoublyeven(msquare, n, size, mult, r, c, i) { if (n < 4 || n % 4 != 0) { printf("Base must be a positive multiple of 4.\n") return 0 } size = n * n mult = n / 4 i = 0 for (r = 0; r < n; r++) { for (c = 0; c < n; c++) { msquare[r, c] = countup(r, c, mult) ? i + 1 : size - i i++ } } return 1 } function countup(r, c, mult, pattern, bitpos) { pattern = "1001011001101001" bitpos = int(c / mult) + int(r / mult) * 4 + 1 return substr(pattern, bitpos, 1) + 0 }
Ensure the translated AWK code behaves exactly like the original VB snippet.
Module Module1 Function Sieve(limit As Long) As List(Of Long) Dim primes As New List(Of Long) From {2} Dim c(limit + 1) As Boolean Dim p = 3L While True Dim p2 = p * p If p2 > limit Then Exit While End If For i = p2 To limit Step 2 * p c(i) = True Next While True p += 2 If Not c(p) Then Exit While End If End While End While For i = 3 To limit Step 2 If Not c(i) Then primes.Add(i) End If Next Return primes End Function Function SquareFree(from As Long, to_ As Long) As List(Of Long) Dim limit = CType(Math.Sqrt(to_), Long) Dim primes = Sieve(limit) Dim results As New List(Of Long) Dim i = from While i <= to_ For Each p In primes Dim p2 = p * p If p2 > i Then Exit For End If If (i Mod p2) = 0 Then i += 1 Continue While End If Next results.Add(i) i += 1 End While Return results End Function ReadOnly TRILLION As Long = 1_000_000_000_000 Sub Main() Console.WriteLine("Square-free integers from 1 to 145:") Dim sf = SquareFree(1, 145) For index = 0 To sf.Count - 1 Dim v = sf(index) If index > 1 AndAlso (index Mod 20) = 0 Then Console.WriteLine() End If Console.Write("{0,4}", v) Next Console.WriteLine() Console.WriteLine() Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145) sf = SquareFree(TRILLION, TRILLION + 145) For index = 0 To sf.Count - 1 Dim v = sf(index) If index > 1 AndAlso (index Mod 5) = 0 Then Console.WriteLine() End If Console.Write("{0,14}", v) Next Console.WriteLine() Console.WriteLine() Console.WriteLine("Number of square-free integers:") For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000} Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count) Next End Sub End Module
BEGIN { main(1,145,1) main(1000000000000,1000000000145,1) main(1,100,0) main(1,1000,0) main(1,10000,0) main(1,100000,0) main(1,1000000,0) exit(0) } function main(lo,hi,show_values, count,i,leng) { printf("%d-%d: ",lo,hi) leng = length(lo) + length(hi) + 3 for (i=lo; i<=hi; i++) { if (square_free(i)) { count++ if (show_values) { if (leng > 110) { printf("\n") leng = 0 } printf("%d ",i) leng += length(i) + 1 } } } printf("count=%d\n\n",count) } function square_free(n, root) { for (root=2; root<=sqrt(n); root++) { if (n % (root * root) == 0) { return(0) } } return(1) }
Write a version of this VB function in AWK with identical behavior.
Public Sub Main() Dim units As String[] = ["tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer"] Dim convs As Single[] = [0.254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000] Dim i, unit As Integer Dim value As Single Dim yn As String Do Shell("clear") Print For i = 1 To units.count Print Format$(i, "##"); " "; units[i - 1] Next Print "\nPlease choose a unit 1 to 13 : " Do Input unit Loop Until unit >= 1 And unit <= 13 Print "\nNow enter a value in that unit : " Do Input value Loop Until value >= 0 Print "\nThe equivalent in the remaining units is : \n" For i = 0 To units.count - 1 If i = unit - 1 Then Continue Print units[i]; Space$(10 - Len(units[i])); Print " : "; value * convs[unit - 1] / convs[i] Next Print "\nDo another one y/n : " Do Input yn yn = LCase(yn) Loop Until yn = "y" Or yn = "n" Loop Until yn = "n" End
BEGIN { units = "kilometer meter centimeter tochka liniya diuym vershok piad fut arshin sazhen versta milia" values = "1000.0 1.0 0.01 0.000254 0.00254 0.0254 0.04445 0.1778 0.3048 0.7112 2.1336 1066.8 7467.6" u_leng = split(units,u_arr," ") v_leng = split(values,v_arr," ") if (u_leng != v_leng) { print("error: lengths of units & values are unequal") exit(1) } print("enter length & measure or C/R to exit") } { if ($0 == "") { exit(0) } measure = tolower($2) sub(/s$/,"",measure) for (i=1; i<=u_leng; i++) { if (u_arr[i] == measure) { for (j=1; j<=u_leng; j++) { str = sprintf("%.8f",$1*v_arr[i]/v_arr[j]) sub(/0+$/,"",str) printf("%10s %s\n",u_arr[j],str) } print("") next } } printf("error: invalid measure; choose from: %s\n\n",units) }
Please provide an equivalent version of this VB code in AWK.
Const n = 2200 Public Sub pq() Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3 Dim l(n) As Boolean, l_add(9680000) As Boolean For x = 1 To n x2 = x * x For y = x To n l_add(x2 + y * y) = True Next y Next x For x = 1 To n s1 = s s = s + 2 s2 = s For y = x + 1 To n If l_add(s1) Then l(y) = True s1 = s1 + s2 s2 = s2 + 2 Next Next For x = 1 To n If Not l(x) Then Debug.Print x; Next Debug.Print End Sub
BEGIN { n = 2200 s = 3 for (a=1; a<=n; a++) { a2 = a * a for (b=a; b<=n; b++) { ab[a2 + b * b] = 1 } } for (c=1; c<=n; c++) { s1 = s s += 2 s2 = s for (d=c+1; d<=n; d++) { if (ab[s1]) { r[d] = 1 } s1 += s2 s2 += 2 } } for (d=1; d<=n; d++) { if (!r[d]) { printf("%d ",d) } } printf("\n") exit(0) }
Change the following VB code into AWK without altering its purpose.
#define isInteger(x) iif(Int(val(x)) = val(x), 1, 0) Dim As String test(1 To 8) = {"25.000000", "24.999999", "25.000100", "-2.1e120", "-5e-2", "NaN", "Inf", "-0.05"} For i As Integer = 1 To Ubound(test) Dim As String s = test(i) Print s, If isInteger(s) then Print "is integer" Else Print "is not integer" Next i Sleep
BEGIN { n = split("25.000000,24.999999,25.000100,-2.1e120,-5e-2,NaN,Inf,-0.05",arr,",") for (i=1; i<=n; i++) { s = arr[i] x = (s == int(s)) ? 1 : 0 printf("%d %s\n",x,s) } exit(0) }
Rewrite the snippet below in AWK so it works the same as the original VB code.
#macro typeDetector(arg) #if TypeOf(foo) = TypeOf(Byte) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(Short) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(Integer) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(LongInt) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(UByte) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(UShort) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(UInteger) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(ULongInt) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(Single) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(Double) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(integer ptr) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(byte ptr) Print arg; " -> It #elseif TypeOf(foo) = TypeOf(String) Print arg; " -> It #endif #endmacro Var foo = "Rosetta Code" typeDetector (foo) Sleep
BEGIN { arr[0] = 0 print(typeof(arr)) print(typeof(0.)) print(typeof(0)) print(typeof(/0/)) print(typeof("0")) print(typeof(x)) print(typeof(addressof("x"))) print(typeof(fopen("x","r"))) exit(0) }
Write the same algorithm in AWK as shown in this VB implementation.
Public Sub Main() For i As Integer = 1 To 10000 If is_steady_square(i) Then Print Format$(i, "####"); "^2 = "; Format$(i ^ 2, "########") Next End Function numdig(n As Integer) As Integer Dim d As Integer = 0 While n d += 1 n \= 10 Wend Return d End Function Function is_steady_square(n As Integer) As Boolean Dim n2 As Integer = n ^ 2 Return IIf(n2 Mod CInt(10 ^ numdig(n)) = n, True, False) End Function
BEGIN { start = 1 stop = 999999 for (i=start; i<=stop; i++) { n = i ^ 2 if (n ~ (i "$")) { printf("%6d^2 = %12d\n",i,n) count++ } } printf("\nSteady squares %d-%d: %d\n",start,stop,count) exit(0) }
Rewrite this program in AWK while keeping its functionality equivalent to the VB version.
Imports System.Console Namespace safety Module SafePrimes Dim pri_HS As HashSet(Of Integer) = Primes(10_000_000).ToHashSet() Sub Main() For Each UnSafe In {False, True} : Dim n As Integer = If(UnSafe, 40, 35) WriteLine($"The first {n} {If(UnSafe, "un", "")}safe primes are:") WriteLine(String.Join(" ", pri_HS.Where(Function(p) UnSafe Xor pri_HS.Contains(p \ 2)).Take(n))) Next : Dim limit As Integer = 1_000_000 : Do Dim part = pri_HS.TakeWhile(Function(l) l < limit), sc As Integer = part.Count(Function(p) pri_HS.Contains(p \ 2)) WriteLine($"Of the primes below {limit:n0}: {sc:n0} are safe, and {part.Count() - sc:n0} are unsafe.") : If limit = 1_000_000 Then limit *= 10 Else Exit Do Loop End Sub Private Iterator Function Primes(ByVal bound As Integer) As IEnumerable(Of Integer) If bound < 2 Then Return Yield 2 Dim composite As BitArray = New BitArray((bound - 1) \ 2) Dim limit As Integer = (CInt((Math.Sqrt(bound))) - 1) \ 2 For i As Integer = 0 To limit - 1 : If composite(i) Then Continue For Dim prime As Integer = 2 * i + 3 : Yield prime Dim j As Integer = (prime * prime - 2) \ 2 While j < composite.Count : composite(j) = True : j += prime : End While Next For i As integer = limit To composite.Count - 1 : If Not composite(i) Then Yield 2 * i + 3 Next End Function End Module End Namespace
BEGIN { for (i=1; i<1E7; i++) { if (is_prime(i)) { arr[i] = "" } } stop1 = 35 ; stop2 = 1E6 ; stop3 = 1E7 count1 = count2 = count3 = 0 printf("The first %d safe primes:",stop1) for (i=3; count1<stop1; i+=2) { if (i in arr && ((i-1)/2 in arr)) { count1++ printf(" %d",i) } } printf("\n") for (i=3; i<stop3; i+=2) { if (i in arr && ((i-1)/2 in arr)) { count3++ if (i < stop2) { count2++ } } } printf("Number below %d: %d\n",stop2,count2) printf("Number below %d: %d\n",stop3,count3) stop1 = 40 ; stop2 = 1E6 ; stop3 = 1E7 count1 = count2 = count3 = 1 printf("The first %d unsafe primes: 2",stop1) for (i=3; count1<stop1; i+=2) { if (i in arr && !((i-1)/2 in arr)) { count1++ printf(" %d",i) } } printf("\n") for (i=3; i<stop3; i+=2) { if (i in arr && !((i-1)/2 in arr)) { count3++ if (i < stop2) { count2++ } } } printf("Number below %d: %d\n",stop2,count2) printf("Number below %d: %d\n",stop3,count3) exit(0) } function is_prime(n, d) { d = 5 if (n < 2) { return(0) } if (n % 2 == 0) { return(n == 2) } if (n % 3 == 0) { return(n == 3) } while (d*d <= n) { if (n % d == 0) { return(0) } d += 2 if (n % d == 0) { return(0) } d += 4 } return(1) }
Generate a AWK translation of this VB snippet without changing its computational steps.
Dim t_age(4,1) t_age(0,0) = 27 : t_age(0,1) = "Jonah" t_age(1,0) = 18 : t_age(1,1) = "Alan" t_age(2,0) = 28 : t_age(2,1) = "Glory" t_age(3,0) = 18 : t_age(3,1) = "Popeye" t_age(4,0) = 28 : t_age(4,1) = "Alan" Dim t_nemesis(4,1) t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales" t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders" t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts" t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies" t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy" Call hash_join(t_age,1,t_nemesis,0) Sub hash_join(table_1,index_1,table_2,index_2) Set hash = CreateObject("Scripting.Dictionary") For i = 0 To UBound(table_1) hash.Add i,Array(table_1(i,0),table_1(i,1)) Next For j = 0 To UBound(table_2) For Each key In hash.Keys If hash(key)(index_1) = table_2(j,index_2) Then WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_ " = " & table_2(j,0) & "," & table_2(j,1) End If Next Next End Sub
BEGIN { FS = "," PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 if (ARGC-1 != 2) { print("error: incorrect number of arguments") ; errors++ exit } } { if (NR == FNR) { if (FNR == 1) { a_head = prefix_column_names("A") next } a_arr[$2][$1] = $0 } if (NR != FNR) { if (FNR == 1) { b_head = prefix_column_names("B") next } b_arr[$1][$2] = $0 } } END { if (errors > 0) { exit(1) } if (debug == 1) { dump_table(a_arr,a_head) dump_table(b_arr,b_head) } printf("%s%s%s\n",a_head,FS,b_head) for (i in a_arr) { if (i in b_arr) { for (j in a_arr[i]) { for (k in b_arr[i]) { print(a_arr[i][j] FS b_arr[i][k]) } } } } exit(0) } function dump_table(arr,heading, i,j) { printf("%s\n",heading) for (i in arr) { for (j in arr[i]) { printf("%s\n",arr[i][j]) } } print("") } function prefix_column_names(p, tmp) { tmp = p "." $0 gsub(/,/,"&" p ".",tmp) return(tmp) }
Preserve the algorithm and functionality while converting the code from C# to Icon.
using System; using System.Collections.Generic; using System.Linq; class Program { static void RunCode(string code) { int accumulator = 0; var opcodes = new Dictionary<char, Action> { {'H', () => Console.WriteLine("Hello, World!"))}, {'Q', () => Console.WriteLine(code) }, {'9', () => Console.WriteLine(Enumerable.Range(1,100).Reverse().Select(n => string.Format("{0} bottles of beer on the wall\n{0} bottles of beer\nTake one down, pass it around\n{1} bottles of beer on the wall\n", n, n-1)).Aggregate((a,b) => a + "\n" + b))}, {'+', () => accumulator++ } } foreach(var c in code) opcodes[c](); } }
procedure main(A) repeat writes("Enter HQ9+ code: ") & HQ9(get(A)|read()|break) end procedure HQ9(code) static bnw,bcr initial { bnw := table(" bottles"); bnw[1] := " bottle"; bnw[0] := "No more bottles" bcr := table("\n"); bcr[0]:="" } every c := map(!code) do case c of { "h" : write("Hello, World!") "q" : write(code) "9" : { every b := 99 to 1 by -1 do writes( bcr[b],b,bnw[b]," of beer on the wall\n", b,bnw[b]," of beer\nTake one down, pass it around\n", 1~=b|"",bnw[b-1]," of beer on the wall",bcr[b-1]) write(", ",map(bnw[b-1])," of beer.\nGo to the store ", "and buy some more, 99 bottles of beer on the wall.") } "+" : { /acc := 0 ; acc +:=1 } default: stop("Syntax error in ",code) } return end
Convert this C# block to Icon, preserving its control flow and logic.
using System; using System.Linq; using System.Collections.Generic; public struct Card { public Card(string rank, string suit) : this() { Rank = rank; Suit = suit; } public string Rank { get; } public string Suit { get; } public override string ToString() => $"{Rank} of {Suit}"; } public class Deck : IEnumerable<Card> { static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" }; static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" }; readonly List<Card> cards; public Deck() { cards = (from suit in suits from rank in ranks select new Card(rank, suit)).ToList(); } public int Count => cards.Count; public void Shuffle() { var random = new Random(); for (int i = 0; i < cards.Count; i++) { int r = random.Next(i, cards.Count); var temp = cards[i]; cards[i] = cards[r]; cards[r] = temp; } } public Card Deal() { int last = cards.Count - 1; Card card = cards[last]; cards.RemoveAt(last); return card; } public IEnumerator<Card> GetEnumerator() { for (int i = cards.Count - 1; i >= 0; i--) yield return cards[i]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); }
procedure main(arglist) cards := 2 players := 5 write("New deck : ", showcards(D := newcarddeck())) write("Shuffled : ", showcards(D := shufflecards(D))) H := list(players) every H[1 to players] := [] every ( c := 1 to cards ) & ( p := 1 to players ) do put(H[p], dealcard(D)) every write("Player write("Remaining: ",showcards(D)) end record card(suit,pip) procedure newcarddeck() local D every put(D := [], card(suits(),pips())) return D end procedure suits() suspend !["H","S","D","C"] end procedure pips() suspend !["2","3","4","5","6","7","8","9","10","J","Q","K","A"] end procedure shufflecards(D) every !D :=: ?D return D end procedure dealcard(D) return get(D) end procedure showcards(D) local s every (s := "") ||:= card2string(!D) || " " return s end procedure card2string(x) return x.pip || x.suit end
Convert this C# block to Icon, preserving its control flow and logic.
using System; namespace prog { class MainClass { class MyClass : ICloneable { public MyClass() { f = new int[3]{2,3,5}; c = '1'; } public object Clone() { MyClass cpy = (MyClass) this.MemberwiseClone(); cpy.f = (int[]) this.f.Clone(); return cpy; } public char c; public int[] f; } public static void Main( string[] args ) { MyClass c1 = new MyClass(); MyClass c2 = (MyClass) c1.Clone(); } } }
link printf,ximage procedure main() knot := makeknot() knota := knot knotc := copy(knot) knotdc := deepcopy(knot) showdeep("knota (assignment) vs. knot",knota,knot) showdeep("knotc (copy) vs. knot",knotc,knot) showdeep("knotdc (deepcopy) vs. knot",knotdc,knot) xdump("knot (original)",knot) xdump("knota (assignment)",knota) xdump("knotc (copy)",knotc) xdump("knotdc (deepcopy)",knotdc) end record rec1(a,b,c) class Class1(a1,a2) method one() self.a1 := 1 return end initially self.a1 := 0 end procedure makeknot() L := [9,8,7] T := table() T["a"] := 1 R := rec1(T) S := set(R) C := Class1() C.one() T["knot"] := [L,R,S,C] put(L,R,S,T,C) return L end procedure showdeep(tag,XC,X) printf("Analysis of copy depth for %s:\n",tag) showequiv(XC,X) every showequiv(XC[i := 1 to *X],X[i]) end procedure showequiv(x,y) return printf(" %i %s %i\n",x,if x === y then "===" else "~===",y) end
Convert this C# snippet to Icon and keep its semantics consistent.
using System; namespace prog { class MainClass { class MyClass : ICloneable { public MyClass() { f = new int[3]{2,3,5}; c = '1'; } public object Clone() { MyClass cpy = (MyClass) this.MemberwiseClone(); cpy.f = (int[]) this.f.Clone(); return cpy; } public char c; public int[] f; } public static void Main( string[] args ) { MyClass c1 = new MyClass(); MyClass c2 = (MyClass) c1.Clone(); } } }
link printf,ximage procedure main() knot := makeknot() knota := knot knotc := copy(knot) knotdc := deepcopy(knot) showdeep("knota (assignment) vs. knot",knota,knot) showdeep("knotc (copy) vs. knot",knotc,knot) showdeep("knotdc (deepcopy) vs. knot",knotdc,knot) xdump("knot (original)",knot) xdump("knota (assignment)",knota) xdump("knotc (copy)",knotc) xdump("knotdc (deepcopy)",knotdc) end record rec1(a,b,c) class Class1(a1,a2) method one() self.a1 := 1 return end initially self.a1 := 0 end procedure makeknot() L := [9,8,7] T := table() T["a"] := 1 R := rec1(T) S := set(R) C := Class1() C.one() T["knot"] := [L,R,S,C] put(L,R,S,T,C) return L end procedure showdeep(tag,XC,X) printf("Analysis of copy depth for %s:\n",tag) showequiv(XC,X) every showequiv(XC[i := 1 to *X],X[i]) end procedure showequiv(x,y) return printf(" %i %s %i\n",x,if x === y then "===" else "~===",y) end
Can you help me rewrite this code in Icon instead of C#, keeping it the same logically?
using System; using System.Drawing; using System.Windows.Forms; class Program { static Color GetPixel(Point position) { using (var bitmap = new Bitmap(1, 1)) { using (var graphics = Graphics.FromImage(bitmap)) { graphics.CopyFromScreen(position, new Point(0, 0), new Size(1, 1)); } return bitmap.GetPixel(0, 0); } } static void Main() { Console.WriteLine(GetPixel(Cursor.Position)); } }
link graphics,printf procedure main() WOpen("canvas=hidden") height := WAttrib("displayheight") - 45 width := WAttrib("displaywidth") - 20 WClose(&window) W := WOpen("size="||width||","||height,"bg=black") | stop("Unable to open window") every 1 to 10 do { x := ?width y := ?(height-100) WAttrib("fg="||?["red","green","blue","purple","yellow"]) FillRectangle(x,x+50,y,y+50) } while Event() do printf("x=%d,y=%d pixel=%s\n",&x,&y,Pixel(&x,&y,&x,&y)) WDone(W) end
Translate this program into Icon but keep the logic exactly as in C#.
using System; using System.Net; using System.Text.RegularExpressions; using System.Collections.Generic; class YahooSearch { private string query; private string content; private int page; const string yahoo = "http: public YahooSearch(string query) : this(query, 0) { } public YahooSearch(string query, int page) { this.query = query; this.page = page; this.content = new WebClient() .DownloadString( string.Format(yahoo + "p={0}&b={1}", query, this.page * 10 + 1) ); } public YahooResult[] Results { get { List<YahooResult> results = new List<YahooResult>(); Func<string, string, string> substringBefore = (str, before) => { int iHref = str.IndexOf(before); return iHref < 0 ? "" : str.Substring(0, iHref); }; Func<string, string, string> substringAfter = (str, after) => { int iHref = str.IndexOf(after); return iHref < 0 ? "" : str.Substring(iHref + after.Length); }; Converter<string, string> getText = p => Regex.Replace(p, "<[^>]*>", x => ""); Regex rx = new Regex(@" <li> <div \s class=""res""> <div> <h3> <a \s (?'LinkAttributes'[^>]+)> (?'LinkText' .*?) (?></a>) </h3> </div> <div \s class=""abstr""> (?'Abstract' .*?) (?></div>) .*? (?></div>) </li>", RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture ); foreach (Match e in rx.Matches(this.content)) { string rurl = getText(substringBefore(substringAfter( e.Groups["LinkAttributes"].Value, @"href="""), @"""")); string rtitle = getText(e.Groups["LinkText"].Value); string rcontent = getText(e.Groups["Abstract"].Value); results.Add(new YahooResult(rurl, rtitle, rcontent)); } return results.ToArray(); } } public YahooSearch NextPage() { return new YahooSearch(this.query, this.page + 1); } public YahooSearch GetPage(int page) { return new YahooSearch(this.query, page); } } class YahooResult { public string URL { get; set; } public string Title { get; set; } public string Content { get; set; } public YahooResult(string url, string title, string content) { this.URL = url; this.Title = title; this.Content = content; } public override string ToString() { return string.Format("\nTitle: {0}\nLink: {1}\nText: {2}", Title, URL, Content); } } class Prog { static void Main() { foreach (int page in new[] { 0, 1 }) { YahooSearch x = new YahooSearch("test", page); foreach (YahooResult result in x.Results) { Console.WriteLine(result); } } } }
link printf,strings procedure main() YS := YahooSearch("rosettacode") every 1 to 2 do { YS.readnext() YS.showinfo() } end class YahooSearch(urlpat,page,response) method readnext() self.page +:= 1 readurl() end method readurl() url := sprintf(self.urlpat,(self.page-1)*10+1) m := open(url,"m") | stop("Unable to open : ",url) every (self.response := "") ||:= |read(m) close(m) self.response := deletec(self.response,"\x00") end method showinfo() self.response ? repeat { (tab(find("<")) & ="<a class=\"yschttl spt\" href=\"") | break url := tab(find("\"")) & tab(find(">")+1) title := tab(find("<")) & ="</a></h3></div>" tab(find("<")) & =("<div class=\"abstr\">" | "<div class=\"sm-abs\">") abstr := tab(find("<")) & ="</div>" printf("\nTitle : %i\n",title) printf("URL  : %i\n",url) printf("Abstr : %i\n",abstr) } end initially(searchtext) urlpat := sprintf("http://search.yahoo.com/search?p=%s&b=%%d",searchtext) page := 0 end
Convert this C# block to Icon, preserving its control flow and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace StraddlingCheckerboard { class Program { public readonly static IReadOnlyDictionary<char, string> val2Key; public readonly static IReadOnlyDictionary<string, char> key2Val; static Program() { val2Key = new Dictionary<char, string> { {'A',"30"}, {'B',"31"}, {'C',"32"}, {'D',"33"}, {'E',"5"}, {'F',"34"}, {'G',"35"}, {'H',"0"}, {'I',"36"}, {'J',"37"}, {'K',"38"}, {'L',"2"}, {'M',"4"}, {'.',"78"}, {'N',"39"}, {'/',"79"}, {'O',"1"}, {'0',"790"}, {'P',"70"}, {'1',"791"}, {'Q',"71"}, {'2',"792"}, {'R',"8"}, {'3',"793"}, {'S',"6"}, {'4',"794"}, {'T',"9"}, {'5',"795"}, {'U',"72"}, {'6',"796"},{'V',"73"}, {'7',"797"}, {'W',"74"}, {'8',"798"}, {'X',"75"}, {'9',"799"}, {'Y',"76"}, {'Z',"77"}}; key2Val = val2Key.ToDictionary(kv => kv.Value, kv => kv.Key); } public static string Encode(string s) { return string.Concat(s.ToUpper().ToCharArray() .Where(c => val2Key.ContainsKey(c)).Select(c => val2Key[c])); } public static string Decode(string s) { return string.Concat(Regex.Matches(s, "79.|7.|3.|.").Cast<Match>() .Where(m => key2Val.ContainsKey(m.Value)).Select(m => key2Val[m.Value])); } static void Main(string[] args) { var enc = Encode("One night-it was on the twentieth of March, 1888-I was returning"); Console.WriteLine(enc); Console.WriteLine(Decode(enc)); Console.ReadLine(); } } }
procedure main() StraddlingCheckerBoard("setup","HOLMESRTABCDFGIJKNPQUVWXYZ./", 3,7) text := "One night. it was on the twentieth of March, 1888. I was returning" write("text = ",image(text)) write("encode = ",image(en := StraddlingCheckerBoard("encode",text))) write("decode = ",image(StraddlingCheckerBoard("decode",en))) end procedure StraddlingCheckerBoard(act,text,b1,b2) static SCE,SCD case act of { "setup" : { if (b1 < b2 < 10) & (*text = *cset(text) = 28) then { SCE := table("") SCD := table() esc := text[-1] every text[(b1|b2)+1+:0] := " " uix := ["",b1,b2] every c := text[1 + (i := 0 to *text-1)] do if c ~== " " then SCD[SCE[c] := SCE[map(c)] := uix[i/10+1]||(i%10) ] := c every c := !&digits do SCD[SCE[c] := SCE[esc] || c] := c delete(SCD,SCE[esc]) delete(SCE,esc) } else stop("Improper setup: ",image(text),", ",b1,", ",b2) } "encode" : { every (s := "") ||:= x := SCE[c := !text] return s } "decode" : { s := "" text ? until pos(0) do s ||:= \SCD[k := move(1 to 3)] return s } } end
Produce a language-to-language conversion: from C# to Icon, same semantics.
using System; namespace TypeDetection { class C { } struct S { } enum E { NONE, } class Program { static void ShowType<T>(T t) { Console.WriteLine("The type of '{0}' is {1}", t, t.GetType()); } static void Main() { ShowType(5); ShowType(7.5); ShowType('d'); ShowType(true); ShowType("Rosetta"); ShowType(new C()); ShowType(new S()); ShowType(E.NONE); ShowType(new int[] { 1, 2, 3 }); } } }
procedure main() print_text("This\nis\na text.\n") print_text(open("type_detection-icon.icn")) end procedure print_text(source) case type(source) of { "string" : writes(source) "file" : while write(read(source)) } end
Transform the following C# implementation into Icon, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; Console.WriteLine(infix.ToPostfix()); } } public static class ShuntingYard { private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators = new (string symbol, int precedence, bool rightAssociative) [] { ("^", 4, true), ("*", 3, false), ("/", 3, false), ("+", 2, false), ("-", 2, false) }.ToDictionary(op => op.symbol); public static string ToPostfix(this string infix) { string[] tokens = infix.Split(' '); var stack = new Stack<string>(); var output = new List<string>(); foreach (string token in tokens) { if (int.TryParse(token, out _)) { output.Add(token); Print(token); } else if (operators.TryGetValue(token, out var op1)) { while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) { int c = op1.precedence.CompareTo(op2.precedence); if (c < 0 || !op1.rightAssociative && c <= 0) { output.Add(stack.Pop()); } else { break; } } stack.Push(token); Print(token); } else if (token == "(") { stack.Push(token); Print(token); } else if (token == ")") { string top = ""; while (stack.Count > 0 && (top = stack.Pop()) != "(") { output.Add(top); } if (top != "(") throw new ArgumentException("No matching left parenthesis."); Print(token); } } while (stack.Count > 0) { var top = stack.Pop(); if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis."); output.Add(top); } Print("pop"); return string.Join(" ", output); void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}"); void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]"); } }
procedure main() infix := "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" printf("Infix = %i\n",infix) printf("RPN = %i\n",Infix2RPN(infix)) end link printf record op_info(pr,as) procedure Infix2RPN(expr) static oi initial { oi := table() every oi[!"+-"] := op_info(2) every oi[!"*/"] := op_info(3) oi["^"] := op_info(4,1) } ostack := [] rpn := "" pat := sprintf("%%5s  :  %%-%ds  :  %%s\n",*expr) printf(pat,"Token","Output","Op Stack") expr ? until pos(0) do { tab(many(' ')) token := tab(upto(' ')|0) printf(pat,token,rpn,list2string(ostack)) if token := numeric(token) then rpn ||:= token || " " else if member(oi,token) then { while member(oi,op2 := ostack[1]) & ( /oi[token].as & oi[token].pr <= oi[op2].pr ) | ( \oi[token].as & oi[token].pr < oi[op2].pr ) do rpn ||:= pop(ostack) || " " push(ostack,token) } else if token == "(" then push(ostack,token) else if token == ")" then { until ostack[1] == "(" do rpn ||:= pop(ostack) || " " | stop("Unbalanced parenthesis") pop(ostack) } } while token := pop(ostack) do if token == ("("|")") then stop("Unbalanced parenthesis") else { rpn ||:= token || " " printf(pat,"",rpn,list2string(ostack)) } return rpn end procedure list2string(L) every (s := "[ ") ||:= !L || " " return s || "]" end
Translate the given C code snippet into C++ without altering its behavior.
void bitwise(int a, int b) { printf("a and b: %d\n", a & b); printf("a or b: %d\n", a | b); printf("a xor b: %d\n", a ^ b); printf("not a: %d\n", ~a); printf("a << n: %d\n", a << b); printf("a >> n: %d\n", a >> b); unsigned int c = a; printf("c >> b: %d\n", c >> b); return 0; }
#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'; }
Generate a C++ translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { long long tmp = dx - dy; dy = dx + dy; dx = tmp; scale *= 2; x *= 2; y *= 2; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / scale; double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long tmp; # define LEFT tmp = -dy; dy = dx; dx = tmp # define RIGHT tmp = dy; dy = -dx; dx = tmp while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("X+YF+", d - 1); continue; case 'Y': if (d) iter_string("-FX-Y", d - 1); continue; case '+': RIGHT; continue; case '-': LEFT; continue; case 'F': clen ++; h_rgb(x/scale, y/scale); x += dx; y += dy; continue; } } } void dragon(long leng, int depth) { long i, d = leng / 3 + 1; long h = leng + 3, w = leng + d * 3 / 2 + 2; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = d; dx = leng; dy = 0; scale = 1; clen = 0; for (i = 0; i < depth; i++) sc_up(); iter_string("FX", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); dragon(size, depth * 2); return 0; }
#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" ); }
Translate the given C code snippet into C++ without altering its behavior.
#include <conio.h> #include <stdio.h> int main() { int n1, n2, n3; printf( "\n Introduzca el primer n%cmero (entero): ", 163 ); scanf( "%d", &n1 ); printf( "\n Introduzca el segundo n%cmero (entero): ", 163 ); scanf( "%d", &n2 ); printf( "\n Introduzca el tercer n%cmero (entero): ", 163 ); scanf( "%d", &n3 ); if ( n1 >= n2 && n1 >= n3 ) printf( "\n %d es el mayor.", n1 ); else if ( n2 > n3 ) printf( "\n %d es el mayor.", n2 ); else printf( "\n %d es el mayor.", n3 ); getch(); return 0; }
#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 ; }
Port the following code from C to C++ with equivalent syntax and logic.
void insert(link* anchor, link* newlink) { newlink->next = anchor->next; newlink->prev = anchor; (newlink->next)->prev = newlink; anchor->next = newlink; }
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; }
Transform the following C implementation into C++, maintaining the same output and logic.
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> typedef uint32_t integer; 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; static const integer wheel[] = { 4,2,4,2,4,6,2,6 }; integer p = 7; for (;;) { for (int i = 0; i < 8; ++i) { if (p * p > n) return true; if (n % p == 0) return false; p += wheel[i]; } } } int main() { setlocale(LC_ALL, ""); const integer limit = 1000000000; integer n = 0, max = 0; printf("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) printf(" "); printf("%'u", n); } else if (i == 25) printf("\n"); ++i; if (i == 100) printf("Hundredth SPDS prime: %'u\n", n); else if (i == 1000) printf("Thousandth SPDS prime: %'u\n", n); else if (i == 10000) printf("Ten thousandth SPDS prime: %'u\n", n); max = n; } printf("Largest SPDS prime less than %'u: %'u\n", limit, max); return 0; }
#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; }
Generate an equivalent C++ version of this C code.
#include <stdio.h> #include <string.h> int qselect(int *v, int len, int k) { # define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; } int i, st, tmp; for (st = i = 0; i < len - 1; i++) { if (v[i] > v[len-1]) continue; SWAP(i, st); st++; } SWAP(len-1, st); return k == st ?v[st] :st > k ? qselect(v, st, k) : qselect(v + st, len - st, k - st); } int main(void) { # define N (sizeof(x)/sizeof(x[0])) int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; int y[N]; int i; for (i = 0; i < 10; i++) { memcpy(y, x, sizeof(x)); printf("%d: %d\n", i, qselect(y, 10, i)); } return 0; }
#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; }
Please provide an equivalent version of this C code in C++.
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> char *to_base(int64_t num, int base) { char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[66] = {'\0'}; char *out; uint64_t n; int i, len = 0, neg = 0; if (base > 36) { fprintf(stderr, "base %d too large\n", base); return 0; } n = ((neg = num < 0)) ? (~num) + 1 : num; do { buf[len++] = tbl[n % base]; } while(n /= base); out = malloc(len + neg + 1); for (i = neg; len > 0; i++) out[i] = buf[--len]; if (neg) out[0] = '-'; return out; } long from_base(const char *num_str, int base) { char *endptr; int result = strtol(num_str, &endptr, base); return result; } int main() { int64_t x; x = ~(1LL << 63) + 1; printf("%lld in base 2: %s\n", x, to_base(x, 2)); x = 383; printf("%lld in base 16: %s\n", x, to_base(x, 16)); return 0; }
#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; }
Generate an equivalent C++ version of this C code.
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
#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"; } }
Rewrite the snippet below in C++ so it works the same as the original C code.
static unsigned char const k8[16] = { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }; static unsigned char const k7[16] = { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }; static unsigned char const k6[16] = { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }; static unsigned char const k5[16] = { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 }; static unsigned char const k4[16] = { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 }; static unsigned char const k3[16] = { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 }; static unsigned char const k2[16] = { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 }; static unsigned char const k1[16] = { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 }; static unsigned char k87[256]; static unsigned char k65[256]; static unsigned char k43[256]; static unsigned char k21[256]; void kboxinit(void) { int i; for (i = 0; i < 256; i++) { k87[i] = k8[i >> 4] << 4 | k7[i & 15]; k65[i] = k6[i >> 4] << 4 | k5[i & 15]; k43[i] = k4[i >> 4] << 4 | k3[i & 15]; k21[i] = k2[i >> 4] << 4 | k1[i & 15]; } } static word32 f(word32 x) { x = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 | k43[x>> 8 & 255] << 8 | k21[x & 255]; return x<<11 | x>>(32-11); }
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 this program into C++ but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define USE_FAKES 1 const char *states[] = { #if USE_FAKES "New Kory", "Wen Kory", "York New", "Kory New", "New Kory", #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" }; int n_states = sizeof(states)/sizeof(*states); typedef struct { unsigned char c[26]; const char *name[2]; } letters; void count_letters(letters *l, const char *s) { int c; if (!l->name[0]) l->name[0] = s; else l->name[1] = s; while ((c = *s++)) { if (c >= 'a' && c <= 'z') l->c[c - 'a']++; if (c >= 'A' && c <= 'Z') l->c[c - 'A']++; } } int lcmp(const void *aa, const void *bb) { int i; const letters *a = aa, *b = bb; for (i = 0; i < 26; i++) if (a->c[i] > b->c[i]) return 1; else if (a->c[i] < b->c[i]) return -1; return 0; } int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } void no_dup() { int i, j; qsort(states, n_states, sizeof(const char*), scmp); for (i = j = 0; i < n_states;) { while (++i < n_states && !strcmp(states[i], states[j])); if (i < n_states) states[++j] = states[i]; } n_states = j + 1; } void find_mix() { int i, j, n; letters *l, *p; no_dup(); n = n_states * (n_states - 1) / 2; p = l = calloc(n, sizeof(letters)); for (i = 0; i < n_states; i++) for (j = i + 1; j < n_states; j++, p++) { count_letters(p, states[i]); count_letters(p, states[j]); } qsort(l, n, sizeof(letters), lcmp); for (j = 0; j < n; j++) { for (i = j + 1; i < n && !lcmp(l + j, l + i); i++) { if (l[j].name[0] == l[i].name[0] || l[j].name[1] == l[i].name[0] || l[j].name[1] == l[i].name[1]) continue; printf("%s + %s => %s + %s\n", l[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]); } } free(l); } int main(void) { find_mix(); return 0; }
#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; } }
Write the same code in C++ as shown below in C.
#include <stdio.h> #include <string.h> #include <zlib.h> int main() { const char *s = "The quick brown fox jumps over the lazy dog"; printf("%lX\n", crc32(0, (const void*)s, strlen(s))); return 0; }
#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'; }
Convert this C block to C++, preserving its control flow and logic.
#include <stdio.h> const char *input = "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!"; int main() { const char *s; printf("<table>\n<tr><td>"); for (s = input; *s; s++) { switch(*s) { case '\n': printf("</td></tr>\n<tr><td>"); break; case ',': printf("</td><td>"); break; case '<': printf("&lt;"); break; case '>': printf("&gt;"); break; case '&': printf("&amp;"); break; default: putchar(*s); } } puts("</td></tr>\n</table>"); return 0; }
#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 ] = { "&lt;" , "&gt;" , " <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 ; }
Write a version of this C function in C++ with identical behavior.
#include <stdio.h> const char *input = "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!"; int main() { const char *s; printf("<table>\n<tr><td>"); for (s = input; *s; s++) { switch(*s) { case '\n': printf("</td></tr>\n<tr><td>"); break; case ',': printf("</td><td>"); break; case '<': printf("&lt;"); break; case '>': printf("&gt;"); break; case '&': printf("&amp;"); break; default: putchar(*s); } } puts("</td></tr>\n</table>"); return 0; }
#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 ] = { "&lt;" , "&gt;" , " <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 ; }
Can you help me rewrite this code in C++ instead of C, keeping it the same logically?
#include <stdlib.h> typedef struct sMyClass { int variable; } *MyClass; MyClass MyClass_new() { MyClass pthis = malloc(sizeof *pthis); pthis->variable = 0; return pthis; } void MyClass_delete(MyClass* pthis) { if (pthis) { free(*pthis); *pthis = NULL; } } void MyClass_someMethod(MyClass pthis) { pthis->variable = 1; } MyClass obj = MyClass_new(); MyClass_someMethod(obj); MyClass_delete(&obj);
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 the snippet below in C++ so it works the same as the original C code.
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
#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 ; }
Convert the following code from C to C++, ensuring the logic remains intact.
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
#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 ; }
Port the following code from C to C++ with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> void* mem_alloc(size_t item_size, size_t n_item) { size_t *x = calloc(1, sizeof(size_t)*2 + n_item * item_size); x[0] = item_size; x[1] = n_item; return x + 2; } void* mem_extend(void *m, size_t new_n) { size_t *x = (size_t*)m - 2; x = realloc(x, sizeof(size_t) * 2 + *x * new_n); if (new_n > x[1]) memset((char*)(x + 2) + x[0] * x[1], 0, x[0] * (new_n - x[1])); x[1] = new_n; return x + 2; } inline void _clear(void *m) { size_t *x = (size_t*)m - 2; memset(m, 0, x[0] * x[1]); } #define _new(type, n) mem_alloc(sizeof(type), n) #define _del(m) { free((size_t*)(m) - 2); m = 0; } #define _len(m) *((size_t*)m - 1) #define _setsize(m, n) m = mem_extend(m, n) #define _extend(m) m = mem_extend(m, _len(m) * 2) typedef uint8_t byte; typedef uint16_t ushort; #define M_CLR 256 #define M_EOD 257 #define M_NEW 258 typedef struct { ushort next[256]; } lzw_enc_t; typedef struct { ushort prev, back; byte c; } lzw_dec_t; byte* lzw_encode(byte *in, int max_bits) { int len = _len(in), bits = 9, next_shift = 512; ushort code, c, nc, next_code = M_NEW; lzw_enc_t *d = _new(lzw_enc_t, 512); if (max_bits > 15) max_bits = 15; if (max_bits < 9 ) max_bits = 12; byte *out = _new(ushort, 4); int out_len = 0, o_bits = 0; uint32_t tmp = 0; inline void write_bits(ushort x) { tmp = (tmp << bits) | x; o_bits += bits; if (_len(out) <= out_len) _extend(out); while (o_bits >= 8) { o_bits -= 8; out[out_len++] = tmp >> o_bits; tmp &= (1 << o_bits) - 1; } } for (code = *(in++); --len; ) { c = *(in++); if ((nc = d[code].next[c])) code = nc; else { write_bits(code); nc = d[code].next[c] = next_code++; code = c; } if (next_code == next_shift) { if (++bits > max_bits) { write_bits(M_CLR); bits = 9; next_shift = 512; next_code = M_NEW; _clear(d); } else _setsize(d, next_shift *= 2); } } write_bits(code); write_bits(M_EOD); if (tmp) write_bits(tmp); _del(d); _setsize(out, out_len); return out; } byte* lzw_decode(byte *in) { byte *out = _new(byte, 4); int out_len = 0; inline void write_out(byte c) { while (out_len >= _len(out)) _extend(out); out[out_len++] = c; } lzw_dec_t *d = _new(lzw_dec_t, 512); int len, j, next_shift = 512, bits = 9, n_bits = 0; ushort code, c, t, next_code = M_NEW; uint32_t tmp = 0; inline void get_code() { while(n_bits < bits) { if (len > 0) { len --; tmp = (tmp << 8) | *(in++); n_bits += 8; } else { tmp = tmp << (bits - n_bits); n_bits = bits; } } n_bits -= bits; code = tmp >> n_bits; tmp &= (1 << n_bits) - 1; } inline void clear_table() { _clear(d); for (j = 0; j < 256; j++) d[j].c = j; next_code = M_NEW; next_shift = 512; bits = 9; }; clear_table(); for (len = _len(in); len;) { get_code(); if (code == M_EOD) break; if (code == M_CLR) { clear_table(); continue; } if (code >= next_code) { fprintf(stderr, "Bad sequence\n"); _del(out); goto bail; } d[next_code].prev = c = code; while (c > 255) { t = d[c].prev; d[t].back = c; c = t; } d[next_code - 1].c = c; while (d[c].back) { write_out(d[c].c); t = d[c].back; d[c].back = 0; c = t; } write_out(d[c].c); if (++next_code >= next_shift) { if (++bits > 16) { fprintf(stderr, "Too many bits\n"); _del(out); goto bail; } _setsize(d, next_shift *= 2); } } if (code != M_EOD) fputs("Bits did not end in EOD\n", stderr); _setsize(out, out_len); bail: _del(d); return out; } int main() { int i, fd = open("unixdict.txt", O_RDONLY); if (fd == -1) { fprintf(stderr, "Can't read file\n"); return 1; }; struct stat st; fstat(fd, &st); byte *in = _new(char, st.st_size); read(fd, in, st.st_size); _setsize(in, st.st_size); close(fd); printf("input size: %d\n", _len(in)); byte *enc = lzw_encode(in, 9); printf("encoded size: %d\n", _len(enc)); byte *dec = lzw_decode(enc); printf("decoded size: %d\n", _len(dec)); for (i = 0; i < _len(dec); i++) if (dec[i] != in[i]) { printf("bad decode at %d\n", i); break; } if (i == _len(dec)) printf("Decoded ok\n"); _del(in); _del(enc); _del(dec); return 0; }
#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; }
Produce a language-to-language conversion: from C to C++, same semantics.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
#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; }
Produce a language-to-language conversion: from C to C++, same semantics.
#include <stdio.h> #include <stdlib.h> typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
#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; }
Write the same code in C++ as shown below in C.
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
#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; }
Please provide an equivalent version of this C code in C++.
#include <stdio.h> #include <stdlib.h> int f(int n, int x, int y) { return (x + y*2 + 1)%n; } int main(int argc, char **argv) { int i, j, n; if(argc!=2) return 1; n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("% 4d", f(n, n - j - 1, i)*n + f(n, j, i) + 1); putchar('\n'); } printf("\n Magic Constant: %d.\n", (n*n+1)/2*n); return 0; }
#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; }
Please provide an equivalent version of this C code in C++.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
#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; }
Keep all operations the same but rewrite the snippet in C++.
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode; Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NULL; node->next = NULL; return node; } void free_lnode(Lnode *node) { if (node == NULL) { return; } node->v = 0; node->prev = NULL; free_lnode(node->next); node->next = NULL; } typedef struct list_t { Lnode *front; Lnode *back; size_t len; } List; List *make_list() { List *list = malloc(sizeof(List)); if (list == NULL) { return NULL; } list->front = NULL; list->back = NULL; list->len = 0; return list; } void free_list(List *list) { if (list == NULL) { return; } list->len = 0; list->back = NULL; free_lnode(list->front); list->front = NULL; } void list_insert(List *list, int v) { Lnode *node; if (list == NULL) { return; } node = make_list_node(v); if (list->front == NULL) { list->front = node; list->back = node; list->len = 1; } else { node->prev = list->back; list->back->next = node; list->back = node; list->len++; } } void list_print(List *list) { Lnode *it; if (list == NULL) { return; } for (it = list->front; it != NULL; it = it->next) { printf("%d ", it->v); } } int list_get(List *list, int idx) { Lnode *it = NULL; if (list != NULL && list->front != NULL) { int i; if (idx < 0) { it = list->back; i = -1; while (it != NULL && i > idx) { it = it->prev; i--; } } else { it = list->front; i = 0; while (it != NULL && i < idx) { it = it->next; i++; } } } if (it == NULL) { return INT_MIN; } return it->v; } typedef struct mnode_t { int k; bool v; struct mnode_t *next; } Mnode; Mnode *make_map_node(int k, bool v) { Mnode *node = malloc(sizeof(Mnode)); if (node == NULL) { return node; } node->k = k; node->v = v; node->next = NULL; return node; } void free_mnode(Mnode *node) { if (node == NULL) { return; } node->k = 0; node->v = false; free_mnode(node->next); node->next = NULL; } typedef struct map_t { Mnode *front; } Map; Map *make_map() { Map *map = malloc(sizeof(Map)); if (map == NULL) { return NULL; } map->front = NULL; return map; } void free_map(Map *map) { if (map == NULL) { return; } free_mnode(map->front); map->front = NULL; } void map_insert(Map *map, int k, bool v) { if (map == NULL) { return; } if (map->front == NULL) { map->front = make_map_node(k, v); } else { Mnode *it = map->front; while (it->next != NULL) { it = it->next; } it->next = make_map_node(k, v); } } bool map_get(Map *map, int k) { if (map != NULL) { Mnode *it = map->front; while (it != NULL && it->k != k) { it = it->next; } if (it != NULL) { return it->v; } } return false; } int gcd(int u, int v) { if (u < 0) u = -u; if (v < 0) v = -v; if (v) { while ((u %= v) && (v %= u)); } return u + v; } List *yellow(size_t n) { List *a; Map *b; int i; a = make_list(); list_insert(a, 1); list_insert(a, 2); list_insert(a, 3); b = make_map(); map_insert(b, 1, true); map_insert(b, 2, true); map_insert(b, 3, true); i = 4; while (n > a->len) { if (!map_get(b, i) && gcd(i, list_get(a, -1)) == 1 && gcd(i, list_get(a, -2)) > 1) { list_insert(a, i); map_insert(b, i, true); i = 4; } i++; } free_map(b); return a; } int main() { List *a = yellow(30); list_print(a); free_list(a); putc('\n', stdout); return 0; }
#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; }
Convert this C snippet to C++ and keep its semantics consistent.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
#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; }
Please provide an equivalent version of this C code in C++.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char byte; byte *grid = 0; int w, h, len; unsigned long long cnt; static int next[4], dir[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; void walk(int y, int x) { int i, t; if (!y || y == h || !x || x == w) { cnt += 2; return; } t = y * (w + 1) + x; grid[t]++, grid[len - t]++; for (i = 0; i < 4; i++) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); grid[t]--, grid[len - t]--; } unsigned long long solve(int hh, int ww, int recur) { int t, cx, cy, x; h = hh, w = ww; if (h & 1) t = w, w = h, h = t; if (h & 1) return 0; if (w == 1) return 1; if (w == 2) return h; if (h == 2) return w; cy = h / 2, cx = w / 2; len = (h + 1) * (w + 1); grid = realloc(grid, len); memset(grid, 0, len--); next[0] = -1; next[1] = -w - 1; next[2] = 1; next[3] = w + 1; if (recur) cnt = 0; for (x = cx + 1; x < w; x++) { t = cy * (w + 1) + x; grid[t] = 1; grid[len - t] = 1; walk(cy - 1, x); } cnt++; if (h == w) cnt *= 2; else if (!(w & 1) && recur) solve(w, h, 0); return cnt; } int main() { int y, x; for (y = 1; y <= 10; y++) for (x = 1; x <= y; x++) if (!(x & 1) || !(y & 1)) printf("%d x %d: %llu\n", y, x, solve(y, x, 1)); return 0; }
#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; }
Rewrite the snippet below in C++ so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> int* mertens_numbers(int max) { int* m = malloc((max + 1) * sizeof(int)); if (m == NULL) return m; m[1] = 1; for (int n = 2; n <= max; ++n) { m[n] = 1; for (int k = 2; k <= n; ++k) m[n] -= m[n/k]; } return m; } int main() { const int max = 1000; int* mertens = mertens_numbers(max); if (mertens == NULL) { fprintf(stderr, "Out of memory\n"); return 1; } printf("First 199 Mertens numbers:\n"); const int count = 200; for (int i = 0, column = 0; i < count; ++i) { if (column > 0) printf(" "); if (i == 0) printf(" "); else printf("%2d", mertens[i]); ++column; if (column == 20) { printf("\n"); column = 0; } } int zero = 0, cross = 0, previous = 0; for (int i = 1; i <= max; ++i) { int m = mertens[i]; if (m == 0) { ++zero; if (previous != 0) ++cross; } previous = m; } free(mertens); printf("M(n) is zero %d times for 1 <= n <= %d.\n", zero, max); printf("M(n) crosses zero %d times for 1 <= n <= %d.\n", cross, max); return 0; }
#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; }
Please provide an equivalent version of this C code in C++.
#include <stdio.h> #include <string.h> #include <stdlib.h> int interactiveCompare(const void *x1, const void *x2) { const char *s1 = *(const char * const *)x1; const char *s2 = *(const char * const *)x2; static int count = 0; printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2); int response; scanf("%d", &response); return response; } void printOrder(const char *items[], int len) { printf("{ "); for (int i = 0; i < len; ++i) printf("%s ", items[i]); printf("}\n"); } int main(void) { const char *items[] = { "violet", "red", "green", "indigo", "blue", "yellow", "orange" }; qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare); printOrder(items, sizeof(items)/sizeof(*items)); return 0; }
#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; }
Translate this program into C++ but keep the logic exactly as in C.
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
#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 ; }
Generate a C++ translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> #include <math.h> float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i); return prob; } float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { perror("Can't open file"); exit(EXIT_FAILURE); } int tally[9] = { 0 }; char c; int total = 0; while ((c = getc(input)) != EOF) { while (c < '1' || c > '9') c = getc(input); tally[c - '1']++; total++; while ((c = getc(input)) != '\n' && c != EOF) ; } fclose(input); static float freq[9]; for (int i = 0; i < 9; i++) freq[i] = tally[i] / (float) total; return freq; } int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
#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 ; }
Keep all operations the same but rewrite the snippet in C++.
#include<unistd.h> #include<stdio.h> #include<time.h> #define SHORTLAG 1000 #define LONGLAG 2000 int main(){ int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; while(1){ time(&t); currentTime = localtime(&t); hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec; hour = 12; min = 0; sec = 0; if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; } if(min==0){ min1 = 0; min2 = 0; } else{ min1 = 3; min2 = 0; } if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times); for(i=1;i<=times;i++){ printf("\a"); (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }
#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; }
Write the same algorithm in C++ as shown in this C implementation.
#include<unistd.h> #include<stdio.h> #include<time.h> #define SHORTLAG 1000 #define LONGLAG 2000 int main(){ int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; while(1){ time(&t); currentTime = localtime(&t); hour = currentTime->tm_hour; min = currentTime->tm_min; sec = currentTime->tm_sec; hour = 12; min = 0; sec = 0; if((min==0 || min==30) && sec==0) times = ((hour*60 + min)%240)%8; if(times==0){ times = 8; } if(min==0){ min1 = 0; min2 = 0; } else{ min1 = 3; min2 = 0; } if((min==0 || min==30) && sec==0){ printf("\nIt is now %d:%d%d %s. Sounding the bell %d times.",hour,min1,min2,(hour>11)?"PM":"AM",times); for(i=1;i<=times;i++){ printf("\a"); (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } } return 0; }
#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; }
Translate this program into C++ but keep the logic exactly as in C.
#include <stdio.h> long fib(long x) { long fib_i(long n) { return n < 2 ? n : fib_i(n - 2) + fib_i(n - 1); }; if (x < 0) { printf("Bad argument: fib(%ld)\n", x); return -1; } return fib_i(x); } long fib_i(long n) { printf("This is not the fib you are looking for\n"); return -1; } int main() { long x; for (x = -1; x < 4; x ++) printf("fib %ld = %ld\n", x, fib(x)); printf("calling fib_i from outside fib:\n"); fib_i(3); return 0; }
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); } }
Convert this C snippet to C++ and keep its semantics consistent.
char nonblocking_getch(); void positional_putch(int x, int y, char ch); void millisecond_sleep(int n); void init_screen(); void update_screen(); void close_screen(); #ifdef __linux__ #define _POSIX_C_SOURCE 200809L #include <time.h> #include <ncurses.h> char nonblocking_getch() { return getch(); } void positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); } void millisecond_sleep(int n) { struct timespec t = { 0, n * 1000000 }; nanosleep(&t, 0); } void update_screen() { refresh(); } void init_screen() { initscr(); noecho(); cbreak(); nodelay(stdscr, TRUE); } void close_screen() { endwin(); } #endif #ifdef _WIN32 #error "not implemented" #endif #include <time.h> #include <stdlib.h> #define w 80 #define h 40 int board[w * h]; int head; enum Dir { N, E, S, W } dir; int quit; enum State { SPACE=0, FOOD=1, BORDER=2 }; void age() { int i; for(i = 0; i < w * h; ++i) if(board[i] < 0) ++board[i]; } void plant() { int r; do r = rand() % (w * h); while(board[r] != SPACE); board[r] = FOOD; } void start(void) { int i; for(i = 0; i < w; ++i) board[i] = board[i + (h - 1) * w] = BORDER; for(i = 0; i < h; ++i) board[i * w] = board[i * w + w - 1] = BORDER; head = w * (h - 1 - h % 2) / 2; board[head] = -5; dir = N; quit = 0; srand(time(0)); plant(); } void step() { int len = board[head]; switch(dir) { case N: head -= w; break; case S: head += w; break; case W: --head; break; case E: ++head; break; } switch(board[head]) { case SPACE: board[head] = len - 1; age(); break; case FOOD: board[head] = len - 1; plant(); break; default: quit = 1; } } void show() { const char * symbol = " @."; int i; for(i = 0; i < w * h; ++i) positional_putch(i / w, i % w, board[i] < 0 ? '#' : symbol[board[i]]); update_screen(); } int main (int argc, char * argv[]) { init_screen(); start(); do { show(); switch(nonblocking_getch()) { case 'i': dir = N; break; case 'j': dir = W; break; case 'k': dir = S; break; case 'l': dir = E; break; case 'q': quit = 1; break; } step(); millisecond_sleep(100); } while(!quit); millisecond_sleep(999); close_screen(); return 0; }
#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; }
Translate this program into C++ but keep the logic exactly as in C.
#include <string.h> #include <stdlib.h> #include <stdio.h> int main( int argc, char ** argv ){ const char * str_a = "knight"; const char * str_b = "socks"; const char * str_c = "brooms"; char * new_a = malloc( strlen( str_a ) - 1 ); char * new_b = malloc( strlen( str_b ) - 1 ); char * new_c = malloc( strlen( str_c ) - 2 ); strcpy( new_a, str_a + 1 ); strncpy( new_b, str_b, strlen( str_b ) - 1 ); strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); printf( "%s\n%s\n%s\n", new_a, new_b, new_c ); free( new_a ); free( new_b ); free( new_c ); return 0; }
#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 ; }